diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml new file mode 100644 index 0000000..ded777d --- /dev/null +++ b/.github/workflows/website.yml @@ -0,0 +1,82 @@ +name: Public website + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: public-website-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + pages: read + defaults: + run: + working-directory: topocode + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + path: topocode + fetch-depth: 0 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + repository: jdylanmc/topo-archify + ref: b94790e99e2ca51fcdb74a9bd0f10f637856f92f + path: renderer + fetch-depth: 0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: topocode/.node-version + - run: corepack enable + - run: yarn install --immutable + - name: Prepare pinned renderer + run: | + node ../renderer/integrations/topo-npm/pack.mjs ../renderer/dist + node scripts/bootstrap-renderer.mjs ../renderer/dist/jdylanmc-topo-archify-0.1.0.tgz + - run: yarn lint + - run: yarn build + - run: yarn workspace @topo/site exec playwright install --with-deps chromium + - run: yarn website:test + - name: Configure Pages + id: pages + if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request' + uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5 + - name: Build publication artifact + env: + PAGES_BASE: ${{ steps.pages.outputs.base_path }} + run: | + if [ "${GITHUB_REF}" = "refs/heads/main" ] && [ "${GITHUB_EVENT_NAME}" != "pull_request" ]; then + SITE_BASE_PATH="${PAGES_BASE%/}/" yarn website:build + else + yarn website:build + fi + - uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3 + with: + path: topocode/dist/public-site + + deploy: + if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request' + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + concurrency: + group: github-pages + cancel-in-progress: false + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy website + id: deployment + uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4 diff --git a/AGENTS.md b/AGENTS.md index 23224a7..1b0f287 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,6 +25,14 @@ Read relevant existing records before exploration. These files are created lazily through separately authorized domain recording, not during setup. See `docs/agents/domain.md`. +### Website and diagram maintenance + +When changing Topocode, update affected documentation and curated diagrams in +the same PR. Re-read changed source before updating diagram evidence; never +refresh hashes blindly. If no updates are needed, briefly explain why in the PR. +Existing CI checks evidence and site builds; humans review whether diagrams +explain the code clearly. Keep the curated set small and question-driven. + ### Commit messages Use the terse Conventional Commits policy in `docs/agents/commit-style.md`, diff --git a/CHANGELOG.md b/CHANGELOG.md index 3aff8e2..df4cb75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,30 @@ versions are independent; publication remains a separate release-owner action. ## Unreleased +### Added + +- Add the public static website with repository-backed documentation, installation + guidance, a curated roadmap, and a live diagram demonstrating the scan-to-review + collaboration. GitHub Actions validates changes and deploys main to GitHub Pages. + See #74 and #75. +- Add eight source-backed self-documentation stories, including module interfaces + and algorithm sequences, with explicit drilldowns and visible return navigation. +- Let authors select a published story subset, add short Architecture captions and + semantic responsibility roles, and request wider Sequence participant spacing. + These repository-build capabilities are not yet in the npm 0.2.0 release. + +### Fixed + +- Keep default Architecture source captions readable across sidebar breakpoints + without changing authored summary styling. Reserve space for open evidence + rather than covering diagram titles or navigation controls. +- Preserve the actual caller through nested story returns and reloads, and keep + drilldown/focus navigation working for all legal authored section IDs across + native and Graphviz viewers. +- Keep adjacent diagonal Architecture routes local instead of taking unnecessary + detours. Preserve readable captions, interactive accessibility, nested theme + ownership, and source evidence while leaving the pinned renderer unchanged. + ## 0.2.0 - 2026-09-30 Release preparation date; npm publication is not implied by these notes. diff --git a/README.md b/README.md index ff6aa92..8879f90 100644 --- a/README.md +++ b/README.md @@ -22,16 +22,15 @@ The goal is to put a software engineer in the human-in-the-loop position: every claim the tool makes about a codebase is backed by evidence you can follow, and everything a human adds is recorded as such. -> **Release preparation: 0.2.0.** The scan-to-site workflow, deterministic reports, +> **Released: 0.2.0.** The scan-to-site workflow, deterministic reports, > source-grounded stories, static analysis modules, optional AI commentary, and > pinned Archify 3.0.0 rendering are implemented. Topo is the storybook for > architects: the generated shell inventories every diagram while preserving -> real Archify viewers. This source prepares the next minor release; registry -> publication remains a separate release-owner step. +> real Archify viewers. Install the published package from npm. ## Install the toolbelt -Once 0.2.0 is published, install the public package below. Its exact +Install the public package below. Its exact `@jdylanmc/topo-archify@0.1.0` dependency is installed automatically; no source checkout or paired tarball is required. Then run `npm exec --no -- topo init . --skills`. This adds project-local Topocode skills @@ -48,6 +47,9 @@ npm exec --no -- topo serve . See [package bootstrap, consumer proof and release procedure](./docs/npm-release.md). +See the [getting-started guide](./docs/getting-started.md), [CLI reference](./docs/cli.md), +and [public website build/deployment guide](./docs/public-website.md). + ## Run locally For the separately preserved, non-integrated prototype, see the diff --git a/docs/cli.md b/docs/cli.md new file mode 100644 index 0000000..4b474fd --- /dev/null +++ b/docs/cli.md @@ -0,0 +1,54 @@ +# CLI reference + +Run commands inside your project using `npm exec --no -- topo`, or use `topo` +directly after a global installation. Node.js 22+ and a Git repository are +required. Repository arguments default to the current directory where shown. + +```text +topo init [repository] [--skills] +topo scan [repository] [--allow-partial] [--responsibilities path] +topo ingest [more.json ...] +topo enrich [repository] +topo preview +topo story validate +topo story preview +topo serve [repository] [--port 4173] +topo bundle [repository] [--output directory] [--base-path /path/] +``` + +| Command | Purpose | +| --- | --- | +| `init` | Create configuration and a ready-to-serve Home without scanning. `--skills` opts into local agent guidance. | +| `scan` | Generate structural evidence and repository exploration; render committed stories. Strict by default. | +| `ingest` | Ingest normalized report evidence against a clean scanned revision. | +| `enrich` | Explicitly run the repository-configured external command for inferred commentary. Never runs as part of scan. | +| `story validate` | Validate an authored draft and resolve its source anchors. | +| `story preview` | Render committed stories and refresh Home without requiring a scan. | +| `preview` | Legacy shorthand for story preview. | +| `serve` | Serve locally on `127.0.0.1`; default port is 4173. | +| `bundle` | Emit static files with all required runtime assets and notices. | + +`--help` (or `-h`) prints the installed CLI contract. Unknown commands, arguments, +and unsupported option combinations fail explicitly. + +## Important options + +`scan --allow-partial` publishes a visibly incomplete preview and returns exit +code **2**. It is not a success override. Explicit Rust/Tauri analysis currently +requires this acknowledgement. + +`scan --responsibilities ` accepts an explicit responsibility-grouping +proposal. See [logical architecture](./logical-architecture.md). + +`bundle --base-path` must be `/` or an absolute URL path ending in `/`. It creates +that path beneath the output directory. Default output is `.topo/bundle`. + +`serve --port 0` requests an available port; use the printed URL. + +## Related contracts + +- [Configuration and workspace lifecycle](./workspace.md) +- [Story authoring](./story-authoring.md) +- [Report ingestion](./reports.md) +- [Explicit enrichment](./enrichment.md) +- [Rust/Tauri support and limits](./rust-tauri.md) diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..54f1c0c --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,88 @@ +# Get started with Topocode + +Topocode is a local-first architecture storybook. Initialize a working Home, +then curate explanations of your code with your coding agent. Scanning is +optional; it supplies structural evidence, not a finished architectural narrative. + +## Install + +You need **Node.js 22 or newer** and **Git**. Run these commands inside your +project's Git repository: + +```sh +npm install --save-dev @jdylanmc/topo-code@0.2.0 +npm exec --no -- topo init . --skills +npm exec --no -- topo serve . +``` + +Open the loopback address printed by the CLI. You have a functional, empty Home. +No scan, model invocation, account, or first Git commit is required to initialize. +The `--no` option prevents `npm exec` from downloading an unexpected package. + +`--skills` installs project-local guidance for your agent. Existing identical +files are preserved; conflicting files are reported rather than overwritten. +Omit `--skills` if you only want the storybook. + +## Make one useful map + +Ask your agent a focused question: “Explain how a request reaches the database,” +or “Show the decisions and failure paths in this workflow.” + +Have the agent read the actual source and the installed +`.agents/skills/topo-story-authoring/SKILL.md`. Work together on one story under +`stories/**/*.topo.json`. Review its explanation and evidence, not just its looks. + +```sh +npm exec --no -- topo story validate . stories/request.topo.json +``` + +Validation accepts uncommitted drafts. Once you have reviewed and committed the +source, configuration, and story, render it: + +```sh +npm exec --no -- topo story preview . stories/request.topo.json +npm exec --no -- topo serve . +``` + +Preview refreshes the inventory of committed stories, not only the selected file. +See [working with an agent](./story-authoring.md) and the +[story contract](./story-preview.md). + +## Optionally scan the repository + +```sh +npm exec --no -- topo scan . +``` + +The default scanner analyzes TypeScript and JavaScript. Scanning adds repository +exploration; it never invokes a model. Unknown or unresolved source fails +explicitly rather than turning assumptions into edges. + +[Rust and Tauri](./rust-tauri.md) require explicit configuration and remain +partial. Their intentional partial preview uses `--allow-partial` and exits +**2**, not success. Do not make CI ignore all scan failures. + +## Share a static storybook + +```sh +npm exec --no -- topo bundle . --output ./site-output --base-path /architecture/ +``` + +The deployable site is under `site-output/architecture/`. Serve `site-output` +with your static host and open `/architecture/`. Use `/` for a domain-root +deployment. Include every emitted asset and license notice. + +No Topocode server is needed for the published bundle. Generated `.topo/cache` +content is disposable; source, configuration, and authored stories are durable. +See [workspace lifecycle](./workspace.md). + +## Know what validation proves + +Valid anchors show that cited evidence exists. Hash-bound anchors detect source +changes. Neither check proves that a narrative is meaningful, correct in every +detail, or complete. Review maps with a person who knows the system, and repair +the explanation when the implementation changes. + +The public self-demo starts with an internal-module map and a companion showing +external dependencies grouped by role. We curate these maps together instead +of publishing development fixtures as an architectural tour. diff --git a/docs/public-website.md b/docs/public-website.md new file mode 100644 index 0000000..b534597 --- /dev/null +++ b/docs/public-website.md @@ -0,0 +1,178 @@ +# Public website + +The public product website is separate from the Home created in consumer +repositories. It is generated by `website/build.mjs`: plain static HTML/CSS, +repository Markdown rendered by Marked, and a small browser module for themes, +clipboard interaction, and background motion. No browser framework, runtime +GitHub API, analytics, third-party fonts, or server-side service is required. + +## Build and preview + +After the normal developer dependency/renderer setup and core build: + +```sh +corepack yarn website:build +node website/serve.mjs +``` + +Open `http://127.0.0.1:4188/topo-code/`. Output lives in `dist/public-site`; +generated files are never committed. The preview server is local only. + +The final visual direction is **Contour + Blueprint**. The comparison page and +temporary theme selector have been removed. + +The marketing homepage embeds the live **From idea to architecture** story +immediately after its introduction. Its "See it in action" link jumps to the +demo, which embeds the generated `viewer.html` directly in its native presentation +mode. Only the diagram, title, and viewer controls appear: no storybook sidebar +or outer details wrapper. Focus, export, Blueprint theme ownership, and +expand/restore remain live. "Open full storybook" supplies source details and +module navigation; the separate Demo page keeps the full shell unchanged. +It is not a screenshot or a separately authored copy. + +`SITE_BASE_PATH=/` builds for a later custom domain. The default is +`/topo-code/`. Build-time path validation rejects traversal and malformed paths. +The website test suite exercises both deployment shapes. + +```sh +corepack yarn website:test +``` + +If another preview owns port 4188, leave it running and use +`WEBSITE_TEST_PORT=4289 corepack yarn website:test` with a free port. The test +server is always separate; the suite never reuses an existing preview. + +## Content ownership + +- Marketing: `website/build.mjs`. +- Public docs: a curated set of maintained `docs/*.md` guides, with primary navigation. Other + repository-relative links resolve to GitHub when they are not published pages. +- Roadmap: `website/roadmap.json`, curated Now / Next / Later. This is a rough + outline, not the entire issue tracker or a delivery-date promise. +- Demo configuration: `website/demo/.topo/config.json`. +- Owner-selected theme: Blueprint in `website/themes.mjs`. Retired browser theme + preferences no longer affect the site. +- Owner-selected mark: Contour in `website/brand.mjs`. The header and generated + favicon share the same contour geometry. + +Documentation is rendered directly from its maintained source, not copied into +a second documentation tree. Public instructions describe the released product; +development and release documents retain their separately labeled procedures. + +## Curated source-backed demo + +Each build validates the eight curated stories against the working source and +requires their story/evidence files to be committed. It clones that exact local +revision into a temporary repository, retains the real origin, applies the demo +catalogue configuration, then runs the actual `topo init` and `topo bundle`. +The emitted bundle is copied unchanged, including notices and evidence receipts. +No scanner or model is invoked. A local unpushed revision has local evidence; +its GitHub source links become available only after that revision is published. + +`stories/public/internal-modules.topo.json` covers the thirteen private runtime +modules; build-only `@topo/eslint-config` remains in the companion context, not +the primary map. +Its twelve visible arrows are a selected dependency spine; each node's narrative +contains all declared incoming/outgoing internal dependencies (31 declarations). +`dependency-context.topo.json` groups internal consumers and nineteen direct +external dependency names into five roles, preserving dependency/dev/peer/optional +kinds and requested versions in details. Neither map claims runtime calls or a +transitive dependency inventory. Stable node IDs are reserved for future curated +drilldowns; only real cross-story links are emitted. + +The internal map's LENS groups modules into command orchestration, source +analysis, contracts/evidence, graph shaping, rendering/view data, and supplemental +evidence. These are authored responsibilities, not inferred frontend/backend +types. Comparing two roles highlights only direct cross-role arrows drawn in +this deliberately sparse map; the full declaration lists remain in node details. + +`cli-surface.topo.json` and `diagram-core-surface.topo.json` are child boundary +views, not implementation walkthroughs. They show the command/package entry +points, exported modules/functions/interfaces, and selected declared references. +CLI's command binary is distinct from its root barrel exports. Only the +renderer root's actual exports are shown, not every exported symbol in its +source tree. These remain private workspace interfaces, not a stable public SDK. + +Explicit node `drilldown` targets connect the module map to both children and +the CLI's renderer reference to diagram-core. A child `parent` declaration +provides a return link even after direct opening. Source evidence and other +related-story links remain available; published targets are validated. + +`story-to-screen.topo.json` now shows **From idea to architecture** as a native +sequence: you ask the agent, the CLI supplies deterministic scan evidence, the +agent uses the scan results to build a diagram, hands it to you for review, and +the cycle repeats. Validation/rendering round-trips are intentionally omitted +from this overview. Its outcome is understanding code at a glance rather than reading +files one by one. The repository lifeline makes source reads and authored stories +explicit; routine Git procedure is omitted from this product explanation. +This is the documented collaboration workflow, not a call trace of one process. +Scan never invokes the model; agent interpretation does not require the separate +`topo enrich` command. Operational prerequisites remain in the usage guides. + +Three algorithm sequences add implementation-level explanations without inventing +services or runtime telemetry: + +- `algorithm-evidence-extraction`: TypeScript/JavaScript scan, compiler resolution, + deterministic graph construction, and the semantic pass. Missing assignments + remain unassigned; no architecture is invented. +- `algorithm-anchor-resolution`: the CLI's captured-source path through exact + anchor resolution and freshness checks. Optional digests, first-name + TypeScript AST lookup, exact patterns, and refusal conditions stay explicit. +- `algorithm-graph-projection`: reusable indexed projection and directed edge + aggregation with hidden-edge accounting. Tarjan cycle groups are prepared + upstream, not recalculated for every view. This is distinct from rendering, + Repository page generation, and the manually authored module map. + +The scanner, story, and graph boxes drill into these sequences. Each has a +canonical return to its module, complete source anchors, and per-message +rationale. Lifelines denote local code/API/data boundaries, not new services. +Each starts with a named logical initiator and its goal: `@topo/languages` +requests code evidence, the CLI story validator checks draft evidence, and the +graph layout session requests a visible graph before placing nodes. Avoid generic +"Caller" lifelines that conceal why the algorithm is being invoked. + +`catalogue.storyIds` selects exactly these eight maps. Existing development stories +and examples are preserved but excluded from the demo. Hash-bound evidence fails +on source drift; it must be reassessed, not silently regenerated during builds. + +The website palette applies a presentation-only stylesheet to the +same-origin embedded storybook shell. It never rewrites generated bundle files or +renderer receipts. The embedded Home uses Blueprint rather than a competing +dark/light button; standalone Home +retains its native dark/light control. Broader renderer palette support is not +implied by this shell styling. + +## Background motion + +The contour artwork is original and procedural, inspired by the owner's +topographic references rather than copied image or shader assets: + +- +- +- + +Keep it subordinate to content, palette-aware, pausable, and static for +`prefers-reduced-motion`. Documentation uses a quieter static background. +The original WebGL field changes slowly at up to 24 frames per second, with +drawing resolution capped at 800,000 pixels. Hidden tabs stop animating. +Graphics unavailability or context loss displays the prebuilt SVG fallback +and reports a browser warning instead of breaking the page. + +## GitHub Pages + +`.github/workflows/website.yml` builds and checks on pull requests, pushes to main, +and manual dispatch. Only a successful main-branch push or dispatch can deploy. +Deployments use GitHub's Pages artifact and OIDC flow; PRs have read-only contents +permissions and never deploy. + +Enable **Settings → Pages → Source → GitHub Actions** once, then allow the +`github-pages` environment to deploy from main. The workflow uses +`actions/configure-pages` to discover the actual base path, supporting project +Pages and later custom-domain deployment. DNS/domain purchase is separate. +No additional visual approval job is inserted. + +CI checks rendered local links and fragments, Blueprint styling, mobile layout, +keyboard access, accessibility, motion preferences, source freshness, dependency +coverage, and module-to-context/return navigation. +A website workflow in a branch is not a published website; deployment requires +integration into main and Pages configuration. diff --git a/docs/rust-tauri.md b/docs/rust-tauri.md index b2ace6f..9d89903 100644 --- a/docs/rust-tauri.md +++ b/docs/rust-tauri.md @@ -1,9 +1,8 @@ # Rust, Tauri and technical stories This is supported **Topocode 0.2.0** behavior of normal `topo` commands, -not an experiment executable. Node 22 and 24 are supported. After publication, -install with `npm install --save-dev @jdylanmc/topo-code@0.2.0`; release -preparation alone is not a registry-availability claim. +not an experiment executable. Node 22 and 24 are supported. +Install the published package with `npm install --save-dev @jdylanmc/topo-code@0.2.0`. The installed package includes this document, the story JSON Schema and `examples/rust-tauri/`; no development checkout or previous agent session is required. diff --git a/docs/story-catalogue.md b/docs/story-catalogue.md index 3d02dff..abc38ed 100644 --- a/docs/story-catalogue.md +++ b/docs/story-catalogue.md @@ -55,6 +55,15 @@ retain their independent data contracts. ## Configuration +For a curated publication, `catalogue.storyIds` selects an explicit subset of +committed stories. Omit it to retain the complete inventory; `[]` deliberately +publishes no stories. Unknown IDs and duplicates fail rather than silently +dropping a requested map. Source validation/rendering applies to selected +stories, and cross-story navigation includes only the published set. This is +publication selection, not deletion of the repository's other stories. +`storyIds` is an unreleased repository-build option; npm 0.2.0 still publishes +the complete committed inventory. + Add only desired presentation and authored-category overrides to `.topo/config.json`: @@ -67,6 +76,7 @@ Add only desired presentation and authored-category overrides to "title": "System tours", "description": "Choose a guided path.", "accentColor": "#ff5500", + "storyIds": ["checkout"], "categoryOrder": ["Critical paths", "Operations"], "storyCategories": { "checkout": "Critical paths" diff --git a/docs/story-preview.md b/docs/story-preview.md index 24f3846..e5f6568 100644 --- a/docs/story-preview.md +++ b/docs/story-preview.md @@ -8,6 +8,93 @@ is matched within that symbol; without a symbol, it is matched within the explicit file. Source line ranges and excerpts are resolved from the current working tree at preview time and are never stored in the authored document. +Architecture sections may include a short `summary` caption (for example, +`"Config and publication"`). It appears beneath the node title instead of the +primary source filename. The full `body` narrative and source anchors remain +available in the evidence panel. Other diagram families do not accept this +caption field. +Explicit summaries retain their compact caption typography. Without a summary, +the source-symbol or filename caption keeps the larger source-reference type; +adding summaries does not reduce the legibility of existing source stories. +This caption is an unreleased repository-build capability, not part of the +published npm 0.2.0 story contract. + +Architecture and Sequence sections can also author `semanticRole`, a lowercase hyphenated +slug such as `"source-analysis"`. The native LENS control groups those explicit +roles and compares only arrows actually drawn in the story. It does not infer +runtime traffic, transitive impact, or omitted dependencies. Missing roles are +neutral `"component"` or `"participant"` entries, never a frontend/backend guess based on position. +This is also an unreleased repository-build capability. + +Topocode adapts the emitted viewer's documented `data-node-kind` metadata before +runtime initialization, preserving geometry and the pinned renderer files. +Their receipts identify `topocode-story-semantics-v2` and distinguish +native output hashes from adapted output hashes. Active lens selection remains +viewer-only; the authored semantic roles are durable diagram metadata. + +## Sequence spacing + +Agents can request wider participant columns through authored data: + +```json +{ + "diagramFamily": "sequence", + "sequenceLayout": { "minimumParticipantGap": 220 } +} +``` + +The gap is a minimum center-to-center distance in SVG units (integer, at least +108). Topocode expands the sequence viewBox and spreads its columns; it does not +stretch text or add zoom. Omission preserves existing automatic spacing. +Readability checks still reject layouts that cannot meet the supported text +floor. This is an unreleased repository-build option, not npm 0.2.0 behavior. + +## Explicit module drilldowns + +An authored section can declare `"drilldown": { "storyId": "cli-surface" }`. +Clicking that node opens the child story's overview; add `nodeId` only when a +particular destination node should be focused. This explicit destination wins +over automatically discovered shared-evidence links. Other related stories and +source evidence remain available in details. +The sidebar docks only when enough diagram reading width is available. Opening +details reserves space below the viewer rather than covering diagram titles. +The evidence pane scrolls independently, and navigation controls remain +keyboard-accessible and unobscured; non-Sequence focus still opens evidence automatically. + +A child can declare `"parent": { "storyId": "internal-modules", "nodeId": "cli" }`. +The storybook displays a visible return link even when the child is opened +directly. Navigation from another story takes precedence over this canonical +parent, so nested drilldowns return to the actual caller. Returning or reloading +a focused parent does not automatically drill in again. +The URL carries a validated stack of caller story IDs and optional authored node +IDs across nested returns and reloads. Legacy `from` / `fromFocus` links still +work; unknown story/node targets are ignored with a browser warning rather than +used as redirect URLs. +Sequence participant focus keeps the native details presentation; opening the +storybook source panel remains explicit. + +Targets must exist in the selected catalogue, target nodes must exist, and parent +cycles are rejected before rendering. Direct hosted `viewer.html` pages can enter +their child storybook routes; a downloaded isolated HTML file does not pretend +to contain other diagrams. These are unreleased repository-build capabilities, +not options in the published npm 0.2.0 schema. + +Section IDs remain renderer-neutral, including IDs such as `1-start`, +`src/api.ts`, or Unicode text. Wrapper focus URLs and drilldown `nodeId` values +use authored IDs. `@topo/diagram-core` exposes `storyNodeIds(document, renderer?)` +as authored/native ID pairs for integrations: Archify may use a stable component +hash, while Graphviz retains the authored ID. Native metadata, edge endpoints, +and exported geometry keep their renderer IDs; activation maps back to the +authored section. Direct viewers also accept authored `#focus=` fragments. + +Native Architecture cards show at most three compact source links, matching the +pinned renderer's schema. Topocode still validates every section anchor and +retains all of them in the story evidence panel and `evidence.json`; grouped +nodes do not discard source evidence to fit the renderer. +The integrated Architecture and Sequence viewers omit the redundant native node-index rail: +the surrounding story shell already supplies node navigation and full evidence. +The diagram, interactive node controls, search, focus, and exports remain intact. + The optional `diagramFamily` selects `architecture`, `workflow`, `sequence`, `dataflow`, or `lifecycle`; omission retains the legacy Architecture behavior. Sequence and Dataflow connections require a nonempty `label` because their diff --git a/package.json b/package.json index 3c9db85..123a0d6 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,8 @@ "tools/eslint-config" ], "scripts": { + "website:build": "node website/build.mjs", + "website:test": "node --test website/build.test.mjs && yarn workspace @topo/site exec playwright test --config ../../website/playwright.config.mjs", "build": "node scripts/run-workspaces.mjs build && node scripts/dependency-notices.mjs --site", "check": "yarn lint && yarn typecheck && yarn build && yarn test && yarn licenses:check", "lint": "eslint . --max-warnings 0", @@ -25,9 +27,12 @@ "topo": "node packages/cli/dist/main.js" }, "devDependencies": { + "@axe-core/playwright": "^4.10.2", "@topo/eslint-config": "workspace:*", "@types/node": "^22", "eslint": "^9.39.5", + "marked": "^16.4.1", + "playwright-core": "^1.55.0", "typescript": "^7.0.2", "vite": "8.2.2", "vitest": "^5.0.0" diff --git a/packages/cli/src/catalogue.test.ts b/packages/cli/src/catalogue.test.ts index 865eee8..5baeacf 100644 --- a/packages/cli/src/catalogue.test.ts +++ b/packages/cli/src/catalogue.test.ts @@ -11,7 +11,7 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeAll, describe, expect, it } from "vitest"; import { initializeWorkspace, loadConfig } from "@topo/workspace"; import { buildCatalogue, @@ -94,8 +94,93 @@ afterEach(async () => { }); describe("generated catalogue", () => { + let repositoryStories: Awaited>; + // Render the real committed catalogue once; assertions retain their 5s budget. + beforeAll(async () => { + repositoryStories = await buildCatalogueStories(repositoryRoot); + }, 60_000); + + it("renders every committed story through its real renderer", () => { + expect(repositoryStories.length).toBeGreaterThan(0); + for (const story of repositoryStories) { + expect(story.contents, story.document.id).toContain(" { + const root = await repository(); + await addStory(root, "stories/overview.topo.json", "overview", "Overview"); + await addStory(root, "stories/details.topo.json", "details", "Details"); + const overviewPath = join(root, "stories/overview.topo.json"); + const detailPath = join(root, "stories/details.topo.json"); + const overview = JSON.parse(await readFile(overviewPath, "utf8")); + const detail = JSON.parse(await readFile(detailPath, "utf8")); + overview.sections[0].drilldown = { storyId: "details" }; + detail.parent = { storyId: "overview", nodeId: "section" }; + const save = async () => { + await writeFile(overviewPath, JSON.stringify(overview)); + await writeFile(detailPath, JSON.stringify(detail)); + await commit(root); + }; + const renderer = { + async render() { + return { kind: "html" as const, mediaType: "text/html" as const, contents: "", renderer: { name: "fixture", pin: "1" } }; + }, + }; + await save(); + const catalogue = await buildCatalogue(root, renderer); + await writeBuiltCatalogue(root, catalogue, undefined); + const rendered = await readFile(join(root, ".topo/cache/site/stories/overview/index.html"), "utf8"); + expect(rendered).toContain("data-drilldown"); + expect(rendered).toContain('../details/?from=overview&fromFocus=section'); + expect(await readFile(join(root, ".topo/cache/site/stories/details/index.html"), "utf8")) + .toContain('data-parent-story="overview" data-parent-node="section"'); + overview.sections[0].drilldown = { storyId: "missing" }; + await save(); + await expect(buildCatalogue(root, renderer)).rejects.toThrow("not in the selected catalogue"); + overview.sections[0].drilldown = { storyId: "details", nodeId: "missing" }; + await save(); + await expect(buildCatalogue(root, renderer)).rejects.toThrow("unknown target node"); + overview.sections[0].drilldown = { storyId: "details" }; + overview.parent = { storyId: "details", nodeId: "section" }; + await save(); + await expect(buildCatalogue(root, renderer)).rejects.toThrow("cyclic story parents"); + expect(await readFile(join(root, ".topo/cache/site/stories/overview/index.html"), "utf8")).toBe(rendered); + }); + + it("curates an explicit story set and rejects unknown selections", async () => { + const root = await repository(); + await addStory(root, "stories/one.topo.json", "one", "One"); + await addStory(root, "stories/two.topo.json", "two", "Two"); + await commit(root); + const config = await loadConfig(root); + const select = async (storyIds: string[]) => writeFile( + join(root, ".topo/config.json"), + JSON.stringify({ ...config, catalogue: { storyIds } }), + ); + const renderer = { + async render() { + return { kind: "html" as const, mediaType: "text/html" as const, contents: "", renderer: { name: "test", pin: "1" } }; + }, + }; + expect((await buildCatalogueStories(root, renderer)).map(story => story.document.id)).toEqual(["one", "two"]); + await select(["two"]); + expect((await buildCatalogueStories(root, renderer)).map(story => story.document.id)).toEqual(["two"]); + await select([]); + expect(await buildCatalogueStories(root, renderer)).toEqual([]); + await select(["missing"]); + await expect(buildCatalogueStories(root, renderer)).rejects.toThrow("Unknown catalogue storyIds: missing"); + }); + + it("makes the empty Home scroll region keyboard-accessible", () => { + expect(renderCataloguePage([], undefined)).toContain( + '
', + ); + }); + it("keeps Topocode's factual architecture stories source-grounded and current", async () => { - const stories = await buildCatalogueStories(repositoryRoot); + const stories = repositoryStories; const factual = ["topo-architecture", "topo-packages"].map((id) => { const story = stories.find(({ document }) => document.id === id); expect(story, id).toBeDefined(); @@ -117,8 +202,9 @@ describe("generated catalogue", () => { }); it("includes a source-grounded Workflow story for the authoring loop", async () => { - const stories = await buildCatalogueStories(repositoryRoot); + const stories = repositoryStories; const workflow = stories.find(({ document }) => + document.id === "story-authoring-workflow" && document.diagramFamily === "workflow" && document.classification !== "capability-demo" ); @@ -143,7 +229,7 @@ describe("generated catalogue", () => { }); it("includes a source-grounded Lifecycle story for story states", async () => { - const stories = await buildCatalogueStories(repositoryRoot); + const stories = repositoryStories; const lifecycle = stories.find(({ document }) => document.diagramFamily === "lifecycle" && document.classification !== "capability-demo" @@ -168,7 +254,7 @@ describe("generated catalogue", () => { }); it("includes non-source-grounded capability demos for the gallery families", async () => { - const stories = await buildCatalogueStories(repositoryRoot); + const stories = repositoryStories; const demos = stories.filter(({ document }) => document.classification === "capability-demo" ); diff --git a/packages/cli/src/catalogue.ts b/packages/cli/src/catalogue.ts index f2232f0..a05e6f5 100644 --- a/packages/cli/src/catalogue.ts +++ b/packages/cli/src/catalogue.ts @@ -3,11 +3,12 @@ import { execFile } from "node:child_process"; import { readFile, readdir, rm, stat } from "node:fs/promises"; import { resolve } from "node:path"; import { promisify } from "node:util"; -import { CORE_THEME_SCRIPT, renderStory } from "@topo/diagram-core"; +import { CORE_THEME_SCRIPT, renderStory, storyNodeIds } from "@topo/diagram-core"; import { parseStoryDocument, resolveStoryDocument, type StoryDocument, + type StoryTarget, type StoryRenderer, type ResolvedSourceAnchor, type StoryArtifact, @@ -259,18 +260,29 @@ export async function buildCatalogue( ]) ).stdout.trim() === "true"; const paths = await committedStoryPaths(root); - const documents = await Promise.all(paths.map(async (documentPath) => { - await assertUnchanged(root, documentPath); + const selectedIds = (await loadConfig(root)).catalogue?.storyIds; + const candidates = await Promise.all(paths.map(async (documentPath) => { const document = parseStoryDocument( await readCommittedStory(root, documentPath), documentPath, ); + return { document, documentPath }; + })); + if (selectedIds !== undefined) { + const missing = selectedIds.filter((id) => !candidates.some(({ document }) => document.id === id)); + if (missing.length) throw new Error(`Unknown catalogue storyIds: ${missing.join(", ")}`); + } + const documents = await Promise.all(candidates + .filter(({ document }) => selectedIds === undefined || selectedIds.includes(document.id)) + .map(async ({ document, documentPath }) => { + await assertUnchanged(root, documentPath); return { document, documentPath, history: await storyHistory(root, documentPath, historyIncomplete), }; })); + validateStoryTargets(documents.map(({ document }) => document)); const snapshot = await captureSourceSnapshot( root, documents.flatMap(({ document }) => @@ -353,8 +365,36 @@ interface StoryLink { readonly sourceNodeId: string; readonly targetStoryId: string; readonly targetStoryTitle: string; - readonly targetNodeId: string; - readonly targetNodeTitle: string; + readonly targetNodeId?: string; + readonly targetNodeTitle?: string; + readonly primary?: boolean; +} + +function validateStoryTargets(documents: readonly StoryDocument[]): void { + const byId = new Map(); + for (const document of documents) { + if (byId.has(document.id)) throw new Error(`Duplicate story id: ${document.id}`); + byId.set(document.id, document); + } + const check = (source: string, target: StoryTarget) => { + const destination = byId.get(target.storyId); + if (!destination) throw new Error(`${source}: navigation target ${target.storyId} is not in the selected catalogue`); + if (target.storyId === source) throw new Error(`${source}: navigation target must be another story`); + if (target.nodeId !== undefined && !destination.sections.some(section => section.id === target.nodeId)) { + throw new Error(`${source}: unknown target node ${target.storyId}/${target.nodeId}`); + } + }; + for (const document of documents) { + if (document.parent) check(document.id, document.parent); + for (const section of document.sections) if (section.drilldown) check(document.id, section.drilldown); + const ancestors = new Set([document.id]); + let parent = document.parent; + while (parent) { + if (ancestors.has(parent.storyId)) throw new Error(`${document.id}: cyclic story parents`); + ancestors.add(parent.storyId); + parent = byId.get(parent.storyId)?.parent; + } + } } const CAPABILITY_CATEGORY = "Diagram capabilities"; @@ -368,6 +408,35 @@ const STORY_NAVIGATION_SCRIPT = `(() => { const nodeLinks = [...document.querySelectorAll("[data-node-id]")]; const crossLinks = [...document.querySelectorAll("[data-cross-story]")]; const params = new URLSearchParams(window.location.search); + const navigation = JSON.parse(document.querySelector("[data-story-navigation]").textContent); + const nodeIds = new Map(navigation.nodeIds); + const authoredIds = new Map([...nodeIds].map(([authored, native]) => [native, authored])); + const catalogue = new Map(navigation.catalogue.map(story => [story.id, story])); + function validCaller(caller) { + if (!caller || typeof caller !== "object" || Array.isArray(caller)) return false; + const target = catalogue.get(caller.storyId); + return Boolean(target) && Object.keys(caller).every(key => key === "storyId" || key === "nodeId") && + (caller.nodeId === undefined || target.nodeIds.includes(caller.nodeId)); + } + const returnLink = document.querySelector("[data-return]"); + function readCallers() { + if (params.has("callers")) { + try { + const callers = JSON.parse(params.get("callers")); + if (!Array.isArray(callers) || callers.length > 64 || !callers.every(validCaller)) { + throw new Error("Unknown story or focus target"); + } + return callers; + } catch (error) { + console.warn("Ignoring invalid Topocode return context:", error.message); + } + } + const legacy = { storyId: params.get("from"), nodeId: params.get("fromFocus") || undefined }; + if (validCaller(legacy)) return [legacy]; + const parent = { storyId: returnLink?.dataset.parentStory, nodeId: returnLink?.dataset.parentNode || undefined }; + return validCaller(parent) ? [parent] : []; + } + const callers = readCallers(); function showEvidence(focus, edge) { for (const evidence of document.querySelectorAll("[data-section-evidence]")) { @@ -377,7 +446,7 @@ const STORY_NAVIGATION_SCRIPT = `(() => { evidence.hidden = edge !== null ? evidence.dataset.edgeEvidence !== edge : Boolean(focus) && evidence.dataset.edgeFrom !== focus && evidence.dataset.edgeTo !== focus; } - if (edge !== null) document.querySelector(".story-details").open = true; + if (edge !== null || (focus && diagramFamily !== "sequence")) document.querySelector(".story-details").open = true; } function setFocus(nodeId) { @@ -388,7 +457,8 @@ const STORY_NAVIGATION_SCRIPT = `(() => { link.removeAttribute("aria-current"); } } - frame.src = "viewer.html" + (nodeId ? "#focus=" + encodeURIComponent(nodeId) : ""); + const nativeId = nodeIds.get(nodeId) ?? nodeId; + frame.src = "viewer.html" + (nativeId ? "#focus=" + encodeURIComponent(nativeId) : ""); } function rememberFocus(nodeId) { @@ -400,35 +470,56 @@ const STORY_NAVIGATION_SCRIPT = `(() => { setFocus(nodeId); } + let navigating = false; function follow(link) { + if (navigating) return; const sourceNodeId = link.getAttribute("data-source-node"); + const destination = new URL(link.href); + if (sourceNodeId && callers.length >= 64) { + console.error("Topocode drilldown limit reached; return to an earlier story before continuing."); + return; + } + navigating = true; if (sourceNodeId) { const current = new URL(window.location.href); current.searchParams.set("focus", sourceNodeId); - current.searchParams.delete("from"); - current.searchParams.delete("fromFocus"); window.history.replaceState(null, "", current); + destination.searchParams.set("callers", JSON.stringify([...callers, { storyId, nodeId: sourceNodeId }])); } - window.location.assign(link.href); + window.location.assign(destination.href); } + for (const link of nodeLinks) { + const destination = new URL(window.location.href); + destination.searchParams.delete("edge"); + destination.searchParams.set("focus", link.getAttribute("data-node-id")); + link.href = destination.href; + } + for (const link of document.querySelectorAll('[data-edge-evidence] a[href^="?"]')) { + const destination = new URL(window.location.href); + destination.searchParams.delete("focus"); + destination.searchParams.set("edge", new URL(link.href).searchParams.get("edge")); + link.href = destination.href; + } for (const link of crossLinks) { + const destination = new URL(link.href); + destination.searchParams.set("callers", JSON.stringify([...callers, { storyId, nodeId: link.getAttribute("data-source-node") }])); + link.href = destination.href; link.addEventListener("click", (event) => { event.preventDefault(); follow(link); }); } - const returnLink = document.querySelector("[data-return]"); - const from = params.get("from"); - const fromFocus = params.get("fromFocus"); - if (returnLink instanceof HTMLAnchorElement && from && fromFocus) { - const source = document.querySelector('[data-story-id="' + CSS.escape(from) + '"]'); - if (source instanceof HTMLAnchorElement) { - returnLink.hidden = false; - returnLink.textContent = "Return to " + source.textContent; - returnLink.href = "../" + encodeURIComponent(from) + "/?focus=" + encodeURIComponent(fromFocus); - } + if (returnLink instanceof HTMLAnchorElement && callers.length) { + const caller = callers.at(-1); + const destination = new URL("../" + encodeURIComponent(caller.storyId) + "/", location.href); + if (caller.nodeId !== undefined) destination.searchParams.set("focus", caller.nodeId); + destination.searchParams.set("callers", JSON.stringify(callers.slice(0, -1))); + returnLink.hidden = false; + returnLink.textContent = "Return to " + catalogue.get(caller.storyId).title; + returnLink.href = destination.href; + document.querySelector("[data-story-breadcrumb]").hidden = false; } frame.addEventListener("load", () => { @@ -437,7 +528,7 @@ const STORY_NAVIGATION_SCRIPT = `(() => { if (!child || !childDocument) return; const currentParams = new URLSearchParams(window.location.search); showEvidence(currentParams.get("focus") || "", currentParams.get("edge")); - const syncSelectedNode = () => { + const syncSelectedNode = (activatedNodeId) => { const selected = new URLSearchParams(child.location.hash.replace(/^#/, "")); const edge = selected.get("edge"); if (edge !== null && document.querySelector('[data-edge-evidence="' + CSS.escape(edge) + '"]')) { @@ -448,7 +539,7 @@ const STORY_NAVIGATION_SCRIPT = `(() => { showEvidence("", edge); return; } - const focus = selected.get("focus"); + const focus = authoredIds.get(selected.get("focus")); if (!focus) return; const candidates = crossLinks.filter((link) => link.getAttribute("data-source-node") === focus); const current = new URL(window.location.href); @@ -456,12 +547,21 @@ const STORY_NAVIGATION_SCRIPT = `(() => { current.searchParams.set("focus", focus); window.history.replaceState(null, "", current); showEvidence(focus, null); - if (diagramFamily !== "sequence" && candidates.length === 1) { - follow(candidates[0]); + if (authoredIds.get(activatedNodeId) === focus) { + const primary = candidates.find(link => link.hasAttribute("data-drilldown")); + if (primary) follow(primary); + else if (diagramFamily !== "sequence" && candidates.length === 1) follow(candidates[0]); } }; - childDocument.addEventListener("click", () => setTimeout(syncSelectedNode)); - childDocument.addEventListener("keyup", () => setTimeout(syncSelectedNode)); + childDocument.addEventListener("click", event => { + const node = event.target.closest?.("[data-node-id]"); + setTimeout(() => syncSelectedNode(node?.getAttribute("data-node-id"))); + }); + childDocument.addEventListener("keyup", event => { + const node = event.target.closest?.("[data-node-id]"); + const activate = event.key === "Enter" || event.key === " "; + setTimeout(() => syncSelectedNode(activate ? node?.getAttribute("data-node-id") : undefined)); + }); }); setFocus(params.get("focus") || ""); @@ -819,11 +919,21 @@ function storyLinks(stories: readonly CatalogueStory[]): Map(); for (const section of document.sections) { + if (section.drilldown) { + const target = stories.find(story => story.document.id === section.drilldown!.storyId)?.document; + if (!target) throw new Error(`${document.id}: missing drilldown story ${section.drilldown.storyId}`); + const node = target.sections.find(node => node.id === section.drilldown!.nodeId); + if (section.drilldown.nodeId !== undefined && !node) throw new Error(`${document.id}: missing drilldown node ${section.drilldown.nodeId}`); + links.push({ + sourceNodeId: section.id, targetStoryId: target.id, targetStoryTitle: target.title, primary: true, + ...(node ? { targetNodeId: node.id, targetNodeTitle: node.title } : {}), + }); + } for (const anchorId of section.anchorIds) { const anchor = anchors.get(anchorId); if (!anchor) continue; for (const target of destinations.get(anchorKey(anchor)) ?? []) { - if (target.storyId === document.id) continue; + if (target.storyId === document.id || target.storyId === section.drilldown?.storyId) continue; const key = `${section.id}\0${target.storyId}\0${target.nodeId}`; if (seen.has(key)) continue; seen.add(key); @@ -864,7 +974,7 @@ export function renderStoryWrapper( const nodes = story.document.sections.map((section) => { const crossLinks = (linksByNode.get(section.id) ?? []).map((link) => - `Open ${escapeHtml(link.targetStoryTitle)}: ${escapeHtml(link.targetNodeTitle)}`, + `Open ${escapeHtml(link.targetStoryTitle)}${link.targetNodeTitle === undefined ? "" : `: ${escapeHtml(link.targetNodeTitle)}`}`, ).join(""); const evidence = (story.anchors ?? []).filter((anchor) => section.anchorIds.includes(anchor.id)).map((anchor) => `
${escapeHtml(anchor.path)}:${anchor.location.startLine}-${anchor.location.endLine}
${escapeHtml(anchor.excerpt)}
`).join(""); @@ -881,13 +991,21 @@ export function renderStoryWrapper( return ``; }).join(""); return renderShellPage(stories, config, historyIncomplete, story, `\ + +
Story navigation and details

${classificationLabel}

${escapeHtml(story.document.summary)}

-
    ${nodes}
${edges}
`, repository); @@ -1007,7 +1125,12 @@ function renderShellPage( .story-links a[aria-current="page"] { background: #17324d; color: white; box-shadow: inset 3px 0 var(--accent); font-weight: 700; } .catalogue-empty { margin: 0; padding: 1rem 0.65rem; color: #a9b7ca; line-height: 1.5; } .catalogue-footer { grid-row: 6; padding: 0.7rem 0.85rem; border-top: 1px solid #29364a; color: #7f8da1; font-size: 0.75rem; } - .story-main { display: grid; grid-template-rows: minmax(0, 1fr) auto; min-width: 0; min-height: 0; background: #f8fafc; } + .story-main { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; min-width: 0; min-height: 0; background: #f8fafc; } + .story-main > iframe { grid-row: 2; } + .story-main > .story-details { grid-row: 3; } + .story-breadcrumb { grid-row: 1; padding: 0.5rem 0.85rem; border-bottom: 1px solid #29364a; background: #0b1524; font-size: 0.875rem; overflow-wrap: anywhere; } + .story-breadcrumb[hidden] { display: none; } + :root[data-theme="light"] .story-breadcrumb { background: #e6eef7; border-color: #a0b6cc; } .classification { color: #a9b7ca; font-size: 0.9rem; font-weight: 600; } a { color: #7dd3fc; } [data-node-id][aria-current="true"] { color: white; font-weight: bold; } @@ -1018,8 +1141,8 @@ function renderShellPage( .story-context p { margin: 0; } .story-context .classification { flex: 0 0 auto; } .story-context [data-return] { margin-left: auto; } - .story-details ul { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap: 0.5rem; margin: 0; padding: 0 0.75rem 0.75rem; list-style: none; } - .story-details li { display: grid; gap: 0.35rem; padding: 0.65rem; background: #111c2e; border-radius: 0.5rem; } + .story-details ul { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(14rem, 100%), 1fr)); gap: 0.5rem; margin: 0; padding: 0 0.75rem 0.75rem; list-style: none; } + .story-details li { display: grid; align-content: start; min-width: 0; gap: 0.35rem; padding: 0.65rem; background: #111c2e; border-radius: 0.5rem; } .home-main { min-width: 0; min-height: 0; overflow: auto; padding: clamp(1.5rem, 4vw, 4rem); } .home-main > * { max-width: 64rem; } .home-main h1 { margin: 0 0 0.75rem; font-size: clamp(1.7rem, 3vw, 2.5rem); } @@ -1056,11 +1179,13 @@ function renderShellPage( [data-repository-evidence] ul, [data-repository-evidence] ol { display: block; padding-left: 1.25rem; } [data-repository-evidence] li { display: list-item; background: transparent; padding: 0.15rem; } .repository-evidence.story-details { position: static; width: auto; max-height: 35vh; } - @media (max-width: 1099px) { + /* Dock the wider sidebar only when source text retains enough reading width. */ + @media (max-width: 1239px) { [data-topo-shell], [data-navigation-collapsed="true"] { grid-template-columns: 1px minmax(0, 1fr); grid-template-rows: minmax(0, 1fr); } .catalogue-panel, body[data-story-id] .catalogue-panel { position: relative; z-index: 3; display: grid; grid-template-rows: auto auto auto auto minmax(0, 1fr) auto; width: 1px; min-width: 0; padding: 0 0 2.6rem; overflow: visible; border-right: 0; border-bottom: 0; background: transparent; } + body:has(.story-main > .story-details[open]) .catalogue-panel { padding-bottom: calc(20vh + 2.6rem); } .catalogue-panel::before { position: absolute; z-index: -1; inset: 0 auto 0 0; width: 14rem; border-right: 1px solid #29364a; background: #0b1524; box-shadow: 0.5rem 0 1.25rem rgb(0 0 0 / 30%); content: ""; } [data-navigation-collapsed="true"] .catalogue-panel::before { width: 3.5rem; box-shadow: none; } .catalogue-panel > * { width: 14rem; } @@ -1077,9 +1202,10 @@ function renderShellPage( .catalogue-footer { display: block; } [data-navigation-collapsed="true"] .brand-row { width: 3.5rem; border-right: 0; background: #0b1524; } .story-main, .home-main, .repository-main { grid-column: 2; grid-row: 1; } + .story-breadcrumb { padding-left: calc(14rem + 0.85rem); } + [data-navigation-collapsed="true"] .story-breadcrumb { padding-left: calc(3.5rem + 0.85rem); } .home-main { padding-left: 4.5rem; } .repository-toolbar { padding-left: 3.75rem; } - .story-main { grid-template-rows: minmax(0, 1fr); } .story-details { position: fixed; z-index: 4; top: auto; right: auto; bottom: 0; left: 0; width: 14rem; max-height: min(70vh, 36rem); border: 1px solid #29364a; border-radius: 0 0.5rem 0 0; box-shadow: 0 0.4rem 1.2rem rgb(0 0 0 / 35%); } .story-details summary { padding: 0.35rem 0.65rem; } .story-details summary { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } @@ -1089,7 +1215,7 @@ function renderShellPage( [data-navigation-collapsed="true"] .story-details:not([open]) summary { overflow: hidden; font-size: 0; text-align: center; } [data-navigation-collapsed="true"] .story-details:not([open]) summary::after { content: "…"; font-size: 1rem; } } - @media (min-width: 1100px) and (max-width: 1280px) and (max-height: 760px) { + @media (min-width: 1240px) and (max-width: 1280px) and (max-height: 760px) { [data-topo-shell] { grid-template-columns: 14rem minmax(0, 1fr); grid-template-rows: minmax(0, 1fr); } [data-navigation-collapsed="true"] { grid-template-columns: 3.5rem minmax(0, 1fr); grid-template-rows: minmax(0, 1fr); } .catalogue-panel, body[data-story-id] .catalogue-panel { display: grid; grid-template-rows: auto auto auto auto minmax(0, 1fr) auto; padding-right: 0; padding-bottom: 2.6rem; border-right: 1px solid #29364a; border-bottom: 0; } @@ -1108,7 +1234,6 @@ function renderShellPage( .catalogue-footer { display: block; } [data-navigation-collapsed="true"] .brand-row { flex-basis: auto; border-right: 0; } .story-main, .home-main, .repository-main { grid-column: 2; grid-row: 1; } - .story-main { grid-template-rows: minmax(0, 1fr); } .story-details { position: fixed; z-index: 4; top: auto; right: auto; bottom: 0; left: 0; width: 14rem; max-height: min(70vh, 36rem); border: 1px solid #29364a; border-radius: 0 0.5rem 0 0; box-shadow: 0 0.4rem 1.2rem rgb(0 0 0 / 35%); } .story-details summary { padding: 0.35rem 0.65rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .story-context { display: grid; } @@ -1117,6 +1242,8 @@ function renderShellPage( [data-navigation-collapsed="true"] .story-details:not([open]) summary { overflow: hidden; font-size: 0; text-align: center; } [data-navigation-collapsed="true"] .story-details:not([open]) summary::after { content: "…"; font-size: 1rem; } } + .story-main > .story-details[open] { position: static; width: auto; max-height: 20vh; border-radius: 0; box-shadow: none; } + .story-main:has(> .story-breadcrumb:not([hidden])):has(> .story-details[open]) { grid-template-rows: auto minmax(0, 5fr) minmax(0, 1fr); } :root[data-theme="light"] body { background: #f4f7fb; color: #183647; } :root[data-theme="light"] .catalogue-panel, :root[data-theme="light"] .catalogue-panel::before, @@ -1135,6 +1262,7 @@ function renderShellPage( :root[data-theme="light"] [data-repository-page], :root[data-theme="light"] [data-repository-status] { color: #37536c; } [data-section-evidence] { font-size: 0.875rem; line-height: 1.5; } + [data-section-evidence] > p { white-space: pre-line; } .story-details figure { margin: 0.5rem 0; overflow-wrap: anywhere; } .story-details pre { white-space: pre-wrap; overflow-wrap: anywhere; max-width: 78ch; font-size: 12px; } @@ -1213,7 +1341,7 @@ export function renderCataloguePage( config, historyIncomplete, undefined, - `
+ `

${escapeHtml(title)}

${escapeHtml(description)}

Diagram inventory

diff --git a/packages/cli/src/dataflow-story.test.ts b/packages/cli/src/dataflow-story.test.ts index b290dd2..15d1917 100644 --- a/packages/cli/src/dataflow-story.test.ts +++ b/packages/cli/src/dataflow-story.test.ts @@ -10,7 +10,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeAll, describe, expect, it } from "vitest"; import { initializeWorkspace, writeGenerated } from "@topo/workspace"; import { buildCatalogueStories } from "./catalogue.js"; import { previewStory } from "./story-preview.js"; @@ -141,8 +141,13 @@ async function flowLabelFixture( } describe("Dataflow story catalogue", () => { + let stories: Awaited>; + // One whole-catalogue integration render, outside individual assertion budgets. + beforeAll(async () => { + stories = await buildCatalogueStories(repositoryRoot); + }, 60_000); + it("renders the source-grounded repository pipeline with native Dataflow stages", async () => { - const stories = await buildCatalogueStories(repositoryRoot); const story = stories.find(({ document }) => document.id === "repository-dataflow" ); @@ -201,7 +206,6 @@ describe("Dataflow story catalogue", () => { }); it("renders a separate non-source-grounded native Dataflow capability demo", async () => { - const stories = await buildCatalogueStories(repositoryRoot); const story = stories.find(({ document }) => document.id === "dataflow-capability" ); diff --git a/packages/cli/src/repository-ui.ts b/packages/cli/src/repository-ui.ts index b68254a..1af5f8a 100644 --- a/packages/cli/src/repository-ui.ts +++ b/packages/cli/src/repository-ui.ts @@ -53,6 +53,7 @@ export const REPOSITORY_SCRIPT = `(() => { return; } const nodes = new Map(index.nodes.map((node) => [node.id, node])); + const diagramSelector = 'svg[data-topo-family="architecture"][data-diagram-type="architecture"][role="group"]'; let scope; let page; let selected; @@ -106,7 +107,7 @@ export const REPOSITORY_SCRIPT = `(() => { node.removeAttribute("aria-current"); } if (!selected) return; - const node = document.querySelector('svg[role="img"] [data-node-id="' + selected.id + '"]'); + const node = document.querySelector(diagramSelector + ' [data-node-id="' + selected.id + '"]'); if (node) { node.setAttribute("data-repository-selected", ""); node.setAttribute("data-focus-selected", ""); @@ -266,7 +267,7 @@ export const REPOSITORY_SCRIPT = `(() => { try { const document = frame.contentDocument; if (!document) throw new Error("The Archify document is unavailable."); - if (!document.querySelector('svg[role="img"]')) { + if (!document.querySelector(diagramSelector)) { throw new Error("The generated Archify artifact is missing; run topo scan again."); } error.hidden = true; diff --git a/packages/cli/src/sequence-capability.test.ts b/packages/cli/src/sequence-capability.test.ts index 650edfd..91f1ada 100644 --- a/packages/cli/src/sequence-capability.test.ts +++ b/packages/cli/src/sequence-capability.test.ts @@ -1,12 +1,16 @@ import { fileURLToPath } from "node:url"; -import { describe, expect, it } from "vitest"; +import { beforeAll, describe, expect, it } from "vitest"; import { buildCatalogueStories } from "./catalogue.js"; const repositoryRoot = fileURLToPath(new URL("../../../", import.meta.url)); describe("Sequence capability demo", () => { + let stories: Awaited>; + beforeAll(async () => { + stories = await buildCatalogueStories(repositoryRoot); + }, 60_000); + it("renders a visibly separate native return message", async () => { - const stories = await buildCatalogueStories(repositoryRoot); const story = stories.find(({ document }) => document.id === "sequence-capability" ); diff --git a/packages/cli/src/sequence-story.test.ts b/packages/cli/src/sequence-story.test.ts index 8430aa9..aa68aa7 100644 --- a/packages/cli/src/sequence-story.test.ts +++ b/packages/cli/src/sequence-story.test.ts @@ -1,12 +1,17 @@ import { readFile } from "node:fs/promises"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; -import { describe, expect, it } from "vitest"; +import { beforeAll, describe, expect, it } from "vitest"; import { buildCatalogueStories } from "./catalogue.js"; const repositoryRoot = fileURLToPath(new URL("../../../", import.meta.url)); describe("source-grounded Sequence story", () => { + let stories: Awaited>; + beforeAll(async () => { + stories = await buildCatalogueStories(repositoryRoot); + }, 60_000); + it("renders actual preview orchestrator calls instead of phase-to-phase calls", async () => { const [mainSource, catalogueSource] = await Promise.all([ readFile(join(repositoryRoot, "packages/cli/src/main.ts"), "utf8"), @@ -25,7 +30,6 @@ describe("source-grounded Sequence story", () => { expect(catalogueSource, callsite).toContain(callsite); } - const stories = await buildCatalogueStories(repositoryRoot); const story = stories.find(({ document }) => document.id === "story-preview-sequence" ); diff --git a/packages/cli/src/topo-packages-story.test.ts b/packages/cli/src/topo-packages-story.test.ts index 9c92097..0251d39 100644 --- a/packages/cli/src/topo-packages-story.test.ts +++ b/packages/cli/src/topo-packages-story.test.ts @@ -14,7 +14,7 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeAll, describe, expect, it } from "vitest"; import { buildCatalogueStories } from "./catalogue.js"; const repositoryRoot = fileURLToPath(new URL("../../../", import.meta.url)); @@ -102,6 +102,11 @@ afterEach(async () => { }); describe("Topocode package story", () => { + let stories: Awaited>; + beforeAll(async () => { + stories = await buildCatalogueStories(repositoryRoot); + }, 60_000); + it("validates an exact file-scoped manifest pattern without a symbol", async () => { const root = await mkdtemp(join(tmpdir(), "topo-file-pattern-")); directories.push(root); @@ -166,7 +171,6 @@ describe("Topocode package story", () => { manifests.set(manifest.name, { path, manifest }); } - const stories = await buildCatalogueStories(repositoryRoot); const packageStory = stories.find(({ document }) => document.id === "topo-packages" ); diff --git a/packages/diagram-core/src/graphviz.ts b/packages/diagram-core/src/graphviz.ts index fd09186..6703ada 100644 --- a/packages/diagram-core/src/graphviz.ts +++ b/packages/diagram-core/src/graphviz.ts @@ -105,7 +105,7 @@ document.getElementById("export-svg").addEventListener("click",()=>{ const link=document.createElement("a");link.href=url;link.download="topocode-flow.svg";link.click();setTimeout(()=>URL.revokeObjectURL(url),1000); }); `; - const contents = adaptViewerTheme(native); + const contents = adaptViewerTheme(native, document); const validation = { engine: "Graphviz", engineVersion: viz.graphvizVersion, package: "@viz-js/viz@3.30.0", checks: ["dot layout succeeded without diagnostics", "every authored node retained", "every authored edge retained", "finite positive layout bounds", "nodes contained within layout", "node boxes do not overlap"], bounds, diff --git a/packages/diagram-core/src/index.ts b/packages/diagram-core/src/index.ts index 36e4e47..49f427f 100644 --- a/packages/diagram-core/src/index.ts +++ b/packages/diagram-core/src/index.ts @@ -13,12 +13,15 @@ import type { ResolvedStoryDocument, StoryArtifact, StoryConnection, + StoryDocument, } from "@topo/story"; import { cliPath as archifyCli } from "@jdylanmc/topo-archify"; import { verifyArchifyIntegrity } from "./integrity.js"; import { adaptViewerTheme, outputHash } from "./theme.js"; import { renderGraphviz } from "./graphviz.js"; +import { componentId } from "./node-ids.js"; export { CORE_THEME_SCRIPT } from "./theme.js"; +export { storyNodeIds } from "./node-ids.js"; export { verifyArchifyIntegrity, @@ -264,12 +267,6 @@ function stableId(prefix: string, value: string): string { return `${prefix}_${hash}`; } -function componentId(sectionId: string): string { - return /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(sectionId) - ? sectionId - : stableId("component", sectionId); -} - // Match the pinned renderer's text-unit model before deciding whether prose // can remain inline at the final readable font size. const fullwidthCharacter = @@ -329,7 +326,7 @@ function sequenceLayout(story: ResolvedStoryDocument): SequenceLayout { sequenceReadability.sideMargin * 2, sequenceReadability.sideMargin + requiredParticipantWidth + - (participantCount - 1) * sequenceReadability.minimumParticipantGap + + (participantCount - 1) * (story.document.sequenceLayout?.minimumParticipantGap ?? sequenceReadability.minimumParticipantGap) + sequenceReadability.rightMargin, ); const messageYs = story.document.connections.map((_, index) => @@ -514,9 +511,9 @@ function archifySpec( const primary = sectionAnchors[0]; // Short, legible sublabel (a code reference), never the full narrative body: // Archify enforces a per-component minimum-legibility width. - const sublabel = primary === undefined || !nativeSourceEvidence + const sublabel = section.summary ?? (primary === undefined || !nativeSourceEvidence ? "" - : primary.symbol ?? primary.path.split("/").pop() ?? primary.path; + : primary.symbol ?? primary.path.split("/").pop() ?? primary.path); const width = architectureComponentWidth(section.title, sublabel, !nativeSourceEvidence); return { section, sectionAnchors, sublabel, width }; }); @@ -564,10 +561,12 @@ function archifySpec( const toIndex = sectionIndexById.get(connection.to)!; const from = cellOf(fromIndex); const to = cellOf(toIndex); + const neighbouringDiagonal = Math.abs(to.row - from.row) === 1 && + Math.abs(to.column - from.column) === 1; if ( Math.abs(to.row - from.row) + Math.abs(to.column - from.column) !== - 1 + 1 && !neighbouringDiagonal ) { detourLaneByConnection.set(connectionIndex, detourLaneCount); detourLaneCount += 1; @@ -645,9 +644,7 @@ function archifySpec( const { row, column } = cellOf(index); return { id: componentIds.get(section.id)!, - type: nativeSourceEvidence && index === sections.length - 1 - ? "frontend" as const - : "backend" as const, + type: "backend" as const, label: section.title, sublabel, pos: [ @@ -658,7 +655,9 @@ function archifySpec( ...(sectionAnchors.length === 0 || !nativeSourceEvidence ? {} : { - sources: sectionAnchors.map((anchor) => ({ + // Native cards allow three links; the story wrapper retains every + // validated anchor and its excerpt in the full evidence panel. + sources: sectionAnchors.slice(0, 3).map((anchor) => ({ path: anchor.path, line: anchor.location.startLine, end_line: anchor.location.endLine, @@ -761,8 +760,8 @@ function archifySpec( }), }, components, - // Adjacent grid cells route directly; non-adjacent endpoints detour through - // a dedicated lane below the grid so an edge never crosses another node. + // Neighbouring cells use native routing and port spreading. Distant + // endpoints retain outside lanes to avoid unrelated nodes. connections: story.document.connections.map((connection, index) => { const fromIndex = sections.findIndex((s) => s.id === connection.from); const toIndex = sections.findIndex((s) => s.id === connection.to); @@ -780,6 +779,9 @@ function archifySpec( ...(connection.label === undefined ? {} : { label: connection.label }), }; const adjacent = Math.abs(deltaRow) + Math.abs(deltaColumn) === 1; + if (Math.abs(deltaRow) === 1 && Math.abs(deltaColumn) === 1) { + return base; + } if (adjacent) { const vertical = deltaRow !== 0; const horizontalLabelBelow = deltaColumn > 0; @@ -979,11 +981,9 @@ function sequenceSpec( column_fit: "spread", viewBox: layout.viewBox, }, - participants: story.document.sections.map((section, index) => ({ + participants: story.document.sections.map((section) => ({ id: participantIds.get(section.id)!, - type: index === story.document.sections.length - 1 - ? "frontend" - : "backend", + type: "backend", label: section.title, sublabel: layout.inlineBodyIds.has(section.id) ? section.body : "", })), @@ -1390,6 +1390,35 @@ function serializeRendererInput(spec: { readonly meta: object }): string { }, null, 2)}\n`; } +function adaptStorySemantics(contents: string, document: StoryDocument): string { + const fallback = document.diagramFamily === "sequence" ? "participant" : "component"; + const roles = new Map(document.sections.map(section => [componentId(section.id), section.semanticRole ?? fallback])); + const summaries = new Set(document.sections + .filter(section => section.summary !== undefined) + .map(section => componentId(section.id))); + const seen = new Set(); + const adapted = contents.replace(/]*\bdata-node-id="([^"]+)"[^>]*>/g, (tag, id: string) => { + const role = roles.get(id); + if (role === undefined) return tag; + if (!/^(?!constructor$)[a-z][a-z0-9-]{0,63}$/.test(role)) throw new Error(`Invalid semantic role for ${id}`); + if (!/\bdata-node-kind="[^"]*"/.test(tag)) throw new Error(`Story node ${id} has no semantic metadata`); + seen.add(id); + const annotated = tag.replace(/\bdata-node-kind="[^"]*"/, `data-node-kind="${role}"`); + return summaries.has(id) ? annotated.replace("]*id="semantic-lens-title"[^>]*>)[^<]*(<\/strong>)/, + "$1Compare responsibilities$2"], + [/(]*class="semantic-lens-instruction"[^>]*>)[^<]*(<\/p>)/, + "$1Choose up to two authored roles. Highlight only the relationships drawn in this story: not runtime traffic, transitive impact, or the complete dependency graph. One role includes connected peers; two compare direct cross-role arrows.$2"], + ]; + return replacements.reduce((html, [pattern, replacement]) => { + if (!pattern.test(html)) throw new Error("Pinned semantic lens presentation seam is missing"); + return html.replace(pattern, replacement); + }, adapted); +} + function improveStoryReadability( contents: string, family: @@ -1399,19 +1428,34 @@ function improveStoryReadability( | "dataflow" | "lifecycle", dataflowLayout?: DataflowLayout, - sequenceFontSize?: number, + sequence?: SequenceLayout, ): string { const headEnd = ""; if (!contents.includes(headEnd)) { throw new Error(`Archify ${family} output is missing its closing head element`); } + if (family === "sequence" && sequence === undefined) throw new Error("Missing sequence readability layout"); + const sequenceRatio = sequence === undefined ? undefined : sequence.viewBox[0] / sequence.viewBox[1]; + const semanticControls = family === "architecture" || family === "sequence" ? ` +html[data-topo-app] .semantic-lens { width: min(34rem, calc(100% - 24px)); max-height: calc(100% - 16px); overflow: auto; } +#semantic-lens-title { font-size: 1rem; } +#semantic-lens .semantic-lens-instruction, +#semantic-lens .semantic-lens-status, +#semantic-lens .semantic-lens-actions button, +#semantic-lens-kinds .semantic-lens-kind em { font-size: 0.8rem; line-height: 1.5; } +#semantic-lens-kinds .semantic-lens-kind strong { font-size: 0.85rem; line-height: 1.4; white-space: normal; overflow: visible; overflow-wrap: anywhere; text-overflow: clip; }` : ""; const rules = family === "architecture" ? ` svg { max-height: 100vh; } +/* The story shell supplies the node index and full source details. */ +.reader-rail { display: none !important; } svg [data-source-evidence-beacon] { display: none; } svg text[data-node-label], svg text[data-detail="context"], -svg g[data-edge-from] > text { font-size: ${architectureFontSize}px; }` +svg g[data-edge-from] > text { font-size: ${architectureFontSize}px; } +/* Native caption baselines are only 16 units below titles. */ +svg text[data-detail="context"] { transform: translateY(20px); } +svg [data-topo-caption="summary"] text[data-detail="context"] { font-size: 17px; transform: translateY(12px); }` : family === "workflow" ? ` svg text[data-node-label], @@ -1424,8 +1468,19 @@ svg g[data-edge-from] > text { : family === "sequence" ? ` svg { max-height: 100vh; } +.reader-rail { display: none !important; } +@media (min-width: 1400px) and (min-height: 900px) { + html[data-topo-app] .container { + min-width: min(calc(100vw - 64px), ${sequence === undefined ? 0 : sequence.viewBox[0] * sequenceReadability.targetEffectiveFontSize / sequence.fontSize + 50}px); + max-width: min(calc(100vw - 64px), calc((100dvh - 260px) * ${sequenceRatio} + 30px)); + } +} +@media (min-width: 1400px) and (min-height: 900px) and (max-height: 920px) { + html[data-topo-app] .container { max-width: min(calc(100vw - 64px), calc((100dvh - 156px) * ${sequenceRatio} + 32px)); } + html[data-topo-app] .diagram-container { padding-bottom: 56px; } +} svg text { - font-size: ${sequenceFontSize}px; + font-size: ${sequence?.fontSize}px; } .semantic-passport-detail { font-size: 0.875rem; @@ -1447,7 +1502,7 @@ svg g[data-edge-from] > text { font-family: Arial, Helvetica, sans-serif; font-size: ${lifecycleFontSize}px; }`; - const style = ``; const adjustedContents = family === "dataflow" && dataflowLayout ? dataflowLayout.flowLabelWidths.reduce((html, width, index) => { @@ -1504,7 +1559,11 @@ svg g[data-edge-from] > text { return next; }, contents) : contents; - return adjustedContents.replace(headEnd, `${style}\n${headEnd}`); + const accessibleContents = family === "architecture" || family === "sequence" + ? adjustedContents.replace(/]*\brole="img"[^>]*>/, tag => + tag.replace('role="img"', 'role="group"').replace(" + [id, renderer === "graphviz" ? id : componentId(id)] as const); +} diff --git a/packages/diagram-core/src/theme.ts b/packages/diagram-core/src/theme.ts index 67f31ab..de0932b 100644 --- a/packages/diagram-core/src/theme.ts +++ b/packages/diagram-core/src/theme.ts @@ -1,4 +1,6 @@ import { createHash } from "node:crypto"; +import type { StoryDocument, StoryTarget } from "@topo/story"; +import { storyNodeIds } from "./node-ids.js"; // The native renderer's documented ?theme= and data-theme seams remain intact. // One application preference wins over renderer storage and OS media queries. @@ -35,7 +37,12 @@ export const CORE_THEME_SCRIPT = `(() => { if (frame.contentWindow && typeof frame.contentWindow.topoSetTheme === "function") frame.contentWindow.topoSetTheme(theme, false); } } - window.topoSetTheme = apply; + window.topoSetTheme = (theme, persist) => { + if (persist && window.parent !== window && typeof window.parent.topoSetTheme === "function") { + return window.parent.topoSetTheme(theme, persist); + } + apply(theme, persist); + }; function toggle(event) { if (event) { event.preventDefault(); @@ -69,9 +76,54 @@ export const CORE_THEME_SCRIPT = `(() => { }); })();`; -export function adaptViewerTheme(contents: string): string { +export function adaptViewerTheme( + contents: string, + document?: StoryDocument, + renderer?: "archify" | "graphviz", +): string { if (!/]*>/i.test(contents)) throw new Error("Renderer output has no head for the core theme integration"); - return contents.replace(/]*>/i, (head) => `${head}\n`); + const drilldowns: [string, StoryTarget][] = []; + for (const section of document?.sections ?? []) { + if (!section.drilldown) continue; + if (!/^[a-z0-9][a-z0-9-]*$/.test(section.drilldown.storyId)) throw new Error("Invalid standalone drilldown target"); + drilldowns.push([section.id, section.drilldown]); + } + const identities = document === undefined ? [] : storyNodeIds(document, renderer); + const navigation = document === undefined || + (drilldowns.length === 0 && identities.every(([authored, native]) => authored === native)) ? "" : ` +`; + return contents.replace(/]*>/i, (head) => `${head}\n${navigation}`); } export function outputHash(contents: string): string { diff --git a/packages/diagram-core/test/diagram-core.test.mjs b/packages/diagram-core/test/diagram-core.test.mjs index 1047791..3c161f1 100644 --- a/packages/diagram-core/test/diagram-core.test.mjs +++ b/packages/diagram-core/test/diagram-core.test.mjs @@ -17,13 +17,46 @@ import { fileURLToPath } from "node:url"; import { renderArchitectureStories, renderStory, + storyNodeIds, verifyArchifyIntegrity, } from "@topo/diagram-core"; import { runtimeDirectory, verifyRuntime } from "@jdylanmc/topo-archify"; +import { parseStoryDocument } from "@topo/story"; const packageRoot = fileURLToPath(new URL("../", import.meta.url)); const execute = promisify(execFile); +test("authored/native identity mapping preserves renderer nodes and edge endpoints", async () => { + const ids = ["1-start", "src/api.ts", "\u5165\u53e3", "normal-slug"]; + for (const renderer of ["archify", "graphviz"]) { + const document = parseStoryDocument(JSON.stringify({ + schemaVersion: "1.0", id: "identities", title: "Identities", summary: "Identity contract", + classification: "capability-demo", diagramFamily: renderer === "archify" ? "architecture" : "workflow", + renderer, anchors: [], + sections: ids.map((id, index) => ({ + id, title: `Node ${index + 1}`, body: "Identity mapping.", anchorIds: [], + drilldown: { storyId: "child", nodeId: "src/api.ts" }, + })), + connections: [{ from: ids[0], to: ids[1], label: "connects", + classification: "inferred", anchorIds: [], rationale: "Conceptual fixture." }], + })); + const pairs = storyNodeIds(document); + assert.deepEqual(pairs.map(([authored]) => authored), ids); + assert.equal(pairs[0][1], renderer === "archify" ? "component_a612388255cfd8d7" : "1-start"); + assert.equal(pairs[3][1], "normal-slug"); + const story = { document, documentPath: "stories/identities.topo.json", repositoryRoot: "/unused", + source: { revision: "fixture", dirty: false }, anchors: [] }; + const artifacts = [await renderStory(story)]; + if (renderer === "archify") artifacts.push(...renderArchitectureStories([story])); + for (const artifact of artifacts) { + for (const [, native] of pairs) assert.ok(artifact.contents.includes(`data-node-id="${native}"`)); + assert.ok(artifact.contents.includes(`data-edge-from="${pairs[0][1]}"`)); + assert.ok(artifact.contents.includes(`data-edge-to="${pairs[1][1]}"`)); + assert.ok(artifact.contents.includes(`new Map(${JSON.stringify(pairs)})`)); + } + } +}); + test("accepts the committed integrity baseline", () => { const integrity = verifyArchifyIntegrity(); @@ -130,6 +163,41 @@ test("renders a resolved story through the packaged Archify CLI", async (context assert.match(first.contents, /Checkout service/); assert.match(first.contents, /Export diagram/); assert.match(first.contents, />Present]*data-node-kind="component"/); + assert.doesNotMatch(first.contents, /]*data-node-kind="frontend"/); + const authoredRoles = { + ...story, + document: { + ...story.document, + sections: story.document.sections.map((section, index) => ({ + ...section, semanticRole: index === 0 ? "source-analysis" : "command-orchestration", + })), + }, + }; + const roleArtifact = renderStory(authoredRoles); + assert.equal(roleArtifact.renderer.sourceOutputSha256, first.renderer.sourceOutputSha256); + assert.notEqual(roleArtifact.renderer.outputSha256, first.renderer.outputSha256); + assert.match(roleArtifact.contents, /]*data-node-kind="source-analysis"/); + assert.match(roleArtifact.contents, /]*data-node-kind="command-orchestration"/); + assert.equal(roleArtifact.renderer.adaptation, "topocode-story-semantics-v2"); + assert.deepEqual(renderArchitectureStories([authoredRoles]), [roleArtifact]); + + const mixedCaptions = { + ...story, + document: { + ...story.document, + sections: story.document.sections.map((section, index) => + index === 0 ? { ...section, summary: "Starts checkout" } : section), + }, + }; + const captionArtifact = renderStory(mixedCaptions); + const nodeTags = captionArtifact.contents.match(/]*data-node-id="[^"]+"[^>]*>/g); + assert.match(nodeTags.find(tag => tag.includes('data-node-id="client-step"')), /data-topo-caption="summary"/); + assert.doesNotMatch(nodeTags.find(tag => tag.includes('data-node-id="service-step"')), /data-topo-caption/); + assert.match(captionArtifact.contents, /svg text\[data-detail="context"\],[\s\S]*?font-size: 24px/); + assert.match(captionArtifact.contents, /svg text\[data-detail="context"\] \{ transform: translateY\(20px\); \}/); + assert.match(captionArtifact.contents, /\[data-topo-caption="summary"\] text\[data-detail="context"\] \{ font-size: 17px; transform: translateY\(12px\); \}/); + assert.deepEqual(renderArchitectureStories([mixedCaptions]), [captionArtifact]); const caller = path.join(repositoryRoot, "caller"); await mkdir(caller); diff --git a/packages/site/tests/e2e/archify-story.spec.ts b/packages/site/tests/e2e/archify-story.spec.ts index faa44ea..40fff0d 100644 --- a/packages/site/tests/e2e/archify-story.spec.ts +++ b/packages/site/tests/e2e/archify-story.spec.ts @@ -12,40 +12,51 @@ import { } from "./helpers/production-cli.js"; const projectRoot = fileURLToPath(new URL("../../../../", import.meta.url)); +const architectureDiagram = 'svg[data-topo-family="architecture"][data-diagram-type="architecture"][role="group"]'; +const nativeDiagram = 'svg[aria-labelledby="archify-diagram-title archify-diagram-description"][role="img"]'; const galleryStories = [ { path: "stories/topo-architecture.topo.json", id: "topo-architecture", + diagram: architectureDiagram, title: "How Topocode turns source into an architecture storybook", }, { path: "stories/story-authoring-workflow.topo.json", id: "story-authoring-workflow", + diagram: nativeDiagram, title: "How a Topocode story reaches preview", }, { path: "stories/story-lifecycle.topo.json", id: "story-lifecycle", + diagram: nativeDiagram, title: "The lifecycle of a Topocode story", }, { path: "stories/capabilities/architecture.topo.json", id: "architecture-capability", + diagram: architectureDiagram, title: "Architecture capability", }, { path: "stories/capabilities/workflow.topo.json", id: "workflow-capability", + diagram: nativeDiagram, title: "Workflow capability", }, { path: "stories/capabilities/lifecycle.topo.json", id: "lifecycle-capability", + diagram: nativeDiagram, title: "Lifecycle capability", }, ] as const; -async function writeActualGalleryFixture(repository: string): Promise { +async function writeActualGalleryFixture( + repository: string, + stories: readonly (typeof galleryStories)[number][] = galleryStories, +): Promise { await writeFile( join(repository, "package.json"), '{"name":"actual-story-gallery-fixture","type":"module"}\n', @@ -87,13 +98,13 @@ async function writeActualGalleryFixture(repository: string): Promise { await commit(repository, "Source", "package.json", "packages", "docs"); await topo(repository, "scan"); - for (const story of galleryStories) { + for (const story of stories) { const destination = join(repository, story.path); await mkdir(dirname(destination), { recursive: true }); await writeFile(destination, await readFile(join(projectRoot, story.path))); } await commit(repository, "Stories", "stories"); - for (const story of galleryStories) { + for (const story of stories) { await topo( repository, "story", @@ -137,8 +148,19 @@ test("actual gallery story text remains readable at a desktop viewport", async ( for (const story of galleryStories) { await page.goto(`${url}/stories/${story.id}/`); const viewer = page.frameLocator("[data-story-viewer]"); - const diagram = viewer.locator('svg[role="img"]'); + const diagram = viewer.locator(story.diagram); await expect(diagram).toBeVisible(); + const captionOverlaps = await diagram.locator("g[data-node-id]").evaluateAll(nodes => + nodes.flatMap(node => { + const title = node.querySelector('text[data-node-label]')?.getBoundingClientRect(); + const caption = node.querySelector('text[data-detail="context"]')?.getBoundingClientRect(); + if (!title || !caption) return []; + return Math.min(title.right, caption.right) > Math.max(title.left, caption.left) && + Math.min(title.bottom, caption.bottom) > Math.max(title.top, caption.top) + ? [{ id: node.getAttribute("data-node-id"), title: { top: title.top, bottom: title.bottom }, + caption: { top: caption.top, bottom: caption.bottom } }] : []; + })); + expect(captionOverlaps, `${story.id} title/caption clearance`).toEqual([]); const iframeScale = await page.locator("[data-story-viewer]").evaluate( (iframe) => { const frame = iframe as HTMLIFrameElement; @@ -238,7 +260,10 @@ test("actual gallery story text remains readable at a desktop viewport", async ( Math.min(...measurements.map(({ effectiveFontSize }) => effectiveFontSize * iframeScale )), - `${story.id} at ${viewport.width}x${viewport.height}`, + `${story.id} at ${viewport.width}x${viewport.height}: ${JSON.stringify( + measurements.filter(({ effectiveFontSize }) => effectiveFontSize * iframeScale < 12) + .map(({ text, effectiveFontSize }) => ({ text, size: effectiveFontSize * iframeScale })), + )}`, ).toBeGreaterThanOrEqual(12); } } @@ -251,6 +276,106 @@ test("actual gallery story text remains readable at a desktop viewport", async ( } }); +for (const height of [720, 760, 768]) { + test(`Architecture sidebar breakpoints preserve reading and evidence at ${height}px high`, async ({ + page, repository, startSite, + }, info) => { + await writeActualGalleryFixture(repository, [galleryStories[0], galleryStories[3]]); + const url = await startSite(); + const results = []; + for (const width of [1099, 1100, 1239, 1240, 1241, 1279, 1280, 1281]) { + await page.setViewportSize({ width, height }); + for (const focused of [false, true]) { + await page.goto(`${url}/stories/topo-architecture/${focused ? "?focus=scan&from=architecture-capability&fromFocus=client" : ""}`); + for (const collapsed of [false, true]) { + const shell = page.locator("[data-topo-shell]"); + const toggle = page.locator("[data-collapse]"); + if (await shell.getAttribute("data-navigation-collapsed") !== String(collapsed)) { + await toggle.press("Enter"); + } + await expect(shell).toHaveAttribute("data-navigation-collapsed", String(collapsed)); + const controls = collapsed ? [toggle] : [ + page.getByLabel("Filter diagrams"), + page.getByRole("link", { name: "Third-party notices", exact: true }), + toggle, + ]; + for (const control of [...controls, ...(focused ? [page.locator("[data-return]")] : [])]) { + await control.focus(); + await expect(control).toBeFocused(); + expect(await control.evaluate(element => { + const box = element.getBoundingClientRect(); + const hit = document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2); + return hit !== null && element.contains(hit); + }), `Navigation control remains unobscured at ${width}x${height}`).toBe(true); + } + const details = page.locator(".story-details"); + if (focused) await expect(details).toHaveAttribute("open", ""); + else await expect(details).not.toHaveAttribute("open", ""); + const frame = page.frameLocator("[data-story-viewer]"); + const diagram = frame.locator(architectureDiagram); + await expect(diagram).toBeVisible(); + await diagram.evaluate(async () => { + await document.fonts.ready; + await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); + }); + const frameBounds = (await page.locator("[data-story-viewer]").boundingBox())!; + const panelBounds = (await details.boundingBox())!; + const metrics = await diagram.evaluate((svg, bounds) => { + const overlap = (a: DOMRect, b: { x: number; y: number; width: number; height: number }) => + Math.min(a.right, b.x + b.width) > Math.max(a.left, b.x) && + Math.min(a.bottom, b.y + b.height) > Math.max(a.top, b.y); + const captions = [...svg.querySelectorAll('g[data-node-id] text[data-detail="context"]')]; + const texts = [...svg.querySelectorAll("text")].filter(text => text.getBoundingClientRect().width > 0); + return { + captions: captions.map(text => { + const box = text.getBoundingClientRect(); + const node = text.closest("g[data-node-id]")!.querySelector("rect")!.getBoundingClientRect(); + return { + text: text.textContent, size: parseFloat(getComputedStyle(text).fontSize) * text.getScreenCTM()!.a, + visible: box.width > 0 && box.height > 0, + insideNode: box.left >= node.left && box.right <= node.right && box.top >= node.top && box.bottom <= node.bottom, + }; + }), + outside: texts.filter(text => { + const box = text.getBoundingClientRect(); + return box.left < 0 || box.top < 0 || box.right > innerWidth || box.bottom > innerHeight; + }).map(text => text.textContent), + panelOverlaps: texts.filter(text => overlap(text.getBoundingClientRect(), { + x: bounds.panel.x - bounds.frame.x, y: bounds.panel.y - bounds.frame.y, + width: bounds.panel.width, height: bounds.panel.height, + })).map(text => text.textContent), + captionOverlaps: captions.filter(text => + overlap(text.getBoundingClientRect(), text.closest("g[data-node-id]")!.querySelector("[data-node-label]")!.getBoundingClientRect())) + .map(text => text.textContent), + }; + }, { frame: frameBounds, panel: panelBounds }); + const scenario = `${width}x${height} collapsed=${collapsed} focused=${focused}`; + expect(metrics.captions, scenario).toHaveLength(7); + for (const caption of metrics.captions) { + expect(caption.visible, `${scenario}: ${caption.text}`).toBe(true); + expect(caption.size, `${scenario}: ${caption.text}`).toBeGreaterThanOrEqual(12); + expect(caption.insideNode, `${scenario}: ${caption.text}`).toBe(true); + } + expect(metrics.outside, scenario).toEqual([]); + expect(metrics.panelOverlaps, scenario).toEqual([]); + expect(metrics.captionOverlaps, scenario).toEqual([]); + if (focused) { + const excerpt = details.locator('[data-section-evidence="scan"] pre'); + await excerpt.scrollIntoViewIfNeeded(); + await expect(excerpt).toBeInViewport(); + await page.locator("[data-return]").click(); + await expect(page.locator("body")).toHaveAttribute("data-story-id", "architecture-capability"); + await page.goBack(); + await expect(page.locator("body")).toHaveAttribute("data-story-id", "topo-architecture"); + } + results.push({ width, height, collapsed, focused, frame: frameBounds, panel: panelBounds, ...metrics }); + } + } + } + await info.attach("breakpoint-metrics", { body: JSON.stringify(results, null, 2), contentType: "application/json" }); + }); +} + test("actual Topocode architecture catalogue text stays inside its node", async ({ page, repository, @@ -510,7 +635,7 @@ test("actual Architecture exports preserve canonical geometry and labels", async try { await page.goto(`${url}/stories/topo-architecture/`); const viewer = page.frameLocator("[data-story-viewer]"); - const diagram = viewer.locator('svg[role="img"]'); + const diagram = viewer.locator(architectureDiagram); await expect(diagram).toBeVisible(); const liveText = await diagram.locator("text").allTextContents(); for (const label of authoredLabels) { @@ -629,7 +754,7 @@ test("actual gallery relationship labels and backdrops clear nodes", async ({ for (const story of galleryStories) { await page.goto(`${url}/stories/${story.id}/`); const diagram = page.frameLocator("[data-story-viewer]") - .locator('svg[role="img"]'); + .locator(story.diagram); await expect(diagram).toBeVisible(); collisions.push(...await diagram.evaluate((svg, storyId) => { const nodes = [...svg.querySelectorAll( @@ -844,15 +969,24 @@ test("actual story details restore unobscured authored content", async ({ ]; const overlappingTitles = async () => { const controlsBounds = await controls.boundingBox(); + const viewerBounds = await page.locator("[data-story-viewer]").boundingBox(); expect(controlsBounds).not.toBeNull(); + expect(viewerBounds).not.toBeNull(); const diagram = page.frameLocator("[data-story-viewer]") - .locator('svg[role="img"]'); + .locator(architectureDiagram); const overlaps: string[] = []; for (const title of authoredTitles) { - const titleBounds = await diagram.locator("text", { hasText: title }) - .first() - .boundingBox(); + const label = diagram.locator("text", { hasText: title }).first(); + const titleBounds = await label.boundingBox(); expect(titleBounds, title).not.toBeNull(); + expect(titleBounds!.x, title).toBeGreaterThanOrEqual(viewerBounds!.x); + expect(titleBounds!.y, title).toBeGreaterThanOrEqual(viewerBounds!.y); + expect(titleBounds!.x + titleBounds!.width, title).toBeLessThanOrEqual(viewerBounds!.x + viewerBounds!.width); + expect(titleBounds!.y + titleBounds!.height, title).toBeLessThanOrEqual(viewerBounds!.y + viewerBounds!.height); + expect(await label.evaluate(element => { + const text = element as SVGTextElement; + return parseFloat(getComputedStyle(text).fontSize) * text.getScreenCTM()!.a; + }), title).toBeGreaterThanOrEqual(12); if ( titleBounds && controlsBounds && @@ -877,7 +1011,8 @@ test("actual story details restore unobscured authored content", async ({ await scanLink.focus(); await page.keyboard.press("Enter"); await expect(page).toHaveURL(`${url}/stories/topo-architecture/?focus=scan`); - await expect(controls).not.toHaveAttribute("open", ""); + await expect(controls).toHaveAttribute("open", ""); + await expect(controls.locator('[data-section-evidence="scan"]')).toBeVisible(); await expect( page.frameLocator("[data-story-viewer]").getByText( "packages/scanner/src/typescript-scanner.ts", @@ -885,6 +1020,9 @@ test("actual story details restore unobscured authored content", async ({ ), ).toBeVisible(); expect(await overlappingTitles()).toEqual([]); + const excerpt = controls.locator('[data-section-evidence="scan"] pre'); + await excerpt.scrollIntoViewIfNeeded(); + await expect(excerpt).toBeInViewport(); await page.goBack(); await expect(page).toHaveURL(`${url}/stories/topo-architecture/`); @@ -897,7 +1035,8 @@ test("actual story details restore unobscured authored content", async ({ { exact: true }, ), ).toBeVisible(); - await expect(controls).not.toHaveAttribute("open", ""); + await expect(controls).toHaveAttribute("open", ""); + await expect(controls.locator('[data-section-evidence="bundle"]')).toBeVisible(); expect(await overlappingTitles()).toEqual([]); } finally { await page.goto("about:blank"); diff --git a/packages/site/tests/e2e/catalogue.spec.ts b/packages/site/tests/e2e/catalogue.spec.ts index f413d01..3f700e9 100644 --- a/packages/site/tests/e2e/catalogue.spec.ts +++ b/packages/site/tests/e2e/catalogue.spec.ts @@ -151,7 +151,7 @@ test("preview populates the same home and category tree without scanning, includ try { await page.goto(`${site.url}/docs/topo/`); await page.locator("[data-home-inventory] [data-story-id=alpha]").click(); - await expect(page.locator("[data-story-viewer]").contentFrame().locator('svg[role="img"]')).toBeVisible(); + await expect(page.locator("[data-story-viewer]").contentFrame().locator('svg[data-diagram-type="architecture"][role="group"]')).toBeVisible(); await page.getByRole("link", { name: "Home", exact: true }).click(); await expect(page).toHaveURL(`${site.url}/docs/topo/`); expect((await page.request.get(`${site.url}/docs/topo/THIRD_PARTY_NOTICES.txt`)).status()).toBe(200); @@ -686,7 +686,7 @@ test("linked story nodes keep durable focus across drill-down, reload, direct op await page.getByRole("link", { name: "Open Order detail: Order code evidence" }).click(); await expect(page).toHaveURL( - `${url}/stories/detail/?focus=evidence&from=overview&fromFocus=order-detail`, + `${url}/stories/detail/?focus=evidence&from=overview&fromFocus=order-detail&callers=${encodeURIComponent(JSON.stringify([{ storyId: "overview", nodeId: "order-detail" }]))}`, ); await expect(page.getByRole("heading", { name: "Order detail" })).toBeVisible(); await expect(page.locator('[data-node-id="evidence"]')).toHaveAttribute("aria-current", "true"); @@ -706,9 +706,9 @@ test("linked story nodes keep durable focus across drill-down, reload, direct op await page.goto( `${url}/stories/detail/?focus=evidence&from=overview&fromFocus=order-detail`, ); - await page.getByText("Story navigation and details", { exact: true }).click(); + await expect(page.locator(".story-details")).toHaveAttribute("open", ""); await page.getByRole("link", { name: "Return to Order overview" }).click(); - await expect(page).toHaveURL(`${url}/stories/overview/?focus=order-detail`); + await expect(page).toHaveURL(`${url}/stories/overview/?focus=order-detail&callers=%5B%5D`); await expect(page.locator('[data-node-id="order-detail"]')).toHaveAttribute("aria-current", "true"); await expect(page.locator("iframe")).toHaveAttribute( "src", diff --git a/packages/site/tests/e2e/dataflow-story.spec.ts b/packages/site/tests/e2e/dataflow-story.spec.ts index 4837e22..4a3da3f 100644 --- a/packages/site/tests/e2e/dataflow-story.spec.ts +++ b/packages/site/tests/e2e/dataflow-story.spec.ts @@ -418,7 +418,11 @@ test("actual Dataflow controls restore clear titles and factual source navigatio await expect(page).toHaveURL( `${url}/stories/repository-dataflow/?focus=repository-source`, ); - await expect(controls).not.toHaveAttribute("open", ""); + await expect(controls).toHaveAttribute("open", ""); + const evidence = controls.locator('[data-section-evidence="repository-source"]'); + await expect(evidence).toBeVisible(); + await expect(evidence.locator("figcaption")).toContainText("packages/scanner/src/typescript-scanner.ts"); + await expect(evidence.locator("pre")).toContainText("const files = await walkFiles(options.root);"); const viewer = page.frameLocator("[data-story-viewer]"); await expect( viewer.locator('svg g[data-node-id="repository-source"]'), diff --git a/packages/site/tests/e2e/repository.spec.ts b/packages/site/tests/e2e/repository.spec.ts index 8d16369..988b132 100644 --- a/packages/site/tests/e2e/repository.spec.ts +++ b/packages/site/tests/e2e/repository.spec.ts @@ -3,6 +3,8 @@ import { join } from "node:path"; import { expect } from "@playwright/test"; import { commit, startStaticServer, stopStaticServer, test, topo } from "./helpers/production-cli.js"; +const architectureDiagram = 'svg[data-topo-family="architecture"][data-diagram-type="architecture"][role="group"]'; + async function fixture(root: string, wide = false): Promise { await mkdir(join(root, "packages/api/src"), { recursive: true }); await writeFile(join(root, "package.json"), '{"private":true,"workspaces":["packages/*"]}\n'); @@ -44,21 +46,23 @@ test("selected Archify repository view drills through packages and files to comp index.nodes.find((item: { path: string; kind: string }) => item.path === path && item.kind === kind); const frame = page.locator("[data-repository-viewer]").contentFrame(); - await expect(frame.locator('svg[role="img"]')).toBeVisible(); + await expect(frame.locator(architectureDiagram)).toBeVisible(); for (const [path, kind] of [ ["packages", "directory"], ["packages/api", "package"], ["packages/api/src", "directory"], ["packages/api/src/order.ts", "file"], ]) { - await frame.locator(`svg[role="img"] [data-node-id="${node(path!, kind!).id}"]`).click(); + await frame.locator(`${architectureDiagram} [data-node-id="${node(path!, kind!).id}"]`).click(); await expect(page).toHaveURL(new RegExp(`scope=${node(path!, kind!).id}`)); - await expect(frame.locator('svg[role="img"]')).toBeVisible(); + await expect(frame.locator(architectureDiagram)).toBeVisible(); } const order = index.nodes.find((item: { name: string; kind: string }) => item.name === "Order" && item.kind === "class"); - await frame.locator(`svg[role="img"] [data-node-id="${order.id}"]`).focus(); + await frame.locator(`${architectureDiagram} [data-node-id="${order.id}"]`).focus(); await page.keyboard.press("Enter"); await expect(page).toHaveURL(new RegExp(`focus=${order.id}`)); + await expect(frame.locator(`${architectureDiagram} [data-node-id="${order.id}"]`)) + .toHaveAttribute("data-repository-selected", ""); await expect(page.locator("[data-repository-evidence]")).toContainText("Declared members"); await expect(page.locator("[data-repository-evidence]")).toContainText("submit"); await expect(page.locator("[data-repository-evidence]")).toContainText("save"); @@ -89,11 +93,11 @@ test("bounded repository pages and source evidence survive a plain static base p await expect(page.locator("[data-repository-page]")).toHaveText("Page 1 of 2 / 5 entries"); await page.getByRole("button", { name: "Next", exact: true }).click(); await expect(page).toHaveURL(`${base}?scope=${src.id}&page=2`); - await expect(page.locator("[data-repository-viewer]").contentFrame().locator('svg[role="img"]')).toBeVisible(); + await expect(page.locator("[data-repository-viewer]").contentFrame().locator(architectureDiagram)).toBeVisible(); const store = index.nodes.find((item: { path: string; kind: string }) => item.path === "packages/api/src/store.ts" && item.kind === "file"); await page.locator("[data-repository-viewer]").contentFrame() - .locator(`svg[role="img"] [data-node-id="${store.id}"]`).click(); + .locator(`${architectureDiagram} [data-node-id="${store.id}"]`).click(); await expect(page).toHaveURL(`${base}?scope=${store.id}`); await page.getByRole("button", { name: "Back", exact: true }).click(); await expect(page).toHaveURL(`${base}?scope=${src.id}&page=2`); @@ -140,8 +144,8 @@ test("repository diagrams retain effective readable text at supported desktop si const frame = page.locator("[data-repository-viewer]").contentFrame(); for (const [width, height] of [[1024, 768], [1280, 720], [1440, 900], [1600, 1000], [1920, 1080]]) { await page.setViewportSize({ width: width!, height: height! }); - await expect(frame.locator('svg[role="img"]')).toBeVisible(); - const measurements = await frame.locator('svg[role="img"]').evaluate((svg) => { + await expect(frame.locator(architectureDiagram)).toBeVisible(); + const measurements = await frame.locator(architectureDiagram).evaluate((svg) => { const texts = [...svg.querySelectorAll("text")].filter((text) => text.textContent?.trim()); return texts.map((text) => { const transform = text.getScreenCTM(); @@ -178,9 +182,9 @@ test("repository diagrams retain effective readable text at supported desktop si const bounds = await page.locator("[data-repository-viewer]").boundingBox(); expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(width! + 1); expect(bounds!.y + bounds!.height).toBeLessThanOrEqual(height! + 1); - await frame.locator(`svg[role="img"] [data-node-id="${selected.id}"]`).click(); + await frame.locator(`${architectureDiagram} [data-node-id="${selected.id}"]`).click(); await expect(page.locator(".repository-evidence")).toHaveAttribute("open", ""); - const selectedGeometry = await frame.locator('svg[role="img"]').evaluate((svg) => + const selectedGeometry = await frame.locator(architectureDiagram).evaluate((svg) => [...svg.querySelectorAll("text")].filter((text) => text.textContent?.trim()).map((text) => { const bounds = text.getBoundingClientRect(); const transform = text.getScreenCTM()!; diff --git a/packages/site/tests/e2e/sequence-stories.spec.ts b/packages/site/tests/e2e/sequence-stories.spec.ts index 8f4e350..9e2a1fb 100644 --- a/packages/site/tests/e2e/sequence-stories.spec.ts +++ b/packages/site/tests/e2e/sequence-stories.spec.ts @@ -416,7 +416,7 @@ test("Sequence final typography preserves wide participant titles", async ({ await page.setViewportSize(viewport); await page.goto(`${url}/stories/${wideSequenceStory.id}/`); const viewer = page.frameLocator("[data-story-viewer]"); - const diagram = viewer.locator('svg[role="img"]'); + const diagram = viewer.locator('svg[data-topo-family="sequence"][role="group"]'); for (const section of wideSequenceStory.sections) { await expect(diagram.getByText(section.body, { exact: true })) .toBeVisible(); @@ -524,7 +524,7 @@ test("Sequence stories remain readable in a plain-server bundle", async ({ ).toBeVisible(); const viewer = page.frameLocator("[data-story-viewer]"); - const diagram = viewer.locator('svg[role="img"]'); + const diagram = viewer.locator('svg[data-topo-family="sequence"][role="group"]'); await expect(diagram).toBeVisible(); const iframeScale = await page.locator("[data-story-viewer]").evaluate( (iframe) => { @@ -739,7 +739,8 @@ test("public Sequence participants retain native details before explicit navigat await explicitCrossStoryLink.click(); await expect(page).toHaveURL( `${baseUrl}stories/topo-architecture/?focus=catalogue` + - "&from=story-preview-sequence&fromFocus=preview-orchestrator", + "&from=story-preview-sequence&fromFocus=preview-orchestrator" + + `&callers=${encodeURIComponent(JSON.stringify([{ storyId: "story-preview-sequence", nodeId: "preview-orchestrator" }]))}`, ); await page.goBack(); await expect(page).toHaveURL( @@ -821,7 +822,7 @@ test("integrated Sequence stories preserve titles, navigation, and exports", asy const controls = page.locator("details.story-details"); const summary = controls.locator("summary"); const viewer = page.frameLocator("[data-story-viewer]"); - const diagram = viewer.locator('svg[role="img"]'); + const diagram = viewer.locator('svg[data-topo-family="sequence"][role="group"]'); const diagramLabels = [ ...document.sections.map(({ title }) => title), ...document.connections.map(({ label }) => label), diff --git a/packages/site/tests/e2e/story-navigation.spec.ts b/packages/site/tests/e2e/story-navigation.spec.ts new file mode 100644 index 0000000..ca8ee0e --- /dev/null +++ b/packages/site/tests/e2e/story-navigation.spec.ts @@ -0,0 +1,103 @@ +import { createHash } from "node:crypto"; +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect } from "@playwright/test"; +import { commit, test, topo } from "./helpers/production-cli.js"; + +const ids = ["1-start", "src/api.ts", "\u5165\u53e3", "normal-slug"]; +const nativeId = (id: string, renderer: string) => + renderer === "graphviz" || /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(id) + ? id : `component_${createHash("sha256").update(id).digest("hex").slice(0, 16)}`; + +async function navigationFixture(repository: string, renderer: "archify" | "graphviz") { + await topo(repository, "init"); + await mkdir(join(repository, "stories"), { recursive: true }); + for (const id of ["origin", "child"]) { + await writeFile(join(repository, `stories/${id}.topo.json`), JSON.stringify({ + schemaVersion: "1.0", id, title: id, summary: "Navigation contract fixture.", + classification: "capability-demo", diagramFamily: renderer === "graphviz" ? "workflow" : "architecture", + renderer, anchors: [], + ...(id === "child" ? { parent: { storyId: "origin", nodeId: "normal-slug" } } : {}), + sections: ids.map((nodeId, index) => ({ + id: nodeId, title: `Section ${index + 1}`, body: `Evidence for ${nodeId}`, anchorIds: [], + ...(id === "origin" ? { drilldown: { storyId: "child", nodeId: ids[(index + 1) % ids.length] } } : {}), + })), + connections: [], + })); + } + await commit(repository, "Navigation fixture", "stories"); + await topo(repository, "preview", repository, join(repository, "stories/origin.topo.json")); +} + +for (const renderer of ["archify", "graphviz"] as const) { + test(`${renderer}: authored IDs survive plain/wrapped activation, explicit targets and reload`, async ({ + page, repository, startSite, + }) => { + await navigationFixture(repository, renderer); + const url = await startSite(); + const errors: string[] = []; + page.on("pageerror", error => errors.push(error.message)); + for (const plain of [false, true]) { + for (const [index, id] of ids.entries()) { + const target = ids[(index + 1) % ids.length]!; + const native = nativeId(id, renderer); + const destinationNative = nativeId(target, renderer); + await page.goto(`${url}/stories/origin/${plain ? "viewer.html" : ""}`); + const node = plain + ? page.locator(`svg [data-node-id="${native}"]`) + : page.frameLocator("[data-story-viewer]").locator(`svg [data-node-id="${native}"]`); + if (index % 2 === 0) await node.click(); + else await node.press(index === 1 ? "Enter" : " "); + await expect(page.locator("body")).toHaveAttribute("data-story-id", "child"); + expect(new URL(page.url()).searchParams.get("focus")).toBe(target); + expect(new URL(page.url()).searchParams.get("fromFocus")).toBe(id); + await expect(page.locator("[data-story-viewer]")).toHaveAttribute("src", `viewer.html#focus=${encodeURIComponent(destinationNative)}`); + await expect(page.frameLocator("[data-story-viewer]").locator(`svg [data-node-id="${destinationNative}"]`)).toBeVisible(); + await expect(page.locator(`a[data-node-id="${target}"]`)).toHaveAttribute("aria-current", "true"); + await page.reload(); + await expect(page.locator("[data-story-viewer]")).toHaveAttribute("src", `viewer.html#focus=${encodeURIComponent(destinationNative)}`); + await page.locator("[data-return]").click(); + await expect(page.locator("body")).toHaveAttribute("data-story-id", "origin"); + expect(new URL(page.url()).searchParams.get("focus")).toBe(id); + await expect(page.locator(`a[data-node-id="${id}"]`)).toHaveAttribute("aria-current", "true"); + await page.reload(); + await expect(page.frameLocator("[data-story-viewer]").locator(`svg [data-node-id="${native}"]`)).toBeVisible(); + await expect(page.locator("body")).toHaveAttribute("data-story-id", "origin"); + + // A direct plain viewer accepts authored fragment IDs before native startup. + await page.goto(`${url}/stories/origin/viewer.html#focus=${encodeURIComponent(id)}`); + await expect.poll(() => new URLSearchParams(new URL(page.url()).hash.slice(1)).get("focus")).toBe(native); + await expect(page.locator(`svg [data-node-id="${native}"]`)).toBeVisible(); + await page.reload(); + await expect.poll(() => new URLSearchParams(new URL(page.url()).hash.slice(1)).get("focus")).toBe(native); + } + } + expect(errors).toEqual([]); + }); +} + +test("return context accepts only catalogue story/node identities and preserves legacy URLs", async ({ + page, repository, startSite, +}) => { + await navigationFixture(repository, "archify"); + const url = await startSite(); + for (const callers of [ + "not-json", + JSON.stringify([{ storyId: "https://example.invalid", nodeId: "normal-slug" }]), + JSON.stringify([{ storyId: "origin", nodeId: "missing" }]), + JSON.stringify([{ storyId: "origin", nodeId: "normal-slug", url: "https://example.invalid" }]), + ]) { + await page.goto(`${url}/stories/child/?callers=${encodeURIComponent(callers)}`); + await expect(page.locator("[data-return]")).toBeVisible(); + const target = new URL((await page.locator("[data-return]").getAttribute("href"))!); + expect(target.origin).toBe(url); + expect(target.pathname).toBe("/stories/origin/"); + expect(target.searchParams.get("focus")).toBe("normal-slug"); + expect(target.searchParams.get("callers")).toBe("[]"); + } + await page.goto(`${url}/stories/child/?from=origin&fromFocus=1-start`); + await page.reload(); + await page.locator("[data-return]").click(); + expect(new URL(page.url()).searchParams.get("focus")).toBe("1-start"); + await expect(page.locator("body")).toHaveAttribute("data-story-id", "origin"); +}); diff --git a/packages/site/tests/e2e/technical-story.spec.ts b/packages/site/tests/e2e/technical-story.spec.ts index a714865..a195d99 100644 --- a/packages/site/tests/e2e/technical-story.spec.ts +++ b/packages/site/tests/e2e/technical-story.spec.ts @@ -86,10 +86,10 @@ test("technical branches retain geometry, exact edge evidence, Home links and ca expect(svgText).not.toContain("prefers-color-scheme"); expect(svgText).toContain("rgb("); await page.goto(`${url}/stories/snapshot/?focus=choose`); - await page.locator(".story-details > summary").click(); + await expect(page.locator(".story-details")).toHaveAttribute("open", ""); await page.locator('[data-cross-story][data-source-node="choose"]').click(); await expect(page).toHaveURL(/snapshot-overview.*focus=handler/); - await page.locator(".story-details > summary").click(); + await expect(page.locator(".story-details")).toHaveAttribute("open", ""); await page.locator("[data-return]").click(); await expect(page).toHaveURL(/snapshot\/.*focus=choose/); const index = JSON.parse(await readFile(join(repository, ".topo/cache/site/repository.json"), "utf8")); diff --git a/packages/site/tests/e2e/topo-packages-story.spec.ts b/packages/site/tests/e2e/topo-packages-story.spec.ts index fcca224..8373b5c 100644 --- a/packages/site/tests/e2e/topo-packages-story.spec.ts +++ b/packages/site/tests/e2e/topo-packages-story.spec.ts @@ -162,7 +162,7 @@ test("package architecture renders a readable multi-row workspace map", async ({ await page.setViewportSize({ width: 1440, height: 900 }); await page.goto(`${url}/stories/topo-packages/`); const diagram = page.frameLocator("[data-story-viewer]") - .locator('svg[role="img"]'); + .locator('svg[data-diagram-type="architecture"][role="group"]'); await expect(diagram).toBeVisible(); const rows = await diagram.locator("g[data-node-id] > rect:not(.c-mask)") @@ -184,6 +184,56 @@ test("package architecture renders a readable multi-row workspace map", async ({ } }); +for (const reverse of [false, true]) { + test(`neighbouring diagonal route stays local without backtracking (${reverse ? "up" : "down"})`, async ({ page, repository, startSite }) => { + const ids = ["story", "diagram-core", "enrichment", "graph", "views", "site", "cli", "workspace", "reports", "languages", "modules", "eslint-config", "scanner", "schema"]; + const from = reverse ? "reports" : "cli"; + const to = reverse ? "cli" : "reports"; + const storyPath = join(repository, "stories/diagonal.topo.json"); + await mkdir(dirname(storyPath), { recursive: true }); + await writeFile(storyPath, JSON.stringify({ + schemaVersion: "1.0", diagramFamily: "architecture", classification: "capability-demo", + id: "diagonal", title: "Diagonal routing regression", summary: "Synthetic original fourteen-node layout; geometry only.", + anchors: [], + sections: ids.map(id => ({ id, title: `@topo/${id}`, body: "Routing fixture.", anchorIds: [] })), + connections: [ + { from: "cli", to: "workspace" }, { from: "cli", to: "languages" }, + { from: "cli", to: "diagram-core" }, { from: "cli", to: "site" }, + { from, to }, + ], + })); + await commit(repository, "Diagonal routing fixture", "stories"); + await topo(repository, "init"); + await topo(repository, "story", "preview", repository, storyPath); + await page.goto(`${await startSite()}/stories/diagonal/`); + const diagram = page.frameLocator("[data-story-viewer]").locator('svg[data-diagram-type="architecture"]'); + await expect(diagram).toBeVisible(); + const metrics = await diagram.evaluate((svg, { from, to }) => { + const route = svg.querySelector(`path[data-edge-from="${from}"][data-edge-to="${to}"]`)!; + const boxes = [...svg.querySelectorAll("g[data-node-id]")].map(node => ({ + id: node.dataset.nodeId, + box: node.querySelector("rect:not(.c-mask)")!.getBoundingClientRect(), + })); + const source = boxes.find(node => node.id === from)!.box; + const target = boxes.find(node => node.id === to)!.box; + const sign = Math.sign(target.y - source.y); + const length = route.getTotalLength(); + const points = Array.from({ length: 201 }, (_, index) => + route.getPointAtLength(length * index / 200).matrixTransform(route.getScreenCTM()!)); + return { + backtracks: points.slice(1).filter((point, index) => sign * (point.y - points[index]!.y) < -0.5).length, + outOfBounds: points.filter(point => + point.y < Math.min(source.top, target.top) - 1 || point.y > Math.max(source.bottom, target.bottom) + 1 || + point.x < Math.min(source.left, target.left) - 1 || point.x > Math.max(source.right, target.right) + 1).length, + nodeIntrusions: points.filter(point => boxes.some(node => node.id !== from && node.id !== to && + point.x > node.box.left + 1 && point.x < node.box.right - 1 && + point.y > node.box.top + 1 && point.y < node.box.bottom - 1)).length, + }; + }, { from, to }); + expect(metrics).toEqual({ backtracks: 0, outOfBounds: 0, nodeIntrusions: 0 }); + }); +} + test("converging Architecture relationships keep both labels readable", async ({ page, repository, @@ -262,7 +312,7 @@ test("converging Architecture relationships keep both labels readable", async ({ await page.setViewportSize({ width: 1024, height: 768 }); await page.goto(`${url}/stories/converging/`); const diagram = page.frameLocator("[data-story-viewer]") - .locator('svg[role="img"]'); + .locator('svg[data-diagram-type="architecture"][role="group"]'); await expect(diagram).toBeVisible(); const labels = diagram.locator("g[data-edge-from] > text"); await expect(labels).toHaveCount(2); @@ -376,7 +426,7 @@ async function verifyRaggedArchitectureScenario( `${url}/stories/chain-${labelSet.id}-${sectionCount}/`, ); const frame = page.frameLocator("[data-story-viewer]"); - const diagram = frame.locator('svg[role="img"]'); + const diagram = frame.locator('svg[data-diagram-type="architecture"][role="group"]'); await expect(diagram).toBeVisible(); await expect(diagram.locator("g[data-node-id]")).toHaveCount(sectionCount); await expect(diagram.locator("g[data-edge-from]")) @@ -944,7 +994,7 @@ test("actual package story stays readable from a plain static bundle", async ({ await expect(shell).toHaveAttribute("data-navigation-collapsed", "false"); const frame = page.frameLocator("[data-story-viewer]"); - const diagram = frame.locator('svg[role="img"]'); + const diagram = frame.locator('svg[data-diagram-type="architecture"][role="group"]'); await expect(diagram).toBeVisible(); await expect(diagram.locator("g[data-node-id]")) .toHaveCount(fixture.workspaces.length); diff --git a/packages/story/src/index.ts b/packages/story/src/index.ts index 22bbc6c..c05a46e 100644 --- a/packages/story/src/index.ts +++ b/packages/story/src/index.ts @@ -14,10 +14,18 @@ export interface SourceAnchor { readonly sha256?: string; } +export interface StoryTarget { + readonly storyId: string; + readonly nodeId?: string; +} + export interface StorySection { readonly id: string; readonly title: string; readonly body: string; + readonly summary?: string; + readonly semanticRole?: string; + readonly drilldown?: StoryTarget; readonly anchorIds: readonly string[]; readonly kind?: "step" | "decision" | "data"; } @@ -50,6 +58,8 @@ export interface StoryDocument { readonly title: string; readonly summary: string; readonly category?: string; + readonly parent?: StoryTarget & { readonly nodeId: string }; + readonly sequenceLayout?: { readonly minimumParticipantGap: number }; readonly anchors: readonly SourceAnchor[]; readonly sections: readonly StorySection[]; readonly connections: readonly StoryConnection[]; @@ -204,12 +214,23 @@ function uniqueStrings(value: unknown): value is string[] { new Set(value).size === value.length; } +function validateStoryTarget(value: unknown, requireNode: boolean): string | undefined { + if (!isRecord(value)) return "must be an object"; + const keys = exactKeys(value, requireNode ? ["storyId", "nodeId"] : ["storyId"], requireNode ? [] : ["nodeId"]); + if (keys) return keys; + if (typeof value.storyId !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(value.storyId)) { + return "storyId must be a valid story id"; + } + if (value.nodeId !== undefined && !nonemptyString(value.nodeId)) return "nodeId must be nonempty"; + return undefined; +} + function validateStoryDocument(value: unknown): string | undefined { if (!isRecord(value)) return "root must be an object"; const rootKeys = exactKeys( value, ["schemaVersion", "id", "title", "summary", "anchors", "sections", "connections"], - ["category", "diagramFamily", "classification", "renderer"], + ["category", "diagramFamily", "classification", "renderer", "parent", "sequenceLayout"], ); if (rootKeys) return rootKeys; if (value.schemaVersion !== "1.0") return 'schemaVersion must be "1.0"'; @@ -234,6 +255,21 @@ function validateStoryDocument(value: unknown): string | undefined { } if (!nonemptyString(value.title)) return "title must be nonempty"; if (!nonemptyString(value.summary)) return "summary must be nonempty"; + if (value.sequenceLayout !== undefined) { + if (value.diagramFamily !== "sequence" || !isRecord(value.sequenceLayout)) { + return "sequenceLayout requires a sequence diagram and an object"; + } + const keys = exactKeys(value.sequenceLayout, ["minimumParticipantGap"], []); + if (keys) return `sequenceLayout ${keys}`; + const gap = value.sequenceLayout.minimumParticipantGap; + if (typeof gap !== "number" || !Number.isSafeInteger(gap) || gap < 108) { + return "sequenceLayout.minimumParticipantGap must be an integer of at least 108 SVG units"; + } + } + if (value.parent !== undefined) { + const error = validateStoryTarget(value.parent, true); + if (error) return `parent ${error}`; + } if ( value.category !== undefined && (!nonemptyString(value.category) || value.category.trim().length === 0) @@ -276,7 +312,7 @@ function validateStoryDocument(value: unknown): string | undefined { const sectionIds = new Set(); for (const [index, sectionValue] of value.sections.entries()) { if (!isRecord(sectionValue)) return `sections[${index}] must be an object`; - const keys = exactKeys(sectionValue, ["id", "title", "body", "anchorIds"], ["kind"]); + const keys = exactKeys(sectionValue, ["id", "title", "body", "anchorIds"], ["kind", "summary", "semanticRole", "drilldown"]); if (keys) return `sections[${index}] ${keys}`; if (sectionValue.kind !== undefined && (!["step", "decision", "data"].includes(String(sectionValue.kind)) || value.renderer !== "graphviz")) return `sections[${index}].kind requires the explicit graphviz backend`; if (!nonemptyString(sectionValue.id)) return `sections[${index}].id must be nonempty`; @@ -284,6 +320,20 @@ function validateStoryDocument(value: unknown): string | undefined { sectionIds.add(sectionValue.id); if (!nonemptyString(sectionValue.title)) return `sections[${index}].title must be nonempty`; if (!nonemptyString(sectionValue.body)) return `sections[${index}].body must be nonempty`; + if (sectionValue.drilldown !== undefined) { + const error = validateStoryTarget(sectionValue.drilldown, false); + if (error) return `sections[${index}].drilldown ${error}`; + } + if (sectionValue.summary !== undefined && + (!nonemptyString(sectionValue.summary) || diagramFamily !== "architecture")) { + return `sections[${index}].summary requires a nonempty architecture caption`; + } + if (sectionValue.semanticRole !== undefined && + (typeof sectionValue.semanticRole !== "string" || + !/^(?!constructor$)[a-z][a-z0-9-]{0,63}$/.test(sectionValue.semanticRole) || + (diagramFamily !== "architecture" && diagramFamily !== "sequence"))) { + return `sections[${index}].semanticRole requires an architecture or sequence role slug`; + } if (!uniqueStrings(sectionValue.anchorIds)) { return `sections[${index}].anchorIds must contain unique nonempty strings`; } diff --git a/packages/story/src/story.test.ts b/packages/story/src/story.test.ts index f631fe6..bee48d1 100644 --- a/packages/story/src/story.test.ts +++ b/packages/story/src/story.test.ts @@ -43,6 +43,77 @@ function validStory(): StoryDocument { } describe("story document contract", () => { + it("accepts explicit sequence spacing only with a bounded sequence contract", async () => { + const value = { ...validStory(), diagramFamily: "sequence", sequenceLayout: { minimumParticipantGap: 220 } }; + const validate = new Ajv2020({ strict: true }).compile(JSON.parse(await readFile(schemaPath, "utf8"))); + expect(validate(value)).toBe(true); + expect(parseStoryDocument(JSON.stringify(value), "wide.topo.json").sequenceLayout).toEqual({ minimumParticipantGap: 220 }); + for (const invalid of [ + { ...value, diagramFamily: "architecture" }, + ...[{}, null, { minimumParticipantGap: 107 }, { minimumParticipantGap: 220.5 }, { minimumParticipantGap: "220" }, + { minimumParticipantGap: 220, width: 1000 }].map(sequenceLayout => ({ ...value, sequenceLayout })), + ]) { + expect(validate(invalid)).toBe(false); + expect(() => parseStoryDocument(JSON.stringify(invalid), "wide.topo.json")).toThrow(); + } + }); + + it("accepts explicit drilldown and parent targets and rejects malformed navigation", async () => { + const story = validStory(); + const value = { + ...story, parent: { storyId: "overview", nodeId: "checkout" }, + sections: [{ ...story.sections[0], drilldown: { storyId: "details" } }], + }; + const validate = new Ajv2020({ strict: true }).compile(JSON.parse(await readFile(schemaPath, "utf8"))); + expect(validate(value)).toBe(true); + expect(parseStoryDocument(JSON.stringify(value), "navigation.topo.json").parent).toEqual(value.parent); + for (const invalid of [ + { ...value, parent: { storyId: "overview" } }, + { ...value, parent: { storyId: "../escape", nodeId: "checkout" } }, + ...[null, { storyId: "details", nodeId: "" }, { storyId: "details", url: "https://example.test" }] + .map(drilldown => ({ ...value, sections: [{ ...story.sections[0], drilldown }] })), + ]) { + expect(validate(invalid)).toBe(false); + expect(() => parseStoryDocument(JSON.stringify(invalid), "navigation.topo.json")).toThrow(); + } + }); + + it("validates authored architecture roles in both schema and parser", async () => { + const story = validStory(); + const value = { ...story, sections: [{ ...story.sections[0], semanticRole: "source-analysis" }] }; + const validate = new Ajv2020({ strict: true }).compile(JSON.parse(await readFile(schemaPath, "utf8"))); + expect(validate(value)).toBe(true); + expect(parseStoryDocument(JSON.stringify(value), "roles.topo.json").sections[0]?.semanticRole).toBe("source-analysis"); + const sequence = { ...value, diagramFamily: "sequence" }; + expect(validate(sequence)).toBe(true); + expect(parseStoryDocument(JSON.stringify(sequence), "roles.topo.json").sections[0]?.semanticRole).toBe("source-analysis"); + for (const invalid of [ + { ...value, diagramFamily: "workflow" }, + ...["", "Source analysis", 'bad"role', "constructor", "a".repeat(65)].map(semanticRole => ({ + ...value, sections: [{ ...story.sections[0], semanticRole }], + })), + ]) { + expect(validate(invalid)).toBe(false); + expect(() => parseStoryDocument(JSON.stringify(invalid), "roles.topo.json")).toThrow(); + } + }); + + it("supports concise architecture captions without replacing full narrative or evidence", async () => { + const story = validStory(); + const value = { ...story, sections: [{ ...story.sections[0], summary: "Charge an order" }] }; + const schema = JSON.parse(await readFile(schemaPath, "utf8")); + const validate = new Ajv2020({ strict: true }).compile(schema); + expect(validate(value)).toBe(true); + expect(parseStoryDocument(JSON.stringify(value), "caption.topo.json").sections[0]?.summary).toBe("Charge an order"); + for (const invalid of [ + { ...value, diagramFamily: "workflow" }, + { ...value, sections: [{ ...story.sections[0], summary: "" }] }, + ]) { + expect(validate(invalid)).toBe(false); + expect(() => parseStoryDocument(JSON.stringify(invalid), "caption.topo.json")).toThrow(); + } + }); + it("accepts an optional catalogue category", () => { expect(parseStoryDocument( JSON.stringify(validStory()), diff --git a/packages/story/story.schema.json b/packages/story/story.schema.json index c25b037..07803a1 100644 --- a/packages/story/story.schema.json +++ b/packages/story/story.schema.json @@ -1,6 +1,17 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://topo.dev/schemas/story-1.0.json", + "$defs": { + "storyTarget": { + "type": "object", + "additionalProperties": false, + "required": ["storyId"], + "properties": { + "storyId": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$" }, + "nodeId": { "type": "string", "minLength": 1 } + } + } + }, "title": "Topo authored story", "type": "object", "additionalProperties": false, @@ -8,6 +19,14 @@ "properties": { "schemaVersion": { "const": "1.0" }, "renderer": { "enum": ["archify", "graphviz"] }, + "sequenceLayout": { + "type": "object", + "additionalProperties": false, + "required": ["minimumParticipantGap"], + "properties": { + "minimumParticipantGap": { "type": "integer", "minimum": 108, "maximum": 9007199254740991 } + } + }, "diagramFamily": { "enum": ["architecture", "workflow", "sequence", "dataflow", "lifecycle"] }, @@ -18,6 +37,12 @@ "title": { "type": "string", "minLength": 1 }, "summary": { "type": "string", "minLength": 1 }, "category": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "parent": { + "allOf": [ + { "$ref": "#/$defs/storyTarget" }, + { "type": "object", "properties": { "nodeId": {} }, "required": ["nodeId"] } + ] + }, "anchors": { "type": "array", "items": { @@ -45,6 +70,9 @@ "id": { "type": "string", "minLength": 1 }, "title": { "type": "string", "minLength": 1 }, "body": { "type": "string", "minLength": 1 }, + "drilldown": { "$ref": "#/$defs/storyTarget" }, + "summary": { "type": "string", "minLength": 1 }, + "semanticRole": { "type": "string", "pattern": "^(?!constructor$)[a-z][a-z0-9-]{0,63}$" }, "kind": { "enum": ["step", "decision", "data"] }, "anchorIds": { "type": "array", @@ -84,6 +112,18 @@ } }, "allOf": [ + { + "if": { "properties": { "sequenceLayout": {} }, "required": ["sequenceLayout"] }, + "then": { "required": ["diagramFamily"], "properties": { "diagramFamily": { "const": "sequence" } } } + }, + { + "if": { "properties": { "sections": { "type": "array", "contains": { "type": "object", "properties": { "summary": {} }, "required": ["summary"] } } } }, + "then": { "properties": { "diagramFamily": { "const": "architecture" } } } + }, + { + "if": { "properties": { "sections": { "type": "array", "contains": { "type": "object", "properties": { "semanticRole": {} }, "required": ["semanticRole"] } } } }, + "then": { "properties": { "diagramFamily": { "enum": ["architecture", "sequence"] } } } + }, { "if": { "properties": { "renderer": { "const": "graphviz" } }, "required": ["renderer"] }, "then": { diff --git a/packages/workspace/src/index.ts b/packages/workspace/src/index.ts index 49133f3..cc2b7e1 100644 --- a/packages/workspace/src/index.ts +++ b/packages/workspace/src/index.ts @@ -19,6 +19,7 @@ export interface WorkspaceCatalogueConfig { accentColor?: string; categoryOrder?: string[]; storyCategories?: Record; + storyIds?: string[]; } export interface WorkspaceConfig { @@ -77,6 +78,15 @@ function parseCatalogueConfig(input: unknown): WorkspaceCatalogueConfig { categoryOrder = [...value.categoryOrder]; } let storyCategories: Record | undefined; + let storyIds: string[] | undefined; + if (value.storyIds !== undefined) { + if (!Array.isArray(value.storyIds) || + !value.storyIds.every((id): id is string => typeof id === "string" && /^[a-z0-9][a-z0-9-]*$/.test(id)) || + new Set(value.storyIds).size !== value.storyIds.length) { + throw new Error("Workspace catalogue storyIds must contain distinct valid story ids"); + } + storyIds = [...value.storyIds]; + } if (value.storyCategories !== undefined) { if ( typeof value.storyCategories !== "object" || @@ -108,6 +118,7 @@ function parseCatalogueConfig(input: unknown): WorkspaceCatalogueConfig { "accentColor", "categoryOrder", "storyCategories", + "storyIds", ].includes(key), ); if (unknown.length) { @@ -119,6 +130,7 @@ function parseCatalogueConfig(input: unknown): WorkspaceCatalogueConfig { ...(accentColor === undefined ? {} : { accentColor }), ...(categoryOrder === undefined ? {} : { categoryOrder }), ...(storyCategories === undefined ? {} : { storyCategories }), + ...(storyIds === undefined ? {} : { storyIds }), }; } diff --git a/packages/workspace/src/workspace.test.ts b/packages/workspace/src/workspace.test.ts index 8e972a2..acb3aac 100644 --- a/packages/workspace/src/workspace.test.ts +++ b/packages/workspace/src/workspace.test.ts @@ -88,6 +88,7 @@ describe("workspace lifecycle", () => { accentColor: "#7c3aed", categoryOrder: ["Journeys", "Reference"], storyCategories: { checkout: "Journeys" }, + storyIds: ["checkout"], }, }).catalogue).toEqual({ title: "Architecture journeys", @@ -95,6 +96,7 @@ describe("workspace lifecycle", () => { accentColor: "#7c3aed", categoryOrder: ["Journeys", "Reference"], storyCategories: { checkout: "Journeys" }, + storyIds: ["checkout"], }); }); @@ -105,6 +107,9 @@ describe("workspace lifecycle", () => { { catalogue: { storyCategories: { checkout: "" } }, error: "storyCategories" }, { catalogue: { explorer: { title: "Map" } }, error: "catalogue keys" }, { catalogue: { extra: true }, error: "catalogue keys" }, + { catalogue: { storyIds: ["checkout", "checkout"] }, error: "storyIds" }, + { catalogue: { storyIds: ["../checkout"] }, error: "storyIds" }, + { catalogue: { storyIds: "checkout" }, error: "storyIds" }, ])("rejects invalid catalogue config: $error", ({ catalogue, error }) => { expect(() => parseConfig({ schemaVersion: "1.0", diff --git a/scripts/lint.test.mjs b/scripts/lint.test.mjs index d6c289e..4a78c95 100644 --- a/scripts/lint.test.mjs +++ b/scripts/lint.test.mjs @@ -17,7 +17,7 @@ test("actual lint results cover the eligible tracked source inventory", async (c // Keep this expectation independent of ESLint's globs so broader ignores fail. const expected = [...tracked].filter((file) => /\.(?:[cm]?[jt]s|[jt]sx)$/.test(file) - && (!file.includes("/") || /^(packages|scripts|benchmarks|tools|distribution|examples)\//.test(file)) + && (!file.includes("/") || /^(packages|scripts|benchmarks|tools|distribution|examples|website)\//.test(file)) && !/(^|\/)(node_modules|\.topo|dist|build|coverage|playwright-report|test-results)\//.test(file) && !/^(benchmarks\/(results|\.generated)|packages\/schema\/src\/generated|packages\/[^/]+\/vendor)\//.test(file), ).sort(); @@ -46,6 +46,9 @@ test("correctness rules cover maintained source, tests, scripts and tooling", as "scripts/test-regression.test.mjs", "eslint.config.mjs", "tools/eslint-config/eslint.config.mjs", + "website/build.mjs", + "website/client.mjs", + "website/tests/site.spec.mjs", ]) { const [result] = await eslint.lintText("debugger;\n", { filePath }); assert.equal(result.errorCount, 1, filePath); diff --git a/stories/public/algorithm-anchor-resolution.topo.json b/stories/public/algorithm-anchor-resolution.topo.json new file mode 100644 index 0000000..ddedf06 --- /dev/null +++ b/stories/public/algorithm-anchor-resolution.topo.json @@ -0,0 +1,239 @@ +{ + "schemaVersion": "1.0", + "diagramFamily": "sequence", + "classification": "source-grounded", + "id": "algorithm-anchor-resolution", + "title": "Source-anchor resolution and freshness", + "category": "Core algorithms", + "parent": { + "storyId": "internal-modules", + "nodeId": "story" + }, + "summary": "The CLI story validator initiates this sequence to validate a draft against its current source. The diagram follows one anchor; resolution repeats for every anchor. Snapshot is a local reader/captured map, and Parser is local language lookup—not another service. Digest checks apply when a hash is supplied; symbol and snippet checks are optional according to the anchor. Rendering/publication are outside this draft-validation path.", + "anchors": [ + { + "id": "validate", + "path": "packages/cli/src/story-validation.ts", + "language": "typescript", + "symbol": "validateStory", + "sha256": "d6f60cad448f66c60c94f6a2f611f52617958a45c0e78eb5fad0e08285e1de58" + }, + { + "id": "capture", + "path": "packages/cli/src/source-snapshot.ts", + "language": "typescript", + "symbol": "captureSourceSnapshot", + "sha256": "5027a3c3ad3b16ebafd3eec698d5f5c9a8b1b211d2a8b71cf2d89dd53602feb6" + }, + { + "id": "stable-read", + "path": "packages/cli/src/source-snapshot.ts", + "language": "typescript", + "symbol": "readStableSource", + "sha256": "5027a3c3ad3b16ebafd3eec698d5f5c9a8b1b211d2a8b71cf2d89dd53602feb6" + }, + { + "id": "assert-snapshot", + "path": "packages/cli/src/source-snapshot.ts", + "language": "typescript", + "symbol": "assertSourceSnapshot", + "sha256": "5027a3c3ad3b16ebafd3eec698d5f5c9a8b1b211d2a8b71cf2d89dd53602feb6" + }, + { + "id": "resolve-document", + "path": "packages/story/src/index.ts", + "language": "typescript", + "symbol": "resolveStoryDocument", + "sha256": "1df6ad0e6be95db8727430ceca42e983ac093d93eed44d90fea083f98b95d965" + }, + { + "id": "resolve-anchor", + "path": "packages/story/src/index.ts", + "language": "typescript", + "symbol": "resolveAnchor", + "sha256": "1df6ad0e6be95db8727430ceca42e983ac093d93eed44d90fea083f98b95d965" + }, + { + "id": "symbol-range", + "path": "packages/story/src/index.ts", + "language": "typescript", + "symbol": "findSymbolRange", + "sha256": "1df6ad0e6be95db8727430ceca42e983ac093d93eed44d90fea083f98b95d965" + }, + { + "id": "rust-symbol", + "path": "packages/languages/src/index.ts", + "language": "typescript", + "symbol": "resolveRustSymbol", + "sha256": "03fb7ff8ece428bf9279a4360735a3dcf6d0e871cb5c3c8684f627dc1aab7592" + }, + { + "id": "story-manifest", + "path": "packages/story/package.json", + "language": "text", + "sha256": "996dc365b6c0bcdc3c4beaddb507c657cf97ee0412232c110f081013e0f7cfde" + } + ], + "sections": [ + { + "id": "caller", + "title": "Story validator", + "semanticRole": "story-validation", + "body": "The CLI's validateStory operation, invoked by topo story validate, needs to establish whether a draft's anchors still identify current code. It checks the draft structure, captures referenced files, delegates anchor resolution, then rechecks bytes and Git state before returning the resolved document.\n\nThis is draft validation, not rendering or publication. These are explicit checkpoints, not a continuously held source-code lock. Valid anchors do not establish the explanation's semantic truth.", + "anchorIds": [ + "validate" + ] + }, + { + "id": "snapshot", + "title": "Source snapshot", + "semanticRole": "source-snapshot", + "body": "captureSourceSnapshot deduplicates and sorts paths, then reads regular files with path, symlink, inode and modification checks. The captured map provides bytes (or absence) to the resolver.\n\nassertSourceSnapshot rereads and compares those bytes. Source changing during capture or after capture causes an explicit error. The reader/map are grouped as a data boundary, not a network service.", + "anchorIds": [ + "capture", + "stable-read", + "assert-snapshot" + ] + }, + { + "id": "resolver", + "title": "Anchor resolver", + "semanticRole": "evidence-resolution", + "body": "resolveStoryDocument checks each path and refuses absent source. resolveAnchor checks a supplied whole-file SHA-256 BEFORE parsing, establishes a file or symbol scope, then finds the exact authored pattern and derives current lines/excerpts.\n\nUnscoped patterns must be unique. Missing symbols/patterns and stale hashes are errors. There is no fuzzy matching or automatic repair of renamed/moved code. Without a pattern, the selected file/symbol range is returned.", + "anchorIds": [ + "resolve-document", + "resolve-anchor", + "story-manifest" + ] + }, + { + "id": "parser", + "title": "Language lookup", + "semanticRole": "language-lookup", + "body": "TypeScript/JavaScript anchors use an AST walk for the first declaration with the requested identifier; this is not the full type-checker resolution used by scanning. Rust delegates to its lexical/parser-backed symbol resolver. Text anchors do not accept symbol lookup.\n\nThe parser returns syntax/range information. Exact snippet matching and final source locations belong to the anchor resolver.", + "anchorIds": [ + "resolve-anchor", + "symbol-range", + "rust-symbol" + ] + } + ], + "connections": [ + { + "from": "caller", + "to": "snapshot", + "label": "Capture draft evidence", + "anchorIds": [ + "validate", + "capture" + ], + "rationale": "The story validator captures the draft's referenced source so all of its anchors can be checked against one consistent set of bytes.", + "classification": "source-traced" + }, + { + "from": "snapshot", + "to": "caller", + "label": "Captured bytes or read error", + "anchorIds": [ + "capture", + "stable-read" + ], + "rationale": "Return a stable map; invalid/unstable paths throw. Missing files are represented as absent until resolution rejects them.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "caller", + "to": "resolver", + "label": "Validate anchors against the snapshot", + "anchorIds": [ + "validate", + "resolve-document" + ], + "rationale": "validateStory supplies the captured-map loader to resolveStoryDocument, preventing different anchors from silently reading different snapshots.", + "classification": "source-traced" + }, + { + "from": "resolver", + "to": "snapshot", + "label": "Load this anchor's file", + "anchorIds": [ + "resolve-document", + "validate" + ], + "rationale": "resolveStoryDocument invokes the supplied loader for each anchor. This is a local map read.", + "classification": "source-traced" + }, + { + "from": "snapshot", + "to": "resolver", + "label": "Source bytes or absence", + "anchorIds": [ + "resolve-document" + ], + "rationale": "Absent source is rejected as missing-file before resolveAnchor proceeds.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "resolver", + "to": "parser", + "label": "If hash passes: parse and scope", + "anchorIds": [ + "resolve-anchor", + "symbol-range", + "rust-symbol" + ], + "rationale": "A supplied digest is checked first. Parse the source and locate the requested symbol when present; otherwise retain whole-file scope.", + "classification": "source-traced" + }, + { + "from": "parser", + "to": "resolver", + "label": "Syntax and optional symbol range", + "anchorIds": [ + "resolve-anchor", + "symbol-range", + "rust-symbol" + ], + "rationale": "The resolver applies the exact pattern inside that scope and derives the resulting excerpt and line positions.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "resolver", + "to": "caller", + "label": "Resolved anchors or explicit refusal", + "anchorIds": [ + "resolve-document", + "resolve-anchor" + ], + "rationale": "Success returns resolved evidence; hash/symbol/pattern failures throw rather than manufacturing an anchor.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "caller", + "to": "snapshot", + "label": "Confirm draft evidence is current", + "anchorIds": [ + "validate", + "assert-snapshot" + ], + "rationale": "After resolution, validateStory rereads the captured paths, then compares repository revision, dirty state and fingerprint before returning.", + "classification": "source-traced" + }, + { + "from": "snapshot", + "to": "caller", + "label": "Unchanged source or stale error", + "anchorIds": [ + "assert-snapshot", + "validate" + ], + "rationale": "Changed bytes refuse validation; the validator also rejects changed Git state. This operation does not publish output.", + "classification": "source-traced", + "variant": "return" + } + ] +} diff --git a/stories/public/algorithm-evidence-extraction.topo.json b/stories/public/algorithm-evidence-extraction.topo.json new file mode 100644 index 0000000..509baf0 --- /dev/null +++ b/stories/public/algorithm-evidence-extraction.topo.json @@ -0,0 +1,240 @@ +{ + "schemaVersion": "1.0", + "diagramFamily": "sequence", + "classification": "source-grounded", + "id": "algorithm-evidence-extraction", + "title": "Compiler-backed evidence extraction", + "category": "Core algorithms", + "parent": { + "storyId": "internal-modules", + "nodeId": "scanner" + }, + "summary": "The TypeScript/JavaScript scan path: repository inputs become a deterministic file/import graph and compiler-backed semantic facts. Lifelines are local code/API boundaries, not separate services. Repeated per-file/import/declaration work is compressed into single exchanges. Failures stop the path unless explicitly permitted partial evidence is returned. This does not infer the right conceptual architecture or runtime behavior.", + "anchors": [ + { + "id": "composition", + "path": "packages/languages/src/index.ts", + "language": "typescript", + "symbol": "scanProject", + "sha256": "03fb7ff8ece428bf9279a4360735a3dcf6d0e871cb5c3c8684f627dc1aab7592" + }, + { + "id": "scan", + "path": "packages/scanner/src/typescript-scanner.ts", + "language": "typescript", + "symbol": "scanRepository", + "sha256": "7c51e70b264d3ff387404dda119f7aef4a30b12881ee3699fe4b5a21d2008ce8" + }, + { + "id": "configured", + "path": "packages/scanner/src/typescript-scanner.ts", + "language": "typescript", + "symbol": "loadConfiguredSources", + "sha256": "7c51e70b264d3ff387404dda119f7aef4a30b12881ee3699fe4b5a21d2008ce8" + }, + { + "id": "source-record", + "path": "packages/scanner/src/typescript-scanner.ts", + "language": "typescript", + "symbol": "createSourceRecord", + "sha256": "7c51e70b264d3ff387404dda119f7aef4a30b12881ee3699fe4b5a21d2008ce8" + }, + { + "id": "workspace-resolution", + "path": "packages/scanner/src/typescript-scanner.ts", + "language": "typescript", + "symbol": "resolveWorkspaceModuleName", + "sha256": "7c51e70b264d3ff387404dda119f7aef4a30b12881ee3699fe4b5a21d2008ce8" + }, + { + "id": "semantic", + "path": "packages/scanner/src/semantic.ts", + "language": "typescript", + "symbol": "extractLogicalArchitecture", + "sha256": "ff530e01801814e92abbf2b9bff7f4a30b4b03104e6ef13c893f07b877d26571" + }, + { + "id": "canonical-symbol", + "path": "packages/scanner/src/semantic.ts", + "language": "typescript", + "symbol": "canonicalSymbol", + "sha256": "ff530e01801814e92abbf2b9bff7f4a30b4b03104e6ef13c893f07b877d26571" + }, + { + "id": "relationship-kind", + "path": "packages/scanner/src/semantic.ts", + "language": "typescript", + "symbol": "relationshipKind", + "sha256": "ff530e01801814e92abbf2b9bff7f4a30b4b03104e6ef13c893f07b877d26571" + }, + { + "id": "scanner-manifest", + "path": "packages/scanner/package.json", + "language": "text", + "sha256": "3027a4fa118d19cd7fa2b165b728a642582b0f5e43d986a595ff25f276bfee48" + } + ], + "sections": [ + { + "id": "caller", + "title": "@topo/languages", + "semanticRole": "language-composition", + "body": "scanProject owns language-capability composition. It requests TypeScript/JavaScript code evidence from the selected scanner adapter so it can build the repository's analysis result. This is the real initiating module, not an unspecified caller.\n\nThe returned graphs, diagnostics, metrics and authoritative/partial flag feed that composition. Separate Rust/Tauri adapters are outside this view. No model is invoked.", + "anchorIds": [ + "composition", + "scan" + ] + }, + { + "id": "scanner", + "title": "Scanner", + "semanticRole": "evidence-extraction", + "body": "scanRepository inventories files, compiler configs and workspaces; captures source text/fingerprints; and resolves imports. Topocode maps compiler-selected outputs to source, distinguishes local/workspace/external/assets, consolidates duplicate import evidence, sorts canonical output, and applies quality gates before the semantic pass.\n\nUnresolved local/workspace imports are diagnostics, not guessed edges. Strict failure stops the scan; explicitly allowed partial output remains marked partial. The scanner returns evidence, not a finished architecture narrative.", + "anchorIds": [ + "scan", + "configured", + "source-record", + "workspace-resolution", + "scanner-manifest" + ] + }, + { + "id": "compiler", + "title": "TypeScript API", + "semanticRole": "compiler-api", + "body": "In-process compiler APIs supply parsed configuration, syntax trees, module resolution and type/symbol information. The scanner's workspace-aware host and source mappings constrain how those results are used. TypeScript does not classify Topocode's graph quality or invent responsibility groups.", + "anchorIds": [ + "configured", + "source-record", + "workspace-resolution", + "semantic" + ] + }, + { + "id": "semantic", + "title": "Semantic pass", + "semanticRole": "semantic-extraction", + "body": "extractLogicalArchitecture builds a compiler program using per-file options and already-resolved import mappings. It canonicalizes aliases, identifies declarations, signatures and members, then walks identifiers to record static relationships and their locations.\n\nResponsibility assignments come from an explicit proposal, not automatic architectural inference. Missing proposals and unassigned entities stay visible. Static references are not runtime reachability.", + "anchorIds": [ + "semantic", + "canonical-symbol", + "relationship-kind" + ] + } + ], + "connections": [ + { + "from": "caller", + "to": "scanner", + "label": "Extract code evidence", + "anchorIds": [ + "composition", + "scan" + ], + "rationale": "@topo/languages.scanProject requests TypeScript/JavaScript evidence through the scanner adapter; scanRepository parses and validates the supplied repository and options.", + "classification": "source-traced" + }, + { + "from": "scanner", + "to": "compiler", + "label": "Parse configs and source files", + "anchorIds": [ + "configured", + "source-record" + ], + "rationale": "Configured source loading and source-record construction use TypeScript configuration and parsing APIs.", + "classification": "source-traced" + }, + { + "from": "compiler", + "to": "scanner", + "label": "Compiler options and syntax trees", + "anchorIds": [ + "configured", + "source-record" + ], + "rationale": "Compiler results feed Topocode source records; file fingerprints and evidence are assembled by Topocode.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "scanner", + "to": "compiler", + "label": "Resolve imports and workspace exports", + "anchorIds": [ + "scan", + "workspace-resolution" + ], + "rationale": "For each import, use compiler resolution and the supported workspace-aware resolution path where applicable.", + "classification": "source-traced" + }, + { + "from": "compiler", + "to": "scanner", + "label": "Resolved target or missing result", + "anchorIds": [ + "scan", + "workspace-resolution" + ], + "rationale": "Topocode classifies the returned target, maps generated outputs to source where unambiguous, and records diagnostics for unresolved local/workspace imports.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "scanner", + "to": "semantic", + "label": "Quality-gated graph and source set", + "anchorIds": [ + "scan", + "semantic" + ], + "rationale": "After constructing and validating canonical file/import evidence and applying strict/partial quality gates, scanRepository invokes extractLogicalArchitecture.", + "classification": "source-traced" + }, + { + "from": "semantic", + "to": "compiler", + "label": "Build program; query symbols", + "anchorIds": [ + "semantic", + "canonical-symbol" + ], + "rationale": "The semantic pass creates a program/checker and queries exports, declarations, types, aliases and identifier targets.", + "classification": "source-traced" + }, + { + "from": "compiler", + "to": "semantic", + "label": "Declarations and symbol resolutions", + "anchorIds": [ + "semantic", + "relationship-kind" + ], + "rationale": "Topocode turns compiler facts into stable semantic entities and static relationships with source locations.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "semantic", + "to": "scanner", + "label": "Semantic facts and assignment status", + "anchorIds": [ + "semantic" + ], + "rationale": "Return the logical-architecture document, including explicit proposed/unassigned responsibility information and diagnostics.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "scanner", + "to": "caller", + "label": "Graphs, diagnostics and quality", + "anchorIds": [ + "scan" + ], + "rationale": "Return ScanResult. A refused scan throws instead; partial evidence never becomes an authoritative success claim.", + "classification": "source-traced", + "variant": "return" + } + ] +} diff --git a/stories/public/algorithm-graph-projection.topo.json b/stories/public/algorithm-graph-projection.topo.json new file mode 100644 index 0000000..eb168b5 --- /dev/null +++ b/stories/public/algorithm-graph-projection.topo.json @@ -0,0 +1,264 @@ +{ + "schemaVersion": "1.0", + "diagramFamily": "sequence", + "classification": "source-grounded", + "id": "algorithm-graph-projection", + "title": "Graph projection and edge aggregation", + "category": "Core algorithms", + "parent": { + "storyId": "internal-modules", + "nodeId": "graph" + }, + "summary": "The @topo/graph layout session requests a projection because it needs the visible graph before placing nodes. Local code and indexed data reduce the view while retaining evidence membership. Directory/cycle derivation is an input preparation step, not rerun by every projection. Coordinate placement follows the returned projection and is outside this diagram. This is not Archify/Graphviz layout, the separate Repository page index, or the hand-curated module map.", + "anchors": [ + { + "id": "session-client", + "path": "packages/graph/src/layout.ts", + "language": "typescript", + "symbol": "createLayoutSession", + "sha256": "73c8e21e141dac10322d72934688ff2628ef6fc779e4c87a4f17e66c95e59954" + }, + { + "id": "one-shot-client", + "path": "packages/graph/src/layout.ts", + "language": "typescript", + "symbol": "layoutGraphWithArchitecture", + "sha256": "73c8e21e141dac10322d72934688ff2628ef6fc779e4c87a4f17e66c95e59954" + }, + { + "id": "session", + "path": "packages/graph/src/project.ts", + "language": "typescript", + "symbol": "createProjectionSession", + "sha256": "be3c37761d187a6101a7af56e8cabe35155067f616fd1e5f55a35d43b0e65638" + }, + { + "id": "index", + "path": "packages/graph/src/project.ts", + "language": "typescript", + "symbol": "indexGraph", + "sha256": "be3c37761d187a6101a7af56e8cabe35155067f616fd1e5f55a35d43b0e65638" + }, + { + "id": "project", + "path": "packages/graph/src/project.ts", + "language": "typescript", + "symbol": "projectIndexedGraph", + "sha256": "be3c37761d187a6101a7af56e8cabe35155067f616fd1e5f55a35d43b0e65638" + }, + { + "id": "one-shot", + "path": "packages/graph/src/project.ts", + "language": "typescript", + "symbol": "projectGraph", + "sha256": "be3c37761d187a6101a7af56e8cabe35155067f616fd1e5f55a35d43b0e65638" + }, + { + "id": "options", + "path": "packages/graph/src/project.ts", + "language": "typescript", + "symbol": "validateOptions", + "sha256": "be3c37761d187a6101a7af56e8cabe35155067f616fd1e5f55a35d43b0e65638" + }, + { + "id": "aggregate", + "path": "packages/graph/src/derive.ts", + "language": "typescript", + "symbol": "aggregateDirectedEdges", + "sha256": "a5f4bf3d7ace95b095d27cefa8d6237a030d5e626bb24d68f8f7aac25b17ea11" + }, + { + "id": "derive", + "path": "packages/graph/src/derive.ts", + "language": "typescript", + "symbol": "deriveArchitecture", + "sha256": "a5f4bf3d7ace95b095d27cefa8d6237a030d5e626bb24d68f8f7aac25b17ea11" + }, + { + "id": "coverage-policy", + "path": "packages/graph/src/derive.ts", + "language": "typescript", + "symbol": "SPARSE_EDGE_COVERAGE", + "sha256": "a5f4bf3d7ace95b095d27cefa8d6237a030d5e626bb24d68f8f7aac25b17ea11" + }, + { + "id": "cycles", + "path": "packages/graph/src/derive.ts", + "language": "typescript", + "symbol": "stronglyConnectedSets", + "sha256": "a5f4bf3d7ace95b095d27cefa8d6237a030d5e626bb24d68f8f7aac25b17ea11" + }, + { + "id": "graph-manifest", + "path": "packages/graph/package.json", + "language": "text", + "sha256": "4ca3e7b8842834077417e360037ebd9281333d5ea3f9d0c197f65367bb1ab7c1" + } + ], + "sections": [ + { + "id": "caller", + "title": "Layout session", + "semanticRole": "layout-session", + "body": "@topo/graph.createLayoutSession prepares the view data needed to place nodes. It creates a projection session once, then calls session.project(options) for each layout request. The returned visible entities and relationships are passed to layoutProjection to compute coordinates.\n\nThis diagram shows that initiating layout unit asking for membership and relationships, not the downstream coordinate-placement algorithm. The one-shot layoutGraphWithArchitecture path uses the same projection core without retaining a session.", + "anchorIds": [ + "session-client", + "one-shot-client", + "one-shot" + ] + }, + { + "id": "index", + "title": "Indexed snapshot", + "semanticRole": "projection-index", + "body": "createProjectionSession copies the fields needed for projection, validates graph/architecture identity, and indexes nodes, directory ancestors, cycle groups and spine-edge IDs. The returned session closes over that index and exposes a frozen graph reference.\n\nThe architecture input was prepared earlier by deriveArchitecture. Its cycle grouping uses Tarjan-style strongly connected components; that detection is not called anew for every expand/collapse request.", + "anchorIds": [ + "session", + "index", + "derive", + "cycles", + "graph-manifest" + ] + }, + { + "id": "projection", + "title": "Projection", + "semanticRole": "graph-projection", + "body": "projectIndexedGraph validates options and requested member/cycle IDs. For each included node, choose its collapsed cycle representative, otherwise its first closed directory ancestor, otherwise itself. External exclusions are explicit.\n\nBuild visible entities and containers, ask for directed aggregates, and separately account for original edges whose endpoints collapse inside the same visible group. IDs/order remain stable for the same inputs and options.", + "anchorIds": [ + "project", + "options" + ] + }, + { + "id": "aggregation", + "title": "Edge aggregation", + "semanticRole": "edge-aggregation", + "body": "aggregateDirectedEdges maps every original edge through the representative map, groups equal directed endpoint pairs, and retains original edge IDs, directions, types and weights. Opposite directions remain distinct. Same-representative edges are accounted for by Projection instead of drawn as misleading cross-group arrows.\n\nOptional sparse selection retains weighted coverage plus spine edges; the default policy is 83% of represented edge weight, not 83% of nodes. It is not a minimum spanning tree or automatic community/architecture discovery.", + "anchorIds": [ + "aggregate", + "derive", + "project", + "coverage-policy" + ] + } + ], + "connections": [ + { + "from": "caller", + "to": "index", + "label": "Prepare a graph for layout", + "anchorIds": [ + "session-client", + "session" + ], + "rationale": "createLayoutSession supplies graph and derived architecture to createProjectionSession so repeated layout requests can reuse indexed evidence.", + "classification": "source-traced" + }, + { + "from": "index", + "to": "caller", + "label": "Reusable projection session", + "anchorIds": [ + "session", + "index" + ], + "rationale": "The session captures its projection index and returns graphRef plus project(options).", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "caller", + "to": "projection", + "label": "Select the visible graph", + "anchorIds": [ + "session-client", + "session", + "project" + ], + "rationale": "The layout request passes scope and collapse options through session.project to obtain the graph that should be placed.", + "classification": "source-traced" + }, + { + "from": "projection", + "to": "index", + "label": "Read nodes, ancestors and cycles", + "anchorIds": [ + "project", + "index" + ], + "rationale": "The projection reads local indexed maps; this arrow is a data dependency, not a service call.", + "classification": "source-traced" + }, + { + "from": "index", + "to": "projection", + "label": "Indexed membership and hierarchy", + "anchorIds": [ + "index", + "project" + ], + "rationale": "Use those maps to choose a visible representative for each included node.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "projection", + "to": "aggregation", + "label": "Original edges + representatives", + "anchorIds": [ + "project", + "aggregate" + ], + "rationale": "aggregateDirectedEdges receives original edges, the representative map, spine IDs and the sparse coverage policy.", + "classification": "source-traced" + }, + { + "from": "aggregation", + "to": "projection", + "label": "Directed aggregates + provenance", + "anchorIds": [ + "aggregate", + "project" + ], + "rationale": "Return weighted, deterministically ordered aggregates. sparseEdgesOnly is applied by the projection when requested.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "projection", + "to": "caller", + "label": "Visible view + hidden-edge accounting", + "anchorIds": [ + "project" + ], + "rationale": "Return GraphProjection with visible entities/containers/edges and explicit collapsed-edge and excluded-external accounting.", + "classification": "source-traced", + "variant": "return" + }, + { + "from": "caller", + "to": "projection", + "label": "Reproject after scope changes", + "anchorIds": [ + "session", + "session-client" + ], + "rationale": "Another layout request can project a different scope/collapse option set over the same indexed input.", + "classification": "source-traced" + }, + { + "from": "projection", + "to": "caller", + "label": "Updated inputs for node placement", + "anchorIds": [ + "session-client", + "session", + "project" + ], + "rationale": "Return a new visible view with provenance to the same source graph. The layout session then uses it for coordinate placement; refresh the session for new source evidence.", + "classification": "source-traced", + "variant": "return" + } + ] +} diff --git a/stories/public/cli-surface.topo.json b/stories/public/cli-surface.topo.json new file mode 100644 index 0000000..59b9d41 --- /dev/null +++ b/stories/public/cli-surface.topo.json @@ -0,0 +1,379 @@ +{ + "schemaVersion": "1.0", + "diagramFamily": "architecture", + "classification": "source-grounded", + "id": "cli-surface", + "title": "@topo/cli: public surface", + "category": "Module surfaces", + "parent": { + "storyId": "internal-modules", + "nodeId": "cli" + }, + "summary": "The command interface and five modules re-exported by @topo/cli's package root. Arrows mean bin/export/type/dependency references, not a call sequence. This is a private workspace boundary bundled into @jdylanmc/topo-code, not a separately published or stable public SDK. Implementation helpers are deliberately omitted. Unlabelled spokes from the package box to API/utility boxes mean root exports; labelled edges distinguish other references.", + "anchors": [ + { + "id": "cli-manifest", + "path": "packages/cli/package.json", + "language": "text", + "sha256": "e1aaebf5b0fe115fe56a658b71022c849e25120794cdbd1b063ccda97c880086" + }, + { + "id": "cli-entry", + "path": "packages/cli/src/index.ts", + "language": "text", + "sha256": "d05f2184becf9a468e04fc3ca8945f277001108c67de0f1ff33c562972e5c28d" + }, + { + "id": "renderer-manifest", + "path": "packages/diagram-core/package.json", + "language": "text", + "sha256": "8e4b7a111ad4234367bc49e0b7b4827e880f9d489ce136a79650923b86cd7386" + }, + { + "id": "story-manifest", + "path": "packages/story/package.json", + "language": "text", + "sha256": "996dc365b6c0bcdc3c4beaddb507c657cf97ee0412232c110f081013e0f7cfde" + }, + { + "id": "commands", + "path": "packages/cli/src/main.ts", + "language": "text", + "sha256": "777350607d51e97214906d4106025f8b8d50200dfee93703e5ff16d22f3ed767", + "pattern": "HELP = `Topocode: local, deterministic repository maps\n\n topo init [repository] [--skills]\n topo scan [repository] [--allow-partial] [--responsibilities path]\n topo ingest [more.json ...]\n topo enrich [repository]\n topo preview \n topo story validate \n topo story preview \n topo serve [repository] [--port 4173]\n topo bundle [repository] [--output directory] [--base-path /path/]\n\nRequires a Git repository and Node.js 22 or newer.\nScan is strict by default. --allow-partial publishes a visibly incomplete\npreview and exits 2; it never turns partial evidence into success.\nServe binds only to 127.0.0.1. Config and authored metadata are never overwritten.\nInit creates a ready-to-serve diagram home without scanning or opening a browser.\nScan adds repository exploration; story preview refreshes all committed stories.\n`" + }, + { + "id": "generate", + "path": "packages/cli/src/pipeline.ts", + "language": "text", + "sha256": "b6b9d1952ea8dcbfec2c5e8f5fcdb5ee8e94ed6ad2f50bf45550e6a491cc9077", + "pattern": "export async function generateArtifacts(\n root: string,\n graph: GraphDocument,\n siteAssets: string,\n logicalArchitecture?: LogicalArchitectureDocument,\n catalogue?: BuiltCatalogue,\n): Promise {" + }, + { + "id": "generation-result", + "path": "packages/cli/src/pipeline.ts", + "language": "text", + "sha256": "b6b9d1952ea8dcbfec2c5e8f5fcdb5ee8e94ed6ad2f50bf45550e6a491cc9077", + "pattern": "export interface ArtifactGenerationResult {\n layout: LayoutResult;\n dashboard: DashboardDocument | null;\n warnings: string[];\n}" + }, + { + "id": "ingest", + "path": "packages/cli/src/pipeline.ts", + "language": "text", + "sha256": "b6b9d1952ea8dcbfec2c5e8f5fcdb5ee8e94ed6ad2f50bf45550e6a491cc9077", + "pattern": "export async function ingestReports(\n root: string,\n inputPaths: string[],\n siteAssets: string,\n expectedRevision?: string,\n catalogue?: BuiltCatalogue,\n): Promise {" + }, + { + "id": "ingest-result", + "path": "packages/cli/src/pipeline.ts", + "language": "text", + "sha256": "b6b9d1952ea8dcbfec2c5e8f5fcdb5ee8e94ed6ad2f50bf45550e6a491cc9077", + "pattern": "export interface ReportIngestionResult {\n dashboard: DashboardDocument;\n warnings: string[];\n}" + }, + { + "id": "serve", + "path": "packages/cli/src/server.ts", + "language": "text", + "sha256": "559e9541d7b2edb97785d6a85a4b43bbc815c80e7341c6e8bad4a5cc55ef74cc", + "pattern": "export async function serveSite(root: string, port = 4173): Promise<{ server: Server; url: string }> {" + }, + { + "id": "compose", + "path": "packages/cli/src/server.ts", + "language": "text", + "sha256": "559e9541d7b2edb97785d6a85a4b43bbc815c80e7341c6e8bad4a5cc55ef74cc", + "pattern": "export async function composeSiteData(\n root: string,\n input: unknown,\n): Promise {" + }, + { + "id": "bundle", + "path": "packages/cli/src/bundle.ts", + "language": "text", + "sha256": "9c5a44ea81e049ae47eb0e5fa87a47133613b08ff3cec037c6d735e3e38015a9", + "pattern": "export async function bundleSite(\n rootInput: string,\n outputInput: string,\n options: BundleSiteOptions = {},\n): Promise {" + }, + { + "id": "bundle-options", + "path": "packages/cli/src/bundle.ts", + "language": "text", + "sha256": "9c5a44ea81e049ae47eb0e5fa87a47133613b08ff3cec037c6d735e3e38015a9", + "pattern": "export interface BundleSiteOptions {\n readonly basePath?: string;\n}" + }, + { + "id": "bundle-result", + "path": "packages/cli/src/bundle.ts", + "language": "text", + "sha256": "9c5a44ea81e049ae47eb0e5fa87a47133613b08ff3cec037c6d735e3e38015a9", + "pattern": "export interface BundleSiteResult {\n readonly basePath: string;\n readonly outputDirectory: string;\n readonly siteDirectory: string;\n}" + }, + { + "id": "enrich", + "path": "packages/cli/src/enrichment.ts", + "language": "text", + "sha256": "44de5f5ab2fdefaa1c08e89143489552e5f5019cac3d4f7bb0a096f7f90e09d4", + "pattern": "export async function runEnrichment(\n root: string,\n options: EnrichmentRunOptions = {},\n): Promise {" + }, + { + "id": "enrich-prompt", + "path": "packages/cli/src/enrichment.ts", + "language": "text", + "sha256": "44de5f5ab2fdefaa1c08e89143489552e5f5019cac3d4f7bb0a096f7f90e09d4", + "pattern": "export function buildEnrichmentPrompt(\n inputPath: string,\n outputPath: string,\n analysisHash: string,\n customPrompt?: string,\n): string {" + }, + { + "id": "enrich-options", + "path": "packages/cli/src/enrichment.ts", + "language": "text", + "sha256": "44de5f5ab2fdefaa1c08e89143489552e5f5019cac3d4f7bb0a096f7f90e09d4", + "pattern": "export interface EnrichmentRunOptions {\n signal?: AbortSignal;\n}" + }, + { + "id": "enrich-result", + "path": "packages/cli/src/enrichment.ts", + "language": "text", + "sha256": "44de5f5ab2fdefaa1c08e89143489552e5f5019cac3d4f7bb0a096f7f90e09d4", + "pattern": "export interface EnrichmentRunResult {\n analysisHash: string;\n comments: number;\n}" + }, + { + "id": "view-build", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export async function buildCuratedViews(\n root: string,\n graph: GraphDocument,\n): Promise {" + }, + { + "id": "view-save", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export async function saveCuratedView(\n root: string,\n request: SaveCuratedViewRequest,\n loadGraph: () => Promise,\n): Promise {" + }, + { + "id": "view-result", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export interface CuratedViewsBuild {\n snapshot: CuratedViewsSnapshot;\n evaluations: Array<{\n id: string;\n evaluation: CuratedViewEvaluation;\n }>;\n}" + }, + { + "id": "view-parse", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export function parseSaveCuratedViewRequest(input: unknown): SaveCuratedViewRequest {" + }, + { + "id": "view-hash", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export function graphHash(graph: GraphDocument): string {" + }, + { + "id": "view-snapshot", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export function serializeCuratedViewsSnapshot(snapshot: CuratedViewsSnapshot): string {" + }, + { + "id": "view-deltas", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export function serializeCuratedViewDeltas(build: CuratedViewsBuild): string {" + }, + { + "id": "view-extract", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export function graphFromSiteBundle(input: unknown): GraphDocument {" + }, + { + "id": "view-augment", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export function augmentSiteBundle(input: unknown, snapshot: CuratedViewsSnapshot): string {" + }, + { + "id": "view-conflict", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export class CuratedViewConflictError extends Error {}" + }, + { + "id": "view-metadata", + "path": "packages/cli/src/views.ts", + "language": "text", + "sha256": "03d66cbba1d8436bdb263a7cf6dbf6e014a0138a97cf9bc4e01ca94f7fd967da", + "pattern": "export class CuratedViewMetadataError extends Error {}" + } + ], + "sections": [ + { + "id": "commands", + "title": "topo commands", + "summary": "Human and agent entry", + "body": "The manifest exposes topo -> dist/main.js.\n\nCommands: init, scan, story validate, story preview (and preview), serve, bundle, ingest, enrich.\n\nInputs: repository paths, authored stories, report files, and documented options. Outputs: diagnostics, generated storybook files, local URLs, and static bundles. scan supplies deterministic evidence; it does not invoke a model. runCli is exported by main.ts but is NOT re-exported from the package root.", + "anchorIds": [ + "cli-manifest", + "commands" + ], + "semanticRole": "command-interface" + }, + { + "id": "generation", + "title": "Generation API", + "summary": "generateArtifacts / ingestReports", + "body": "Root exports from pipeline.ts:\n\ngenerateArtifacts(root, graph, siteAssets, logicalArchitecture?, catalogue?) -> Promise\ningestReports(root, inputPaths, siteAssets, expectedRevision?, catalogue?) -> Promise\n\nArtifactGenerationResult: layout, optional dashboard, warnings.\nReportIngestionResult: dashboard, warnings.\n\nGeneration takes an already-supplied GraphDocument; do not confuse this API with the topo scan command. Referenced contracts include @topo/schema, @topo/graph and @topo/reports. BuiltCatalogue appears in signatures but is not itself a root re-export.", + "anchorIds": [ + "cli-entry", + "generate", + "generation-result", + "ingest", + "ingest-result" + ], + "semanticRole": "public-interface" + }, + { + "id": "contracts", + "title": "Referenced contracts", + "summary": "Types, not re-exports", + "body": "The exposed functions reference GraphDocument and LogicalArchitectureDocument (@topo/schema), LayoutResult (@topo/graph), DashboardDocument (@topo/reports), CuratedViewsSnapshot / SaveCuratedViewRequest (@topo/views), Node's Server, and AbortSignal.\n\nThese are signature dependencies, not claims that @topo/cli re-exports all those types. Named result/option interfaces defined in the five exported modules are root exports.", + "anchorIds": [ + "generate", + "generation-result", + "ingest-result", + "view-save", + "view-result", + "serve", + "enrich-options" + ], + "semanticRole": "data-contract" + }, + { + "id": "serving", + "title": "Serving API", + "summary": "serveSite / composeSiteData", + "body": "Root exports from server.ts:\n\nserveSite(root, port?) -> Promise<{ server: Server; url: string }>\ncomposeSiteData(root, input) -> Promise\n\nserveSite exposes a loopback HTTP server over the generated site; it does not author architecture. composeSiteData composes site data for consumers. Source-backed diagrams and website assets remain separate from these function signatures.", + "anchorIds": [ + "cli-entry", + "serve", + "compose" + ], + "semanticRole": "public-interface" + }, + { + "id": "cli", + "title": "@topo/cli", + "summary": "Exports the API groups", + "body": "Two entry surfaces: the topo binary and the package-root index.ts barrel. The barrel re-exports server, bundle, pipeline, enrichment, and views.\n\nDeclared runtime module references:\n@topo/diagram-core: workspace:*\n@topo/enrichment: workspace:*\n@topo/graph: workspace:*\n@topo/languages: workspace:*\n@topo/modules: workspace:*\n@topo/reports: workspace:*\n@topo/scanner: workspace:*\n@topo/schema: workspace:*\n@topo/site: workspace:*\n@topo/story: workspace:*\n@topo/views: workspace:*\n@topo/workspace: workspace:*\n\nThe diagram singles out diagram-core so you can continue into its exposed rendering contract. Catalogue, snapshot, skills, and repository-generation helpers are not root exports and are not expanded here.", + "anchorIds": [ + "cli-manifest", + "cli-entry" + ], + "semanticRole": "module-boundary" + }, + { + "id": "bundling", + "title": "Bundling API", + "summary": "bundleSite", + "body": "Root exports from bundle.ts:\n\nbundleSite(rootInput, outputInput, options?) -> Promise\nBundleSiteOptions: optional basePath.\nBundleSiteResult: basePath, outputDirectory, siteDirectory.\n\nProduces a static site directory. Deployment, a domain, and publication approval are not implied by this API.", + "anchorIds": [ + "cli-entry", + "bundle", + "bundle-options", + "bundle-result" + ], + "semanticRole": "public-interface" + }, + { + "id": "enrichment", + "title": "Enrichment API", + "summary": "runEnrichment", + "body": "Root exports from enrichment.ts:\n\nrunEnrichment(root, options?) -> Promise\nbuildEnrichmentPrompt(inputPath, outputPath, analysisHash, customPrompt?) -> string\nEnrichmentRunOptions: optional AbortSignal.\nEnrichmentRunResult: analysisHash and comments count.\n\nThis is the explicit configured provider-command workflow. It is not automatically called by scan, and it is not the same thing as an agent independently interpreting evidence while authoring a story.", + "anchorIds": [ + "cli-entry", + "enrich", + "enrich-prompt", + "enrich-options", + "enrich-result" + ], + "semanticRole": "public-interface" + }, + { + "id": "views", + "title": "Curated-view API", + "summary": "buildCuratedViews / saveCuratedView", + "body": "Root exports from views.ts:\n\nbuildCuratedViews; saveCuratedView; graphHash; parseSaveCuratedViewRequest;\nserializeCuratedViewsSnapshot; serializeCuratedViewDeltas;\ngraphFromSiteBundle; augmentSiteBundle.\n\nContracts: CuratedViewsBuild, CuratedViewConflictError, CuratedViewMetadataError. Save requests and returned snapshots use @topo/views types; graph inputs use @topo/schema.\n\nThis is the exposed path-based curated-view surface, not arbitrary diagram authoring or a private implementation map.", + "anchorIds": [ + "cli-entry", + "view-build", + "view-save", + "view-result", + "view-parse", + "view-hash", + "view-snapshot", + "view-deltas", + "view-extract", + "view-augment", + "view-conflict", + "view-metadata" + ], + "semanticRole": "public-interface" + }, + { + "id": "diagram-core", + "title": "@topo/diagram-core", + "summary": "Rendering dependency", + "body": "A declared workspace dependency of @topo/cli. It exposes renderers that consume resolved stories and return HTML artifacts with provenance.\n\nClick to open its public-surface diagram. This is a dependency reference, not a claim that the CLI barrel re-exports diagram-core's APIs.", + "anchorIds": [ + "cli-manifest", + "renderer-manifest" + ], + "semanticRole": "module-reference", + "drilldown": { + "storyId": "diagram-core-surface" + } + } + ], + "connections": [ + { + "from": "cli", + "to": "commands", + "label": "bin" + }, + { + "from": "cli", + "to": "generation" + }, + { + "from": "cli", + "to": "serving" + }, + { + "from": "cli", + "to": "bundling" + }, + { + "from": "cli", + "to": "enrichment" + }, + { + "from": "cli", + "to": "views" + }, + { + "from": "generation", + "to": "contracts", + "label": "uses types" + }, + { + "from": "cli", + "to": "diagram-core", + "label": "depends on" + } + ] +} diff --git a/stories/public/dependency-context.topo.json b/stories/public/dependency-context.topo.json new file mode 100644 index 0000000..67065f5 --- /dev/null +++ b/stories/public/dependency-context.topo.json @@ -0,0 +1,318 @@ +{ + "schemaVersion": "1.0", + "diagramFamily": "architecture", + "classification": "source-grounded", + "id": "dependency-context", + "title": "Dependency context by role", + "summary": "A companion to the internal-module map. Internal consumers and 19 direct external package names are grouped into five roles, rather than drawing 102 arrows. Select a role for every declaring manifest, dependency/dev/peer/optional kind, and requested version. This includes root tooling and the public distribution manifest; it is not a transitive dependency inventory.", + "category": "Topocode", + "anchors": [ + { + "id": "package", + "path": "package.json", + "language": "text", + "sha256": "33000f4207c9aac395f97011d417c6e715d6cb7d8d82f5601399b7ffd8f44884" + }, + { + "id": "distribution-package", + "path": "distribution/package.json", + "language": "text", + "sha256": "db65f3f51df0e796b8af677a51e0021504798a092c052b775d78788ec335e5f4" + }, + { + "id": "packages-story-package", + "path": "packages/story/package.json", + "language": "text", + "sha256": "996dc365b6c0bcdc3c4beaddb507c657cf97ee0412232c110f081013e0f7cfde" + }, + { + "id": "packages-languages-package", + "path": "packages/languages/package.json", + "language": "text", + "sha256": "d3e3979ed95f8d0d293de2cd6bc6a8c77a7f28c429b02e386da7e035118f623d" + }, + { + "id": "packages-scanner-package", + "path": "packages/scanner/package.json", + "language": "text", + "sha256": "3027a4fa118d19cd7fa2b165b728a642582b0f5e43d986a595ff25f276bfee48" + }, + { + "id": "packages-schema-package", + "path": "packages/schema/package.json", + "language": "text", + "sha256": "2d6152ff84f0d5d72736905a3cd191d2a244c704f9d06cb39843c7bc7eb9a170" + }, + { + "id": "packages-reports-package", + "path": "packages/reports/package.json", + "language": "text", + "sha256": "463d6841820655ca502e0e4eafb7ccc7e3c28700cbcfdcd5de7a6f2da13e73af" + }, + { + "id": "packages-cli-package", + "path": "packages/cli/package.json", + "language": "text", + "sha256": "e1aaebf5b0fe115fe56a658b71022c849e25120794cdbd1b063ccda97c880086" + }, + { + "id": "packages-diagram-core-package", + "path": "packages/diagram-core/package.json", + "language": "text", + "sha256": "8e4b7a111ad4234367bc49e0b7b4827e880f9d489ce136a79650923b86cd7386" + }, + { + "id": "packages-views-package", + "path": "packages/views/package.json", + "language": "text", + "sha256": "9c5d8a09b49c1c34f037deaaa3a03c17369cceb375f4f5a7cbe232b76054fab4" + }, + { + "id": "packages-site-package", + "path": "packages/site/package.json", + "language": "text", + "sha256": "2e651e2869f1284464fda093c54d52ecc49a7f90594c7746facf03528df87a38" + }, + { + "id": "packages-workspace-package", + "path": "packages/workspace/package.json", + "language": "text", + "sha256": "02528f44aace1f01cff29eb9d1a3fc3c5b0beb1d456ba0876714012ff152bdd0" + }, + { + "id": "packages-modules-package", + "path": "packages/modules/package.json", + "language": "text", + "sha256": "d114052b1fedb9b0cca1fd70b84d8fb78b38afb3b83c87d66dab63bece2e9391" + }, + { + "id": "packages-enrichment-package", + "path": "packages/enrichment/package.json", + "language": "text", + "sha256": "45c6597b6b9490312313efe5f7b36a4c7bb4475c7be76b3322b0ddaf450006ca" + }, + { + "id": "packages-graph-package", + "path": "packages/graph/package.json", + "language": "text", + "sha256": "4ca3e7b8842834077417e360037ebd9281333d5ea3f9d0c197f65367bb1ab7c1" + }, + { + "id": "tools-eslint-config-package", + "path": "tools/eslint-config/package.json", + "language": "text", + "sha256": "3ffd0d483e9f8244ead246c249d8ce44d16ff5a811ddff77c910f0a92ed8b0b0" + } + ], + "sections": [ + { + "id": "render-consumers", + "title": "Rendering", + "semanticRole": "repository-consumers", + "summary": "diagram-core", + "body": "Internal/repository consumers grouped by responsibility:\n@jdylanmc/topo-code\n@topo/diagram-core\n\nDeclared references:\n@jdylanmc/topo-code -> @jdylanmc/topo-archify [dependencies: 0.1.0]\n@topo/diagram-core -> @viz-js/viz [dependencies: 3.30.0]\n@topo/diagram-core -> @jdylanmc/topo-archify [peerDependencies: 0.1.0]\n\nThis is a manifest view, not observed imports or runtime execution. Root topo-code is the development project; @jdylanmc/topo-code is the public distribution manifest.", + "anchorIds": [ + "distribution-package", + "packages-diagram-core-package" + ] + }, + { + "id": "render-dependencies", + "title": "Archify and Graphviz", + "summary": "Pinned render engines", + "semanticRole": "external-dependencies", + "body": "Direct external dependencies grouped by role:\n@jdylanmc/topo-archify\n@viz-js/viz\n\nExact declarations and requested versions:\n@jdylanmc/topo-code -> @jdylanmc/topo-archify [dependencies: 0.1.0]\n@topo/diagram-core -> @viz-js/viz [dependencies: 3.30.0]\n@topo/diagram-core -> @jdylanmc/topo-archify [peerDependencies: 0.1.0]\n\nDependency kind is per declaration, not an inherent package property. typescript-compiler-api is an npm alias to typescript@6.0.3; the compiler used to build the repository is separate. Optional Rust packages stay optional. No transitive lockfile dependencies are shown.", + "anchorIds": [ + "distribution-package", + "packages-diagram-core-package" + ] + }, + { + "id": "analysis-consumers", + "title": "Code analysis", + "semanticRole": "repository-consumers", + "summary": "languages, scanner, story", + "body": "Internal/repository consumers grouped by responsibility:\n@topo/languages\n@topo/scanner\n@topo/story\n\nDeclared references:\n@topo/story -> typescript-compiler-api [dependencies: npm:typescript@6.0.3]\n@topo/languages -> typescript-compiler-api [dependencies: npm:typescript@6.0.3]\n@topo/languages -> @ast-grep/lang-rust [optionalDependencies: 0.0.7]\n@topo/languages -> @ast-grep/napi [optionalDependencies: 0.45.3]\n@topo/languages -> @iarna/toml [optionalDependencies: 2.2.5]\n@topo/scanner -> typescript-compiler-api [dependencies: npm:typescript@6.0.3]\n\nThis is a manifest view, not observed imports or runtime execution. Root topo-code is the development project; @jdylanmc/topo-code is the public distribution manifest.", + "anchorIds": [ + "packages-story-package", + "packages-languages-package", + "packages-scanner-package" + ] + }, + { + "id": "analysis-dependencies", + "title": "Language parsing", + "summary": "Compiler, Rust, TOML", + "semanticRole": "external-dependencies", + "body": "Direct external dependencies grouped by role:\ntypescript-compiler-api\n@ast-grep/lang-rust\n@ast-grep/napi\n@iarna/toml\n\nExact declarations and requested versions:\n@topo/story -> typescript-compiler-api [dependencies: npm:typescript@6.0.3]\n@topo/languages -> typescript-compiler-api [dependencies: npm:typescript@6.0.3]\n@topo/languages -> @ast-grep/lang-rust [optionalDependencies: 0.0.7]\n@topo/languages -> @ast-grep/napi [optionalDependencies: 0.45.3]\n@topo/languages -> @iarna/toml [optionalDependencies: 2.2.5]\n@topo/scanner -> typescript-compiler-api [dependencies: npm:typescript@6.0.3]\n\nDependency kind is per declaration, not an inherent package property. typescript-compiler-api is an npm alias to typescript@6.0.3; the compiler used to build the repository is separate. Optional Rust packages stay optional. No transitive lockfile dependencies are shown.", + "anchorIds": [ + "packages-story-package", + "packages-languages-package", + "packages-scanner-package" + ] + }, + { + "id": "contracts-consumers", + "title": "Schema contracts", + "semanticRole": "repository-consumers", + "summary": "schema, story", + "body": "Internal/repository consumers grouped by responsibility:\n@topo/schema\n@topo/story\n\nDeclared references:\n@topo/story -> ajv [devDependencies: 8.17.1]\n@topo/schema -> ajv [dependencies: 8.17.1]\n@topo/schema -> ajv-formats [dependencies: 3.0.1]\n\nThis is a manifest view, not observed imports or runtime execution. Root topo-code is the development project; @jdylanmc/topo-code is the public distribution manifest.", + "anchorIds": [ + "packages-story-package", + "packages-schema-package" + ] + }, + { + "id": "contracts-dependencies", + "title": "JSON validation", + "summary": "AJV and formats", + "semanticRole": "external-dependencies", + "body": "Direct external dependencies grouped by role:\najv\najv-formats\n\nExact declarations and requested versions:\n@topo/story -> ajv [devDependencies: 8.17.1]\n@topo/schema -> ajv [dependencies: 8.17.1]\n@topo/schema -> ajv-formats [dependencies: 3.0.1]\n\nDependency kind is per declaration, not an inherent package property. typescript-compiler-api is an npm alias to typescript@6.0.3; the compiler used to build the repository is separate. Optional Rust packages stay optional. No transitive lockfile dependencies are shown.", + "anchorIds": [ + "packages-story-package", + "packages-schema-package" + ] + }, + { + "id": "paths-consumers", + "title": "Path selection", + "semanticRole": "repository-consumers", + "summary": "scanner, views", + "body": "Internal/repository consumers grouped by responsibility:\n@topo/scanner\n@topo/views\n\nDeclared references:\n@topo/scanner -> ignore [dependencies: ^7.0.0]\n@topo/views -> ignore [dependencies: ^7.0.0]\n\nThis is a manifest view, not observed imports or runtime execution. Root topo-code is the development project; @jdylanmc/topo-code is the public distribution manifest.", + "anchorIds": [ + "packages-scanner-package", + "packages-views-package" + ] + }, + { + "id": "paths-dependencies", + "title": "Ignore matching", + "summary": "Repository path rules", + "semanticRole": "external-dependencies", + "body": "Direct external dependencies grouped by role:\nignore\n\nExact declarations and requested versions:\n@topo/scanner -> ignore [dependencies: ^7.0.0]\n@topo/views -> ignore [dependencies: ^7.0.0]\n\nDependency kind is per declaration, not an inherent package property. typescript-compiler-api is an npm alias to typescript@6.0.3; the compiler used to build the repository is separate. Optional Rust packages stay optional. No transitive lockfile dependencies are shown.", + "anchorIds": [ + "packages-scanner-package", + "packages-views-package" + ] + }, + { + "id": "tooling-consumers", + "title": "Build, test, docs", + "semanticRole": "repository-consumers", + "summary": "All workspace packages", + "body": "Internal/repository consumers grouped by responsibility:\n@topo/cli\n@topo/diagram-core\n@topo/enrichment\n@topo/eslint-config\n@topo/graph\n@topo/languages\n@topo/modules\n@topo/reports\n@topo/scanner\n@topo/schema\n@topo/site\n@topo/story\n@topo/views\n@topo/workspace\ntopo-code\n\nDeclared references:\ntopo-code -> @axe-core/playwright [devDependencies: ^4.10.2]\ntopo-code -> @types/node [devDependencies: ^22]\ntopo-code -> eslint [devDependencies: ^9.39.5]\ntopo-code -> marked [devDependencies: ^16.4.1]\ntopo-code -> playwright-core [devDependencies: ^1.55.0]\ntopo-code -> typescript [devDependencies: ^7.0.2]\ntopo-code -> vite [devDependencies: 8.2.2]\ntopo-code -> vitest [devDependencies: ^5.0.0]\n@topo/story -> @types/node [devDependencies: ^22]\n@topo/story -> typescript [devDependencies: ^7.0.2]\n@topo/story -> vite [devDependencies: 8.2.2]\n@topo/story -> vitest [devDependencies: ^5.0.0]\n@topo/languages -> @types/node [devDependencies: ^22]\n@topo/languages -> typescript [devDependencies: ^7.0.2]\n@topo/scanner -> @types/node [devDependencies: ^22.0.0]\n@topo/scanner -> typescript [devDependencies: ^7.0.2]\n@topo/scanner -> vite [devDependencies: 8.2.2]\n@topo/scanner -> vitest [devDependencies: ^5.0.0]\n@topo/schema -> @types/node [devDependencies: ^22]\n@topo/schema -> typescript [devDependencies: ^7.0.2]\n@topo/schema -> vite [devDependencies: 8.2.2]\n@topo/schema -> vitest [devDependencies: ^5.0.0]\n@topo/reports -> @types/node [devDependencies: ^22.20.1]\n@topo/reports -> typescript [devDependencies: ^7.0.2]\n@topo/reports -> vite [devDependencies: 8.2.2]\n@topo/reports -> vitest [devDependencies: ^5.0.0]\n@topo/cli -> @types/node [devDependencies: ^22.20.1]\n@topo/cli -> typescript [devDependencies: ^7.0.2]\n@topo/cli -> vite [devDependencies: 8.2.2]\n@topo/cli -> vitest [devDependencies: ^5.0.0]\n@topo/diagram-core -> @types/node [devDependencies: ^22]\n@topo/diagram-core -> typescript [devDependencies: ^7.0.2]\n@topo/views -> typescript [devDependencies: ^7.0.2]\n@topo/views -> vite [devDependencies: 8.2.2]\n@topo/views -> vitest [devDependencies: ^5.0.0]\n@topo/site -> @playwright/test [devDependencies: ^1.55.0]\n@topo/site -> @types/node [devDependencies: ^22.18.0]\n@topo/site -> typescript [devDependencies: ^7.0.2]\n@topo/site -> vite [devDependencies: 8.2.2]\n@topo/site -> vitest [devDependencies: ^5.0.0]\n@topo/workspace -> @types/node [devDependencies: ^22.20.1]\n@topo/workspace -> typescript [devDependencies: ^7.0.2]\n@topo/workspace -> vite [devDependencies: 8.2.2]\n@topo/workspace -> vitest [devDependencies: ^5.0.0]\n@topo/modules -> typescript [devDependencies: ^7.0.2]\n@topo/modules -> vite [devDependencies: 8.2.2]\n@topo/modules -> vitest [devDependencies: ^5.0.0]\n@topo/enrichment -> typescript [devDependencies: ^7.0.2]\n@topo/enrichment -> vite [devDependencies: 8.2.2]\n@topo/enrichment -> vitest [devDependencies: ^5.0.0]\n@topo/graph -> typescript [devDependencies: ^7.0.2]\n@topo/graph -> vite [devDependencies: 8.2.2]\n@topo/graph -> vitest [devDependencies: ^5.0.0]\n@topo/eslint-config -> @typescript-eslint/parser [dependencies: 8.70.0]\n@topo/eslint-config -> eslint [dependencies: ^9.39.5]\n@topo/eslint-config -> typescript [dependencies: 6.0.3]\n\nThis is a manifest view, not observed imports or runtime execution. Root topo-code is the development project; @jdylanmc/topo-code is the public distribution manifest.", + "anchorIds": [ + "package", + "packages-story-package", + "packages-languages-package", + "packages-scanner-package", + "packages-schema-package", + "packages-reports-package", + "packages-cli-package", + "packages-diagram-core-package", + "packages-views-package", + "packages-site-package", + "packages-workspace-package", + "packages-modules-package", + "packages-enrichment-package", + "packages-graph-package", + "tools-eslint-config-package" + ] + }, + { + "id": "tooling-dependencies", + "title": "Development tools", + "summary": "Build, lint, test, docs", + "semanticRole": "external-dependencies", + "body": "Direct external dependencies grouped by role:\n@axe-core/playwright\n@playwright/test\n@types/node\n@typescript-eslint/parser\neslint\nmarked\nplaywright-core\ntypescript\nvite\nvitest\n\nExact declarations and requested versions:\ntopo-code -> @axe-core/playwright [devDependencies: ^4.10.2]\ntopo-code -> @types/node [devDependencies: ^22]\ntopo-code -> eslint [devDependencies: ^9.39.5]\ntopo-code -> marked [devDependencies: ^16.4.1]\ntopo-code -> playwright-core [devDependencies: ^1.55.0]\ntopo-code -> typescript [devDependencies: ^7.0.2]\ntopo-code -> vite [devDependencies: 8.2.2]\ntopo-code -> vitest [devDependencies: ^5.0.0]\n@topo/story -> @types/node [devDependencies: ^22]\n@topo/story -> typescript [devDependencies: ^7.0.2]\n@topo/story -> vite [devDependencies: 8.2.2]\n@topo/story -> vitest [devDependencies: ^5.0.0]\n@topo/languages -> @types/node [devDependencies: ^22]\n@topo/languages -> typescript [devDependencies: ^7.0.2]\n@topo/scanner -> @types/node [devDependencies: ^22.0.0]\n@topo/scanner -> typescript [devDependencies: ^7.0.2]\n@topo/scanner -> vite [devDependencies: 8.2.2]\n@topo/scanner -> vitest [devDependencies: ^5.0.0]\n@topo/schema -> @types/node [devDependencies: ^22]\n@topo/schema -> typescript [devDependencies: ^7.0.2]\n@topo/schema -> vite [devDependencies: 8.2.2]\n@topo/schema -> vitest [devDependencies: ^5.0.0]\n@topo/reports -> @types/node [devDependencies: ^22.20.1]\n@topo/reports -> typescript [devDependencies: ^7.0.2]\n@topo/reports -> vite [devDependencies: 8.2.2]\n@topo/reports -> vitest [devDependencies: ^5.0.0]\n@topo/cli -> @types/node [devDependencies: ^22.20.1]\n@topo/cli -> typescript [devDependencies: ^7.0.2]\n@topo/cli -> vite [devDependencies: 8.2.2]\n@topo/cli -> vitest [devDependencies: ^5.0.0]\n@topo/diagram-core -> @types/node [devDependencies: ^22]\n@topo/diagram-core -> typescript [devDependencies: ^7.0.2]\n@topo/views -> typescript [devDependencies: ^7.0.2]\n@topo/views -> vite [devDependencies: 8.2.2]\n@topo/views -> vitest [devDependencies: ^5.0.0]\n@topo/site -> @playwright/test [devDependencies: ^1.55.0]\n@topo/site -> @types/node [devDependencies: ^22.18.0]\n@topo/site -> typescript [devDependencies: ^7.0.2]\n@topo/site -> vite [devDependencies: 8.2.2]\n@topo/site -> vitest [devDependencies: ^5.0.0]\n@topo/workspace -> @types/node [devDependencies: ^22.20.1]\n@topo/workspace -> typescript [devDependencies: ^7.0.2]\n@topo/workspace -> vite [devDependencies: 8.2.2]\n@topo/workspace -> vitest [devDependencies: ^5.0.0]\n@topo/modules -> typescript [devDependencies: ^7.0.2]\n@topo/modules -> vite [devDependencies: 8.2.2]\n@topo/modules -> vitest [devDependencies: ^5.0.0]\n@topo/enrichment -> typescript [devDependencies: ^7.0.2]\n@topo/enrichment -> vite [devDependencies: 8.2.2]\n@topo/enrichment -> vitest [devDependencies: ^5.0.0]\n@topo/graph -> typescript [devDependencies: ^7.0.2]\n@topo/graph -> vite [devDependencies: 8.2.2]\n@topo/graph -> vitest [devDependencies: ^5.0.0]\n@topo/eslint-config -> @typescript-eslint/parser [dependencies: 8.70.0]\n@topo/eslint-config -> eslint [dependencies: ^9.39.5]\n@topo/eslint-config -> typescript [dependencies: 6.0.3]\n\nDependency kind is per declaration, not an inherent package property. typescript-compiler-api is an npm alias to typescript@6.0.3; the compiler used to build the repository is separate. Optional Rust packages stay optional. No transitive lockfile dependencies are shown.", + "anchorIds": [ + "package", + "packages-story-package", + "packages-languages-package", + "packages-scanner-package", + "packages-schema-package", + "packages-reports-package", + "packages-cli-package", + "packages-diagram-core-package", + "packages-views-package", + "packages-site-package", + "packages-workspace-package", + "packages-modules-package", + "packages-enrichment-package", + "packages-graph-package", + "tools-eslint-config-package" + ] + } + ], + "connections": [ + { + "from": "render-consumers", + "to": "render-dependencies", + "label": "manifest declarations", + "classification": "source-traced", + "rationale": "Each grouped arrow represents only the exact 3 declarations listed in both endpoint details; kind and version are preserved.", + "anchorIds": [ + "distribution-package", + "packages-diagram-core-package" + ] + }, + { + "from": "analysis-consumers", + "to": "analysis-dependencies", + "label": "manifest declarations", + "classification": "source-traced", + "rationale": "Each grouped arrow represents only the exact 6 declarations listed in both endpoint details; kind and version are preserved.", + "anchorIds": [ + "packages-story-package", + "packages-languages-package", + "packages-scanner-package" + ] + }, + { + "from": "contracts-consumers", + "to": "contracts-dependencies", + "label": "manifest declarations", + "classification": "source-traced", + "rationale": "Each grouped arrow represents only the exact 3 declarations listed in both endpoint details; kind and version are preserved.", + "anchorIds": [ + "packages-story-package", + "packages-schema-package" + ] + }, + { + "from": "paths-consumers", + "to": "paths-dependencies", + "label": "manifest declarations", + "classification": "source-traced", + "rationale": "Each grouped arrow represents only the exact 2 declarations listed in both endpoint details; kind and version are preserved.", + "anchorIds": [ + "packages-scanner-package", + "packages-views-package" + ] + }, + { + "from": "tooling-consumers", + "to": "tooling-dependencies", + "label": "manifest declarations", + "classification": "source-traced", + "rationale": "Each grouped arrow represents only the exact 56 declarations listed in both endpoint details; kind and version are preserved.", + "anchorIds": [ + "package", + "packages-story-package", + "packages-languages-package", + "packages-scanner-package", + "packages-schema-package", + "packages-reports-package", + "packages-cli-package", + "packages-diagram-core-package", + "packages-views-package", + "packages-site-package", + "packages-workspace-package", + "packages-modules-package", + "packages-enrichment-package", + "packages-graph-package", + "tools-eslint-config-package" + ] + } + ] +} diff --git a/stories/public/diagram-core-surface.topo.json b/stories/public/diagram-core-surface.topo.json new file mode 100644 index 0000000..2b2221f --- /dev/null +++ b/stories/public/diagram-core-surface.topo.json @@ -0,0 +1,269 @@ +{ + "schemaVersion": "1.0", + "diagramFamily": "architecture", + "classification": "source-grounded", + "id": "diagram-core-surface", + "title": "@topo/diagram-core: public surface", + "category": "Module surfaces", + "parent": { + "storyId": "internal-modules", + "nodeId": "diagram-core" + }, + "summary": "The rendering module's exposed functions, shared input/output interfaces, and declared renderer dependencies. Arrows mean exports, contract references, or declared package dependencies—not private rendering steps. This private workspace API is bundled into @jdylanmc/topo-code; it is not a separately published stable SDK. Unlabelled spokes from the package box to API/utility boxes mean root exports; labelled edges distinguish other references.", + "anchors": [ + { + "id": "cli-manifest", + "path": "packages/cli/package.json", + "language": "text", + "sha256": "e1aaebf5b0fe115fe56a658b71022c849e25120794cdbd1b063ccda97c880086" + }, + { + "id": "cli-entry", + "path": "packages/cli/src/index.ts", + "language": "text", + "sha256": "d05f2184becf9a468e04fc3ca8945f277001108c67de0f1ff33c562972e5c28d" + }, + { + "id": "renderer-manifest", + "path": "packages/diagram-core/package.json", + "language": "text", + "sha256": "8e4b7a111ad4234367bc49e0b7b4827e880f9d489ce136a79650923b86cd7386" + }, + { + "id": "story-manifest", + "path": "packages/story/package.json", + "language": "text", + "sha256": "996dc365b6c0bcdc3c4beaddb507c657cf97ee0412232c110f081013e0f7cfde" + }, + { + "id": "render-story", + "path": "packages/diagram-core/src/index.ts", + "language": "text", + "sha256": "2591adad4e02d9b6da5288acf9f83371565b1d82447658be11196bfecf301100", + "pattern": "export function renderStory(story: ResolvedStoryDocument): StoryArtifact | Promise {" + }, + { + "id": "render-array", + "path": "packages/diagram-core/src/index.ts", + "language": "text", + "sha256": "2591adad4e02d9b6da5288acf9f83371565b1d82447658be11196bfecf301100", + "pattern": "export function renderArchitectureStories(\n stories: readonly ResolvedStoryDocument[],\n options: { readonly sourceEvidence?: \"native\" | \"wrapper\" } = {},\n): StoryArtifact[] {" + }, + { + "id": "render-stream", + "path": "packages/diagram-core/src/index.ts", + "language": "text", + "sha256": "2591adad4e02d9b6da5288acf9f83371565b1d82447658be11196bfecf301100", + "pattern": "export function* renderArchitectureStoryBatch(\n stories: readonly ResolvedStoryDocument[],\n options: { readonly sourceEvidence?: \"native\" | \"wrapper\" } = {},\n): Generator {" + }, + { + "id": "width-helper", + "path": "packages/diagram-core/src/index.ts", + "language": "text", + "sha256": "2591adad4e02d9b6da5288acf9f83371565b1d82447658be11196bfecf301100", + "pattern": "export function architectureComponentWidth(\n title: string,\n sublabel = \"\",\n finalTypography = false,\n): number {" + }, + { + "id": "node-identities", + "path": "packages/diagram-core/src/node-ids.ts", + "language": "text", + "sha256": "643285f22e4bf993d69f88c714711c48957b700a637c2ad1b97044d32340003c", + "pattern": "export function storyNodeIds(\n document: StoryDocument,\n renderer: \"archify\" | \"graphviz\" = document.renderer ?? \"archify\",\n): readonly (readonly [string, string])[] {" + }, + { + "id": "verify", + "path": "packages/diagram-core/src/integrity.ts", + "language": "text", + "sha256": "ccc71499fd0f35ec47eefda19f21d62b5ac9e419110cca65b24f954b05419f19", + "pattern": "export function verifyArchifyIntegrity(): ArchifyIntegrity {" + }, + { + "id": "integrity-type", + "path": "packages/diagram-core/src/integrity.ts", + "language": "text", + "sha256": "ccc71499fd0f35ec47eefda19f21d62b5ac9e419110cca65b24f954b05419f19", + "pattern": "export type ArchifyIntegrity = RuntimeIntegrity;" + }, + { + "id": "resolved-story", + "path": "packages/story/src/index.ts", + "language": "text", + "sha256": "1df6ad0e6be95db8727430ceca42e983ac093d93eed44d90fea083f98b95d965", + "pattern": "export interface ResolvedStoryDocument {\n readonly document: StoryDocument;\n readonly documentPath: string;\n readonly repositoryRoot: string;\n readonly source: {\n readonly revision: string;\n readonly dirty: boolean;\n };\n readonly anchors: readonly ResolvedSourceAnchor[];\n}" + }, + { + "id": "story-artifact", + "path": "packages/story/src/index.ts", + "language": "text", + "sha256": "1df6ad0e6be95db8727430ceca42e983ac093d93eed44d90fea083f98b95d965", + "pattern": "export interface StoryArtifact {\n readonly kind: \"html\";\n readonly mediaType: \"text/html\";\n readonly contents: string;\n readonly assets?: Readonly>;\n readonly renderer: {\n readonly name: string;\n readonly pin: string;\n readonly sha256?: string;\n readonly sourceOutputSha256?: string;\n readonly outputSha256?: string;\n readonly adaptation?: string;\n };\n}" + }, + { + "id": "theme-export", + "path": "packages/diagram-core/src/index.ts", + "language": "text", + "sha256": "2591adad4e02d9b6da5288acf9f83371565b1d82447658be11196bfecf301100", + "pattern": "export { CORE_THEME_SCRIPT } from \"./theme.js\";" + }, + { + "id": "integrity-export", + "path": "packages/diagram-core/src/index.ts", + "language": "text", + "sha256": "2591adad4e02d9b6da5288acf9f83371565b1d82447658be11196bfecf301100", + "pattern": "export {\n verifyArchifyIntegrity,\n type ArchifyIntegrity,\n} from \"./integrity.js\";" + } + ], + "sections": [ + { + "id": "archify", + "title": "@jdylanmc/topo-archify", + "summary": "Pinned peer dependency", + "body": "Declared peer: @jdylanmc/topo-archify@0.1.0. This package supplies the pinned native Archify runtime. Consumers meet the peer requirement; it is not a child module re-exported by diagram-core.", + "anchorIds": [ + "renderer-manifest" + ], + "semanticRole": "module-reference" + }, + { + "id": "render", + "title": "Single-story API", + "summary": "renderStory", + "body": "renderStory(story: ResolvedStoryDocument) -> StoryArtifact | Promise.\n\nInput is already resolved source evidence, not raw repository scanning or an unvalidated JSON draft. The return can be synchronous or asynchronous, so callers can await it uniformly. The story's renderer selection controls the backend; this view deliberately does not expand private layout or rendering algorithms.", + "anchorIds": [ + "render-story" + ], + "semanticRole": "public-interface" + }, + { + "id": "contracts", + "title": "@topo/story", + "summary": "Resolved input and artifact", + "body": "Referenced interfaces:\n\nResolvedStoryDocument: authored document, document path, repository root, source revision/dirty state, and resolved anchors.\n\nStoryArtifact: HTML kind/media type, contents, optional backend assets, and renderer identity/provenance (including original/adapted output hashes when supplied).\n\nThese interfaces belong to @topo/story; diagram-core consumes/returns them. The legacy RenderInput / Artifact declarations in types.ts are not re-exported by diagram-core's package-root index.", + "anchorIds": [ + "resolved-story", + "story-artifact", + "story-manifest" + ], + "semanticRole": "data-contract" + }, + { + "id": "batch", + "title": "Architecture batch API", + "summary": "renderArchitectureStories", + "body": "renderArchitectureStories(stories, options?) -> StoryArtifact[]\nrenderArchitectureStoryBatch(stories, options?) -> Generator\n\nInput: readonly ResolvedStoryDocument[]. The optional sourceEvidence mode is native or wrapper. These entry points accept Architecture stories; they are not general-purpose batching APIs for every diagram family.", + "anchorIds": [ + "render-array", + "render-stream" + ], + "semanticRole": "public-interface" + }, + { + "id": "diagram-core", + "title": "@topo/diagram-core", + "summary": "Exports the API groups", + "body": "The root exports renderStory, renderArchitectureStories, renderArchitectureStoryBatch, verifyArchifyIntegrity, the ArchifyIntegrity type, architectureComponentWidth, storyNodeIds, and CORE_THEME_SCRIPT.\n\nIt references @topo/story for contracts, @jdylanmc/topo-archify as its native peer, and @viz-js/viz as a dependency. No bin entry is declared. Private helpers such as specification builders, renderGraphviz and viewer adaptation routines are intentionally not presented as public APIs.", + "anchorIds": [ + "renderer-manifest", + "render-story", + "render-array", + "render-stream", + "verify", + "integrity-type", + "width-helper", + "node-identities", + "theme-export" + ], + "semanticRole": "module-boundary" + }, + { + "id": "integrity", + "title": "Integrity API", + "summary": "verifyArchifyIntegrity", + "body": "verifyArchifyIntegrity() -> ArchifyIntegrity.\n\nThe root also re-exports the ArchifyIntegrity type, an alias of the renderer package's RuntimeIntegrity contract. This reports verified runtime identity/inventory; it does not certify the correctness of an authored architecture explanation.", + "anchorIds": [ + "verify", + "integrity-type", + "integrity-export" + ], + "semanticRole": "public-interface" + }, + { + "id": "cli", + "title": "@topo/cli", + "summary": "Declared runtime consumer", + "body": "The CLI manifest declares @topo/diagram-core as a runtime workspace dependency. This is the consumer boundary you drilled through—not an assertion that every CLI function directly calls a renderer.\n\nClick to return to the CLI's exposed surface.", + "anchorIds": [ + "cli-manifest" + ], + "semanticRole": "module-reference", + "drilldown": { + "storyId": "cli-surface" + } + }, + { + "id": "utilities", + "title": "Exported utilities", + "summary": "Identity, width and theme", + "body": "architectureComponentWidth(title, sublabel?, finalTypography?) -> number.\nstoryNodeIds(document, renderer?) -> readonly authored/native ID pairs.\nCORE_THEME_SCRIPT -> string.\n\nstoryNodeIds keeps authored section IDs separate from native renderer identities. Archify uses stable component hashes for IDs outside its identifier syntax; Graphviz keeps authored IDs. Activation maps native IDs back to authored sections, and authored focus maps to native targets. Renderer metadata and edge endpoints keep native IDs.\n\nThese are current root exports supporting integration and presentation. They are exposed helpers, not separate renderer backends or an invitation to depend on private implementation functions.", + "anchorIds": [ + "width-helper", + "node-identities", + "theme-export" + ], + "semanticRole": "public-interface" + }, + { + "id": "graphviz", + "title": "@viz-js/viz", + "summary": "Graphviz dependency", + "body": "Declared dependency: @viz-js/viz@3.30.0. It supplies Graphviz for explicitly selected technical workflows. It is not a silent fallback when native Archify rendering fails, and its artifacts have separate provenance.", + "anchorIds": [ + "renderer-manifest" + ], + "semanticRole": "module-reference" + } + ], + "connections": [ + { + "from": "diagram-core", + "to": "render" + }, + { + "from": "diagram-core", + "to": "batch" + }, + { + "from": "diagram-core", + "to": "integrity" + }, + { + "from": "diagram-core", + "to": "utilities" + }, + { + "from": "render", + "to": "contracts", + "label": "uses types" + }, + { + "from": "batch", + "to": "contracts", + "label": "uses types" + }, + { + "from": "diagram-core", + "to": "archify", + "label": "peer" + }, + { + "from": "diagram-core", + "to": "graphviz", + "label": "dependency" + }, + { + "from": "cli", + "to": "diagram-core", + "label": "depends on" + } + ] +} diff --git a/stories/public/internal-modules.topo.json b/stories/public/internal-modules.topo.json new file mode 100644 index 0000000..3155590 --- /dev/null +++ b/stories/public/internal-modules.topo.json @@ -0,0 +1,437 @@ +{ + "schemaVersion": "1.0", + "diagramFamily": "architecture", + "classification": "source-grounded", + "id": "internal-modules", + "title": "Topocode internal modules", + "summary": "Thirteen private @topo/* runtime modules bundled by @jdylanmc/topo-code. Arrows are selected direct dependencies from package manifests, arranged as a readable composition spine, not a complete edge drawing or runtime call graph. Select a module for every declared incoming/outgoing internal dependency and its responsibility. Build-only eslint-config is excluded from this view; tooling and external context live in the companion map.", + "category": "Topocode", + "anchors": [ + { + "id": "packages-story-package", + "path": "packages/story/package.json", + "language": "text", + "sha256": "996dc365b6c0bcdc3c4beaddb507c657cf97ee0412232c110f081013e0f7cfde" + }, + { + "id": "packages-languages-package", + "path": "packages/languages/package.json", + "language": "text", + "sha256": "d3e3979ed95f8d0d293de2cd6bc6a8c77a7f28c429b02e386da7e035118f623d" + }, + { + "id": "packages-scanner-package", + "path": "packages/scanner/package.json", + "language": "text", + "sha256": "3027a4fa118d19cd7fa2b165b728a642582b0f5e43d986a595ff25f276bfee48" + }, + { + "id": "packages-schema-package", + "path": "packages/schema/package.json", + "language": "text", + "sha256": "2d6152ff84f0d5d72736905a3cd191d2a244c704f9d06cb39843c7bc7eb9a170" + }, + { + "id": "packages-reports-package", + "path": "packages/reports/package.json", + "language": "text", + "sha256": "463d6841820655ca502e0e4eafb7ccc7e3c28700cbcfdcd5de7a6f2da13e73af" + }, + { + "id": "packages-cli-package", + "path": "packages/cli/package.json", + "language": "text", + "sha256": "e1aaebf5b0fe115fe56a658b71022c849e25120794cdbd1b063ccda97c880086" + }, + { + "id": "packages-diagram-core-package", + "path": "packages/diagram-core/package.json", + "language": "text", + "sha256": "8e4b7a111ad4234367bc49e0b7b4827e880f9d489ce136a79650923b86cd7386" + }, + { + "id": "packages-views-package", + "path": "packages/views/package.json", + "language": "text", + "sha256": "9c5d8a09b49c1c34f037deaaa3a03c17369cceb375f4f5a7cbe232b76054fab4" + }, + { + "id": "packages-site-package", + "path": "packages/site/package.json", + "language": "text", + "sha256": "2e651e2869f1284464fda093c54d52ecc49a7f90594c7746facf03528df87a38" + }, + { + "id": "packages-workspace-package", + "path": "packages/workspace/package.json", + "language": "text", + "sha256": "02528f44aace1f01cff29eb9d1a3fc3c5b0beb1d456ba0876714012ff152bdd0" + }, + { + "id": "packages-modules-package", + "path": "packages/modules/package.json", + "language": "text", + "sha256": "d114052b1fedb9b0cca1fd70b84d8fb78b38afb3b83c87d66dab63bece2e9391" + }, + { + "id": "packages-enrichment-package", + "path": "packages/enrichment/package.json", + "language": "text", + "sha256": "45c6597b6b9490312313efe5f7b36a4c7bb4475c7be76b3322b0ddaf450006ca" + }, + { + "id": "packages-graph-package", + "path": "packages/graph/package.json", + "language": "text", + "sha256": "4ca3e7b8842834077417e360037ebd9281333d5ea3f9d0c197f65367bb1ab7c1" + }, + { + "id": "workspace-implementation", + "path": "packages/workspace/src/index.ts", + "language": "text", + "sha256": "df2c638987c1f8c0f27e12ad2f5463d8246767a219800d3fc3d1490889dd0253" + }, + { + "id": "reports-implementation", + "path": "packages/reports/src/index.ts", + "language": "text", + "sha256": "83afb998efb51d42d48c3945ade41272eee90e0409a04963f49ec34e81e1dcc1" + }, + { + "id": "cli-implementation", + "path": "packages/cli/src/main.ts", + "language": "text", + "sha256": "777350607d51e97214906d4106025f8b8d50200dfee93703e5ff16d22f3ed767" + }, + { + "id": "site-implementation", + "path": "packages/site/src/data.ts", + "language": "text", + "sha256": "943e3dbf9c6416c0a31dc42b8a0935a933c02c4d2c9308baf6147bddb618039c" + }, + { + "id": "views-implementation", + "path": "packages/views/src/core.ts", + "language": "text", + "sha256": "71bc9824245bcfd5d080f409c5d00f17bbb92ad7d4e59de06e732c2d1e00325a" + }, + { + "id": "modules-implementation", + "path": "packages/modules/src/modules.ts", + "language": "text", + "sha256": "09716a405dd9e80bcd1ecac4faf2913d2225e94652b7cbccc9cbd9ae3549e894" + }, + { + "id": "diagram-core-implementation", + "path": "packages/diagram-core/src/index.ts", + "language": "text", + "sha256": "2591adad4e02d9b6da5288acf9f83371565b1d82447658be11196bfecf301100" + }, + { + "id": "languages-implementation", + "path": "packages/languages/src/index.ts", + "language": "text", + "sha256": "03fb7ff8ece428bf9279a4360735a3dcf6d0e871cb5c3c8684f627dc1aab7592" + }, + { + "id": "scanner-implementation", + "path": "packages/scanner/src/typescript-scanner.ts", + "language": "text", + "sha256": "7c51e70b264d3ff387404dda119f7aef4a30b12881ee3699fe4b5a21d2008ce8" + }, + { + "id": "schema-implementation", + "path": "packages/schema/src/index.ts", + "language": "text", + "sha256": "20d89ca90e05af449d8c787cbdfca422e6b4a6782be8834986a66d53af5b778a" + }, + { + "id": "enrichment-implementation", + "path": "packages/enrichment/src/enrichment.ts", + "language": "text", + "sha256": "4599e96357224c70f1111c86186dc0c44107b0c69c1302a81d78716847e7cfcc" + }, + { + "id": "graph-implementation", + "path": "packages/graph/src/index.ts", + "language": "text", + "sha256": "e12c06d77714755cf9f625e1ef46d439687b0b63d69c3c7adcbe9b4c7dc6d403" + }, + { + "id": "story-implementation", + "path": "packages/story/src/index.ts", + "language": "text", + "sha256": "1df6ad0e6be95db8727430ceca42e983ac093d93eed44d90fea083f98b95d965" + } + ], + "sections": [ + { + "id": "story", + "title": "@topo/story", + "summary": "Resolve story evidence", + "semanticRole": "contracts-and-evidence", + "body": "Parses authored stories and resolves file/symbol/excerpt anchors against a source snapshot. Defines the renderer-neutral story contract.\n\nAll declared internal dependencies (not runtime calls):\n@topo/story -> @topo/languages [dependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/cli -> @topo/story [dependencies: workspace:*]\n@topo/diagram-core -> @topo/story [dependencies: workspace:*]\n\nStable drilldown identity: story. Open the source-backed sequence for this module's core algorithm.", + "anchorIds": [ + "packages-story-package", + "story-implementation" + ], + "drilldown": { + "storyId": "algorithm-anchor-resolution" + } + }, + { + "id": "languages", + "title": "@topo/languages", + "summary": "Language composition", + "semanticRole": "source-analysis", + "body": "Selects the first-party TypeScript/JavaScript scanner, partial Rust adapter, and Tauri bridge. Owns captured source inventory and language evidence; never runs a model or Cargo build.\n\nAll declared internal dependencies (not runtime calls):\n@topo/languages -> @topo/scanner [dependencies: workspace:*]\n@topo/languages -> @topo/schema [dependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/story -> @topo/languages [dependencies: workspace:*]\n@topo/cli -> @topo/languages [dependencies: workspace:*]\n\nStable drilldown identity: languages. Module-specific detail maps will be curated later; there is no placeholder target.", + "anchorIds": [ + "packages-languages-package", + "languages-implementation" + ] + }, + { + "id": "scanner", + "title": "@topo/scanner", + "summary": "TypeScript source facts", + "semanticRole": "source-analysis", + "body": "Extracts TypeScript/JavaScript declarations, references, and graph evidence with the pinned compiler API and repository file-selection rules.\n\nAll declared internal dependencies (not runtime calls):\n@topo/scanner -> @topo/schema [dependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/languages -> @topo/scanner [dependencies: workspace:*]\n@topo/cli -> @topo/scanner [dependencies: workspace:*]\n\nStable drilldown identity: scanner. Open the source-backed sequence for this module's core algorithm.", + "anchorIds": [ + "packages-scanner-package", + "scanner-implementation" + ], + "drilldown": { + "storyId": "algorithm-evidence-extraction" + } + }, + { + "id": "schema", + "title": "@topo/schema", + "summary": "Shared data contracts", + "semanticRole": "contracts-and-evidence", + "body": "Defines graph/artifact types, JSON schemas, validation, stable IDs, canonical serialization and compatibility rules.\n\nAll declared internal dependencies (not runtime calls):\nNo matching declarations.\n\nReferenced by internal modules:\n@topo/languages -> @topo/schema [dependencies: workspace:*]\n@topo/scanner -> @topo/schema [dependencies: workspace:*]\n@topo/reports -> @topo/schema [dependencies: workspace:*]\n@topo/cli -> @topo/schema [dependencies: workspace:*]\n@topo/views -> @topo/schema [dependencies: workspace:*]\n@topo/site -> @topo/schema [dependencies: workspace:*]\n@topo/workspace -> @topo/schema [dependencies: workspace:*]\n@topo/modules -> @topo/schema [dependencies: workspace:*]\n@topo/enrichment -> @topo/schema [dependencies: workspace:*]\n@topo/graph -> @topo/schema [dependencies: workspace:*]\n\nStable drilldown identity: schema. Module-specific detail maps will be curated later; there is no placeholder target.", + "anchorIds": [ + "packages-schema-package", + "schema-implementation" + ] + }, + { + "id": "reports", + "title": "@topo/reports", + "summary": "Normalize report evidence", + "semanticRole": "supplemental-evidence", + "body": "Parses normalized reports, checks them against graph evidence, and produces dashboard artifacts.\n\nAll declared internal dependencies (not runtime calls):\n@topo/reports -> @topo/schema [dependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/cli -> @topo/reports [dependencies: workspace:*]\n\nStable drilldown identity: reports. Module-specific detail maps will be curated later; there is no placeholder target.", + "anchorIds": [ + "packages-reports-package", + "reports-implementation" + ] + }, + { + "id": "cli", + "title": "@topo/cli", + "summary": "Compose the toolbelt", + "semanticRole": "command-orchestration", + "body": "Implements init, scan, story validation/preview, serving, bundling, ingestion, and explicit enrichment; generates Home and story navigation.\n\nAll declared internal dependencies (not runtime calls):\n@topo/cli -> @topo/diagram-core [dependencies: workspace:*]\n@topo/cli -> @topo/enrichment [dependencies: workspace:*]\n@topo/cli -> @topo/graph [dependencies: workspace:*]\n@topo/cli -> @topo/languages [dependencies: workspace:*]\n@topo/cli -> @topo/modules [dependencies: workspace:*]\n@topo/cli -> @topo/reports [dependencies: workspace:*]\n@topo/cli -> @topo/scanner [dependencies: workspace:*]\n@topo/cli -> @topo/schema [dependencies: workspace:*]\n@topo/cli -> @topo/site [dependencies: workspace:*]\n@topo/cli -> @topo/story [dependencies: workspace:*]\n@topo/cli -> @topo/views [dependencies: workspace:*]\n@topo/cli -> @topo/workspace [dependencies: workspace:*]\n\nReferenced by internal modules:\nNo matching declarations.\n\nStable drilldown identity: cli. Open this module's public-surface diagram to inspect its exposed interfaces and references.", + "anchorIds": [ + "packages-cli-package", + "cli-implementation" + ], + "drilldown": { + "storyId": "cli-surface" + } + }, + { + "id": "diagram-core", + "title": "@topo/diagram-core", + "summary": "Render authored diagrams", + "semanticRole": "rendering-and-view-data", + "body": "Adapts source-grounded stories to the pinned Archify renderer or explicit Graphviz backend; owns renderer integrity, output adaptation, and viewer theme/export behavior.\n\nAll declared internal dependencies (not runtime calls):\n@topo/diagram-core -> @topo/story [dependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/cli -> @topo/diagram-core [dependencies: workspace:*]\n@topo/site -> @topo/diagram-core [devDependencies: workspace:*]\n\nStable drilldown identity: diagram-core. Open this module's public-surface diagram to inspect its exposed interfaces and references.", + "anchorIds": [ + "packages-diagram-core-package", + "diagram-core-implementation" + ], + "drilldown": { + "storyId": "diagram-core-surface" + } + }, + { + "id": "views", + "title": "@topo/views", + "summary": "Curated view membership", + "semanticRole": "graph-shaping", + "body": "Resolves authored path-based views, review baselines, overrides and layout pins against graph evidence.\n\nAll declared internal dependencies (not runtime calls):\n@topo/views -> @topo/graph [dependencies: workspace:*]\n@topo/views -> @topo/schema [dependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/cli -> @topo/views [dependencies: workspace:*]\n@topo/site -> @topo/views [dependencies: workspace:*]\n\nStable drilldown identity: views. Module-specific detail maps will be curated later; there is no placeholder target.", + "anchorIds": [ + "packages-views-package", + "views-implementation" + ] + }, + { + "id": "site", + "title": "@topo/site", + "summary": "Validate site data", + "semanticRole": "rendering-and-view-data", + "body": "Owns the site-data contract, artifact loading checks, notices, and browser regressions. It is not the marketing website or the generated shell implementation.\n\nAll declared internal dependencies (not runtime calls):\n@topo/site -> @topo/enrichment [dependencies: workspace:*]\n@topo/site -> @topo/graph [dependencies: workspace:*]\n@topo/site -> @topo/modules [dependencies: workspace:*]\n@topo/site -> @topo/schema [dependencies: workspace:*]\n@topo/site -> @topo/views [dependencies: workspace:*]\n@topo/site -> @topo/diagram-core [devDependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/cli -> @topo/site [dependencies: workspace:*]\n\nStable drilldown identity: site. Module-specific detail maps will be curated later; there is no placeholder target.", + "anchorIds": [ + "packages-site-package", + "site-implementation" + ] + }, + { + "id": "workspace", + "title": "@topo/workspace", + "summary": "Config and publication", + "semanticRole": "command-orchestration", + "body": "Owns .topo configuration, safe authored/generated file access, workspace locking, and publication transactions.\n\nAll declared internal dependencies (not runtime calls):\n@topo/workspace -> @topo/schema [dependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/cli -> @topo/workspace [dependencies: workspace:*]\n\nStable drilldown identity: workspace. Module-specific detail maps will be curated later; there is no placeholder target.", + "anchorIds": [ + "packages-workspace-package", + "workspace-implementation" + ] + }, + { + "id": "modules", + "title": "@topo/modules", + "summary": "Analysis overlays", + "semanticRole": "graph-shaping", + "body": "Composes the built-in degree and cycle contributions. These are graph overlays, not language plugins.\n\nAll declared internal dependencies (not runtime calls):\n@topo/modules -> @topo/graph [dependencies: workspace:*]\n@topo/modules -> @topo/schema [dependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/cli -> @topo/modules [dependencies: workspace:*]\n@topo/site -> @topo/modules [dependencies: workspace:*]\n\nStable drilldown identity: modules. Module-specific detail maps will be curated later; there is no placeholder target.", + "anchorIds": [ + "packages-modules-package", + "modules-implementation" + ] + }, + { + "id": "enrichment", + "title": "@topo/enrichment", + "summary": "Inferred commentary data", + "semanticRole": "supplemental-evidence", + "body": "Parses and validates enrichment documents, reference membership and analysis hashes. The CLI, not this data package, executes the configured enrichment command.\n\nAll declared internal dependencies (not runtime calls):\n@topo/enrichment -> @topo/schema [dependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/cli -> @topo/enrichment [dependencies: workspace:*]\n@topo/site -> @topo/enrichment [dependencies: workspace:*]\n\nStable drilldown identity: enrichment. Module-specific detail maps will be curated later; there is no placeholder target.", + "anchorIds": [ + "packages-enrichment-package", + "enrichment-implementation" + ] + }, + { + "id": "graph", + "title": "@topo/graph", + "summary": "Project and lay out graphs", + "semanticRole": "graph-shaping", + "body": "Derives architecture, graph projections, aggregation, deterministic layout and layout deltas from validated source evidence.\n\nAll declared internal dependencies (not runtime calls):\n@topo/graph -> @topo/schema [dependencies: workspace:*]\n\nReferenced by internal modules:\n@topo/cli -> @topo/graph [dependencies: workspace:*]\n@topo/views -> @topo/graph [dependencies: workspace:*]\n@topo/site -> @topo/graph [dependencies: workspace:*]\n@topo/modules -> @topo/graph [dependencies: workspace:*]\n\nStable drilldown identity: graph. Open the source-backed sequence for this module's core algorithm.", + "anchorIds": [ + "packages-graph-package", + "graph-implementation" + ], + "drilldown": { + "storyId": "algorithm-graph-projection" + } + } + ], + "connections": [ + { + "from": "cli", + "to": "languages", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-cli-package" + ] + }, + { + "from": "languages", + "to": "scanner", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-languages-package" + ] + }, + { + "from": "scanner", + "to": "schema", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-scanner-package" + ] + }, + { + "from": "cli", + "to": "diagram-core", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-cli-package" + ] + }, + { + "from": "diagram-core", + "to": "story", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-diagram-core-package" + ] + }, + { + "from": "cli", + "to": "workspace", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-cli-package" + ] + }, + { + "from": "cli", + "to": "reports", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-cli-package" + ] + }, + { + "from": "cli", + "to": "site", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-cli-package" + ] + }, + { + "from": "site", + "to": "views", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-site-package" + ] + }, + { + "from": "views", + "to": "graph", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-views-package" + ] + }, + { + "from": "site", + "to": "enrichment", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-site-package" + ] + }, + { + "from": "site", + "to": "modules", + "classification": "source-traced", + "rationale": "Direct dependencies declaration; not a runtime call. See node details for the complete manifest relationship set.", + "anchorIds": [ + "packages-site-package" + ] + } + ] +} diff --git a/stories/public/story-to-screen.topo.json b/stories/public/story-to-screen.topo.json new file mode 100644 index 0000000..473a88c --- /dev/null +++ b/stories/public/story-to-screen.topo.json @@ -0,0 +1,134 @@ +{ + "schemaVersion": "1.0", + "diagramFamily": "sequence", + "sequenceLayout": { "minimumParticipantGap": 220 }, + "classification": "source-grounded", + "id": "story-to-screen", + "title": "From idea to architecture", + "category": "Topocode", + "summary": "Turn a question about code into a diagram that explains it at a glance, faster than reading files. Topocode supplies source evidence and checks; the agent turns that evidence into a clear visual explanation; you review and refine it. This is the product's collaboration loop, not a command-by-command setup or Git procedure. Scan is useful here but not required for authored stories.", + "anchors": [ + { + "id": "authoring-guide", + "path": "docs/story-authoring.md", + "language": "text", + "sha256": "effa3dfed08ab628b5d9f5b4a35a21f9f40dcf355beba8037b9ec453ed3fddb5" + }, + { + "id": "agent-skill", + "path": ".agents/skills/topo-story-authoring/SKILL.md", + "language": "text", + "sha256": "c1725116905afd2e3387d4d934da5e102fff7da69e18cc8d955c815157cac35f" + }, + { + "id": "cli-contract", + "path": "docs/cli.md", + "language": "text", + "sha256": "42d611b4bf7b2c033927bc714de5d34f7a83ec732f824d3f937a15af42cba8f1" + }, + { + "id": "enrichment-boundary", + "path": "docs/enrichment.md", + "language": "text", + "sha256": "7618a97ed64f81aab129188f9e11213a4d05586797a4173d34474908625b235f" + }, + { + "id": "cli-manifest", + "path": "packages/cli/package.json", + "language": "text", + "sha256": "e1aaebf5b0fe115fe56a658b71022c849e25120794cdbd1b063ccda97c880086" + }, + { + "id": "repository-workspace", + "path": "docs/workspace.md", + "language": "text", + "sha256": "5ee9bc0818206b67cb7e3fde77b038e036f826d10ac2a153c6703b6644909bbe" + } + ], + "sections": [ + { + "id": "user", + "title": "You", + "semanticRole": "human", + "body": "Set the question and scope. Review meaning, accuracy, and usefulness. Feedback starts another iteration; your approval, not a green check, accepts the architecture document.", + "anchorIds": [ + "authoring-guide", + "agent-skill" + ] + }, + { + "id": "agent", + "title": "Coding agent", + "semanticRole": "coding-agent", + "body": "Use the scan result and source code to identify what matters, then build a diagram that explains responsibilities and relationships at a glance. Hand that visual explanation to the human for review and refine it from their feedback. The detailed authoring and rendering commands are intentionally omitted from this product overview.", + "anchorIds": [ + "authoring-guide", + "agent-skill", + "enrichment-boundary" + ] + }, + { + "id": "cli", + "title": "Topocode CLI", + "semanticRole": "command-line-tool", + "body": "Supply deterministic scan results and source evidence for the agent to interpret. Scanning does not call a model or choose the explanation for the human. This overview focuses on how the scan informs the diagram; detailed validation, rendering, and publishing procedures belong in the usage guides.", + "anchorIds": [ + "cli-contract", + "authoring-guide", + "cli-manifest" + ], + "drilldown": { + "storyId": "cli-surface" + } + }, + { + "id": "repository", + "title": "Repository", + "semanticRole": "repository", + "body": "Holds source code, configuration, and authored stories. The agent writes the explanation; the CLI reads source and generates the diagram. Source-backed stories are durable, while generated cache/output is disposable. This is a repository boundary, not a separate hosted service.", + "anchorIds": [ + "repository-workspace", + "agent-skill" + ] + } + ], + "connections": [ + { + "from": "user", + "to": "agent", + "label": "Question, scope and intent" + }, + { + "from": "agent", + "to": "cli", + "label": "Initialize; scan source" + }, + { + "from": "cli", + "to": "repository", + "label": "Read code (no model)" + }, + { + "from": "cli", + "to": "agent", + "label": "Scan results and source evidence", + "variant": "return" + }, + { + "from": "agent", + "to": "repository", + "label": "Build diagram from scan results" + }, + { + "from": "agent", + "to": "user", + "label": "Diagram explains the code", + "variant": "return" + }, + { + "from": "user", + "to": "agent", + "label": "Review, refine, repeat" + } + ] +} diff --git a/tools/eslint-config/eslint.config.mjs b/tools/eslint-config/eslint.config.mjs index 063f38a..6194e06 100644 --- a/tools/eslint-config/eslint.config.mjs +++ b/tools/eslint-config/eslint.config.mjs @@ -2,7 +2,7 @@ import parser from "@typescript-eslint/parser"; const maintainedFiles = [ "*.{js,mjs,cjs,jsx,ts,mts,cts,tsx}", - "{packages,scripts,benchmarks,tools,distribution,examples}/**/*.{js,mjs,cjs,jsx,ts,mts,cts,tsx}", + "{packages,scripts,benchmarks,tools,distribution,examples,website}/**/*.{js,mjs,cjs,jsx,ts,mts,cts,tsx}", ]; export default [ diff --git a/website/brand.mjs b/website/brand.mjs new file mode 100644 index 0000000..9356cb4 --- /dev/null +++ b/website/brand.mjs @@ -0,0 +1,8 @@ +import { themes } from "./themes.mjs"; + +export const contourPath = "M16 3C22 2 24 7 27 12C31 19 26 27 19 29C12 31 4 27 3 20C2 14 7 12 9 7C10 4 13 3 16 3Z M16 9C20 8 21 12 23 15C26 20 22 24 18 24C13 26 8 23 8 19C8 15 12 14 12 11C13 9 14 9 16 9Z M17 15C20 15 20 18 20 19C19 22 14 21 14 19C14 17 15 15 17 15Z"; + +export function contourIcon(favicon = false) { + const theme = themes.blueprint; + return ``; +} diff --git a/website/build.mjs b/website/build.mjs new file mode 100644 index 0000000..105614c --- /dev/null +++ b/website/build.mjs @@ -0,0 +1,181 @@ +import { execFileSync } from "node:child_process"; +import { cp, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { Marked } from "marked"; +import { contourSvg } from "./contours.mjs"; +import { contourIcon } from "./brand.mjs"; +import { validateStory } from "../packages/cli/dist/story-validation.js"; + +export const root = fileURLToPath(new URL("../", import.meta.url)); +export const github = "https://github.com/jdylanmc/topo-code"; +export function basePath(value = "/topo-code/") { + if (!/^\/(?:[a-zA-Z0-9_-]+\/)*$/.test(value)) throw new Error("SITE_BASE_PATH must be / or an absolute path ending in /"); + return value; +} +export function escapeHtml(value) { + return String(value).replace(/[&<>"']/g, character => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[character]); +} +export function resolveDocLink(href, source, routes, base) { + if (/^(?:https?:|mailto:|#)/i.test(href)) return href; + if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("//")) throw new Error(`Unsupported documentation link: ${href}`); + const [file, fragment] = href.split("#"); + const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(source), file)); + if (resolved.startsWith("../") || resolved.startsWith("/")) throw new Error(`Documentation link escapes repository: ${href}`); + const suffix = fragment ? `#${fragment}` : ""; + return routes.has(resolved) ? `${base}${routes.get(resolved)}${suffix}` : `${github}/blob/main/${resolved}${suffix}`; +} +export function markdown(text, source, routes, base) { + const counts = new Map(); + const marked = new Marked({ + gfm: true, + renderer: { + code({ text, lang }) { + const language = lang ? ` class="language-${escapeHtml(lang.split(/\s/)[0])}"` : ""; + return `
${escapeHtml(text)}\n
\n`; + }, + table(token) { + const row = (cells, tag) => `${cells.map(cell => `<${tag}>${this.parser.parseInline(cell.tokens)}`).join("")}`; + return `
${row(token.header, "th")}${token.rows.map(cells => row(cells, "td")).join("")}
`; + }, + heading({ tokens, depth }) { + const content = this.parser.parseInline(tokens); + const slug = content.replace(/<[^>]*>/g, "").replace(/&[^;]+;/g, "") + .toLowerCase().replace(/[^\p{L}\p{N}_\s-]/gu, "").replace(/\s/g, "-"); + const count = counts.get(slug) ?? 0; + counts.set(slug, count + 1); + return `${content}\n`; + }, + }, + walkTokens(token) { + if (token.type === "link" || token.type === "image") token.href = resolveDocLink(token.href, source, routes, base); + }, + }); + return marked.parse(text); +} + +const primaryDocs = [ + ["Getting started", "docs/getting-started.md"], + ["Working with an agent", "docs/story-authoring.md"], + ["Stories and evidence", "docs/story-preview.md"], + ["Home and catalogue", "docs/story-catalogue.md"], + ["CLI reference", "docs/cli.md"], + ["Configuration", "docs/workspace.md"], + ["Rust and Tauri", "docs/rust-tauri.md"], + ["Repository exploration", "docs/repository-exploration.md"], + ["Scanner and limitations", "docs/scanner.md"], +]; +const referenceDocs = [ + "modules", "enrichment", "reports", "logical-architecture", "curated-views", + "renderer", "public-website", +]; + +export async function build() { + const base = basePath(process.env.SITE_BASE_PATH); + const manifest = JSON.parse(await readFile(path.join(root, "distribution/package.json"), "utf8")); + const version = manifest.version; + const sourceRevision = execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim(); + const demoConfig = JSON.parse(await readFile(path.join(root, "website/demo/.topo/config.json"), "utf8")); + const curatedStories = demoConfig.catalogue.storyIds.map(id => `stories/public/${id}.topo.json`); + for (const file of curatedStories) { + const story = await validateStory(root, file); + const inputs = [file, ...story.document.anchors.map(anchor => anchor.path)]; + try { + execFileSync("git", ["diff", "--quiet", "HEAD", "--", ...inputs], { cwd: root }); + execFileSync("git", ["cat-file", "-e", `${sourceRevision}:${file}`], { cwd: root }); + } catch (error) { + throw new Error(`Commit the curated story and its source before building the demo: ${file}`, { cause: error }); + } + } + const docs = [...primaryDocs.map(([, file]) => path.posix.basename(file)), ...referenceDocs.map(name => `${name}.md`)]; + const routes = new Map(docs.map(name => [`docs/${name}`, `docs/${name.slice(0, -3)}/`])); + routes.set("docs/getting-started.md", "docs/"); + const route = value => `${base}${value}`; + const install = `npm install --save-dev @jdylanmc/topo-code@${version}`; + const nav = [["Home", ""], ["Docs", "docs/"], ["Roadmap", "roadmap/"], ["Demo", "demo/"]]; + const shell = (title, active, content) => ` + + + +${escapeHtml(title)} | Topocode + + + + + + +
${content}
+ +`; + const pages = new Map(); + pages.set("index.html", shell("Architecture you can explain", "Home", ` +

Make your codebase make sense.

+

An architecture storybook for people building software with agents. Map one meaningful question at a time. Keep the explanation close to the code.

+
+

Start in your repository.

Node.js 22+ and Git. No account or hosted service.

+
${escapeHtml(install)}
+
npx --no topo init . --skills
+npx --no topo serve .

A working Home, before your first map.

+
+

From idea to architecture

+

Understand the code at a glance, faster than reading files. Your agent turns source evidence into a diagram; you review and refine the explanation.

+
+
+

Read the implementation.

Deterministic scanning supplies structural evidence. Your coding agent reads the source and helps explain what matters. Scanning never calls a model.

Author the explanation.

Trace a boundary, a request, a decision, or a lifecycle. Curate stories with your agent instead of accepting a wall of generated boxes.

Keep the evidence.

Follow claims back to source. Validate anchors, repair stale evidence, and share the storybook as static files.

+

A map is an explanation, not an inventory.

Fast-changing code needs more than another dependency graph. Topocode gives you a place to build and maintain a shared understanding: what a system does, why its boundaries matter, and what happens when things go wrong.

You and your agent own the narrative. Validation checks its structure and evidence; it does not certify that the explanation is complete.

Useful today. Honest about limits.

TypeScript and JavaScript analysis, source-grounded stories, a browsable Home, and static publishing. Version ${escapeHtml(version)} also supports explicitly selected, partial Rust and Tauri analysis.

No compiler-complete Rust semantics, runtime reachability guarantees, or automatic architectural truth.

Read the support boundaries
`)); + for (const filename of docs) { + const source = `docs/${filename}`; + const text = await readFile(path.join(root, source), "utf8"); + const title = text.match(/^# (.+)$/m)?.[1] ?? filename.slice(0, -3); + const sidebar = ``; + pages.set(`${routes.get(source)}index.html`, shell(title, "Docs", `
${sidebar}
`)); + } + const roadmap = await readFile(path.join(root, "website/roadmap.json"), "utf8"); + const columns = JSON.parse(roadmap); + pages.set("roadmap/index.html", shell("Roadmap", "Roadmap", `

Where we’re heading.

A curated direction, not a delivery calendar. GitHub issues hold the discussions and current status.

${columns.map(column => `

${escapeHtml(column.title)}

${escapeHtml(column.description)}

`).join("")}

Already available: the npm toolbelt, a branded Home, source-backed stories, and minimal Rust/Tauri support. Roadmap grouping reflects intent, not issue readiness or promised dates.

`)); + pages.set("demo/index.html", shell("Topocode’s own storybook", "Demo", `

Meet the modules.

Explore thirteen runtime packages, drill into their interfaces and core algorithms, and follow the collaboration that turns an idea into a reviewed architecture document.

Click @topo/cli or @topo/diagram-core for public interfaces. @topo/scanner, @topo/story, and @topo/graph open algorithm sequences. Return links keep your place. LENS highlights authored responsibility groups; the module-map arrows remain selected manifest dependencies, not runtime traffic.

Dependency context groups external tools by role. Idea to architecture shows the human-agent review loop. The three algorithms below instead show local code/API/data exchanges, with the exact checks and boundaries in participant details.

+ +
+

Source snapshot: ${sourceRevision.slice(0, 12)}. Node evidence and cross-story links are available inside the storybook. Existing development fixtures are excluded. Rendered artifacts retain their own provenance; website styling does not recolor exported maps.

`)); + pages.set("404.html", shell("Page not found", "Home", `

This path has no map.

The page may have moved. Return home or browse the documentation.

`)); + + await mkdir(path.join(root, "dist"), { recursive: true }); + const staging = await mkdtemp(path.join(root, "dist/public-site-build-")); + const demoRepo = await mkdtemp(path.join(tmpdir(), "topocode-public-demo-")); + try { + for (const [file, html] of pages) { + await mkdir(path.dirname(path.join(staging, file)), { recursive: true }); + await writeFile(path.join(staging, file), html); + } + await mkdir(path.join(staging, "assets")); + for (const file of ["style.css", "client.mjs", "themes.mjs", "demo-palette.css", "terrain.mjs"]) { + await cp(path.join(root, "website", file), path.join(staging, "assets", file)); + } + await writeFile(path.join(staging, "assets/icon.svg"), contourIcon(true)); + await writeFile(path.join(staging, "assets/contours.svg"), contourSvg()); + await writeFile(path.join(staging, ".nojekyll"), ""); + execFileSync("git", ["clone", "--quiet", "--shared", "--no-checkout", root, demoRepo]); + execFileSync("git", ["-C", demoRepo, "checkout", "--quiet", "--detach", sourceRevision]); + const origin = execFileSync("git", ["remote", "get-url", "origin"], { cwd: root, encoding: "utf8" }).trim(); + execFileSync("git", ["-C", demoRepo, "remote", "set-url", "origin", origin]); + await cp(path.join(root, "website/demo/.topo"), path.join(demoRepo, ".topo"), { recursive: true }); + const cli = path.join(root, "packages/cli/dist/main.js"); + for (const args of [ + ["init", demoRepo], + ["bundle", demoRepo, "--output", path.join(demoRepo, "output"), "--base-path", `${base}demo/home/`], + ]) execFileSync(process.execPath, [cli, ...args], { cwd: root, stdio: "inherit" }); + await cp(path.join(demoRepo, "output", base.slice(1), "demo/home"), path.join(staging, "demo/home"), { recursive: true }); + const output = path.join(root, "dist/public-site"); + await rm(output, { recursive: true, force: true }); + await rename(staging, output); + console.log(`Built ${pages.size} pages and ${curatedStories.length} source-backed stories at ${output} (base ${base})`); + } finally { + await rm(staging, { recursive: true, force: true }); + await rm(demoRepo, { recursive: true, force: true }); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) await build(); diff --git a/website/build.test.mjs b/website/build.test.mjs new file mode 100644 index 0000000..e66bf3f --- /dev/null +++ b/website/build.test.mjs @@ -0,0 +1,187 @@ +import assert from "node:assert/strict"; +import { cp, readFile, rm, access } from "node:fs/promises"; +import path from "node:path"; +import test from "node:test"; +import { basePath, build, markdown, resolveDocLink, root } from "./build.mjs"; +import { themes } from "./themes.mjs"; +import { contourSvg } from "./contours.mjs"; +import { contourIcon, contourPath } from "./brand.mjs"; +import { resolveStoryDocument } from "../packages/story/dist/index.js"; + +test("Contour header and favicon share geometry with Blueprint favicon colors", () => { + for (const svg of [contourIcon(), contourIcon(true)]) { + assert.ok(svg.includes(`d="${contourPath}"`)); + assert.match(svg, /viewBox="0 0 32 32"/); + } + assert.ok(contourIcon(true).includes(themes.blueprint.bg)); + assert.ok(contourIcon(true).includes(themes.blueprint.accent)); +}); + +test("deployment paths are explicit and traversal-safe", () => { + for (const valid of ["/", "/topo-code/", "/preview/topocode/"]) assert.equal(basePath(valid), valid); + for (const invalid of ["", "topo-code", "/topo-code", "/../", "//", "/%2e%2e/", "/x?/", "/x#/"]) assert.throws(() => basePath(invalid)); +}); +test("repository Markdown links map to published docs or source without losing fragments", () => { + const routes = new Map([["docs/workspace.md", "docs/workspace/"]]); + assert.equal(resolveDocLink("./workspace.md#configuration", "docs/start.md", routes, "/topo-code/"), "/topo-code/docs/workspace/#configuration"); + assert.equal(resolveDocLink("../README.md", "docs/start.md", routes, "/"), "https://github.com/jdylanmc/topo-code/blob/main/README.md"); + assert.throws(() => resolveDocLink("javascript:alert(1)", "docs/start.md", routes, "/")); + assert.throws(() => resolveDocLink("../../secret", "docs/start.md", routes, "/")); + const html = markdown("# Same\n\n## Same\n\n[config](./workspace.md#configuration)\n\n```js\nconst value = '