From 77567637927713f0439ae985a761f9ca1030aa26 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 08:43:00 -0400 Subject: [PATCH 01/39] feat(site): add Blueprint public website Add repository-backed docs, roadmap, Contour branding, and the empty\nTopocode demo. Keep deployment pending owner authorization.\n\nRefs #74, #75 --- .github/workflows/website.yml | 73 ++++++++++++ README.md | 10 +- docs/cli.md | 54 +++++++++ docs/getting-started.md | 87 ++++++++++++++ docs/public-website.md | 101 ++++++++++++++++ docs/rust-tauri.md | 5 +- package.json | 5 + packages/cli/src/catalogue.test.ts | 6 + packages/cli/src/catalogue.ts | 2 +- tools/eslint-config/eslint.config.mjs | 2 +- website/brand.mjs | 8 ++ website/build.mjs | 158 ++++++++++++++++++++++++++ website/build.test.mjs | 86 ++++++++++++++ website/client.mjs | 83 ++++++++++++++ website/contours.mjs | 33 ++++++ website/demo-palette.css | 25 ++++ website/demo/.topo/config.json | 10 ++ website/playwright.config.mjs | 21 ++++ website/roadmap.json | 29 +++++ website/serve.mjs | 48 ++++++++ website/style.css | 103 +++++++++++++++++ website/terrain.mjs | 124 ++++++++++++++++++++ website/tests/site.spec.mjs | 140 +++++++++++++++++++++++ website/themes.mjs | 3 + yarn.lock | 32 +++++- 25 files changed, 1238 insertions(+), 10 deletions(-) create mode 100644 .github/workflows/website.yml create mode 100644 docs/cli.md create mode 100644 docs/getting-started.md create mode 100644 docs/public-website.md create mode 100644 website/brand.mjs create mode 100644 website/build.mjs create mode 100644 website/build.test.mjs create mode 100644 website/client.mjs create mode 100644 website/contours.mjs create mode 100644 website/demo-palette.css create mode 100644 website/demo/.topo/config.json create mode 100644 website/playwright.config.mjs create mode 100644 website/roadmap.json create mode 100644 website/serve.mjs create mode 100644 website/style.css create mode 100644 website/terrain.mjs create mode 100644 website/tests/site.spec.mjs create mode 100644 website/themes.mjs diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml new file mode 100644 index 0000000..04f5cff --- /dev/null +++ b/.github/workflows/website.yml @@ -0,0 +1,73 @@ +name: Public website + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + defaults: + run: + working-directory: topocode + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + path: topocode + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + repository: jdylanmc/topo-archify + ref: b94790e99e2ca51fcdb74a9bd0f10f637856f92f + path: renderer + - 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/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..d1af8a4 --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,87 @@ +# 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 empty by design. We will curate its 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..a9a3b66 --- /dev/null +++ b/docs/public-website.md @@ -0,0 +1,101 @@ +# 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. + +`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 +``` + +## 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. + +## The intentionally empty demo + +Each build initializes a fresh temporary, unborn Git repository with the checked-in +demo configuration and runs the real built `topo init` and `topo bundle` commands. +It copies their bundle unchanged, including notices. This proves the empty Home +workflow, not source analysis or architectural quality. + +Existing root `stories/` and `examples/` are preserved and are not included in the +public demo. Do not automatically author a showcase. Maps will be curated with +the owner one at a time. When that starts, extend the build to validate the +approved stories against actual Topocode source and fail on stale evidence +before publishing. Do not claim this empty-demo build checks story freshness. + +The website palette applies a presentation-only stylesheet to the +same-origin embedded empty Home. 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 empty-Home 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, and the real empty Home. +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/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..cdc3a25 100644 --- a/packages/cli/src/catalogue.test.ts +++ b/packages/cli/src/catalogue.test.ts @@ -94,6 +94,12 @@ afterEach(async () => { }); describe("generated catalogue", () => { + 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 factual = ["topo-architecture", "topo-packages"].map((id) => { diff --git a/packages/cli/src/catalogue.ts b/packages/cli/src/catalogue.ts index f2232f0..409db9b 100644 --- a/packages/cli/src/catalogue.ts +++ b/packages/cli/src/catalogue.ts @@ -1213,7 +1213,7 @@ export function renderCataloguePage( config, historyIncomplete, undefined, - `
+ `

${escapeHtml(title)}

${escapeHtml(description)}

Diagram inventory

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..c4ae671 --- /dev/null +++ b/website/build.mjs @@ -0,0 +1,158 @@ +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"; + +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 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.

+

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", `

A home for our own maps.

This is the real Topocode Home, intentionally empty. We’ll curate maps of Topocode together, one question at a time.

No architecture has been scanned or published here. Existing development fixtures are not being presented as a curated public tour.

+
Live scaffold · no maps yetOpen standalone Home
+

The embedded Home uses the website’s Blueprint theme. Standalone Home retains Topocode’s own dark/light control. No rendered maps or export artifacts are recolored.

`)); + 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", ["init", "--quiet", demoRepo]); + 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 an empty CLI-generated Home 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..a08e25c --- /dev/null +++ b/website/build.test.mjs @@ -0,0 +1,86 @@ +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"; + +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 = '`; - 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 1daa536..5967ae5 100644 --- a/packages/diagram-core/src/index.ts +++ b/packages/diagram-core/src/index.ts @@ -1587,7 +1587,7 @@ export function* renderArchitectureStoryBatch( const sourceContents = readFileSync(output, "utf8"); const contents = adaptViewerTheme(adaptArchitectureSemantics( improveStoryReadability(sourceContents, "architecture"), stories[index]!.document, - )); + ), stories[index]!.document); yield { kind: "html", mediaType: "text/html", @@ -1669,7 +1669,7 @@ export function renderStory(story: ResolvedStoryDocument): StoryArtifact | Promi ); const adapted = adaptViewerTheme(family === "architecture" ? adaptArchitectureSemantics(readable, story.document) - : readable); + : readable, story.document); return { kind: "html", mediaType: "text/html", diff --git a/packages/diagram-core/src/theme.ts b/packages/diagram-core/src/theme.ts index 4280dc8..960d6ce 100644 --- a/packages/diagram-core/src/theme.ts +++ b/packages/diagram-core/src/theme.ts @@ -1,4 +1,5 @@ import { createHash } from "node:crypto"; +import type { StoryDocument, StoryTarget } from "@topo/story"; // The native renderer's documented ?theme= and data-theme seams remain intact. // One application preference wins over renderer storage and OS media queries. @@ -74,9 +75,37 @@ export const CORE_THEME_SCRIPT = `(() => { }); })();`; -export function adaptViewerTheme(contents: string): string { +export function adaptViewerTheme(contents: string, document?: StoryDocument): 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 navigation = document === undefined || drilldowns.length === 0 ? "" : ` +`; + return contents.replace(/]*>/i, (head) => `${head}\n${navigation}`); } export function outputHash(contents: string): string { diff --git a/packages/story/src/index.ts b/packages/story/src/index.ts index 38a186c..456e920 100644 --- a/packages/story/src/index.ts +++ b/packages/story/src/index.ts @@ -14,12 +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"; } @@ -52,6 +58,7 @@ export interface StoryDocument { readonly title: string; readonly summary: string; readonly category?: string; + readonly parent?: StoryTarget & { readonly nodeId: string }; readonly anchors: readonly SourceAnchor[]; readonly sections: readonly StorySection[]; readonly connections: readonly StoryConnection[]; @@ -206,12 +213,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"], ); if (rootKeys) return rootKeys; if (value.schemaVersion !== "1.0") return 'schemaVersion must be "1.0"'; @@ -236,6 +254,10 @@ 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.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) @@ -278,7 +300,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", "summary", "semanticRole"]); + 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`; @@ -286,6 +308,10 @@ 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`; diff --git a/packages/story/src/story.test.ts b/packages/story/src/story.test.ts index abc69a7..3b97f6e 100644 --- a/packages/story/src/story.test.ts +++ b/packages/story/src/story.test.ts @@ -43,6 +43,26 @@ function validStory(): StoryDocument { } describe("story document contract", () => { + 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" }] }; diff --git a/packages/story/story.schema.json b/packages/story/story.schema.json index d084152..8755946 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, @@ -18,6 +29,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 +62,7 @@ "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"] }, diff --git a/stories/public/cli-surface.topo.json b/stories/public/cli-surface.topo.json new file mode 100644 index 0000000..7fffe34 --- /dev/null +++ b/stories/public/cli-surface.topo.json @@ -0,0 +1,384 @@ +{ + "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.", + "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": "Graph and report artifacts", + "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": "Server and local URL", + "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": "Package boundary", + "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": "Static output contract", + "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": "Explicit provider invocation", + "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": "Views, saves and conflicts", + "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", + "label": "exports" + }, + { + "from": "cli", + "to": "serving", + "label": "exports" + }, + { + "from": "cli", + "to": "bundling", + "label": "exports" + }, + { + "from": "cli", + "to": "enrichment", + "label": "exports" + }, + { + "from": "cli", + "to": "views", + "label": "exports" + }, + { + "from": "generation", + "to": "contracts", + "label": "uses types" + }, + { + "from": "cli", + "to": "diagram-core", + "label": "depends on" + } + ] +} diff --git a/stories/public/diagram-core-surface.topo.json b/stories/public/diagram-core-surface.topo.json new file mode 100644 index 0000000..bc46bdd --- /dev/null +++ b/stories/public/diagram-core-surface.topo.json @@ -0,0 +1,264 @@ +{ + "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.", + "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": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "pattern": "export function renderStory(story: ResolvedStoryDocument): StoryArtifact | Promise {" + }, + { + "id": "render-array", + "path": "packages/diagram-core/src/index.ts", + "language": "text", + "sha256": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "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": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "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": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "pattern": "export function architectureComponentWidth(\n title: string,\n sublabel = \"\",\n finalTypography = false,\n): number {" + }, + { + "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": "5e035e2eecfd25ad8451d0bf1d3dc84eae14f5e6e9b11700de2e006b970140da", + "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": "5e035e2eecfd25ad8451d0bf1d3dc84eae14f5e6e9b11700de2e006b970140da", + "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": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "pattern": "export { CORE_THEME_SCRIPT } from \"./theme.js\";" + }, + { + "id": "integrity-export", + "path": "packages/diagram-core/src/index.ts", + "language": "text", + "sha256": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "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": "Array or generator result", + "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": "Package-root exports", + "body": "The root exports renderStory, renderArchitectureStories, renderArchitectureStoryBatch, verifyArchifyIntegrity, the ArchifyIntegrity type, architectureComponentWidth, 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", + "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": "Width helper and theme script", + "body": "architectureComponentWidth(title, sublabel?, finalTypography?) -> number.\nCORE_THEME_SCRIPT -> string.\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", + "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", + "label": "exports" + }, + { + "from": "diagram-core", + "to": "batch", + "label": "exports" + }, + { + "from": "diagram-core", + "to": "integrity", + "label": "exports" + }, + { + "from": "diagram-core", + "to": "utilities", + "label": "exports" + }, + { + "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 index 8273dd2..9380b63 100644 --- a/stories/public/internal-modules.topo.json +++ b/stories/public/internal-modules.topo.json @@ -125,7 +125,7 @@ "id": "diagram-core-implementation", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "93578683a1fd4986b4fabd91b142ac75cac06d356ac5e7347c7317d271d12d2c" + "sha256": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e" }, { "id": "languages-implementation", @@ -161,7 +161,7 @@ "id": "story-implementation", "path": "packages/story/src/index.ts", "language": "text", - "sha256": "f62fefd750bfcfddca1f8802fed2abb8cb0ca1519922bc4d4979623ce5450af7" + "sha256": "5e035e2eecfd25ad8451d0bf1d3dc84eae14f5e6e9b11700de2e006b970140da" } ], "sections": [ @@ -225,22 +225,28 @@ "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. Module-specific detail maps will be curated later; there is no placeholder target.", + "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. Module-specific detail maps will be curated later; there is no placeholder target.", + "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", diff --git a/stories/public/story-to-screen.topo.json b/stories/public/story-to-screen.topo.json index 9269942..0a86859 100644 --- a/stories/public/story-to-screen.topo.json +++ b/stories/public/story-to-screen.topo.json @@ -1,407 +1,136 @@ { "schemaVersion": "1.0", - "renderer": "graphviz", - "diagramFamily": "workflow", + "diagramFamily": "sequence", "classification": "source-grounded", "id": "story-to-screen", - "title": "Story to screen", - "summary": "Follow topo story preview from committed story intent to generated browser files. These arrows are an authored trace of actual calls, data handoffs, and error propagation—not package dependencies or compiler-derived control flow. The selected catalogue is rendered as a set; individual stories resolve/render in parallel. Preview launches neither a model nor a browser/server.", + "title": "From idea to architecture", "category": "Topocode", + "summary": "One human-agent collaboration cycle, grounded in Topocode's documented workflow—not a trace of one CLI process. The CLI supplies deterministic evidence and objective checks; the agent interprets and authors; you judge whether the explanation is meaningful. Feedback loops back to interpretation/authoring, and source changes may require another scan. Scan is useful here but not a prerequisite for authored stories.", "anchors": [ { - "id": "preview-command", - "path": "packages/cli/src/main.ts", - "language": "typescript", - "symbol": "runCli", - "sha256": "777350607d51e97214906d4106025f8b8d50200dfee93703e5ff16d22f3ed767" - }, - { - "id": "catalogue", - "path": "packages/cli/src/catalogue.ts", - "language": "typescript", - "symbol": "buildCatalogue", - "sha256": "a9b4f4b9145c69cbd818f7efa36253a6ce9056e88c191512448b50cef344cb28" - }, - { - "id": "default-renderer", - "path": "packages/cli/src/catalogue.ts", - "language": "typescript", - "symbol": "defaultRenderer", - "sha256": "a9b4f4b9145c69cbd818f7efa36253a6ce9056e88c191512448b50cef344cb28" - }, - { - "id": "snapshot", - "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": "resolve-story", - "path": "packages/story/src/index.ts", - "language": "typescript", - "symbol": "resolveStoryDocument", - "sha256": "f62fefd750bfcfddca1f8802fed2abb8cb0ca1519922bc4d4979623ce5450af7" - }, - { - "id": "resolve-anchor", - "path": "packages/story/src/index.ts", - "language": "typescript", - "symbol": "resolveAnchor", - "sha256": "f62fefd750bfcfddca1f8802fed2abb8cb0ca1519922bc4d4979623ce5450af7" - }, - { - "id": "render-story", - "path": "packages/diagram-core/src/index.ts", - "language": "typescript", - "symbol": "renderStory", - "sha256": "93578683a1fd4986b4fabd91b142ac75cac06d356ac5e7347c7317d271d12d2c" - }, - { - "id": "fresh-catalogue", - "path": "packages/cli/src/catalogue.ts", - "language": "typescript", - "symbol": "assertCatalogueCurrent", - "sha256": "a9b4f4b9145c69cbd818f7efa36253a6ce9056e88c191512448b50cef344cb28" - }, - { - "id": "fresh-snapshot", - "path": "packages/cli/src/source-snapshot.ts", - "language": "typescript", - "symbol": "assertSourceSnapshot", - "sha256": "5027a3c3ad3b16ebafd3eec698d5f5c9a8b1b211d2a8b71cf2d89dd53602feb6" - }, - { - "id": "publish-entry", - "path": "packages/cli/src/catalogue.ts", - "language": "typescript", - "symbol": "writeBuiltCatalogue", - "sha256": "a9b4f4b9145c69cbd818f7efa36253a6ce9056e88c191512448b50cef344cb28" - }, - { - "id": "publish-wrapper", - "path": "packages/cli/src/catalogue.ts", - "language": "typescript", - "symbol": "writeCatalogue", - "sha256": "a9b4f4b9145c69cbd818f7efa36253a6ce9056e88c191512448b50cef344cb28" - }, - { - "id": "publish-files", - "path": "packages/cli/src/catalogue.ts", - "language": "typescript", - "symbol": "publishCatalogue", - "sha256": "a9b4f4b9145c69cbd818f7efa36253a6ce9056e88c191512448b50cef344cb28" - }, - { - "id": "write-lock", - "path": "packages/workspace/src/index.ts", - "language": "typescript", - "symbol": "withWorkspaceLock", - "sha256": "df2c638987c1f8c0f27e12ad2f5463d8246767a219800d3fc3d1490889dd0253" - }, - { - "id": "transaction", - "path": "packages/workspace/src/index.ts", - "language": "typescript", - "symbol": "withGeneratedTransaction", - "sha256": "df2c638987c1f8c0f27e12ad2f5463d8246767a219800d3fc3d1490889dd0253" - }, - { - "id": "generated-write", - "path": "packages/workspace/src/index.ts", - "language": "typescript", - "symbol": "writeGenerated", - "sha256": "df2c638987c1f8c0f27e12ad2f5463d8246767a219800d3fc3d1490889dd0253" + "id": "authoring-guide", + "path": "docs/story-authoring.md", + "language": "text", + "sha256": "effa3dfed08ab628b5d9f5b4a35a21f9f40dcf355beba8037b9ec453ed3fddb5" }, { - "id": "cli-manifest", - "path": "packages/cli/package.json", + "id": "agent-skill", + "path": ".agents/skills/topo-story-authoring/SKILL.md", "language": "text", - "sha256": "e1aaebf5b0fe115fe56a658b71022c849e25120794cdbd1b063ccda97c880086" + "sha256": "c1725116905afd2e3387d4d934da5e102fff7da69e18cc8d955c815157cac35f" }, { - "id": "story-manifest", - "path": "packages/story/package.json", + "id": "cli-contract", + "path": "docs/cli.md", "language": "text", - "sha256": "996dc365b6c0bcdc3c4beaddb507c657cf97ee0412232c110f081013e0f7cfde" + "sha256": "42d611b4bf7b2c033927bc714de5d34f7a83ec732f824d3f937a15af42cba8f1" }, { - "id": "diagram-core-manifest", - "path": "packages/diagram-core/package.json", + "id": "enrichment-boundary", + "path": "docs/enrichment.md", "language": "text", - "sha256": "8e4b7a111ad4234367bc49e0b7b4827e880f9d489ce136a79650923b86cd7386" + "sha256": "7618a97ed64f81aab129188f9e11213a4d05586797a4173d34474908625b235f" }, { - "id": "workspace-manifest", - "path": "packages/workspace/package.json", + "id": "cli-manifest", + "path": "packages/cli/package.json", "language": "text", - "sha256": "02528f44aace1f01cff29eb9d1a3fc3c5b0beb1d456ba0876714012ff152bdd0" + "sha256": "e1aaebf5b0fe115fe56a658b71022c849e25120794cdbd1b063ccda97c880086" } ], "sections": [ { - "id": "cli", - "title": "Request preview", - "kind": "step", - "anchorIds": [ - "preview-command", - "cli-manifest" - ], - "body": "Owner: @topo/cli, runCli.\n\nInput: topo story preview . Check argument count and the initialized cache/site/index.html before doing work. The requested path is checked for membership AFTER buildCatalogue returns; it does not restrict rendering to one story.\n\nStories must be committed and unchanged. Repository source may be dirty; successful preview warns that evidence describes the working tree. No scanner or model is invoked by this branch." - }, - { - "id": "snapshot", - "title": "Load stories + snapshot", - "kind": "step", + "id": "user", + "title": "You", + "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": [ - "catalogue", - "snapshot", - "stable-read", - "cli-manifest" - ], - "body": "Owner: @topo/cli.\n\nCapture Git revision, status/diff fingerprint and history depth. Read committed stories, apply catalogue.storyIds when configured, and reject changed selected story documents. Capture each distinct referenced source file once.\n\nThe stable reader rejects escaped paths, symlinks, non-files, replaced files, or files changing during a read. A missing file is recorded as absent and rejected during anchor resolution. This is a bounded source snapshot, not a compiler build." + "authoring-guide", + "agent-skill" + ] }, { - "id": "story", - "title": "Resolve evidence", - "kind": "step", + "id": "agent", + "title": "Coding agent", + "body": "Read code and scan evidence, enrich the understanding, and author an anchored story. Repair diagnostics, preserve story identity, and commit only with authorization. Present the result for human review. Interpretation here does not require the separate topo enrich command.", "anchorIds": [ - "resolve-story", - "resolve-anchor", - "catalogue", - "story-manifest" - ], - "body": "Owner: @topo/story.\n\nFor each selected story, resolve every source anchor from the captured bytes. When a SHA-256 is authored, compare the whole file. Resolve requested symbols and exact excerpts; derive current line ranges and evidence text.\n\nMissing files/symbols/patterns, ambiguous patterns, and stale hashes fail explicitly. Successful resolution proves structure and evidence existence, not the narrative's truth or completeness." + "authoring-guide", + "agent-skill", + "enrichment-boundary" + ] }, { - "id": "diagram-core", - "title": "Render each story", - "kind": "step", - "anchorIds": [ - "default-renderer", - "catalogue", - "render-story", - "diagram-core-manifest" - ], - "body": "Owner: @topo/diagram-core.\n\nThe catalogue's default renderer delegates to renderStory. An explicit graphviz story selects Graphviz; otherwise the adapter verifies the pinned Archify runtime, builds its typed specification, calls native deliver, and applies Topocode's viewer adaptations.\n\nReturn HTML, renderer provenance, and backend-owned assets in memory. The catalogue adds source evidence and renderer receipts. Promise.all runs resolution/rendering per selected story; one rejected story prevents publication of the set." - }, - { - "id": "freshness", - "title": "Still current and selected?", - "kind": "decision", - "anchorIds": [ - "fresh-catalogue", - "fresh-snapshot", - "catalogue", - "preview-command", - "publish-entry" - ], - "body": "Owner: @topo/cli.\n\nAfter rendering, reread anchor files and compare Git revision, dirty state, and the status/diff fingerprint. runCli then checks that the requested story is in the built catalogue. writeBuiltCatalogue checks freshness again before acquiring the workspace lock.\n\nChanged evidence or a missing selected story refuses publication. These are explicit pre-publication checks, not a continuously held source-code lock." - }, - { - "id": "workspace", - "title": "Stage + replace output", - "kind": "step", - "anchorIds": [ - "publish-entry", - "publish-wrapper", - "publish-files", - "write-lock", - "transaction", - "generated-write", - "workspace-manifest" - ], - "body": "Owners: @topo/cli composes output; @topo/workspace controls publication.\n\nAcquire the workspace write lock. Inside withGeneratedTransaction, generate Home, story wrappers, viewer HTML, navigation/theme scripts, evidence and renderer assets; queue obsolete generated files for retirement.\n\nwriteGenerated collects bytes in the transaction. Prepare staged files/backups and check destination contents before replacing files. Authored stories and repository source are not rewritten. Lock acquisition and preparation failures stop before replacing the generation." - }, - { - "id": "screen", - "title": "Ready to browse", - "kind": "data", - "anchorIds": [ - "publish-files", - "generated-write", - "preview-command" - ], - "body": "Output: .topo/cache/site/ contains the refreshed selected catalogue, rendered viewers, source evidence, and provenance.\n\nThe CLI prints the selected story's generated path and a topo serve instruction. It does NOT launch a server or browser. An already-running local server can show the new generation after refresh; static hosting is a separate topo bundle/deployment step.\n\nGenerated cache is disposable. Committed stories, configuration, and repository source remain the durable inputs." - }, - { - "id": "refused", - "title": "Stop before publication", - "kind": "step", - "anchorIds": [ - "preview-command", - "catalogue", - "stable-read", - "resolve-anchor", - "render-story", - "fresh-catalogue", - "write-lock", - "transaction" - ], - "body": "An input, snapshot, anchor, renderer, freshness, selection, lock, or preparation error propagates as failure. Do not label it as a successful preview or replace existing viewer content with plausible fallback output.\n\nThese branches occur before replacing the generation. Fix the reported cause, then run preview again. Temporary locks/staging are not a promise that no transient filesystem activity occurred." - }, - { - "id": "rollback", - "title": "Attempt rollback", - "kind": "step", + "id": "cli", + "title": "Topocode CLI", + "body": "Initialize and optionally scan the repository without calling a model. Validate drafts and render committed stories. serve supplies a local viewer; bundle supplies static files. These are separate invocations across the collaboration cycle, not one long-running call.", "anchorIds": [ - "transaction", - "workspace-manifest" + "cli-contract", + "authoring-guide", + "cli-manifest" ], - "body": "Owner: @topo/workspace.\n\nOn a reported replacement error, walk already-committed replacements in reverse and restore backups (or remove newly created files). The original error is rethrown.\n\nRollback can itself fail: report an AggregateError and preserve rollback files for repair. This is rollback-capable publication, not crash-atomicity and not an unconditional guarantee that the prior generation survived." + "drilldown": { + "storyId": "cli-surface" + } } ], "connections": [ { - "from": "cli", - "to": "snapshot", - "label": "initialized", - "anchorIds": [ - "preview-command", - "catalogue" - ], - "rationale": "The preview branch checks the site and awaits buildCatalogue(root).", - "classification": "source-traced" + "from": "user", + "to": "agent", + "label": "Question, scope and intent" }, { - "from": "cli", - "to": "refused", - "label": "bad request / no site", - "anchorIds": [ - "preview-command" - ], - "rationale": "Argument and site-index preconditions throw before catalogue generation.", - "classification": "source-traced" - }, - { - "from": "snapshot", - "to": "story", - "label": "captured bytes", - "anchorIds": [ - "catalogue", - "snapshot", - "resolve-story" - ], - "rationale": "The captured snapshot loader is passed to resolveStoryDocument for each selected document.", - "classification": "source-traced" + "from": "agent", + "to": "cli", + "label": "Initialize; scan source" }, { - "from": "snapshot", - "to": "refused", - "label": "invalid or unstable input", - "anchorIds": [ - "catalogue", - "stable-read" - ], - "rationale": "Committed-story/config/path/read failures reject catalogue construction.", - "classification": "source-traced" + "from": "cli", + "to": "agent", + "label": "Graph, evidence, diagnostics", + "variant": "return" }, { - "from": "story", - "to": "diagram-core", - "label": "resolved story", - "anchorIds": [ - "catalogue", - "default-renderer" - ], - "rationale": "Each resolved document is awaited before renderer.render(resolved) is called.", - "classification": "source-traced" + "from": "agent", + "to": "agent", + "label": "Interpret; author anchored story" }, { - "from": "story", - "to": "refused", - "label": "missing / stale anchor", - "anchorIds": [ - "resolve-story", - "resolve-anchor" - ], - "rationale": "Anchor failures reject that story's Promise and prevent the catalogue from reaching publication.", - "classification": "source-traced" + "from": "agent", + "to": "cli", + "label": "Validate the draft" }, { - "from": "diagram-core", - "to": "freshness", - "label": "all artifacts ready", - "anchorIds": [ - "catalogue", - "fresh-catalogue" - ], - "rationale": "After every render succeeds and duplicate IDs are checked, buildCatalogue calls assertCatalogueCurrent.", - "classification": "source-traced" - }, - { - "from": "diagram-core", - "to": "refused", - "label": "renderer failure", - "anchorIds": [ - "render-story", - "catalogue" - ], - "rationale": "Backend errors and unsupported artifact types reject catalogue construction; no fallback viewer is published.", - "classification": "source-traced" + "from": "cli", + "to": "agent", + "label": "Anchor results; repair feedback", + "variant": "return" }, { - "from": "freshness", - "to": "workspace", - "label": "yes", - "anchorIds": [ - "preview-command", - "publish-entry" - ], - "rationale": "A current catalogue containing the requested story is passed through the second freshness check into the workspace lock and publication.", - "classification": "source-traced" + "from": "agent", + "to": "agent", + "label": "Commit with authorization" }, { - "from": "freshness", - "to": "refused", - "label": "no", - "anchorIds": [ - "fresh-catalogue", - "fresh-snapshot", - "preview-command" - ], - "rationale": "Changed anchor bytes/Git state or missing requested membership throws instead of publishing stale output.", - "classification": "source-traced" + "from": "agent", + "to": "cli", + "label": "Preview; serve or bundle" }, { - "from": "workspace", - "to": "screen", - "label": "replacement succeeds", - "anchorIds": [ - "transaction", - "publish-files", - "preview-command" - ], - "rationale": "After successful generated publication, runCli prints the rendered story and serve instruction.", - "classification": "source-traced" + "from": "cli", + "to": "agent", + "label": "Diagram and source evidence", + "variant": "return" }, { - "from": "workspace", - "to": "refused", - "label": "lock / preparation error", - "anchorIds": [ - "write-lock", - "transaction" - ], - "rationale": "A busy lock or failed preparation does not reach the replacement loop.", - "classification": "source-traced" + "from": "agent", + "to": "user", + "label": "Present architecture document", + "variant": "return" }, { - "from": "workspace", - "to": "rollback", - "label": "replacement error", - "anchorIds": [ - "transaction" - ], - "rationale": "Reported failures in the replacement loop restore already-committed files in reverse; incomplete rollback is explicitly reported.", - "classification": "source-traced" + "from": "user", + "to": "agent", + "label": "Review, refine, repeat" } ] } diff --git a/website/build.mjs b/website/build.mjs index 9d070ff..751e92f 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -131,8 +131,8 @@ npx --no topo serve .

A working Home, before your first map.

< 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 by responsibility, then follow an actual story through the system.

In Internal modules, open LENS to highlight or compare authored responsibility groups without moving the boxes. These arrows are selected manifest dependencies, not runtime traffic; click a module for its complete internal declarations.

Dependency context groups external tools by role. Story to screen is a different lens: source-traced calls, evidence checks, publication, and failure paths for topo story preview.

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

Meet the modules.

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

Click @topo/cli or @topo/diagram-core to open its public-surface diagram. The return link keeps your place. Other modules show their responsibility and complete internal declaration lists. LENS highlights authored responsibility groups; the arrows remain selected manifest dependencies, not runtime traffic.

Dependency context groups external tools by role. Idea to architecture shows you, your coding agent, and the CLI working through evidence, story authoring, presentation, review, and refinement.

+

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.

`)); diff --git a/website/build.test.mjs b/website/build.test.mjs index 137f38b..2fd8a1a 100644 --- a/website/build.test.mjs +++ b/website/build.test.mjs @@ -93,6 +93,21 @@ test("curated module maps retain all manifest declarations and reject stale evid ), /stale-source/); }); +test("module surface narratives cover actual root exports with signature-only function evidence", async () => { + for (const [id, modulePath] of [["cli-surface", "../packages/cli/dist/index.js"], ["diagram-core-surface", "../packages/diagram-core/dist/index.js"]]) { + const document = JSON.parse(await readFile(path.join(root, `stories/public/${id}.topo.json`), "utf8")); + const publicModule = await import(modulePath); + const narrative = document.sections.map(section => section.body).join("\n"); + for (const name of Object.keys(publicModule)) assert.ok(narrative.includes(name), `${id} must cover ${name}`); + for (const evidence of document.anchors.filter(anchor => anchor.pattern?.startsWith("export") && anchor.pattern.includes("function "))) { + assert.ok(evidence.pattern.trimEnd().endsWith("{")); + assert.doesNotMatch(evidence.pattern, /\bawait\s|\breturn\s/); + } + assert.equal(document.parent.storyId, "internal-modules"); + assert.equal(document.sections.length, 9); + } +}); + test("build only the curated story set for project Pages and custom-domain roots", async () => { const original = process.env.SITE_BASE_PATH; try { @@ -106,10 +121,12 @@ test("build only the curated story set for project Pages and custom-domain roots const home = await readFile(path.join(output, "demo/home/index.html"), "utf8"); const state = JSON.parse(await readFile(path.join(output, "demo/home/site-state.json"), "utf8")); assert.match(home, /data-topo-shell/); - assert.equal((home.match(/data-kind="story"/g) ?? []).length, 3); + assert.equal((home.match(/data-kind="story"/g) ?? []).length, 5); assert.match(home, /Topocode internal modules/); assert.match(home, /Dependency context by role/); - assert.match(home, /Story to screen/); + assert.match(home, /From idea to architecture/); + assert.match(home, /@topo\/cli: public surface/); + assert.match(home, /@topo\/diagram-core: public surface/); assert.doesNotMatch(home, /Workflow capability|topo-packages/); assert.match(JSON.stringify(state), /unscanned/); assert.match(await readFile(path.join(output, "index.html"), "utf8"), new RegExp(`${base}assets/client.mjs`)); @@ -118,8 +135,9 @@ test("build only the curated story set for project Pages and custom-domain roots const evidence = JSON.parse(await readFile(path.join(output, "demo/home/stories/dependency-context/evidence.json"), "utf8")); assert.equal(evidence.anchors.length, 16); const flow = JSON.parse(await readFile(path.join(output, "demo/home/stories/story-to-screen/evidence.json"), "utf8")); - assert.equal(flow.connections.length, 13); - assert.ok(flow.connections.every(edge => edge.classification === "source-traced" && edge.anchorIds.length > 0)); + assert.equal(flow.connections.length, 11); + assert.equal(flow.connections.at(-1).label, "Review, refine, repeat"); + assert.ok(flow.connections.every(edge => edge.label)); assert.ok(flow.anchors.every(anchor => /^[a-f0-9]{64}$/.test(anchor.sha256))); if (base === "/") { const rootOutput = path.join(root, "dist/public-site-root"); diff --git a/website/demo-palette.css b/website/demo-palette.css index 0c0327a..2b4ec2b 100644 --- a/website/demo-palette.css +++ b/website/demo-palette.css @@ -4,6 +4,7 @@ :root[data-website-palette] .catalogue-panel, :root[data-website-palette] .catalogue-panel::before, :root[data-website-palette] .brand-row, +:root[data-website-palette] .story-breadcrumb, :root[data-website-palette] input, :root[data-website-palette] select, :root[data-website-palette] button { background: var(--panel); color: var(--text); border-color: var(--line); } diff --git a/website/demo/.topo/config.json b/website/demo/.topo/config.json index 3fb51b1..457f1d3 100644 --- a/website/demo/.topo/config.json +++ b/website/demo/.topo/config.json @@ -4,8 +4,8 @@ "modules": [], "catalogue": { "title": "Topocode", - "description": "Explore module responsibilities with semantic lenses, inspect dependency context, or follow a story from preview request to generated browser files.", + "description": "Explore module responsibilities, drill into the CLI and renderer's exposed interfaces, or follow the human-agent loop from an idea to a reviewed architecture document.", "accentColor": "#80d8ed", - "storyIds": ["internal-modules", "dependency-context", "story-to-screen"] + "storyIds": ["internal-modules", "dependency-context", "story-to-screen", "cli-surface", "diagram-core-surface"] } } diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index 46dc2ab..a849967 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -89,17 +89,17 @@ test("module details preserve complete dependencies and cross-story return navig await page.goto("demo/"); const frame = page.frameLocator("[data-demo]"); const viewer = frame.frameLocator("[data-story-viewer]"); - await viewer.locator('svg g[data-node-id="cli"]').click(); + await viewer.locator('svg g[data-node-id="languages"]').click(); await expect(frame.locator(".story-details")).toHaveAttribute("open", ""); - await expect(frame.locator('[data-section-evidence="cli"] > p')).toContainText("@topo/cli -> @topo/schema [dependencies: workspace:*]"); - const link = frame.locator('a[data-cross-story][data-source-node="cli"]').filter({ hasText: "Build, test, docs" }); + await expect(frame.locator('[data-section-evidence="languages"] > p')).toContainText("@topo/languages -> @topo/scanner [dependencies: workspace:*]"); + const link = frame.locator('a[data-cross-story][data-source-node="languages"]').filter({ hasText: "Code analysis" }); await link.click(); await expect(frame.locator("body")).toHaveAttribute("data-story-id", "dependency-context"); - await expect(frame.locator('[data-section-evidence="tooling-consumers"] > p')).toContainText("devDependencies"); + await expect(frame.locator('[data-section-evidence="analysis-consumers"] > p')).toContainText("optionalDependencies"); await expect(frame.locator("[data-return]")).toBeVisible(); await frame.locator("[data-return]").click(); await expect(frame.locator("body")).toHaveAttribute("data-story-id", "internal-modules"); - await expect(frame.locator('[data-section-evidence="cli"]')).toBeVisible(); + await expect(frame.locator('[data-section-evidence="languages"]')).toBeVisible(); await page.getByRole("link", { name: "Dependency context", exact: true }).click(); await expect(frame.locator("body")).toHaveAttribute("data-story-id", "dependency-context"); await expect(frame.frameLocator("[data-story-viewer]").locator("svg g[data-node-id]")).toHaveCount(10); @@ -159,40 +159,36 @@ test("semantic lenses classify responsibilities, preserve geometry, and compare expect(await geometry()).toEqual(before); }); -test("story-to-screen exposes actual phases, failure evidence, and module drillbacks", async ({ page }) => { +test("idea-to-architecture sequence shows the collaboration and review loop", async ({ page }) => { await page.goto("demo/"); - await page.getByRole("link", { name: "Story to screen", exact: true }).click(); + await page.getByRole("link", { name: "Idea to architecture", exact: true }).click(); const wrapper = page.frameLocator("[data-demo]"); await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "story-to-screen"); const flow = wrapper.frameLocator("[data-story-viewer]"); - await expect(flow.locator("svg g[data-node-id]")).toHaveCount(9); - await expect(flow.locator("svg g[data-edge-index]")).toHaveCount(13); - await flow.locator('svg g[data-node-id="rollback"]').click(); - await expect(wrapper.locator('[data-section-evidence="rollback"] > p')).toContainText("not crash-atomicity"); - await expect(wrapper.locator('[data-section-evidence="rollback"]')).toContainText("AggregateError"); + await expect(flow.locator("svg g[data-node-id]")).toHaveCount(3); + await expect(flow.locator("svg")).toContainText("Review, refine, repeat"); + await expect(flow.locator("svg")).toContainText("Interpret; author anchored story"); + await expect(flow.locator("svg")).toContainText("Commit with authorization"); await flow.locator('svg g[data-node-id="cli"]').click(); - const back = wrapper.locator('a[data-cross-story][data-source-node="cli"]') - .filter({ hasText: "Topocode internal modules: @topo/cli" }); - await back.click(); - await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "internal-modules"); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); await expect(wrapper.locator("[data-return]")).toBeVisible(); await wrapper.locator("[data-return]").click(); await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "story-to-screen"); await expect(wrapper.locator('[data-section-evidence="cli"]')).toBeVisible(); }); -test("execution lens remains readable without internal scrolling on desktop", async ({ page }) => { +test("collaboration sequence remains readable on desktop", async ({ page }) => { for (const [width, height] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) { await page.setViewportSize({ width, height }); await page.goto("demo/home/stories/story-to-screen/viewer.html"); - const metrics = await page.locator("svg").evaluate(svg => { + await page.evaluate(() => document.fonts.ready); + const metrics = await page.locator('svg[role="img"]').evaluate(svg => { const scale = svg.getScreenCTM().a; - const main = document.querySelector("main"); + const labels = [...svg.querySelectorAll("text")].filter(text => text.textContent.trim() && getComputedStyle(text).display !== "none"); return { overflow: document.documentElement.scrollWidth > innerWidth || - document.documentElement.scrollHeight > innerHeight || - main.scrollWidth > main.clientWidth || main.scrollHeight > main.clientHeight, - textFloor: Math.min(...[...svg.querySelectorAll("text")].map(text => parseFloat(getComputedStyle(text).fontSize) * scale)), + document.documentElement.scrollHeight > innerHeight, + textFloor: Math.min(...labels.map(text => parseFloat(getComputedStyle(text).fontSize) * scale)), }; }); expect(metrics.overflow).toBe(false); @@ -201,7 +197,7 @@ test("execution lens remains readable without internal scrolling on desktop", as }); test("curated maps fit desktop viewports with readable role captions", async ({ page }) => { - for (const [id, count] of [["internal-modules", 13], ["dependency-context", 10]]) { + for (const [id, count] of [["internal-modules", 13], ["dependency-context", 10], ["cli-surface", 9], ["diagram-core-surface", 9]]) { for (const [width, height] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) { await page.setViewportSize({ width, height }); await page.goto(`demo/home/stories/${id}/viewer.html`); @@ -223,6 +219,35 @@ test("curated maps fit desktop viewports with readable role captions", async ({ }).length, }; }); + + test("module boxes drill into public surfaces with clear nested and direct returns", async ({ page }) => { + await page.goto("demo/"); + const wrapper = page.frameLocator("[data-demo]"); + await wrapper.getByLabel("Filter diagrams").fill("cli"); + await wrapper.frameLocator("[data-story-viewer]").locator('svg g[data-node-id="cli"]').click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); + await expect(wrapper.locator("[data-return]")).toBeVisible(); + await expect(wrapper.locator("[data-return]")).toContainText("Topocode internal modules"); + await expect(wrapper.frameLocator("[data-story-viewer]").locator("svg g[data-node-id]")).toHaveCount(9); + await wrapper.frameLocator("[data-story-viewer]").locator('svg g[data-node-id="diagram-core"]').click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "diagram-core-surface"); + await expect(wrapper.locator("[data-return]")).toContainText("@topo/cli: public surface"); + await wrapper.locator("[data-return]").click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); + await wrapper.frameLocator("[data-story-viewer]").locator("#btn-semantic-lens").click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); + await wrapper.locator("[data-return]").click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "internal-modules"); + await page.goto("demo/home/stories/diagram-core-surface/"); + await expect(page.locator("[data-return]")).toBeVisible(); + await expect(page.locator("[data-return]")).toContainText("Topocode internal modules"); + await page.reload(); + await expect(page.locator("[data-return]")).toBeVisible(); + await page.goto("demo/home/stories/internal-modules/viewer.html"); + await page.locator('svg g[data-node-id="diagram-core"]').click(); + await expect(page).toHaveURL(/stories\/diagram-core-surface\/\?from=internal-modules/); + await expect(page.locator("[data-return]")).toBeVisible(); + }); expect(metrics, `${id} at ${width}x${height}`).toMatchObject({ overflowX: false, overflowY: false, captionOverlaps: 0 }); expect(metrics.captionFloor).toBeGreaterThanOrEqual(12); } From ebe64a19d0a190b2231c4c6c6deae576730f0d2b Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 13:57:06 -0400 Subject: [PATCH 14/39] docs(sequence): show the repository collaboration boundary Represent source reads and authored-story writes as interactions with the real repository, rather than unsupported self-message geometry. --- stories/public/story-to-screen.topo.json | 26 +++++++++++++++++++++--- website/build.test.mjs | 2 +- website/tests/site.spec.mjs | 4 ++-- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/stories/public/story-to-screen.topo.json b/stories/public/story-to-screen.topo.json index 0a86859..0da1009 100644 --- a/stories/public/story-to-screen.topo.json +++ b/stories/public/story-to-screen.topo.json @@ -36,6 +36,12 @@ "path": "packages/cli/package.json", "language": "text", "sha256": "e1aaebf5b0fe115fe56a658b71022c849e25120794cdbd1b063ccda97c880086" + }, + { + "id": "repository-workspace", + "path": "docs/workspace.md", + "language": "text", + "sha256": "5ee9bc0818206b67cb7e3fde77b038e036f826d10ac2a153c6703b6644909bbe" } ], "sections": [ @@ -70,6 +76,15 @@ "drilldown": { "storyId": "cli-surface" } + }, + { + "id": "repository", + "title": "Repository", + "body": "Holds source code, configuration, and authored stories. The agent writes and commits the story; the CLI reads source and generates disposable cache/output. This is a file and Git boundary, not a separate hosted service.", + "anchorIds": [ + "repository-workspace", + "agent-skill" + ] } ], "connections": [ @@ -83,6 +98,11 @@ "to": "cli", "label": "Initialize; scan source" }, + { + "from": "cli", + "to": "repository", + "label": "Read code (no model)" + }, { "from": "cli", "to": "agent", @@ -91,8 +111,8 @@ }, { "from": "agent", - "to": "agent", - "label": "Interpret; author anchored story" + "to": "repository", + "label": "Write interpreted story" }, { "from": "agent", @@ -107,7 +127,7 @@ }, { "from": "agent", - "to": "agent", + "to": "repository", "label": "Commit with authorization" }, { diff --git a/website/build.test.mjs b/website/build.test.mjs index 2fd8a1a..82a209f 100644 --- a/website/build.test.mjs +++ b/website/build.test.mjs @@ -135,7 +135,7 @@ test("build only the curated story set for project Pages and custom-domain roots const evidence = JSON.parse(await readFile(path.join(output, "demo/home/stories/dependency-context/evidence.json"), "utf8")); assert.equal(evidence.anchors.length, 16); const flow = JSON.parse(await readFile(path.join(output, "demo/home/stories/story-to-screen/evidence.json"), "utf8")); - assert.equal(flow.connections.length, 11); + assert.equal(flow.connections.length, 12); assert.equal(flow.connections.at(-1).label, "Review, refine, repeat"); assert.ok(flow.connections.every(edge => edge.label)); assert.ok(flow.anchors.every(anchor => /^[a-f0-9]{64}$/.test(anchor.sha256))); diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index a849967..19aace7 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -165,9 +165,9 @@ test("idea-to-architecture sequence shows the collaboration and review loop", as const wrapper = page.frameLocator("[data-demo]"); await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "story-to-screen"); const flow = wrapper.frameLocator("[data-story-viewer]"); - await expect(flow.locator("svg g[data-node-id]")).toHaveCount(3); + await expect(flow.locator("svg g[data-node-id]")).toHaveCount(4); await expect(flow.locator("svg")).toContainText("Review, refine, repeat"); - await expect(flow.locator("svg")).toContainText("Interpret; author anchored story"); + await expect(flow.locator("svg")).toContainText("Write interpreted story"); await expect(flow.locator("svg")).toContainText("Commit with authorization"); await flow.locator('svg g[data-node-id="cli"]').click(); await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); From df93e2895b987c6285a9bd1db3500e70a7f345ca Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 14:23:23 -0400 Subject: [PATCH 15/39] fix(diagrams): clarify surfaces and sequence framing Keep export relationships explicit in API-group captions without repeating crowded spoke labels. Use authored participant roles and height-aware outer reading width for the collaboration sequence. Preserve public signatures, diagram geometry, and pinned renderers. --- docs/public-website.md | 3 +- docs/story-preview.md | 6 +- packages/cli/src/catalogue.ts | 3 + packages/diagram-core/src/index.ts | 61 +++++++++++-------- packages/diagram-core/src/theme.ts | 3 + .../site/tests/e2e/sequence-stories.spec.ts | 6 +- packages/story/src/index.ts | 4 +- packages/story/src/story.test.ts | 3 + packages/story/story.schema.json | 2 +- stories/public/cli-surface.topo.json | 29 ++++----- stories/public/diagram-core-surface.topo.json | 34 +++++------ stories/public/internal-modules.topo.json | 4 +- stories/public/story-to-screen.topo.json | 4 ++ website/tests/site.spec.mjs | 9 ++- 14 files changed, 96 insertions(+), 75 deletions(-) diff --git a/docs/public-website.md b/docs/public-website.md index 645bea2..b2daa8a 100644 --- a/docs/public-website.md +++ b/docs/public-website.md @@ -88,7 +88,8 @@ 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 interprets and authors, the CLI validates/previews, you review, and the -cycle repeats. This is the documented collaboration workflow, not a call trace +cycle repeats. The repository lifeline makes source reads and authorized story +writes explicit. 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. Commits still require authorization. diff --git a/docs/story-preview.md b/docs/story-preview.md index f18514e..4c1eb98 100644 --- a/docs/story-preview.md +++ b/docs/story-preview.md @@ -16,16 +16,16 @@ caption field. This caption is an unreleased repository-build capability, not part of the published npm 0.2.0 story contract. -Architecture sections can also author `semanticRole`, a lowercase hyphenated +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"` entries, never a frontend/backend guess based on position. +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. -Architecture receipts identify `topocode-story-semantics-v2` and distinguish +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. diff --git a/packages/cli/src/catalogue.ts b/packages/cli/src/catalogue.ts index 1ffc99a..97ffe79 100644 --- a/packages/cli/src/catalogue.ts +++ b/packages/cli/src/catalogue.ts @@ -440,7 +440,10 @@ const STORY_NAVIGATION_SCRIPT = `(() => { setFocus(nodeId); } + let navigating = false; function follow(link) { + if (navigating) return; + navigating = true; const sourceNodeId = link.getAttribute("data-source-node"); if (sourceNodeId) { const current = new URL(window.location.href); diff --git a/packages/diagram-core/src/index.ts b/packages/diagram-core/src/index.ts index 5967ae5..cb323d5 100644 --- a/packages/diagram-core/src/index.ts +++ b/packages/diagram-core/src/index.ts @@ -985,11 +985,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 : "", })), @@ -1396,18 +1394,19 @@ function serializeRendererInput(spec: { readonly meta: object }): string { }, null, 2)}\n`; } -function adaptArchitectureSemantics(contents: string, document: StoryDocument): string { - const roles = new Map(document.sections.map(section => [componentId(section.id), section.semanticRole ?? "component"])); +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 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(`Architecture node ${id} has no semantic metadata`); + if (!/\bdata-node-kind="[^"]*"/.test(tag)) throw new Error(`Story node ${id} has no semantic metadata`); seen.add(id); return tag.replace(/\bdata-node-kind="[^"]*"/, `data-node-kind="${role}"`); }); - if (seen.size !== roles.size) throw new Error("Architecture semantic adaptation omitted an authored node"); + if (seen.size !== roles.size) throw new Error("Story semantic adaptation omitted an authored node"); const replacements: readonly [RegExp, string][] = [ [/(]*id="semantic-lens-title"[^>]*>)[^<]*(<\/strong>)/, "$1Compare responsibilities$2"], @@ -1429,12 +1428,22 @@ 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; } @@ -1443,14 +1452,7 @@ svg { max-height: 100vh; } svg [data-source-evidence-beacon] { display: none; } svg text[data-node-label], svg g[data-edge-from] > text { font-size: ${architectureFontSize}px; } -svg text[data-detail="context"] { font-size: 17px; transform: translateY(12px); } -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; }` +svg text[data-detail="context"] { font-size: 17px; transform: translateY(12px); }` : family === "workflow" ? ` svg text[data-node-label], @@ -1463,8 +1465,14 @@ svg g[data-edge-from] > text { : family === "sequence" ? ` svg { max-height: 100vh; } +@media (min-width: 1400px) and (min-height: 900px) { + html[data-topo-app] .container { max-width: min(calc(100vw - 64px), calc((100dvh - 172px) * ${sequenceRatio} + 48px)); } +} +@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)); } +} svg text { - font-size: ${sequenceFontSize}px; + font-size: ${sequence?.fontSize}px; } .semantic-passport-detail { font-size: 0.875rem; @@ -1486,7 +1494,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) => { @@ -1543,8 +1551,9 @@ svg g[data-edge-from] > text { return next; }, contents) : contents; - const accessibleContents = family === "architecture" - ? adjustedContents.replace(/(]*data-diagram-type="architecture")[^>]*\brole=)"img"/, '$1"group"') + const accessibleContents = family === "architecture" || family === "sequence" + ? adjustedContents.replace(/]*\brole="img"[^>]*>/, tag => + tag.replace('role="img"', 'role="group"').replace(" { @@ -821,7 +821,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/story/src/index.ts b/packages/story/src/index.ts index 456e920..9b4e200 100644 --- a/packages/story/src/index.ts +++ b/packages/story/src/index.ts @@ -319,8 +319,8 @@ function validateStoryDocument(value: unknown): string | undefined { if (sectionValue.semanticRole !== undefined && (typeof sectionValue.semanticRole !== "string" || !/^(?!constructor$)[a-z][a-z0-9-]{0,63}$/.test(sectionValue.semanticRole) || - diagramFamily !== "architecture")) { - return `sections[${index}].semanticRole requires an architecture role slug`; + (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 3b97f6e..1255bf4 100644 --- a/packages/story/src/story.test.ts +++ b/packages/story/src/story.test.ts @@ -69,6 +69,9 @@ describe("story document contract", () => { 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 => ({ diff --git a/packages/story/story.schema.json b/packages/story/story.schema.json index 8755946..7f8acae 100644 --- a/packages/story/story.schema.json +++ b/packages/story/story.schema.json @@ -110,7 +110,7 @@ }, { "if": { "properties": { "sections": { "type": "array", "contains": { "type": "object", "properties": { "semanticRole": {} }, "required": ["semanticRole"] } } } }, - "then": { "properties": { "diagramFamily": { "const": "architecture" } } } + "then": { "properties": { "diagramFamily": { "enum": ["architecture", "sequence"] } } } }, { "if": { "properties": { "renderer": { "const": "graphviz" } }, "required": ["renderer"] }, diff --git a/stories/public/cli-surface.topo.json b/stories/public/cli-surface.topo.json index 7fffe34..59b9d41 100644 --- a/stories/public/cli-surface.topo.json +++ b/stories/public/cli-surface.topo.json @@ -9,7 +9,7 @@ "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.", + "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", @@ -226,7 +226,7 @@ { "id": "generation", "title": "Generation API", - "summary": "Graph and report artifacts", + "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", @@ -256,7 +256,7 @@ { "id": "serving", "title": "Serving API", - "summary": "Server and local URL", + "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", @@ -268,7 +268,7 @@ { "id": "cli", "title": "@topo/cli", - "summary": "Package boundary", + "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", @@ -279,7 +279,7 @@ { "id": "bundling", "title": "Bundling API", - "summary": "Static output contract", + "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", @@ -292,7 +292,7 @@ { "id": "enrichment", "title": "Enrichment API", - "summary": "Explicit provider invocation", + "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", @@ -306,7 +306,7 @@ { "id": "views", "title": "Curated-view API", - "summary": "Views, saves and conflicts", + "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", @@ -347,28 +347,23 @@ }, { "from": "cli", - "to": "generation", - "label": "exports" + "to": "generation" }, { "from": "cli", - "to": "serving", - "label": "exports" + "to": "serving" }, { "from": "cli", - "to": "bundling", - "label": "exports" + "to": "bundling" }, { "from": "cli", - "to": "enrichment", - "label": "exports" + "to": "enrichment" }, { "from": "cli", - "to": "views", - "label": "exports" + "to": "views" }, { "from": "generation", diff --git a/stories/public/diagram-core-surface.topo.json b/stories/public/diagram-core-surface.topo.json index bc46bdd..5496ee5 100644 --- a/stories/public/diagram-core-surface.topo.json +++ b/stories/public/diagram-core-surface.topo.json @@ -9,7 +9,7 @@ "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.", + "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", @@ -39,28 +39,28 @@ "id": "render-story", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", "pattern": "export function renderStory(story: ResolvedStoryDocument): StoryArtifact | Promise {" }, { "id": "render-array", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", "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": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", "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": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", "pattern": "export function architectureComponentWidth(\n title: string,\n sublabel = \"\",\n finalTypography = false,\n): number {" }, { @@ -81,28 +81,28 @@ "id": "resolved-story", "path": "packages/story/src/index.ts", "language": "text", - "sha256": "5e035e2eecfd25ad8451d0bf1d3dc84eae14f5e6e9b11700de2e006b970140da", + "sha256": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27", "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": "5e035e2eecfd25ad8451d0bf1d3dc84eae14f5e6e9b11700de2e006b970140da", + "sha256": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27", "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": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", "pattern": "export { CORE_THEME_SCRIPT } from \"./theme.js\";" }, { "id": "integrity-export", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e", + "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", "pattern": "export {\n verifyArchifyIntegrity,\n type ArchifyIntegrity,\n} from \"./integrity.js\";" } ], @@ -142,7 +142,7 @@ { "id": "batch", "title": "Architecture batch API", - "summary": "Array or generator result", + "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", @@ -153,7 +153,7 @@ { "id": "diagram-core", "title": "@topo/diagram-core", - "summary": "Package-root exports", + "summary": "Exports the API groups", "body": "The root exports renderStory, renderArchitectureStories, renderArchitectureStoryBatch, verifyArchifyIntegrity, the ArchifyIntegrity type, architectureComponentWidth, 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", @@ -217,23 +217,19 @@ "connections": [ { "from": "diagram-core", - "to": "render", - "label": "exports" + "to": "render" }, { "from": "diagram-core", - "to": "batch", - "label": "exports" + "to": "batch" }, { "from": "diagram-core", - "to": "integrity", - "label": "exports" + "to": "integrity" }, { "from": "diagram-core", - "to": "utilities", - "label": "exports" + "to": "utilities" }, { "from": "render", diff --git a/stories/public/internal-modules.topo.json b/stories/public/internal-modules.topo.json index 9380b63..b2ec524 100644 --- a/stories/public/internal-modules.topo.json +++ b/stories/public/internal-modules.topo.json @@ -125,7 +125,7 @@ "id": "diagram-core-implementation", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "637b738763f90aba463010c19626649e4d6703c49018a369167cb4b73568c45e" + "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776" }, { "id": "languages-implementation", @@ -161,7 +161,7 @@ "id": "story-implementation", "path": "packages/story/src/index.ts", "language": "text", - "sha256": "5e035e2eecfd25ad8451d0bf1d3dc84eae14f5e6e9b11700de2e006b970140da" + "sha256": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27" } ], "sections": [ diff --git a/stories/public/story-to-screen.topo.json b/stories/public/story-to-screen.topo.json index 0da1009..2d3a635 100644 --- a/stories/public/story-to-screen.topo.json +++ b/stories/public/story-to-screen.topo.json @@ -48,6 +48,7 @@ { "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", @@ -57,6 +58,7 @@ { "id": "agent", "title": "Coding agent", + "semanticRole": "coding-agent", "body": "Read code and scan evidence, enrich the understanding, and author an anchored story. Repair diagnostics, preserve story identity, and commit only with authorization. Present the result for human review. Interpretation here does not require the separate topo enrich command.", "anchorIds": [ "authoring-guide", @@ -67,6 +69,7 @@ { "id": "cli", "title": "Topocode CLI", + "semanticRole": "command-line-tool", "body": "Initialize and optionally scan the repository without calling a model. Validate drafts and render committed stories. serve supplies a local viewer; bundle supplies static files. These are separate invocations across the collaboration cycle, not one long-running call.", "anchorIds": [ "cli-contract", @@ -80,6 +83,7 @@ { "id": "repository", "title": "Repository", + "semanticRole": "repository", "body": "Holds source code, configuration, and authored stories. The agent writes and commits the story; the CLI reads source and generates disposable cache/output. This is a file and Git boundary, not a separate hosted service.", "anchorIds": [ "repository-workspace", diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index 19aace7..f7a32cc 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -166,6 +166,8 @@ test("idea-to-architecture sequence shows the collaboration and review loop", as await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "story-to-screen"); const flow = wrapper.frameLocator("[data-story-viewer]"); await expect(flow.locator("svg g[data-node-id]")).toHaveCount(4); + expect(await flow.locator("svg g[data-node-id]").evaluateAll(nodes => nodes.map(node => node.dataset.nodeKind))) + .toEqual(["human", "coding-agent", "command-line-tool", "repository"]); await expect(flow.locator("svg")).toContainText("Review, refine, repeat"); await expect(flow.locator("svg")).toContainText("Write interpreted story"); await expect(flow.locator("svg")).toContainText("Commit with authorization"); @@ -182,7 +184,7 @@ test("collaboration sequence remains readable on desktop", async ({ page }) => { await page.setViewportSize({ width, height }); await page.goto("demo/home/stories/story-to-screen/viewer.html"); await page.evaluate(() => document.fonts.ready); - const metrics = await page.locator('svg[role="img"]').evaluate(svg => { + const metrics = await page.locator('svg[data-topo-family="sequence"]').evaluate(svg => { const scale = svg.getScreenCTM().a; const labels = [...svg.querySelectorAll("text")].filter(text => text.textContent.trim() && getComputedStyle(text).display !== "none"); return { @@ -207,6 +209,7 @@ test("curated maps fit desktop viewports with readable role captions", async ({ await expect(diagram.locator("g[data-node-id]")).toHaveCount(count); const metrics = await diagram.evaluate(svg => { const scale = svg.getBoundingClientRect().width / svg.viewBox.baseVal.width; + const labels = [...svg.querySelectorAll("g[data-edge-from] > text")].map(text => text.getBoundingClientRect()); return { overflowX: document.documentElement.scrollWidth > innerWidth, overflowY: document.documentElement.scrollHeight > innerHeight, @@ -217,6 +220,9 @@ test("curated maps fit desktop viewports with readable role captions", async ({ const caption = node.querySelector('text[data-detail="context"]')?.getBoundingClientRect(); return title && caption && caption.top < title.bottom; }).length, + edgeLabelOverlaps: labels.flatMap((a, index) => labels.slice(index + 1).filter(b => + Math.min(a.right, b.right) - Math.max(a.left, b.left) > 1 && + Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top) > 1)).length, }; }); @@ -250,6 +256,7 @@ test("curated maps fit desktop viewports with readable role captions", async ({ }); expect(metrics, `${id} at ${width}x${height}`).toMatchObject({ overflowX: false, overflowY: false, captionOverlaps: 0 }); expect(metrics.captionFloor).toBeGreaterThanOrEqual(12); + if (id.endsWith("-surface")) expect(metrics.edgeLabelOverlaps).toBe(0); } } }); From a7c85edefba89a4a24b200eb4074793d6a645924 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 14:44:26 -0400 Subject: [PATCH 16/39] fix(viewer): bound sequence framing and evidence cards Fit the measured viewer chrome while preserving readable SVG scale. Keep narrow evidence cards within their pane and anchor their contents to the top so related-story links remain reachable. --- packages/cli/src/catalogue.ts | 4 +- packages/diagram-core/src/index.ts | 5 +- stories/public/diagram-core-surface.topo.json | 12 ++-- stories/public/internal-modules.topo.json | 2 +- website/tests/site.spec.mjs | 63 ++++++++++--------- 5 files changed, 45 insertions(+), 41 deletions(-) diff --git a/packages/cli/src/catalogue.ts b/packages/cli/src/catalogue.ts index 97ffe79..5c80248 100644 --- a/packages/cli/src/catalogue.ts +++ b/packages/cli/src/catalogue.ts @@ -1096,8 +1096,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); } diff --git a/packages/diagram-core/src/index.ts b/packages/diagram-core/src/index.ts index cb323d5..26e9b1a 100644 --- a/packages/diagram-core/src/index.ts +++ b/packages/diagram-core/src/index.ts @@ -1466,7 +1466,10 @@ svg g[data-edge-from] > text { ? ` svg { max-height: 100vh; } @media (min-width: 1400px) and (min-height: 900px) { - html[data-topo-app] .container { max-width: min(calc(100vw - 64px), calc((100dvh - 172px) * ${sequenceRatio} + 48px)); } + 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)); } diff --git a/stories/public/diagram-core-surface.topo.json b/stories/public/diagram-core-surface.topo.json index 5496ee5..7b78257 100644 --- a/stories/public/diagram-core-surface.topo.json +++ b/stories/public/diagram-core-surface.topo.json @@ -39,28 +39,28 @@ "id": "render-story", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", + "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", "pattern": "export function renderStory(story: ResolvedStoryDocument): StoryArtifact | Promise {" }, { "id": "render-array", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", + "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", "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": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", + "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", "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": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", + "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", "pattern": "export function architectureComponentWidth(\n title: string,\n sublabel = \"\",\n finalTypography = false,\n): number {" }, { @@ -95,14 +95,14 @@ "id": "theme-export", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", + "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", "pattern": "export { CORE_THEME_SCRIPT } from \"./theme.js\";" }, { "id": "integrity-export", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776", + "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", "pattern": "export {\n verifyArchifyIntegrity,\n type ArchifyIntegrity,\n} from \"./integrity.js\";" } ], diff --git a/stories/public/internal-modules.topo.json b/stories/public/internal-modules.topo.json index b2ec524..a85db65 100644 --- a/stories/public/internal-modules.topo.json +++ b/stories/public/internal-modules.topo.json @@ -125,7 +125,7 @@ "id": "diagram-core-implementation", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "c0436026fae0d1948637891469730dfcc88fa1bdd23ac019a1c9b977691c9776" + "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d" }, { "id": "languages-implementation", diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index f7a32cc..bb3fad4 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -168,9 +168,9 @@ test("idea-to-architecture sequence shows the collaboration and review loop", as await expect(flow.locator("svg g[data-node-id]")).toHaveCount(4); expect(await flow.locator("svg g[data-node-id]").evaluateAll(nodes => nodes.map(node => node.dataset.nodeKind))) .toEqual(["human", "coding-agent", "command-line-tool", "repository"]); - await expect(flow.locator("svg")).toContainText("Review, refine, repeat"); - await expect(flow.locator("svg")).toContainText("Write interpreted story"); - await expect(flow.locator("svg")).toContainText("Commit with authorization"); + await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Review, refine, repeat"); + await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Write interpreted story"); + await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Commit with authorization"); await flow.locator('svg g[data-node-id="cli"]').click(); await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); await expect(wrapper.locator("[data-return]")).toBeVisible(); @@ -226,34 +226,6 @@ test("curated maps fit desktop viewports with readable role captions", async ({ }; }); - test("module boxes drill into public surfaces with clear nested and direct returns", async ({ page }) => { - await page.goto("demo/"); - const wrapper = page.frameLocator("[data-demo]"); - await wrapper.getByLabel("Filter diagrams").fill("cli"); - await wrapper.frameLocator("[data-story-viewer]").locator('svg g[data-node-id="cli"]').click(); - await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); - await expect(wrapper.locator("[data-return]")).toBeVisible(); - await expect(wrapper.locator("[data-return]")).toContainText("Topocode internal modules"); - await expect(wrapper.frameLocator("[data-story-viewer]").locator("svg g[data-node-id]")).toHaveCount(9); - await wrapper.frameLocator("[data-story-viewer]").locator('svg g[data-node-id="diagram-core"]').click(); - await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "diagram-core-surface"); - await expect(wrapper.locator("[data-return]")).toContainText("@topo/cli: public surface"); - await wrapper.locator("[data-return]").click(); - await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); - await wrapper.frameLocator("[data-story-viewer]").locator("#btn-semantic-lens").click(); - await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); - await wrapper.locator("[data-return]").click(); - await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "internal-modules"); - await page.goto("demo/home/stories/diagram-core-surface/"); - await expect(page.locator("[data-return]")).toBeVisible(); - await expect(page.locator("[data-return]")).toContainText("Topocode internal modules"); - await page.reload(); - await expect(page.locator("[data-return]")).toBeVisible(); - await page.goto("demo/home/stories/internal-modules/viewer.html"); - await page.locator('svg g[data-node-id="diagram-core"]').click(); - await expect(page).toHaveURL(/stories\/diagram-core-surface\/\?from=internal-modules/); - await expect(page.locator("[data-return]")).toBeVisible(); - }); expect(metrics, `${id} at ${width}x${height}`).toMatchObject({ overflowX: false, overflowY: false, captionOverlaps: 0 }); expect(metrics.captionFloor).toBeGreaterThanOrEqual(12); if (id.endsWith("-surface")) expect(metrics.edgeLabelOverlaps).toBe(0); @@ -261,6 +233,35 @@ test("curated maps fit desktop viewports with readable role captions", async ({ } }); +test("module boxes drill into public surfaces with clear nested and direct returns", async ({ page }) => { + await page.goto("demo/"); + const wrapper = page.frameLocator("[data-demo]"); + await wrapper.getByLabel("Filter diagrams").fill("cli"); + await wrapper.frameLocator("[data-story-viewer]").locator('svg g[data-node-id="cli"]').click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); + await expect(wrapper.locator("[data-return]")).toBeVisible(); + await expect(wrapper.locator("[data-return]")).toContainText("Topocode internal modules"); + await expect(wrapper.frameLocator("[data-story-viewer]").locator("svg g[data-node-id]")).toHaveCount(9); + await wrapper.frameLocator("[data-story-viewer]").locator('svg g[data-node-id="diagram-core"]').click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "diagram-core-surface"); + await expect(wrapper.locator("[data-return]")).toContainText("@topo/cli: public surface"); + await wrapper.locator("[data-return]").click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); + await wrapper.frameLocator("[data-story-viewer]").locator("#btn-semantic-lens").click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); + await wrapper.locator("[data-return]").click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "internal-modules"); + await page.goto("demo/home/stories/diagram-core-surface/"); + await expect(page.locator("[data-return]")).toBeVisible(); + await expect(page.locator("[data-return]")).toContainText("Topocode internal modules"); + await page.reload(); + await expect(page.locator("[data-return]")).toBeVisible(); + await page.goto("demo/home/stories/internal-modules/viewer.html"); + await page.locator('svg g[data-node-id="diagram-core"]').click(); + await expect(page).toHaveURL(/stories\/diagram-core-surface\/\?from=internal-modules/); + await expect(page.locator("[data-return]")).toBeVisible(); +}); + test("retired theme preferences cannot override Blueprint", async ({ page }) => { for (const retired of ["porcelain", "forest", "sandstone", "oxide", "aubergine", "graphite"]) { await page.goto("./"); From 4a9c5f70cef894d529918cb7e2efc8c5d005aa20 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 15:01:50 -0400 Subject: [PATCH 17/39] fix(navigation): preserve native sequence focus details Keep sequence participant focus in the native viewer until the reader explicitly opens source details. Preserve explicit module drilldowns and the always-visible parent return path. --- docs/story-preview.md | 2 ++ packages/cli/src/catalogue.ts | 2 +- website/tests/site.spec.mjs | 5 +++++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/story-preview.md b/docs/story-preview.md index 4c1eb98..145adcc 100644 --- a/docs/story-preview.md +++ b/docs/story-preview.md @@ -42,6 +42,8 @@ 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. +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 diff --git a/packages/cli/src/catalogue.ts b/packages/cli/src/catalogue.ts index 5c80248..8a90688 100644 --- a/packages/cli/src/catalogue.ts +++ b/packages/cli/src/catalogue.ts @@ -417,7 +417,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 || focus) document.querySelector(".story-details").open = true; + if (edge !== null || (focus && diagramFamily !== "sequence")) document.querySelector(".story-details").open = true; } function setFocus(nodeId) { diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index bb3fad4..cb638b2 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -93,6 +93,8 @@ test("module details preserve complete dependencies and cross-story return navig await expect(frame.locator(".story-details")).toHaveAttribute("open", ""); await expect(frame.locator('[data-section-evidence="languages"] > p')).toContainText("@topo/languages -> @topo/scanner [dependencies: workspace:*]"); const link = frame.locator('a[data-cross-story][data-source-node="languages"]').filter({ hasText: "Code analysis" }); + // Fixed in-frame details need the enclosing frame inside the outer viewport. + await page.locator("[data-demo]").scrollIntoViewIfNeeded(); await link.click(); await expect(frame.locator("body")).toHaveAttribute("data-story-id", "dependency-context"); await expect(frame.locator('[data-section-evidence="analysis-consumers"] > p')).toContainText("optionalDependencies"); @@ -176,6 +178,9 @@ test("idea-to-architecture sequence shows the collaboration and review loop", as await expect(wrapper.locator("[data-return]")).toBeVisible(); await wrapper.locator("[data-return]").click(); await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "story-to-screen"); + await expect(wrapper.locator('[data-node-id="cli"]')).toHaveAttribute("aria-current", "true"); + await expect(wrapper.locator(".story-details")).not.toHaveAttribute("open", ""); + await wrapper.locator(".story-details > summary").click(); await expect(wrapper.locator('[data-section-evidence="cli"]')).toBeVisible(); }); From 8a53c8895bbf885e0f770e5e375782008dc6ebaf Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 15:10:58 -0400 Subject: [PATCH 18/39] test(website): scroll embedded controls into view --- website/tests/site.spec.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index cb638b2..d77a26e 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -180,6 +180,7 @@ test("idea-to-architecture sequence shows the collaboration and review loop", as await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "story-to-screen"); await expect(wrapper.locator('[data-node-id="cli"]')).toHaveAttribute("aria-current", "true"); await expect(wrapper.locator(".story-details")).not.toHaveAttribute("open", ""); + await page.locator("[data-demo]").scrollIntoViewIfNeeded(); await wrapper.locator(".story-details > summary").click(); await expect(wrapper.locator('[data-section-evidence="cli"]')).toBeVisible(); }); From 56a6c706f4d6878e000045d540b02b6a84a2830d Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 17:47:17 -0400 Subject: [PATCH 19/39] docs(algorithms): add three source-backed sequences Explain compiler evidence extraction, exact anchor resolution and freshness, and hierarchy-aware graph projection with edge accounting. Link each sequence to its owning module; keep publication paused. --- docs/public-website.md | 22 +- .../algorithm-anchor-resolution.topo.json | 259 +++++++++++++++++ .../algorithm-evidence-extraction.topo.json | 240 ++++++++++++++++ .../algorithm-graph-projection.topo.json | 262 ++++++++++++++++++ stories/public/internal-modules.topo.json | 21 +- website/build.mjs | 3 +- website/build.test.mjs | 24 +- website/demo/.topo/config.json | 2 +- website/tests/site.spec.mjs | 33 +++ 9 files changed, 855 insertions(+), 11 deletions(-) create mode 100644 stories/public/algorithm-anchor-resolution.topo.json create mode 100644 stories/public/algorithm-evidence-extraction.topo.json create mode 100644 stories/public/algorithm-graph-projection.topo.json diff --git a/docs/public-website.md b/docs/public-website.md index b2daa8a..d709856 100644 --- a/docs/public-website.md +++ b/docs/public-website.md @@ -48,7 +48,7 @@ development and release documents retain their separately labeled procedures. ## Curated source-backed demo -Each build validates the five curated stories against the working source and +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`. @@ -93,7 +93,25 @@ writes explicit. 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. Commits still require authorization. -`catalogue.storyIds` selects exactly these five maps. Existing development stories +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. + +`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. diff --git a/stories/public/algorithm-anchor-resolution.topo.json b/stories/public/algorithm-anchor-resolution.topo.json new file mode 100644 index 0000000..a72d498 --- /dev/null +++ b/stories/public/algorithm-anchor-resolution.topo.json @@ -0,0 +1,259 @@ +{ + "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 snapshot-backed CLI path binds authored anchors to exact 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 view.", + "anchors": [ + { + "id": "validate", + "path": "packages/cli/src/story-validation.ts", + "language": "typescript", + "symbol": "validateStory", + "sha256": "d6f60cad448f66c60c94f6a2f611f52617958a45c0e78eb5fad0e08285e1de58" + }, + { + "id": "catalogue", + "path": "packages/cli/src/catalogue.ts", + "language": "typescript", + "symbol": "buildCatalogue", + "sha256": "f9a15c78eaa48770f9dfc64ce33545677d24765720db1d6f81c23f62592afbbb" + }, + { + "id": "freshness", + "path": "packages/cli/src/catalogue.ts", + "language": "typescript", + "symbol": "assertCatalogueCurrent", + "sha256": "f9a15c78eaa48770f9dfc64ce33545677d24765720db1d6f81c23f62592afbbb" + }, + { + "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": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27" + }, + { + "id": "resolve-anchor", + "path": "packages/story/src/index.ts", + "language": "typescript", + "symbol": "resolveAnchor", + "sha256": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27" + }, + { + "id": "symbol-range", + "path": "packages/story/src/index.ts", + "language": "typescript", + "symbol": "findSymbolRange", + "sha256": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27" + }, + { + "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": "CLI caller", + "semanticRole": "validation-client", + "body": "validateStory and catalogue construction capture the referenced source and pass a loader into resolveStoryDocument. They later compare the snapshot and relevant Git state again. The catalogue may render between resolution and the final check; this diagram deliberately omits rendering.\n\nThese are explicit checkpoints, not a continuously held source-code lock. Resolving anchors does not establish the explanation's semantic truth.", + "anchorIds": [ + "validate", + "catalogue", + "freshness" + ] + }, + { + "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 referenced source", + "anchorIds": [ + "validate", + "catalogue", + "capture" + ], + "rationale": "The CLI captures the source files referenced by the selected authored document(s).", + "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": "Resolve story with snapshot loader", + "anchorIds": [ + "validate", + "catalogue", + "resolve-document" + ], + "rationale": "The caller passes a loader that reads the captured map, 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", + "catalogue" + ], + "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": "Recheck bytes before use", + "anchorIds": [ + "validate", + "freshness", + "assert-snapshot" + ], + "rationale": "The CLI rereads the captured paths at its post-resolution or pre-publication checkpoint; it also checks repository state.", + "classification": "source-traced" + }, + { + "from": "snapshot", + "to": "caller", + "label": "Unchanged source or stale error", + "anchorIds": [ + "assert-snapshot", + "freshness" + ], + "rationale": "Changed bytes or repository state refuse the operation. No output is published by this algorithm itself.", + "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..6e18e1d --- /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": "Caller", + "semanticRole": "scan-client", + "body": "The language-composition layer invokes the TypeScript scanner adapter when selected. This view focuses on that scanner, not the separate partial Rust/Tauri adapters. The result carries graphs, diagnostics, metrics and an authoritative/partial flag; no model is called.", + "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": "Repository and scan options", + "anchorIds": [ + "composition", + "scan" + ], + "rationale": "scanProject delegates through the TypeScript scanner adapter; scanRepository parses and validates its 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..dd06037 --- /dev/null +++ b/stories/public/algorithm-graph-projection.topo.json @@ -0,0 +1,262 @@ +{ + "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 reusable @topo/graph projection-session path. Local code and indexed data collaborate to show a smaller view while retaining evidence membership. Directory/cycle derivation is an input preparation step, not rerun by every projection. This is not Archify/Graphviz layout, the separately built 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": "Caller", + "semanticRole": "projection-client", + "body": "A consumer such as createLayoutSession supplies a validated graph and its derived architecture, then calls session.project(options). The one-shot projectGraph/layoutGraphWithArchitecture path uses the same projection core without retaining a session.\n\nChanging the view does not rescan source or choose screen coordinates. Layout is downstream of the returned projection.", + "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": "Graph and derived architecture", + "anchorIds": [ + "session-client", + "session" + ], + "rationale": "createLayoutSession creates a projection session from existing graph and architecture data.", + "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": "Scope and collapse options", + "anchorIds": [ + "session", + "project" + ], + "rationale": "session.project invokes projectIndexedGraph using the captured index.", + "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": "Expand or collapse; project again", + "anchorIds": [ + "session", + "session-client" + ], + "rationale": "A reusable session can project another option set over the same captured input.", + "classification": "source-traced" + }, + { + "from": "projection", + "to": "caller", + "label": "New view of the same snapshot", + "anchorIds": [ + "session", + "project" + ], + "rationale": "The result changes presentation scope while retaining provenance to the original graph. Refresh the session for new source evidence.", + "classification": "source-traced", + "variant": "return" + } + ] +} diff --git a/stories/public/internal-modules.topo.json b/stories/public/internal-modules.topo.json index a85db65..e6578b7 100644 --- a/stories/public/internal-modules.topo.json +++ b/stories/public/internal-modules.topo.json @@ -170,11 +170,14 @@ "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. Module-specific detail maps will be curated later; there is no placeholder target.", + "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", @@ -192,11 +195,14 @@ "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. Module-specific detail maps will be curated later; there is no placeholder target.", + "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", @@ -308,11 +314,14 @@ "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. Module-specific detail maps will be curated later; there is no placeholder target.", + "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": [ diff --git a/website/build.mjs b/website/build.mjs index 751e92f..bb8ca1f 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -131,7 +131,8 @@ npx --no topo serve .

A working Home, before your first map.

< 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 exposed interfaces, and follow the collaboration that turns an idea into a reviewed architecture document.

Click @topo/cli or @topo/diagram-core to open its public-surface diagram. The return link keeps your place. Other modules show their responsibility and complete internal declaration lists. LENS highlights authored responsibility groups; the arrows remain selected manifest dependencies, not runtime traffic.

Dependency context groups external tools by role. Idea to architecture shows you, your coding agent, and the CLI working through evidence, story authoring, presentation, review, and refinement.

+ 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.

`)); diff --git a/website/build.test.mjs b/website/build.test.mjs index 82a209f..973a21a 100644 --- a/website/build.test.mjs +++ b/website/build.test.mjs @@ -108,6 +108,25 @@ test("module surface narratives cover actual root exports with signature-only fu } }); +test("core algorithm sequences retain trace evidence and module parents", async () => { + for (const [id, module] of [ + ["algorithm-evidence-extraction", "scanner"], + ["algorithm-anchor-resolution", "story"], + ["algorithm-graph-projection", "graph"], + ]) { + const document = JSON.parse(await readFile(path.join(root, `stories/public/${id}.topo.json`), "utf8")); + assert.equal(document.diagramFamily, "sequence"); + assert.equal(document.sections.length, 4); + assert.equal(document.connections.length, 10); + assert.deepEqual(document.parent, { storyId: "internal-modules", nodeId: module }); + assert.ok(document.anchors.every(anchor => /^[a-f0-9]{64}$/.test(anchor.sha256))); + const ids = new Set(document.anchors.map(anchor => anchor.id)); + assert.ok(document.connections.every(edge => + edge.from !== edge.to && edge.classification === "source-traced" && + edge.rationale && edge.anchorIds.length && edge.anchorIds.every(id => ids.has(id)))); + } +}); + test("build only the curated story set for project Pages and custom-domain roots", async () => { const original = process.env.SITE_BASE_PATH; try { @@ -121,12 +140,15 @@ test("build only the curated story set for project Pages and custom-domain roots const home = await readFile(path.join(output, "demo/home/index.html"), "utf8"); const state = JSON.parse(await readFile(path.join(output, "demo/home/site-state.json"), "utf8")); assert.match(home, /data-topo-shell/); - assert.equal((home.match(/data-kind="story"/g) ?? []).length, 5); + assert.equal((home.match(/data-kind="story"/g) ?? []).length, 8); assert.match(home, /Topocode internal modules/); assert.match(home, /Dependency context by role/); assert.match(home, /From idea to architecture/); assert.match(home, /@topo\/cli: public surface/); assert.match(home, /@topo\/diagram-core: public surface/); + assert.match(home, /Compiler-backed evidence extraction/); + assert.match(home, /Source-anchor resolution and freshness/); + assert.match(home, /Graph projection and edge aggregation/); assert.doesNotMatch(home, /Workflow capability|topo-packages/); assert.match(JSON.stringify(state), /unscanned/); assert.match(await readFile(path.join(output, "index.html"), "utf8"), new RegExp(`${base}assets/client.mjs`)); diff --git a/website/demo/.topo/config.json b/website/demo/.topo/config.json index 457f1d3..9040d10 100644 --- a/website/demo/.topo/config.json +++ b/website/demo/.topo/config.json @@ -6,6 +6,6 @@ "title": "Topocode", "description": "Explore module responsibilities, drill into the CLI and renderer's exposed interfaces, or follow the human-agent loop from an idea to a reviewed architecture document.", "accentColor": "#80d8ed", - "storyIds": ["internal-modules", "dependency-context", "story-to-screen", "cli-surface", "diagram-core-surface"] + "storyIds": ["internal-modules", "dependency-context", "story-to-screen", "cli-surface", "diagram-core-surface", "algorithm-evidence-extraction", "algorithm-anchor-resolution", "algorithm-graph-projection"] } } diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index d77a26e..348bfae 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -268,6 +268,39 @@ test("module boxes drill into public surfaces with clear nested and direct retur await expect(page.locator("[data-return]")).toBeVisible(); }); +for (const [id, module, detailNode, boundary] of [ + ["algorithm-evidence-extraction", "scanner", "semantic", "runtime reachability"], + ["algorithm-anchor-resolution", "story", "resolver", "no fuzzy matching"], + ["algorithm-graph-projection", "graph", "aggregation", "83% of represented edge weight"], +]) { + test(`${id}: readable source-backed sequence with module drill-in and return`, async ({ page }) => { + for (const [width, height] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) { + await page.setViewportSize({ width, height }); + await page.goto(`demo/home/stories/${id}/viewer.html`); + await page.evaluate(() => document.fonts.ready); + const diagram = page.locator('svg[data-topo-family="sequence"]'); + await expect(diagram.locator("g[data-node-id]")).toHaveCount(4); + const metrics = await diagram.evaluate(svg => ({ + overflow: document.documentElement.scrollWidth > innerWidth || document.documentElement.scrollHeight > innerHeight, + fontFloor: Math.min(...[...svg.querySelectorAll("text")].filter(text => text.textContent.trim()) + .map(text => parseFloat(getComputedStyle(text).fontSize) * svg.getScreenCTM().a)), + })); + expect(metrics.overflow).toBe(false); + expect(metrics.fontFloor).toBeGreaterThanOrEqual(12); + } + await page.goto("demo/home/stories/internal-modules/"); + await page.frameLocator("[data-story-viewer]").locator(`svg g[data-node-id="${module}"]`).click(); + await expect(page.locator("body")).toHaveAttribute("data-story-id", id); + await expect(page.locator("[data-return]")).toBeVisible(); + await page.frameLocator("[data-story-viewer]").locator(`svg g[data-node-id="${detailNode}"]`).click(); + await page.locator(".story-details > summary").click(); + await expect(page.locator(`[data-section-evidence="${detailNode}"] > p`)).toContainText(boundary); + await page.locator("[data-return]").click(); + await expect(page.locator("body")).toHaveAttribute("data-story-id", "internal-modules"); + await expect(page.locator(`[data-node-id="${module}"]`)).toHaveAttribute("aria-current", "true"); + }); +} + test("retired theme preferences cannot override Blueprint", async ({ page }) => { for (const retired of ["porcelain", "forest", "sandstone", "oxide", "aubergine", "graphite"]) { await page.goto("./"); From 196b7f4accda5ba98add96f27b92fb9b35cb83e6 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 17:55:42 -0400 Subject: [PATCH 20/39] fix(sequence): trim unused compact viewer padding Retain diagram geometry and text size while reserving enough room for compact desktop viewer controls without a spurious vertical scrollbar. --- packages/diagram-core/src/index.ts | 1 + stories/public/diagram-core-surface.topo.json | 12 ++++++------ stories/public/internal-modules.topo.json | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/diagram-core/src/index.ts b/packages/diagram-core/src/index.ts index 26e9b1a..e3f9cd2 100644 --- a/packages/diagram-core/src/index.ts +++ b/packages/diagram-core/src/index.ts @@ -1473,6 +1473,7 @@ svg { max-height: 100vh; } } @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: ${sequence?.fontSize}px; diff --git a/stories/public/diagram-core-surface.topo.json b/stories/public/diagram-core-surface.topo.json index 7b78257..e7272f4 100644 --- a/stories/public/diagram-core-surface.topo.json +++ b/stories/public/diagram-core-surface.topo.json @@ -39,28 +39,28 @@ "id": "render-story", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", + "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", "pattern": "export function renderStory(story: ResolvedStoryDocument): StoryArtifact | Promise {" }, { "id": "render-array", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", + "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", "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": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", + "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", "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": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", + "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", "pattern": "export function architectureComponentWidth(\n title: string,\n sublabel = \"\",\n finalTypography = false,\n): number {" }, { @@ -95,14 +95,14 @@ "id": "theme-export", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", + "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", "pattern": "export { CORE_THEME_SCRIPT } from \"./theme.js\";" }, { "id": "integrity-export", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d", + "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", "pattern": "export {\n verifyArchifyIntegrity,\n type ArchifyIntegrity,\n} from \"./integrity.js\";" } ], diff --git a/stories/public/internal-modules.topo.json b/stories/public/internal-modules.topo.json index e6578b7..bd4c45c 100644 --- a/stories/public/internal-modules.topo.json +++ b/stories/public/internal-modules.topo.json @@ -125,7 +125,7 @@ "id": "diagram-core-implementation", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "732d4a9e30086726ba3ddb27c06d7346a1fe7d606ed7877b812ef84ce893008d" + "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88" }, { "id": "languages-implementation", From d59b15c2a8da4064ec688b2948a3576553e8d43c Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 18:05:04 -0400 Subject: [PATCH 21/39] test(viewer): measure settled sequence layouts Wait for fonts and finite viewer entrance transitions before asserting viewport bounds; keep all geometry and text-size thresholds unchanged. --- website/tests/site.spec.mjs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index 348bfae..37f19cd 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -6,6 +6,17 @@ import { root } from "../build.mjs"; import { themes } from "../themes.mjs"; import { contourPath } from "../brand.mjs"; +async function settleViewer(page) { + await page.evaluate(async () => { + await document.fonts.ready; + await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); + await Promise.all(document.getAnimations() + .filter(animation => animation.effect?.getTiming().iterations !== Infinity) + .map(animation => animation.finished)); + await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); + }); +} + test("Contour is the final header mark and favicon", async ({ page, request, baseURL }) => { await page.goto("./"); await expect(page.locator(".brand svg path")).toHaveAttribute("d", contourPath); @@ -109,7 +120,7 @@ test("module details preserve complete dependencies and cross-story return navig test("semantic lenses classify responsibilities, preserve geometry, and compare only drawn arrows", async ({ page }) => { await page.goto("demo/home/stories/internal-modules/viewer.html"); - await page.evaluate(() => document.fonts.ready); + await settleViewer(page); const diagram = page.locator('svg[data-diagram-type="architecture"]'); const geometry = () => diagram.locator("g[data-node-id]").evaluateAll(nodes => nodes.map(node => { @@ -189,7 +200,7 @@ test("collaboration sequence remains readable on desktop", async ({ page }) => { for (const [width, height] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) { await page.setViewportSize({ width, height }); await page.goto("demo/home/stories/story-to-screen/viewer.html"); - await page.evaluate(() => document.fonts.ready); + await settleViewer(page); const metrics = await page.locator('svg[data-topo-family="sequence"]').evaluate(svg => { const scale = svg.getScreenCTM().a; const labels = [...svg.querySelectorAll("text")].filter(text => text.textContent.trim() && getComputedStyle(text).display !== "none"); @@ -209,7 +220,7 @@ test("curated maps fit desktop viewports with readable role captions", async ({ for (const [width, height] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) { await page.setViewportSize({ width, height }); await page.goto(`demo/home/stories/${id}/viewer.html`); - await page.evaluate(() => document.fonts.ready); + await settleViewer(page); const diagram = page.locator('svg[data-diagram-type="architecture"]'); await expect(diagram).toBeVisible(); await expect(diagram.locator("g[data-node-id]")).toHaveCount(count); @@ -277,7 +288,7 @@ for (const [id, module, detailNode, boundary] of [ for (const [width, height] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) { await page.setViewportSize({ width, height }); await page.goto(`demo/home/stories/${id}/viewer.html`); - await page.evaluate(() => document.fonts.ready); + await settleViewer(page); const diagram = page.locator('svg[data-topo-family="sequence"]'); await expect(diagram.locator("g[data-node-id]")).toHaveCount(4); const metrics = await diagram.evaluate(svg => ({ From d3579853784aabd84104de1151f9857443a888e4 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 18:13:47 -0400 Subject: [PATCH 22/39] docs(algorithms): name initiators and their goals Replace generic Caller labels with language composition, draft story validation, and layout-session ownership. Make the initiating request purposeful and bind validation to its concrete CLI route. --- docs/public-website.md | 4 ++ .../algorithm-anchor-resolution.topo.json | 48 ++++++------------- .../algorithm-evidence-extraction.topo.json | 10 ++-- .../algorithm-graph-projection.topo.json | 26 +++++----- website/build.test.mjs | 13 +++-- 5 files changed, 45 insertions(+), 56 deletions(-) diff --git a/docs/public-website.md b/docs/public-website.md index d709856..e6c4543 100644 --- a/docs/public-website.md +++ b/docs/public-website.md @@ -110,6 +110,10 @@ services or runtime telemetry: 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 diff --git a/stories/public/algorithm-anchor-resolution.topo.json b/stories/public/algorithm-anchor-resolution.topo.json index a72d498..c258864 100644 --- a/stories/public/algorithm-anchor-resolution.topo.json +++ b/stories/public/algorithm-anchor-resolution.topo.json @@ -9,7 +9,7 @@ "storyId": "internal-modules", "nodeId": "story" }, - "summary": "The snapshot-backed CLI path binds authored anchors to exact 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 view.", + "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", @@ -18,20 +18,6 @@ "symbol": "validateStory", "sha256": "d6f60cad448f66c60c94f6a2f611f52617958a45c0e78eb5fad0e08285e1de58" }, - { - "id": "catalogue", - "path": "packages/cli/src/catalogue.ts", - "language": "typescript", - "symbol": "buildCatalogue", - "sha256": "f9a15c78eaa48770f9dfc64ce33545677d24765720db1d6f81c23f62592afbbb" - }, - { - "id": "freshness", - "path": "packages/cli/src/catalogue.ts", - "language": "typescript", - "symbol": "assertCatalogueCurrent", - "sha256": "f9a15c78eaa48770f9dfc64ce33545677d24765720db1d6f81c23f62592afbbb" - }, { "id": "capture", "path": "packages/cli/src/source-snapshot.ts", @@ -91,13 +77,11 @@ "sections": [ { "id": "caller", - "title": "CLI caller", - "semanticRole": "validation-client", - "body": "validateStory and catalogue construction capture the referenced source and pass a loader into resolveStoryDocument. They later compare the snapshot and relevant Git state again. The catalogue may render between resolution and the final check; this diagram deliberately omits rendering.\n\nThese are explicit checkpoints, not a continuously held source-code lock. Resolving anchors does not establish the explanation's semantic truth.", + "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", - "catalogue", - "freshness" + "validate" ] }, { @@ -138,13 +122,12 @@ { "from": "caller", "to": "snapshot", - "label": "Capture referenced source", + "label": "Capture draft evidence", "anchorIds": [ "validate", - "catalogue", "capture" ], - "rationale": "The CLI captures the source files referenced by the selected authored document(s).", + "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" }, { @@ -162,13 +145,12 @@ { "from": "caller", "to": "resolver", - "label": "Resolve story with snapshot loader", + "label": "Validate anchors against the snapshot", "anchorIds": [ "validate", - "catalogue", "resolve-document" ], - "rationale": "The caller passes a loader that reads the captured map, preventing different anchors from silently reading different snapshots.", + "rationale": "validateStory supplies the captured-map loader to resolveStoryDocument, preventing different anchors from silently reading different snapshots.", "classification": "source-traced" }, { @@ -177,8 +159,7 @@ "label": "Load this anchor's file", "anchorIds": [ "resolve-document", - "validate", - "catalogue" + "validate" ], "rationale": "resolveStoryDocument invokes the supplied loader for each anchor. This is a local map read.", "classification": "source-traced" @@ -234,13 +215,12 @@ { "from": "caller", "to": "snapshot", - "label": "Recheck bytes before use", + "label": "Confirm draft evidence is current", "anchorIds": [ "validate", - "freshness", "assert-snapshot" ], - "rationale": "The CLI rereads the captured paths at its post-resolution or pre-publication checkpoint; it also checks repository state.", + "rationale": "After resolution, validateStory rereads the captured paths, then compares repository revision, dirty state and fingerprint before returning.", "classification": "source-traced" }, { @@ -249,9 +229,9 @@ "label": "Unchanged source or stale error", "anchorIds": [ "assert-snapshot", - "freshness" + "validate" ], - "rationale": "Changed bytes or repository state refuse the operation. No output is published by this algorithm itself.", + "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 index 6e18e1d..509baf0 100644 --- a/stories/public/algorithm-evidence-extraction.topo.json +++ b/stories/public/algorithm-evidence-extraction.topo.json @@ -77,9 +77,9 @@ "sections": [ { "id": "caller", - "title": "Caller", - "semanticRole": "scan-client", - "body": "The language-composition layer invokes the TypeScript scanner adapter when selected. This view focuses on that scanner, not the separate partial Rust/Tauri adapters. The result carries graphs, diagnostics, metrics and an authoritative/partial flag; no model is called.", + "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" @@ -126,12 +126,12 @@ { "from": "caller", "to": "scanner", - "label": "Repository and scan options", + "label": "Extract code evidence", "anchorIds": [ "composition", "scan" ], - "rationale": "scanProject delegates through the TypeScript scanner adapter; scanRepository parses and validates its options.", + "rationale": "@topo/languages.scanProject requests TypeScript/JavaScript evidence through the scanner adapter; scanRepository parses and validates the supplied repository and options.", "classification": "source-traced" }, { diff --git a/stories/public/algorithm-graph-projection.topo.json b/stories/public/algorithm-graph-projection.topo.json index dd06037..eb168b5 100644 --- a/stories/public/algorithm-graph-projection.topo.json +++ b/stories/public/algorithm-graph-projection.topo.json @@ -9,7 +9,7 @@ "storyId": "internal-modules", "nodeId": "graph" }, - "summary": "The reusable @topo/graph projection-session path. Local code and indexed data collaborate to show a smaller view while retaining evidence membership. Directory/cycle derivation is an input preparation step, not rerun by every projection. This is not Archify/Graphviz layout, the separately built Repository page index, or the hand-curated module map.", + "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", @@ -98,9 +98,9 @@ "sections": [ { "id": "caller", - "title": "Caller", - "semanticRole": "projection-client", - "body": "A consumer such as createLayoutSession supplies a validated graph and its derived architecture, then calls session.project(options). The one-shot projectGraph/layoutGraphWithArchitecture path uses the same projection core without retaining a session.\n\nChanging the view does not rescan source or choose screen coordinates. Layout is downstream of the returned projection.", + "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", @@ -147,12 +147,12 @@ { "from": "caller", "to": "index", - "label": "Graph and derived architecture", + "label": "Prepare a graph for layout", "anchorIds": [ "session-client", "session" ], - "rationale": "createLayoutSession creates a projection session from existing graph and architecture data.", + "rationale": "createLayoutSession supplies graph and derived architecture to createProjectionSession so repeated layout requests can reuse indexed evidence.", "classification": "source-traced" }, { @@ -170,12 +170,13 @@ { "from": "caller", "to": "projection", - "label": "Scope and collapse options", + "label": "Select the visible graph", "anchorIds": [ + "session-client", "session", "project" ], - "rationale": "session.project invokes projectIndexedGraph using the captured index.", + "rationale": "The layout request passes scope and collapse options through session.project to obtain the graph that should be placed.", "classification": "source-traced" }, { @@ -238,23 +239,24 @@ { "from": "caller", "to": "projection", - "label": "Expand or collapse; project again", + "label": "Reproject after scope changes", "anchorIds": [ "session", "session-client" ], - "rationale": "A reusable session can project another option set over the same captured input.", + "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": "New view of the same snapshot", + "label": "Updated inputs for node placement", "anchorIds": [ + "session-client", "session", "project" ], - "rationale": "The result changes presentation scope while retaining provenance to the original graph. Refresh the session for new source evidence.", + "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/website/build.test.mjs b/website/build.test.mjs index 973a21a..a730bbd 100644 --- a/website/build.test.mjs +++ b/website/build.test.mjs @@ -108,16 +108,19 @@ test("module surface narratives cover actual root exports with signature-only fu } }); -test("core algorithm sequences retain trace evidence and module parents", async () => { - for (const [id, module] of [ - ["algorithm-evidence-extraction", "scanner"], - ["algorithm-anchor-resolution", "story"], - ["algorithm-graph-projection", "graph"], +test("core algorithm sequences retain trace evidence, purposeful initiators and module parents", async () => { + for (const [id, module, initiator, purpose] of [ + ["algorithm-evidence-extraction", "scanner", "@topo/languages", "Extract code evidence"], + ["algorithm-anchor-resolution", "story", "Story validator", "Capture draft evidence"], + ["algorithm-graph-projection", "graph", "Layout session", "Prepare a graph for layout"], ]) { const document = JSON.parse(await readFile(path.join(root, `stories/public/${id}.topo.json`), "utf8")); assert.equal(document.diagramFamily, "sequence"); assert.equal(document.sections.length, 4); assert.equal(document.connections.length, 10); + assert.equal(document.sections[0].title, initiator); + assert.equal(document.connections[0].from, document.sections[0].id); + assert.equal(document.connections[0].label, purpose); assert.deepEqual(document.parent, { storyId: "internal-modules", nodeId: module }); assert.ok(document.anchors.every(anchor => /^[a-f0-9]{64}$/.test(anchor.sha256))); const ids = new Set(document.anchors.map(anchor => anchor.id)); From 77f164a8d010721383862c82b620ae6c13406f96 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 18:40:28 -0400 Subject: [PATCH 23/39] feat(website): embed the collaboration demo on home Show the live From idea to architecture story after the introduction. Reuse the generated viewer, theme, drilldowns, and expand controls. --- docs/public-website.md | 5 +++++ website/build.mjs | 7 ++++++- website/client.mjs | 2 +- website/style.css | 2 ++ website/tests/site.spec.mjs | 25 +++++++++++++++++++++++++ 5 files changed, 39 insertions(+), 2 deletions(-) diff --git a/docs/public-website.md b/docs/public-website.md index e6c4543..243209a 100644 --- a/docs/public-website.md +++ b/docs/public-website.md @@ -21,6 +21,11 @@ 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 reuses the generated storybook, Blueprint styling, drilldowns, and +expand/restore controls. 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. diff --git a/website/build.mjs b/website/build.mjs index bb8ca1f..5e6c911 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -114,11 +114,16 @@ export async function build() { 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

+

A live Topocode diagram of the process itself: you ask, your agent investigates and authors, you review, and the explanation improves.

+
+

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) { diff --git a/website/client.mjs b/website/client.mjs index 1a95666..113d401 100644 --- a/website/client.mjs +++ b/website/client.mjs @@ -16,7 +16,7 @@ function applyTheme() { const frame = document.querySelector("[data-demo]"); if (frame?.contentDocument?.querySelector("[data-topo-shell]")) { const doc = frame.contentDocument; - // Presentation-only styling for the empty Home, not a renderer transformation. + // Presentation-only styling for the embedded shell, not a renderer transformation. let stylesheet = doc.querySelector("[data-website-palette]"); if (!stylesheet) { stylesheet = doc.createElement("link"); diff --git a/website/style.css b/website/style.css index fd20953..6c57672 100644 --- a/website/style.css +++ b/website/style.css @@ -73,6 +73,8 @@ pre { overflow: auto; padding: 1.2rem; background: var(--panel); border: 1px sol .roadmap section { border-top: 3px solid var(--accent); } .roadmap li { margin: 1rem 0; } .demo-stage { margin-top: 2rem; } +.home-demo { margin-bottom: 3.5rem; scroll-margin-top: 1.5rem; } +.home-demo .demo-stage { margin-top: 1.5rem; } .demo-toolbar { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 1rem; margin-bottom: 1rem; } .demo-stage iframe { width: 100%; height: 42rem; background: var(--bg); border: 1px solid var(--line); border-radius: .6rem; } .demo-stage.expanded { position: fixed; inset: 0; z-index: 20; margin: 0; padding: 1rem; background: var(--bg); display: flex; flex-direction: column; } diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index 37f19cd..f531be1 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -312,6 +312,31 @@ for (const [id, module, detailNode, boundary] of [ }); } +test("homepage embeds the real collaboration sequence with working demo controls", async ({ page }, info) => { + await page.goto("./"); + await page.getByRole("link", { name: "See it in action", exact: true }).click(); + await expect(page.getByRole("heading", { name: "From idea to architecture", exact: true })).toBeVisible(); + const wrapper = page.frameLocator("[data-demo]"); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "story-to-screen"); + await expect(wrapper.locator("html")).toHaveAttribute("data-website-palette", "blueprint"); + const viewer = wrapper.frameLocator("[data-story-viewer]"); + await expect(viewer.locator('svg[data-topo-family="sequence"] g[data-node-id]')).toHaveCount(4); + await expect(viewer.locator('svg[data-topo-family="sequence"]')).toContainText("Review, refine, repeat"); + await page.locator("[data-demo]").scrollIntoViewIfNeeded(); + await page.screenshot({ path: info.outputPath("homepage-live-demo.png") }); + await page.getByRole("button", { name: "Expand demo", exact: true }).click(); + await expect(page.locator(".demo-stage")).toHaveClass(/expanded/); + await viewer.locator('svg g[data-node-id="cli"]').click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); + await wrapper.locator("[data-return]").click(); + await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "story-to-screen"); + await page.getByRole("button", { name: "Restore demo", exact: true }).click(); + await expect(page.locator(".demo-stage")).not.toHaveClass(/expanded/); + await page.setViewportSize({ width: 390, height: 844 }); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + await expect(page.getByRole("link", { name: "Open full storybook", exact: true })).toHaveAttribute("href", /\/demo\/home\/stories\/story-to-screen\/$/); +}); + test("retired theme preferences cannot override Blueprint", async ({ page }) => { for (const retired of ["porcelain", "forest", "sandstone", "oxide", "aubergine", "graphite"]) { await page.goto("./"); From c9363d30f74b8a141e271b889e5097be7bbbba3a Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 18:56:02 -0400 Subject: [PATCH 24/39] feat(home): show only the native diagram viewer Use native presentation mode for the homepage embed, retaining title and viewer controls without storybook sidebar or details chrome. Keep the Demo page and full storybook unchanged. --- docs/public-website.md | 8 ++++++-- website/build.mjs | 2 +- website/client.mjs | 7 ++++--- website/style.css | 2 ++ website/tests/site.spec.mjs | 37 +++++++++++++++++++++++++++++-------- 5 files changed, 42 insertions(+), 14 deletions(-) diff --git a/docs/public-website.md b/docs/public-website.md index 243209a..56ad77f 100644 --- a/docs/public-website.md +++ b/docs/public-website.md @@ -23,8 +23,12 @@ 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 reuses the generated storybook, Blueprint styling, drilldowns, and -expand/restore controls. It is not a screenshot or a separately authored copy. +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. diff --git a/website/build.mjs b/website/build.mjs index 5e6c911..f59d884 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -122,7 +122,7 @@ npx --no topo serve .

A working Home, before your first map.

<

From idea to architecture

A live Topocode diagram of the process itself: you ask, your agent investigates and authors, you review, and the explanation improves.

-
+

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
`)); diff --git a/website/client.mjs b/website/client.mjs index 113d401..f54c86f 100644 --- a/website/client.mjs +++ b/website/client.mjs @@ -14,8 +14,9 @@ function applyTheme() { } refreshTerrain(); const frame = document.querySelector("[data-demo]"); - if (frame?.contentDocument?.querySelector("[data-topo-shell]")) { - const doc = frame.contentDocument; + const doc = frame?.contentDocument; + if (!doc || typeof frame.contentWindow?.topoSetTheme !== "function") return; + if (doc.querySelector("[data-topo-shell]")) { // Presentation-only styling for the embedded shell, not a renderer transformation. let stylesheet = doc.querySelector("[data-website-palette]"); if (!stylesheet) { @@ -29,8 +30,8 @@ function applyTheme() { for (const key of ["bg", "panel", "text", "muted", "accent", "line"]) { doc.documentElement.style.setProperty(`--${key}`, theme[key]); } - frame.contentWindow.topoSetTheme(theme.mode, false); } + frame.contentWindow.topoSetTheme(theme.mode, false); } applyTheme(); diff --git a/website/style.css b/website/style.css index 6c57672..8dc5bdb 100644 --- a/website/style.css +++ b/website/style.css @@ -77,6 +77,7 @@ pre { overflow: auto; padding: 1.2rem; background: var(--panel); border: 1px sol .home-demo .demo-stage { margin-top: 1.5rem; } .demo-toolbar { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 1rem; margin-bottom: 1rem; } .demo-stage iframe { width: 100%; height: 42rem; background: var(--bg); border: 1px solid var(--line); border-radius: .6rem; } +.home-demo .demo-stage:not(.expanded) iframe { height: 54rem; } .demo-stage.expanded { position: fixed; inset: 0; z-index: 20; margin: 0; padding: 1rem; background: var(--bg); display: flex; flex-direction: column; } .demo-stage.expanded iframe { flex: 1; min-height: 0; } @media (max-width: 1000px) { @@ -97,6 +98,7 @@ pre { overflow: auto; padding: 1.2rem; background: var(--panel); border: 1px sol .docs-nav h2 { margin: .75rem 0 .25rem; } .site-footer { padding: 1.5rem; } .site-footer a:first-of-type { margin-left: 0; } + .home-demo .demo-stage:not(.expanded) iframe { height: 42rem; } } @media (prefers-reduced-motion: reduce) { *, *::before, *::after { scroll-behavior: auto !important; } diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index f531be1..bc00368 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -312,29 +312,50 @@ for (const [id, module, detailNode, boundary] of [ }); } -test("homepage embeds the real collaboration sequence with working demo controls", async ({ page }, info) => { +test("homepage embeds only the blueprint viewer and leaves full storybook navigation separate", async ({ page }, info) => { await page.goto("./"); await page.getByRole("link", { name: "See it in action", exact: true }).click(); await expect(page.getByRole("heading", { name: "From idea to architecture", exact: true })).toBeVisible(); - const wrapper = page.frameLocator("[data-demo]"); - await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "story-to-screen"); - await expect(wrapper.locator("html")).toHaveAttribute("data-website-palette", "blueprint"); - const viewer = wrapper.frameLocator("[data-story-viewer]"); + const viewer = page.frameLocator("[data-demo]"); + await expect(page.locator("[data-demo]")).toHaveAttribute("src", /\/story-to-screen\/viewer\.html\?present=1$/); + await expect(viewer.locator("[data-topo-shell], .catalogue-panel, .story-details, iframe")).toHaveCount(0); + await expect(viewer.locator("html")).toHaveAttribute("data-theme", "dark"); + await expect(viewer.locator("html")).toHaveAttribute("data-present", "true"); + await expect(viewer.getByRole("heading", { name: "From idea to architecture", exact: true })).toBeVisible(); await expect(viewer.locator('svg[data-topo-family="sequence"] g[data-node-id]')).toHaveCount(4); await expect(viewer.locator('svg[data-topo-family="sequence"]')).toContainText("Review, refine, repeat"); + const containment = await viewer.locator('svg[data-topo-family="sequence"]').evaluate(svg => { + const transform = svg.getScreenCTM(); + const text = [...svg.querySelectorAll("text")].filter(node => node.textContent.trim()); + return { + uniformScale: Math.abs(transform.a - transform.d) < 0.0001 && transform.b === 0 && transform.c === 0, + allTextVisible: text.every(node => { + const bounds = node.getBoundingClientRect(); + return bounds.left >= 0 && bounds.top >= 0 && bounds.right <= innerWidth && bounds.bottom <= innerHeight; + }), + fontFloor: Math.min(...text.map(node => parseFloat(getComputedStyle(node).fontSize) * transform.a)), + }; + }); + expect(containment.uniformScale).toBe(true); + expect(containment.allTextVisible).toBe(true); + expect(containment.fontFloor).toBeGreaterThanOrEqual(12); await page.locator("[data-demo]").scrollIntoViewIfNeeded(); await page.screenshot({ path: info.outputPath("homepage-live-demo.png") }); await page.getByRole("button", { name: "Expand demo", exact: true }).click(); await expect(page.locator(".demo-stage")).toHaveClass(/expanded/); await viewer.locator('svg g[data-node-id="cli"]').click(); - await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); - await wrapper.locator("[data-return]").click(); - await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "story-to-screen"); + await expect.poll(() => viewer.locator("html").evaluate(() => location.hash)).toContain("focus=cli"); + await expect(viewer.locator("[data-topo-shell]")).toHaveCount(0); + await viewer.locator("#btn-theme").click(); + await expect(viewer.locator("html")).toHaveAttribute("data-theme", "dark"); await page.getByRole("button", { name: "Restore demo", exact: true }).click(); await expect(page.locator(".demo-stage")).not.toHaveClass(/expanded/); await page.setViewportSize({ width: 390, height: 844 }); expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); await expect(page.getByRole("link", { name: "Open full storybook", exact: true })).toHaveAttribute("href", /\/demo\/home\/stories\/story-to-screen\/$/); + await page.getByRole("link", { name: "Open full storybook", exact: true }).click(); + await expect(page.locator("[data-topo-shell]")).toBeVisible(); + await expect(page.locator(".catalogue-panel")).toHaveCount(1); }); test("retired theme preferences cannot override Blueprint", async ({ page }) => { From 648c7ac678e98cafd3a4377900cd4e322a51238f Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 20:56:38 -0400 Subject: [PATCH 25/39] feat(sequence): allow authored participant spacing Spread the collaboration demo across its available width using a validated story option instead of stretching SVG output. Preserve existing automatic defaults and text-readability constraints. --- docs/story-preview.md | 17 +++++++++++++++++ packages/diagram-core/src/index.ts | 2 +- packages/story/src/index.ts | 14 +++++++++++++- packages/story/src/story.test.ts | 15 +++++++++++++++ packages/story/story.schema.json | 12 ++++++++++++ .../algorithm-anchor-resolution.topo.json | 6 +++--- stories/public/diagram-core-surface.topo.json | 16 ++++++++-------- stories/public/internal-modules.topo.json | 4 ++-- stories/public/story-to-screen.topo.json | 1 + website/tests/site.spec.mjs | 5 +++++ 10 files changed, 77 insertions(+), 15 deletions(-) diff --git a/docs/story-preview.md b/docs/story-preview.md index 145adcc..52baf1a 100644 --- a/docs/story-preview.md +++ b/docs/story-preview.md @@ -29,6 +29,23 @@ 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" }`. diff --git a/packages/diagram-core/src/index.ts b/packages/diagram-core/src/index.ts index e3f9cd2..386fc5b 100644 --- a/packages/diagram-core/src/index.ts +++ b/packages/diagram-core/src/index.ts @@ -330,7 +330,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) => diff --git a/packages/story/src/index.ts b/packages/story/src/index.ts index 9b4e200..c05a46e 100644 --- a/packages/story/src/index.ts +++ b/packages/story/src/index.ts @@ -59,6 +59,7 @@ export interface StoryDocument { 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[]; @@ -229,7 +230,7 @@ function validateStoryDocument(value: unknown): string | undefined { const rootKeys = exactKeys( value, ["schemaVersion", "id", "title", "summary", "anchors", "sections", "connections"], - ["category", "diagramFamily", "classification", "renderer", "parent"], + ["category", "diagramFamily", "classification", "renderer", "parent", "sequenceLayout"], ); if (rootKeys) return rootKeys; if (value.schemaVersion !== "1.0") return 'schemaVersion must be "1.0"'; @@ -254,6 +255,17 @@ 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}`; diff --git a/packages/story/src/story.test.ts b/packages/story/src/story.test.ts index 1255bf4..bee48d1 100644 --- a/packages/story/src/story.test.ts +++ b/packages/story/src/story.test.ts @@ -43,6 +43,21 @@ 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 = { diff --git a/packages/story/story.schema.json b/packages/story/story.schema.json index 7f8acae..07803a1 100644 --- a/packages/story/story.schema.json +++ b/packages/story/story.schema.json @@ -19,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"] }, @@ -104,6 +112,10 @@ } }, "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" } } } diff --git a/stories/public/algorithm-anchor-resolution.topo.json b/stories/public/algorithm-anchor-resolution.topo.json index c258864..ddedf06 100644 --- a/stories/public/algorithm-anchor-resolution.topo.json +++ b/stories/public/algorithm-anchor-resolution.topo.json @@ -44,21 +44,21 @@ "path": "packages/story/src/index.ts", "language": "typescript", "symbol": "resolveStoryDocument", - "sha256": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27" + "sha256": "1df6ad0e6be95db8727430ceca42e983ac093d93eed44d90fea083f98b95d965" }, { "id": "resolve-anchor", "path": "packages/story/src/index.ts", "language": "typescript", "symbol": "resolveAnchor", - "sha256": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27" + "sha256": "1df6ad0e6be95db8727430ceca42e983ac093d93eed44d90fea083f98b95d965" }, { "id": "symbol-range", "path": "packages/story/src/index.ts", "language": "typescript", "symbol": "findSymbolRange", - "sha256": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27" + "sha256": "1df6ad0e6be95db8727430ceca42e983ac093d93eed44d90fea083f98b95d965" }, { "id": "rust-symbol", diff --git a/stories/public/diagram-core-surface.topo.json b/stories/public/diagram-core-surface.topo.json index e7272f4..fc03afb 100644 --- a/stories/public/diagram-core-surface.topo.json +++ b/stories/public/diagram-core-surface.topo.json @@ -39,28 +39,28 @@ "id": "render-story", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", + "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", "pattern": "export function renderStory(story: ResolvedStoryDocument): StoryArtifact | Promise {" }, { "id": "render-array", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", + "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", "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": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", + "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", "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": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", + "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", "pattern": "export function architectureComponentWidth(\n title: string,\n sublabel = \"\",\n finalTypography = false,\n): number {" }, { @@ -81,28 +81,28 @@ "id": "resolved-story", "path": "packages/story/src/index.ts", "language": "text", - "sha256": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27", + "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": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27", + "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": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", + "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", "pattern": "export { CORE_THEME_SCRIPT } from \"./theme.js\";" }, { "id": "integrity-export", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88", + "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", "pattern": "export {\n verifyArchifyIntegrity,\n type ArchifyIntegrity,\n} from \"./integrity.js\";" } ], diff --git a/stories/public/internal-modules.topo.json b/stories/public/internal-modules.topo.json index bd4c45c..4134f35 100644 --- a/stories/public/internal-modules.topo.json +++ b/stories/public/internal-modules.topo.json @@ -125,7 +125,7 @@ "id": "diagram-core-implementation", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "65e2c94e4c4be5dee870606ac10e108f10761e822ed6133eac5c2704cddc9b88" + "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd" }, { "id": "languages-implementation", @@ -161,7 +161,7 @@ "id": "story-implementation", "path": "packages/story/src/index.ts", "language": "text", - "sha256": "602b02bbafeac68b888b5b53690c5afb6475edbe2131aba8f1a21dfb6becfb27" + "sha256": "1df6ad0e6be95db8727430ceca42e983ac093d93eed44d90fea083f98b95d965" } ], "sections": [ diff --git a/stories/public/story-to-screen.topo.json b/stories/public/story-to-screen.topo.json index 2d3a635..4df3c58 100644 --- a/stories/public/story-to-screen.topo.json +++ b/stories/public/story-to-screen.topo.json @@ -1,6 +1,7 @@ { "schemaVersion": "1.0", "diagramFamily": "sequence", + "sequenceLayout": { "minimumParticipantGap": 220 }, "classification": "source-grounded", "id": "story-to-screen", "title": "From idea to architecture", diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index bc00368..2f81851 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -334,11 +334,16 @@ test("homepage embeds only the blueprint viewer and leaves full storybook naviga return bounds.left >= 0 && bounds.top >= 0 && bounds.right <= innerWidth && bounds.bottom <= innerHeight; }), fontFloor: Math.min(...text.map(node => parseFloat(getComputedStyle(node).fontSize) * transform.a)), + participantSpan: (() => { + const boxes = [...svg.querySelectorAll("g[data-node-id] > rect:not(.c-mask)")].map(node => node.getBoundingClientRect()); + return (Math.max(...boxes.map(box => box.right)) - Math.min(...boxes.map(box => box.left))) / svg.getBoundingClientRect().width; + })(), }; }); expect(containment.uniformScale).toBe(true); expect(containment.allTextVisible).toBe(true); expect(containment.fontFloor).toBeGreaterThanOrEqual(12); + expect(containment.participantSpan).toBeGreaterThanOrEqual(0.8); await page.locator("[data-demo]").scrollIntoViewIfNeeded(); await page.screenshot({ path: info.outputPath("homepage-live-demo.png") }); await page.getByRole("button", { name: "Expand demo", exact: true }).click(); From e16d480c99416f30440d236bd3ad9ee9fba2f62f Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 21:19:20 -0400 Subject: [PATCH 26/39] docs(demo): emphasize understanding code at a glance Remove the commit-authorization exchange from the product overview. Center the homepage and collaboration sequence on a useful visual explanation, leaving operational prerequisites in the usage guides. --- docs/public-website.md | 10 ++++++---- stories/public/story-to-screen.topo.json | 13 ++++--------- website/build.mjs | 2 +- website/build.test.mjs | 4 +++- website/tests/site.spec.mjs | 3 ++- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/docs/public-website.md b/docs/public-website.md index 56ad77f..93d6142 100644 --- a/docs/public-website.md +++ b/docs/public-website.md @@ -97,10 +97,12 @@ 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 interprets and authors, the CLI validates/previews, you review, and the -cycle repeats. The repository lifeline makes source reads and authorized story -writes explicit. 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. Commits still require authorization. +cycle repeats. 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: diff --git a/stories/public/story-to-screen.topo.json b/stories/public/story-to-screen.topo.json index 4df3c58..1ff6a3e 100644 --- a/stories/public/story-to-screen.topo.json +++ b/stories/public/story-to-screen.topo.json @@ -6,7 +6,7 @@ "id": "story-to-screen", "title": "From idea to architecture", "category": "Topocode", - "summary": "One human-agent collaboration cycle, grounded in Topocode's documented workflow—not a trace of one CLI process. The CLI supplies deterministic evidence and objective checks; the agent interprets and authors; you judge whether the explanation is meaningful. Feedback loops back to interpretation/authoring, and source changes may require another scan. Scan is useful here but not a prerequisite for authored stories.", + "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", @@ -60,7 +60,7 @@ "id": "agent", "title": "Coding agent", "semanticRole": "coding-agent", - "body": "Read code and scan evidence, enrich the understanding, and author an anchored story. Repair diagnostics, preserve story identity, and commit only with authorization. Present the result for human review. Interpretation here does not require the separate topo enrich command.", + "body": "Read code and scan evidence, identify what matters, and author an anchored story that explains the code visually. Repair diagnostics and preserve story identity as the explanation evolves. Present the diagram so the user can understand responsibilities and relationships without first reading every file. Interpretation here does not require the separate topo enrich command.", "anchorIds": [ "authoring-guide", "agent-skill", @@ -85,7 +85,7 @@ "id": "repository", "title": "Repository", "semanticRole": "repository", - "body": "Holds source code, configuration, and authored stories. The agent writes and commits the story; the CLI reads source and generates disposable cache/output. This is a file and Git boundary, not a separate hosted service.", + "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" @@ -130,11 +130,6 @@ "label": "Anchor results; repair feedback", "variant": "return" }, - { - "from": "agent", - "to": "repository", - "label": "Commit with authorization" - }, { "from": "agent", "to": "cli", @@ -149,7 +144,7 @@ { "from": "agent", "to": "user", - "label": "Present architecture document", + "label": "Diagram explains the code", "variant": "return" }, { diff --git a/website/build.mjs b/website/build.mjs index f59d884..105614c 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -121,7 +121,7 @@ export async function build() { npx --no topo serve .

A working Home, before your first map.

From idea to architecture

-

A live Topocode diagram of the process itself: you ask, your agent investigates and authors, you review, and the explanation improves.

+

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.

diff --git a/website/build.test.mjs b/website/build.test.mjs index a730bbd..9518cda 100644 --- a/website/build.test.mjs +++ b/website/build.test.mjs @@ -160,7 +160,9 @@ test("build only the curated story set for project Pages and custom-domain roots const evidence = JSON.parse(await readFile(path.join(output, "demo/home/stories/dependency-context/evidence.json"), "utf8")); assert.equal(evidence.anchors.length, 16); const flow = JSON.parse(await readFile(path.join(output, "demo/home/stories/story-to-screen/evidence.json"), "utf8")); - assert.equal(flow.connections.length, 12); + assert.equal(flow.connections.length, 11); + assert.ok(flow.connections.some(edge => edge.from === "agent" && edge.to === "user" && edge.label === "Diagram explains the code")); + assert.ok(flow.connections.every(edge => !/commit|authorization/i.test(edge.label))); assert.equal(flow.connections.at(-1).label, "Review, refine, repeat"); assert.ok(flow.connections.every(edge => edge.label)); assert.ok(flow.anchors.every(anchor => /^[a-f0-9]{64}$/.test(anchor.sha256))); diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index 2f81851..21b5a04 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -183,7 +183,8 @@ test("idea-to-architecture sequence shows the collaboration and review loop", as .toEqual(["human", "coding-agent", "command-line-tool", "repository"]); await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Review, refine, repeat"); await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Write interpreted story"); - await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Commit with authorization"); + await expect(flow.locator('svg[data-topo-family="sequence"]')).not.toContainText("Commit with authorization"); + await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Diagram explains the code"); await flow.locator('svg g[data-node-id="cli"]').click(); await expect(wrapper.locator("body")).toHaveAttribute("data-story-id", "cli-surface"); await expect(wrapper.locator("[data-return]")).toBeVisible(); From 58ef705a11957b751776c4d3ef82e2243836b615 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 21:27:58 -0400 Subject: [PATCH 27/39] fix(sequence): omit redundant native node index Keep the shortened collaboration sequence within its reading frame; the story shell and native participant focus retain navigation. --- docs/story-preview.md | 2 +- packages/diagram-core/src/index.ts | 1 + stories/public/diagram-core-surface.topo.json | 12 ++++++------ stories/public/internal-modules.topo.json | 2 +- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/story-preview.md b/docs/story-preview.md index 52baf1a..a1c4425 100644 --- a/docs/story-preview.md +++ b/docs/story-preview.md @@ -72,7 +72,7 @@ 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 viewer omits the redundant native node-index rail: +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. diff --git a/packages/diagram-core/src/index.ts b/packages/diagram-core/src/index.ts index 386fc5b..9f76004 100644 --- a/packages/diagram-core/src/index.ts +++ b/packages/diagram-core/src/index.ts @@ -1465,6 +1465,7 @@ 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); diff --git a/stories/public/diagram-core-surface.topo.json b/stories/public/diagram-core-surface.topo.json index fc03afb..3cb3b67 100644 --- a/stories/public/diagram-core-surface.topo.json +++ b/stories/public/diagram-core-surface.topo.json @@ -39,28 +39,28 @@ "id": "render-story", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", + "sha256": "87bc4ed6e1c380aeca423b911461b05b95329a72f50b3d453a767e6178f267c9", "pattern": "export function renderStory(story: ResolvedStoryDocument): StoryArtifact | Promise {" }, { "id": "render-array", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", + "sha256": "87bc4ed6e1c380aeca423b911461b05b95329a72f50b3d453a767e6178f267c9", "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": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", + "sha256": "87bc4ed6e1c380aeca423b911461b05b95329a72f50b3d453a767e6178f267c9", "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": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", + "sha256": "87bc4ed6e1c380aeca423b911461b05b95329a72f50b3d453a767e6178f267c9", "pattern": "export function architectureComponentWidth(\n title: string,\n sublabel = \"\",\n finalTypography = false,\n): number {" }, { @@ -95,14 +95,14 @@ "id": "theme-export", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", + "sha256": "87bc4ed6e1c380aeca423b911461b05b95329a72f50b3d453a767e6178f267c9", "pattern": "export { CORE_THEME_SCRIPT } from \"./theme.js\";" }, { "id": "integrity-export", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd", + "sha256": "87bc4ed6e1c380aeca423b911461b05b95329a72f50b3d453a767e6178f267c9", "pattern": "export {\n verifyArchifyIntegrity,\n type ArchifyIntegrity,\n} from \"./integrity.js\";" } ], diff --git a/stories/public/internal-modules.topo.json b/stories/public/internal-modules.topo.json index 4134f35..ae0330a 100644 --- a/stories/public/internal-modules.topo.json +++ b/stories/public/internal-modules.topo.json @@ -125,7 +125,7 @@ "id": "diagram-core-implementation", "path": "packages/diagram-core/src/index.ts", "language": "text", - "sha256": "a24ca5523d125dad472cc4706cdf02d61036ab86dc27797c831c1c68af1147dd" + "sha256": "87bc4ed6e1c380aeca423b911461b05b95329a72f50b3d453a767e6178f267c9" }, { "id": "languages-implementation", From d6ce584c4f189f3792ccde8a5173874d1e74e6ba Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 21:37:08 -0400 Subject: [PATCH 28/39] test(website): isolate terrain motion from demo pixels Do not interpret lazy-loaded iframe content beneath the transparent canvas as continued background animation after pausing. --- website/tests/site.spec.mjs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index 21b5a04..960735c 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -57,19 +57,23 @@ for (const [palette, theme] of Object.entries(themes)) { await page.goto("./"); await expect(page.locator(".terrain")).toHaveAttribute("data-animated", "true"); const canvas = page.locator(".terrain canvas"); + // Compare the transparent terrain, not unrelated lazy-loaded viewer pixels. + const captureTerrain = () => canvas.screenshot({ + style: "body > :not(.terrain) { visibility: hidden !important; }", + }); expect(await canvas.evaluate(element => element.width * element.height)).toBeLessThanOrEqual(800000); - const moving = await canvas.screenshot(); + const moving = await captureTerrain(); await page.waitForTimeout(500); - expect(await canvas.screenshot()).not.toEqual(moving); + expect(await captureTerrain()).not.toEqual(moving); await page.getByRole("button", { name: "Pause background" }).click(); - const paused = await canvas.screenshot(); + const paused = await captureTerrain(); await page.waitForTimeout(300); - expect(await canvas.screenshot()).toEqual(paused); + expect(await captureTerrain()).toEqual(paused); await page.getByRole("button", { name: "Resume background" }).click(); await page.emulateMedia({ reducedMotion: "reduce" }); - const reduced = await canvas.screenshot(); + const reduced = await captureTerrain(); await page.waitForTimeout(300); - expect(await canvas.screenshot()).toEqual(reduced); + expect(await captureTerrain()).toEqual(reduced); await page.addInitScript(() => { const getContext = HTMLCanvasElement.prototype.getContext; HTMLCanvasElement.prototype.getContext = function (kind, ...args) { From 229e5667f31b56f119b3f614144ee7682e637e7a Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 21:51:20 -0400 Subject: [PATCH 29/39] docs(demo): simplify scan-to-diagram review loop Remove validation and rendering round-trips from the product overview. Show the agent using scan results to build the explanation, then handing it to the human for review and refinement. --- docs/public-website.md | 5 ++-- stories/public/story-to-screen.topo.json | 30 ++++-------------------- website/build.test.mjs | 10 +++++++- website/tests/site.spec.mjs | 5 +++- 4 files changed, 20 insertions(+), 30 deletions(-) diff --git a/docs/public-website.md b/docs/public-website.md index 93d6142..c209601 100644 --- a/docs/public-website.md +++ b/docs/public-website.md @@ -96,8 +96,9 @@ 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 interprets and authors, the CLI validates/previews, you review, and the -cycle repeats. Its outcome is understanding code at a glance rather than reading +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. diff --git a/stories/public/story-to-screen.topo.json b/stories/public/story-to-screen.topo.json index 1ff6a3e..473a88c 100644 --- a/stories/public/story-to-screen.topo.json +++ b/stories/public/story-to-screen.topo.json @@ -60,7 +60,7 @@ "id": "agent", "title": "Coding agent", "semanticRole": "coding-agent", - "body": "Read code and scan evidence, identify what matters, and author an anchored story that explains the code visually. Repair diagnostics and preserve story identity as the explanation evolves. Present the diagram so the user can understand responsibilities and relationships without first reading every file. Interpretation here does not require the separate topo enrich command.", + "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", @@ -71,7 +71,7 @@ "id": "cli", "title": "Topocode CLI", "semanticRole": "command-line-tool", - "body": "Initialize and optionally scan the repository without calling a model. Validate drafts and render committed stories. serve supplies a local viewer; bundle supplies static files. These are separate invocations across the collaboration cycle, not one long-running call.", + "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", @@ -111,35 +111,13 @@ { "from": "cli", "to": "agent", - "label": "Graph, evidence, diagnostics", + "label": "Scan results and source evidence", "variant": "return" }, { "from": "agent", "to": "repository", - "label": "Write interpreted story" - }, - { - "from": "agent", - "to": "cli", - "label": "Validate the draft" - }, - { - "from": "cli", - "to": "agent", - "label": "Anchor results; repair feedback", - "variant": "return" - }, - { - "from": "agent", - "to": "cli", - "label": "Preview; serve or bundle" - }, - { - "from": "cli", - "to": "agent", - "label": "Diagram and source evidence", - "variant": "return" + "label": "Build diagram from scan results" }, { "from": "agent", diff --git a/website/build.test.mjs b/website/build.test.mjs index 9518cda..e66bf3f 100644 --- a/website/build.test.mjs +++ b/website/build.test.mjs @@ -160,7 +160,15 @@ test("build only the curated story set for project Pages and custom-domain roots const evidence = JSON.parse(await readFile(path.join(output, "demo/home/stories/dependency-context/evidence.json"), "utf8")); assert.equal(evidence.anchors.length, 16); const flow = JSON.parse(await readFile(path.join(output, "demo/home/stories/story-to-screen/evidence.json"), "utf8")); - assert.equal(flow.connections.length, 11); + assert.deepEqual(flow.connections.map(edge => edge.label), [ + "Question, scope and intent", + "Initialize; scan source", + "Read code (no model)", + "Scan results and source evidence", + "Build diagram from scan results", + "Diagram explains the code", + "Review, refine, repeat", + ]); assert.ok(flow.connections.some(edge => edge.from === "agent" && edge.to === "user" && edge.label === "Diagram explains the code")); assert.ok(flow.connections.every(edge => !/commit|authorization/i.test(edge.label))); assert.equal(flow.connections.at(-1).label, "Review, refine, repeat"); diff --git a/website/tests/site.spec.mjs b/website/tests/site.spec.mjs index 960735c..f6844f2 100644 --- a/website/tests/site.spec.mjs +++ b/website/tests/site.spec.mjs @@ -186,7 +186,10 @@ test("idea-to-architecture sequence shows the collaboration and review loop", as expect(await flow.locator("svg g[data-node-id]").evaluateAll(nodes => nodes.map(node => node.dataset.nodeKind))) .toEqual(["human", "coding-agent", "command-line-tool", "repository"]); await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Review, refine, repeat"); - await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Write interpreted story"); + await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Build diagram from scan results"); + for (const removed of ["Validate the draft", "Anchor results; repair feedback", "Preview; serve or bundle", "Diagram and source evidence"]) { + await expect(flow.locator('svg[data-topo-family="sequence"]')).not.toContainText(removed); + } await expect(flow.locator('svg[data-topo-family="sequence"]')).not.toContainText("Commit with authorization"); await expect(flow.locator('svg[data-topo-family="sequence"]')).toContainText("Diagram explains the code"); await flow.locator('svg g[data-node-id="cli"]').click(); From aacf9ee2c03cc981c3f7eae304dc73fdb4fa7376 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 22:09:40 -0400 Subject: [PATCH 30/39] ci(website): prepare automatic Pages deployment Fetch full pinned renderer history required by its package builder and full story history for source-backed site generation. Serialize main site deliveries and grant only read permissions to the build job. --- .github/workflows/website.yml | 9 +++++++++ CHANGELOG.md | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml index 04f5cff..ded777d 100644 --- a/.github/workflows/website.yml +++ b/.github/workflows/website.yml @@ -9,9 +9,16 @@ on: 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 @@ -19,11 +26,13 @@ jobs: - 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d8f021..bff30f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,24 @@ 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 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. From 4f09fdbafc157f7a7ab87d0b9f1f549ef5e69c4f Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 22:30:46 -0400 Subject: [PATCH 31/39] docs(agents): maintain site and diagrams in the same PR --- AGENTS.md | 8 ++++++++ 1 file changed, 8 insertions(+) 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`, From 29e0448cdf376780a63d83351d2f10759d05519b Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Thu, 1 Oct 2026 22:44:03 -0400 Subject: [PATCH 32/39] fix(stories): preserve drilldown identity and origin Retain validated caller stacks across nested returns and reloads. Map\nauthored section IDs through the selected renderer without changing\nnative node or edge metadata. Share catalogue integration fixtures\ninstead of rendering all stories inside each five-second assertion. --- docs/public-website.md | 4 + docs/story-preview.md | 12 ++ packages/cli/src/catalogue.test.ts | 24 +++- packages/cli/src/catalogue.ts | 100 ++++++++++++----- packages/cli/src/dataflow-story.test.ts | 10 +- packages/cli/src/sequence-capability.test.ts | 8 +- packages/cli/src/sequence-story.test.ts | 8 +- packages/cli/src/topo-packages-story.test.ts | 8 +- packages/diagram-core/src/index.ts | 10 +- packages/diagram-core/src/node-ids.ts | 17 +++ packages/diagram-core/src/theme.ts | 19 +++- .../diagram-core/test/diagram-core.test.mjs | 33 ++++++ packages/site/tests/e2e/catalogue.spec.ts | 4 +- .../site/tests/e2e/story-navigation.spec.ts | 103 ++++++++++++++++++ stories/public/diagram-core-surface.topo.json | 27 +++-- stories/public/internal-modules.topo.json | 2 +- website/playwright.config.mjs | 12 +- website/tests/site.spec.mjs | 22 ++++ 18 files changed, 356 insertions(+), 67 deletions(-) create mode 100644 packages/diagram-core/src/node-ids.ts create mode 100644 packages/site/tests/e2e/story-navigation.spec.ts diff --git a/docs/public-website.md b/docs/public-website.md index c209601..b534597 100644 --- a/docs/public-website.md +++ b/docs/public-website.md @@ -38,6 +38,10 @@ The website test suite exercises both deployment shapes. 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`. diff --git a/docs/story-preview.md b/docs/story-preview.md index a1c4425..1ea64ea 100644 --- a/docs/story-preview.md +++ b/docs/story-preview.md @@ -59,6 +59,10 @@ 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. @@ -68,6 +72,14 @@ 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 diff --git a/packages/cli/src/catalogue.test.ts b/packages/cli/src/catalogue.test.ts index c1d2bf9..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,6 +94,20 @@ 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"); @@ -166,7 +180,7 @@ describe("generated catalogue", () => { }); 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(); @@ -188,7 +202,7 @@ 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" && @@ -215,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" @@ -240,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 8a90688..40721f5 100644 --- a/packages/cli/src/catalogue.ts +++ b/packages/cli/src/catalogue.ts @@ -3,7 +3,7 @@ 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, @@ -408,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]")) { @@ -428,7 +457,8 @@ const STORY_NAVIGATION_SCRIPT = `(() => { link.removeAttribute("aria-current"); } } - frame.src = "viewer.html" + (nodeId ? "#focus=" + encodeURIComponent(nodeId) : ""); + const nativeId = nodeIds.get(nodeId); + frame.src = "viewer.html" + (nativeId ? "#focus=" + encodeURIComponent(nativeId) : ""); } function rememberFocus(nodeId) { @@ -438,49 +468,59 @@ const STORY_NAVIGATION_SCRIPT = `(() => { else url.searchParams.delete("focus"); window.history.replaceState(null, "", url); setFocus(nodeId); + showEvidence(nodeId, null); } let navigating = false; function follow(link) { if (navigating) return; - navigating = true; 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) { + link.addEventListener("click", event => { + event.preventDefault(); + rememberFocus(link.getAttribute("data-node-id")); + }); + } + 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]"); - if (returnLink instanceof HTMLAnchorElement) { - const targets = [ - [params.get("from"), params.get("fromFocus")], - [returnLink.dataset.parentStory, returnLink.dataset.parentNode], - ]; - for (const [from, fromFocus] of targets) { - if (!from || !fromFocus) continue; - const inventory = document.querySelector("template[data-catalogue-data]"); - const source = document.querySelector('[data-story-id="' + CSS.escape(from) + '"]') || - (inventory instanceof HTMLTemplateElement ? inventory.content.querySelector('a[data-id="' + CSS.escape(from) + '"]') : null); - if (source instanceof HTMLAnchorElement) { - returnLink.hidden = false; - returnLink.textContent = "Return to " + (source.dataset.title || source.textContent); - returnLink.href = "../" + encodeURIComponent(from) + "/?focus=" + encodeURIComponent(fromFocus); - document.querySelector("[data-story-breadcrumb]").hidden = false; - break; - } - } + 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", () => { @@ -500,7 +540,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); @@ -508,7 +548,7 @@ const STORY_NAVIGATION_SCRIPT = `(() => { current.searchParams.set("focus", focus); window.history.replaceState(null, "", current); showEvidence(focus, null); - if (activatedNodeId === focus) { + 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]); @@ -952,6 +992,12 @@ export function renderStoryWrapper( return ``; }).join(""); return renderShellPage(stories, config, historyIncomplete, story, `\ + 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/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/index.ts b/packages/diagram-core/src/index.ts index 9f76004..eeda0e6 100644 --- a/packages/diagram-core/src/index.ts +++ b/packages/diagram-core/src/index.ts @@ -19,7 +19,9 @@ 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, @@ -265,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 = @@ -1601,7 +1597,7 @@ export function* renderArchitectureStoryBatch( const sourceContents = readFileSync(output, "utf8"); const contents = adaptViewerTheme(adaptStorySemantics( improveStoryReadability(sourceContents, "architecture"), stories[index]!.document, - ), stories[index]!.document); + ), stories[index]!.document, "archify"); yield { kind: "html", mediaType: "text/html", diff --git a/packages/diagram-core/src/node-ids.ts b/packages/diagram-core/src/node-ids.ts new file mode 100644 index 0000000..1dd292a --- /dev/null +++ b/packages/diagram-core/src/node-ids.ts @@ -0,0 +1,17 @@ +import { createHash } from "node:crypto"; +import type { StoryDocument } from "@topo/story"; + +export function componentId(sectionId: string): string { + return /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(sectionId) + ? sectionId + : `component_${createHash("sha256").update(sectionId).digest("hex").slice(0, 16)}`; +} + +/** Authored/native pairs; renderer metadata and edges keep their native IDs. */ +export function storyNodeIds( + document: StoryDocument, + renderer: "archify" | "graphviz" = document.renderer ?? "archify", +): readonly (readonly [string, string])[] { + return document.sections.map(({ id }) => + [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 1a1b317..898b498 100644 --- a/packages/diagram-core/src/theme.ts +++ b/packages/diagram-core/src/theme.ts @@ -1,5 +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. @@ -75,7 +76,11 @@ export const CORE_THEME_SCRIPT = `(() => { }); })();`; -export function adaptViewerTheme(contents: string, document?: StoryDocument): 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"); const drilldowns: [string, StoryTarget][] = []; for (const section of document?.sections ?? []) { @@ -83,9 +88,17 @@ export function adaptViewerTheme(contents: string, document?: StoryDocument): st 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 navigation = document === undefined || drilldowns.length === 0 ? "" : ` + const navigation = document === undefined ? "" : `