@warpgogol/forge 6.2.0 → 6.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/os/compass/compass.module.d.ts.map +1 -1
  2. package/dist/os/compass/compass.module.js +44 -7
  3. package/dist/os/compass/compass.module.js.map +1 -1
  4. package/dist/os/compass/handlers/compass-docs-scaffold.d.ts +22 -0
  5. package/dist/os/compass/handlers/compass-docs-scaffold.d.ts.map +1 -0
  6. package/dist/os/compass/handlers/compass-docs-scaffold.js +304 -0
  7. package/dist/os/compass/handlers/compass-docs-scaffold.js.map +1 -0
  8. package/dist/os/compass/handlers/compass-docs-validate.d.ts.map +1 -1
  9. package/dist/os/compass/handlers/compass-docs-validate.js +62 -10
  10. package/dist/os/compass/handlers/compass-docs-validate.js.map +1 -1
  11. package/dist/os/core/core.module.d.ts.map +1 -1
  12. package/dist/os/core/core.module.js +40 -11
  13. package/dist/os/core/core.module.js.map +1 -1
  14. package/dist/os/core/handlers/package-health.d.ts +6 -1
  15. package/dist/os/core/handlers/package-health.d.ts.map +1 -1
  16. package/dist/os/core/handlers/package-health.js +91 -25
  17. package/dist/os/core/handlers/package-health.js.map +1 -1
  18. package/dist/os/core/handlers/validate.d.ts +11 -1
  19. package/dist/os/core/handlers/validate.d.ts.map +1 -1
  20. package/dist/os/core/handlers/validate.js +29 -1
  21. package/dist/os/core/handlers/validate.js.map +1 -1
  22. package/dist/src/onboarding/agents-generate.d.ts.map +1 -1
  23. package/dist/src/onboarding/agents-generate.js +17 -2
  24. package/dist/src/onboarding/agents-generate.js.map +1 -1
  25. package/dist/src/onboarding/compass-docs/constants.d.ts +9 -0
  26. package/dist/src/onboarding/compass-docs/constants.d.ts.map +1 -0
  27. package/dist/src/onboarding/compass-docs/constants.js +35 -0
  28. package/dist/src/onboarding/compass-docs/constants.js.map +1 -0
  29. package/dist/src/onboarding/doctor.d.ts.map +1 -1
  30. package/dist/src/onboarding/doctor.js +18 -0
  31. package/dist/src/onboarding/doctor.js.map +1 -1
  32. package/docs/reference/cli.md +6 -0
  33. package/docs/reference/compass-docs.md +102 -0
  34. package/docs/reference/forge-yaml.md +15 -0
  35. package/os/compass/compass.module.ts +46 -7
  36. package/os/compass/handlers/compass-docs-scaffold.ts +396 -0
  37. package/os/compass/handlers/compass-docs-validate.ts +67 -10
  38. package/os/core/core.module.ts +50 -11
  39. package/os/core/handlers/package-health.test.ts +92 -9
  40. package/os/core/handlers/package-health.ts +99 -24
  41. package/os/core/handlers/validate.ts +40 -1
  42. package/package.json +1 -1
  43. package/src/onboarding/agents-generate.ts +22 -2
  44. package/src/onboarding/compass-docs/constants.ts +42 -0
  45. package/src/onboarding/doctor.ts +18 -0
  46. package/src/onboarding/templates/compass-docs/development-plan.xml +29 -0
  47. package/src/onboarding/templates/compass-docs/knowledge-graph.xml +57 -0
  48. package/src/onboarding/templates/compass-docs/requirements.xml +28 -0
  49. package/src/onboarding/templates/compass-docs/source-markup.xml +121 -0
  50. package/src/onboarding/templates/compass-docs/technology.xml +30 -0
  51. package/src/onboarding/templates/compass-docs/verification-plan.xml +25 -0
  52. package/src/tests/agents-generate.test.ts +30 -0
  53. package/src/tests/compass-docs-flag.test.ts +99 -0
  54. package/src/tests/compass-docs-scaffold.test.ts +196 -0
  55. package/src/tests/compass-docs-validate-scope.test.ts +178 -0
  56. package/src/tests/doctor-bindings.test.ts +79 -0
  57. package/src/tests/fixtures/agents-generate-business-before.txt +8 -0
  58. package/src/tests/forge-validate-compass-docs.test.ts +154 -0
  59. package/src/tests/package-files.test.ts +3 -0
  60. package/src/tests/package-health-lint-surface.test.ts +153 -0
@@ -0,0 +1,102 @@
1
+ # Compass docs corpus
2
+
3
+ The Compass docs corpus is a small set of machine-readable XML documents that
4
+ gives AI agents a semantic layer over the repository: *what reads X, what breaks
5
+ if I change Y* — without a full re-scan.
6
+
7
+ Canonical documents (default layout, all under `docs/`):
8
+
9
+ | Document | Status on scaffold | Content |
10
+ | ------------------------- | ------------------ | ---------------------------------------------------- |
11
+ | `requirements.xml` | draft (TODOs) | What the repository exists to do; what "correct" is |
12
+ | `technology.xml` | active | Stack, toolchain, workspace inventory (from state) |
13
+ | `development-plan.xml` | draft (TODOs) | Durable principles and change workflow |
14
+ | `knowledge-graph.xml` | active | Workspace nodes + links (generated, merge-only) |
15
+ | `verification-plan.xml` | draft (TODOs) | Gates, commands, evidence standards |
16
+ | `source-markup.xml` | active | Compass source-markup contract (resolved policy) |
17
+
18
+ ## Format contract
19
+
20
+ Every corpus document declares the schema marker inside its `<meta>` block:
21
+
22
+ ```xml
23
+ <meta>
24
+ <document-id>requirements</document-id>
25
+ <version>1.0.0</version>
26
+ <status>active</status>
27
+ <schema>forge/compass-docs@1</schema>
28
+ </meta>
29
+ ```
30
+
31
+ `forge/compass-docs@1` identifies the corpus format generation. Documents
32
+ without the marker — or with a different schema id — still validate but earn a
33
+ `COMPASS-DOC-04` warning so migration drift stays visible.
34
+
35
+ Corpus membership for that check: the six canonical basenames plus every path
36
+ listed in `bindings.paths.compassDocs`. Generated non-corpus XML such as
37
+ `docs/compass-inventory.xml` is never expected to carry the marker.
38
+
39
+ ## Binding
40
+
41
+ The corpus lives behind `bindings.paths.compassDocs` in `forge.yaml`:
42
+
43
+ ```yaml
44
+ bindings:
45
+ paths:
46
+ compassDocs:
47
+ - docs/requirements.xml
48
+ - docs/technology.xml
49
+ - docs/development-plan.xml
50
+ - docs/knowledge-graph.xml
51
+ - docs/verification-plan.xml
52
+ - docs/source-markup.xml
53
+ ```
54
+
55
+ Paths may point anywhere in the workspace; `compass.docs.scaffold` maps the
56
+ canonical documents onto declared paths by basename (custom layouts are
57
+ honored, never rewritten). `forge doctor` reports declared-but-missing paths
58
+ as invalid and emits a scaffold remediation notice; paths outside `docs/` get
59
+ a convention notice.
60
+
61
+ ## Commands
62
+
63
+ ```sh
64
+ forge compass.docs.scaffold [--dry-run] # materialize/merge the corpus
65
+ forge compass.docs.validate # corpus integrity gate
66
+ ```
67
+
68
+ `compass.docs.scaffold` reads the real repository state — workspace discovery,
69
+ stack profile, resolved Compass policy — and:
70
+
71
+ - creates missing corpus documents from templates,
72
+ - merges **only missing workspace nodes** into an existing
73
+ `knowledge-graph.xml` (authored content is never overwritten),
74
+ - writes/merges `bindings.paths.compassDocs` in `forge.yaml`,
75
+ - stays byte-stable on reruns; `--dry-run` prints the action manifest.
76
+
77
+ `compass.docs.validate` scans `docs/*.xml` ∪ the bound paths (deduplicated)
78
+ and enforces:
79
+
80
+ | Rule | Severity | Check |
81
+ | --------------- | -------- | -------------------------------------------------------- |
82
+ | `COMPASS-DOC-00` | error | well-formed XML (tag balance) |
83
+ | `COMPASS-DOC-01` | error | `<path>` references resolve under the workspace root |
84
+ | `COMPASS-DOC-02` | error | workspace ids (`pkg-*`, `svc-*`, `app-*`) exist |
85
+ | `COMPASS-DOC-03` | warning | `<link>` targets resolve to nodes or files |
86
+ | `COMPASS-DOC-04` | warning | corpus docs carry the `forge/compass-docs@1` marker |
87
+
88
+ `forge validate` runs the corpus validator automatically when the binding
89
+ resolves non-empty and feeds errors into `allPassed`.
90
+
91
+ ## Lifecycle opt-in
92
+
93
+ ```sh
94
+ forge create --in-place --profile <profile> --compass-docs
95
+ forge init --compass-docs # (hidden recovery command)
96
+ forge upgrade --compass-docs
97
+ ```
98
+
99
+ `--compass-docs` runs `compass.docs.scaffold` after the primary operation.
100
+ When the binding resolves non-empty, `forge agents.generate` emits a
101
+ "Semantic layer — read first" block into the generated `AGENTS.md` so agents
102
+ read the corpus before planning or editing code.
@@ -65,8 +65,23 @@ Additional path bindings that the agent can reference:
65
65
  bindings:
66
66
  paths:
67
67
  invariantsFile: docs/architecture-dna.md
68
+ compassDocs:
69
+ - docs/requirements.xml
70
+ - docs/technology.xml
71
+ - docs/development-plan.xml
72
+ - docs/knowledge-graph.xml
73
+ - docs/verification-plan.xml
74
+ - docs/source-markup.xml
68
75
  ```
69
76
 
77
+ | Field | Type | Description |
78
+ | --- | --- | --- |
79
+ | `invariantsFile` | string | Invariant document (e.g. `docs/architecture-dna.md`) |
80
+ | `reviewsDir` | string | Review reports directory |
81
+ | `handoffsDir` | string | Cross-repo handoff documents directory |
82
+ | `sessionsDir` | string | Session records directory |
83
+ | `compassDocs` | string[] | Compass docs corpus paths (RFC-1253) — see [compass-docs.md](compass-docs.md). Written by `compass.docs.scaffold` |
84
+
70
85
  ## bindings.terminology
71
86
 
72
87
  Maps generic terms to project-specific names:
@@ -6,9 +6,6 @@
6
6
  </non-goals>
7
7
  </MODULE_CONTRACT>
8
8
  <CHANGE_SUMMARY>
9
- <item>RFC-1097: steps 1-4 — compass.migrate codemod
10
-
11
- Add the v1 to v2 Compass header codemod: migrateFile pure transform (collapse, strip, seed, reorder, purpose-flag actions), migrateWorkspace walker, runCompassMigrate handler with dirty-tree refusal and --force/--files/--dry-run flags, module registration, and 15 unit tests.</item>
12
9
  <item>RFC-1173: declare mutatesState on all kernel commands — collectDeclarationDiagnostics emits error-severity MUTATES-STATE-DECLARED, command.manifest.validate is the blocking consumer in packages.check, sweep declares the flag on every command definition (factories hardcode false for read-only check specs)</item>
13
10
  <item>KERNEL-FLAG-02: Declare compass --root as kind "string[]" — resolveScanRoots reads it as multi-value via getFlagValues, so repeated --root stays legal now that repeated kind-"string" flags are rejected at flag resolution.</item>
14
11
  <item>RFC-1231: step 1 — rename supportsAllSites to acceptsAllFlag
@@ -18,7 +15,8 @@ follows the parsed selector. Guard renamed assertAllSitesAllowed ->
18
15
  assertAllFlagAccepted, message updated. 417 declaration sites + type
19
16
  surfaces (KernelCommandMetadata, ForgeCommandMetadata) in one atomic pass.</item>
20
17
  <item>RFC-1248: VITE-CLIENT-DEP-02 lazy-import gate + SCAN-02 validator reads-root existence check (RFC-1248)</item>
21
- <history>RFC-0374, RFC-0538, RFC-0556, RFC-1095, RFC-1242</history>
18
+ <item>RFC-1251: step 3 — diagnostic.rule-id.validate gate + RULEID-CANONICAL-01, pipeline-wired</item>
19
+ <history>RFC-0374, RFC-0538, RFC-0556, RFC-1095, RFC-1097, RFC-1242</history>
22
20
  </CHANGE_SUMMARY>
23
21
  */
24
22
 
@@ -35,6 +33,7 @@ import { runCompassSummaryTrim } from "./handlers/compass-change-summary-handler
35
33
  import { runCompassSummaryRecord } from "./handlers/summary-record.ts";
36
34
  import { runCompassMigrate } from "./handlers/compass-migrate-handler.ts";
37
35
  import { runCompassDocsValidate } from "./handlers/compass-docs-validate.ts";
36
+ import { runCompassDocsScaffold } from "./handlers/compass-docs-scaffold.ts";
38
37
 
39
38
  const compassScanFlags = {
40
39
  packages: {
@@ -320,19 +319,59 @@ export const forgeCompassModule: ForgeModule = {
320
319
  modulePath: "packages/forge/os/compass/compass.module.ts",
321
320
  mutatesState: false,
322
321
  contract: "compass",
323
- rules: ["COMPASS-DOC-00", "COMPASS-DOC-01", "COMPASS-DOC-02", "COMPASS-DOC-03"],
322
+ rules: [
323
+ "COMPASS-DOC-00",
324
+ "COMPASS-DOC-01",
325
+ "COMPASS-DOC-02",
326
+ "COMPASS-DOC-03",
327
+ "COMPASS-DOC-04",
328
+ ],
324
329
  description:
325
- "Validate that the live docs/*.xml corpus resolves every path, workspace id, and knowledge-graph link target it references (RFC-1242). Read-only.",
330
+ "Validate that the live docs/*.xml corpus ∪ bindings.paths.compassDocs resolves every path, workspace id, and knowledge-graph link target it references, and that corpus documents carry the forge/compass-docs@1 schema marker (RFC-1242, RFC-1253). Read-only.",
326
331
  scope: "workspace",
327
332
  acceptsAllFlag: true,
328
333
  flags: {},
329
- reads: ["docs/*.xml", "docs/command-manifest.generated.yaml", "docs/architecture-dna.md"],
334
+ reads: [
335
+ "docs/*.xml",
336
+ "docs/command-manifest.generated.yaml",
337
+ "docs/architecture-dna.md",
338
+ "forge.yaml",
339
+ ],
330
340
  execute: runCompassDocsValidate,
331
341
  gate: {
332
342
  severity: "mixed",
333
343
  phase: "workspace",
334
344
  },
335
345
  },
346
+ {
347
+ name: "compass.docs.scaffold",
348
+ modulePath: "packages/forge/os/compass/compass.module.ts",
349
+ coverage: "operator" as const,
350
+ coverageNote:
351
+ "operator-invoked corpus setup; also reachable via --compass-docs on forge.create/init/upgrade (flag dispatch, not a pipeline step)",
352
+ mutatesState: true,
353
+ description:
354
+ "Scaffold the six-document Compass corpus (requirements, technology, development-plan, knowledge-graph, verification-plan, source-markup) from real repository state and write/merge bindings.paths.compassDocs (RFC-1253). Idempotent — existing files are preserved; knowledge-graph only gains missing workspace nodes.",
355
+ scope: "workspace",
356
+ acceptsAllFlag: true,
357
+ flags: {
358
+ "dry-run": {
359
+ kind: "boolean",
360
+ description: "Print the action manifest without writing any file.",
361
+ },
362
+ },
363
+ generates: [{ path: "docs/*.xml", phase: "on-demand" }],
364
+ reads: [
365
+ "forge.yaml",
366
+ "package.json",
367
+ "packages/*/package.json",
368
+ "apps/*/package.json",
369
+ "services/*/package.json",
370
+ "docs/*.xml",
371
+ ],
372
+ writes: ["docs/*.xml", "forge.yaml"],
373
+ execute: runCompassDocsScaffold,
374
+ },
336
375
  ],
337
376
  pipelines: [],
338
377
  };
@@ -0,0 +1,396 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1253: compass.docs.scaffold kernel handler — materialize the six-document Compass corpus in a consumer workspace from real repository state (workspaces, stack profile, resolved Compass policy), write or merge bindings.paths.compassDocs, and stay byte-stable on reruns.</purpose>
4
+ <non-goals>
5
+ <item>Do not invent authored intent — requirements/development-plan/verification-plan ship as TODO skeletons with status draft.</item>
6
+ <item>Do not overwrite existing corpus files — only knowledge-graph.xml gains missing workspace nodes; everything else is skipped verbatim.</item>
7
+ <item>Do not import from @warpgogol/* runtime packages — forge-internal modules only.</item>
8
+ </non-goals>
9
+ </MODULE_CONTRACT>
10
+ <KEY_DECISIONS>
11
+ <item>Canonical docs map onto binding paths by basename; unmapped docs fall back to docs/&lt;name&gt;.xml — consumer layouts never rewritten.</item>
12
+ <item>Final binding = declared set ∪ resolved doc paths; absent binding gets the default six.</item>
13
+ <item>forge.yaml write goes through applyForgeYamlPatches with the serializeForgeConfig fallback + warning — same comment-preserving contract as forge.upgrade.</item>
14
+ </KEY_DECISIONS>
15
+ <CHANGE_SUMMARY>
16
+ <item>RFC-1253: created — six-doc scaffold, KG node merge, binding patch, dry-run manifest.</item>
17
+ </CHANGE_SUMMARY>
18
+ */
19
+
20
+ import { basename, dirname, resolve } from "node:path";
21
+ import { readFileSync } from "../../../src/utils/sync-fs.ts";
22
+ import {
23
+ applyForgeYamlPatches,
24
+ loadForgeConfig,
25
+ resolveBinding,
26
+ resolveForgePackageRoot,
27
+ serializeForgeConfig,
28
+ type ForgeConfig,
29
+ } from "../../../src/config/forge-config.ts";
30
+ import { stringify as stringifyYaml } from "yaml";
31
+ import { resolveIo } from "../../../src/utils/io.ts";
32
+ import { resolveCompassPolicy } from "../policy.ts";
33
+ import {
34
+ discoverWorkspaces,
35
+ type WorkspaceDir,
36
+ } from "../../../src/onboarding/workspace-discovery.ts";
37
+ import {
38
+ CANONICAL_CORPUS_DOCS,
39
+ COMPASS_DOCS_SCHEMA_ID,
40
+ DEFAULT_COMPASS_DOCS_BINDING,
41
+ type CanonicalCorpusDoc,
42
+ } from "../../../src/onboarding/compass-docs/constants.ts";
43
+ import type {
44
+ ForgeCommandInput,
45
+ ForgeCommandResult,
46
+ ForgeRuntimeContext,
47
+ } from "../../../src/types.ts";
48
+
49
+ const TEMPLATES_DIR = resolve(
50
+ resolveForgePackageRoot(import.meta.dirname),
51
+ "src",
52
+ "onboarding",
53
+ "templates",
54
+ "compass-docs",
55
+ );
56
+
57
+ export interface ScaffoldFileAction {
58
+ path: string;
59
+ action: "created" | "merged" | "skipped" | "failed";
60
+ detail?: string;
61
+ }
62
+
63
+ export interface CompassDocsScaffoldResult {
64
+ command: "compass.docs.scaffold";
65
+ status: "ok" | "partial" | "fail";
66
+ dryRun: boolean;
67
+ schema: typeof COMPASS_DOCS_SCHEMA_ID;
68
+ files: ScaffoldFileAction[];
69
+ binding: { declared: string[]; final: string[]; written: boolean; fallback: boolean };
70
+ }
71
+
72
+ function loadTemplate(name: CanonicalCorpusDoc): string {
73
+ return readFileSync(resolve(TEMPLATES_DIR, `${name}.xml`), "utf8");
74
+ }
75
+
76
+ function xmlEscape(value: string): string {
77
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
78
+ }
79
+
80
+ function render(template: string, slots: Record<string, string>): string {
81
+ let out = template;
82
+ for (const [key, value] of Object.entries(slots)) {
83
+ out = out.replaceAll(`{{${key}}}`, value);
84
+ }
85
+ return out;
86
+ }
87
+
88
+ /** <item> list lines at 6-space indent for the scan-policy slots. */
89
+ function itemLines(values: readonly string[]): string {
90
+ return values.map((v) => ` <item>${xmlEscape(v)}</item>`).join("\n");
91
+ }
92
+
93
+ interface ScaffoldWorkspace {
94
+ id: string;
95
+ type: string;
96
+ dir: string;
97
+ name: string;
98
+ }
99
+
100
+ function workspaceNodeId(dir: WorkspaceDir): string {
101
+ const name = basename(dir.path);
102
+ const prefix = dir.type === "service" ? "svc" : dir.type === "app" ? "app" : "pkg";
103
+ return `${prefix}-${name}`;
104
+ }
105
+
106
+ function readPackageName(
107
+ root: string,
108
+ relDir: string,
109
+ ioRead: (p: string) => string | null,
110
+ ): string {
111
+ const raw = ioRead(resolve(root, relDir, "package.json"));
112
+ if (!raw) return basename(relDir);
113
+ try {
114
+ return String(JSON.parse(raw)["name"] ?? basename(relDir));
115
+ } catch {
116
+ return basename(relDir);
117
+ }
118
+ }
119
+
120
+ function collectWorkspaces(workspaceRoot: string, config: ForgeConfig): ScaffoldWorkspace[] {
121
+ const dirs = discoverWorkspaces(
122
+ workspaceRoot,
123
+ config.profile?.workspaceTypes?.length ? config.profile.workspaceTypes : undefined,
124
+ config.bindings?.workspaces?.skipDirs,
125
+ );
126
+ return dirs.map((dir) => ({
127
+ id: workspaceNodeId(dir),
128
+ type: dir.type,
129
+ dir: dir.path,
130
+ name: readPackageName(workspaceRoot, dir.path, (p) => {
131
+ try {
132
+ return readFileSync(p, "utf8");
133
+ } catch {
134
+ return null;
135
+ }
136
+ }),
137
+ }));
138
+ }
139
+
140
+ function kgNode(ws: ScaffoldWorkspace): string {
141
+ return [
142
+ ` <node id="${xmlEscape(ws.id)}" type="workspace">`,
143
+ ` <name>${xmlEscape(ws.name)}</name>`,
144
+ ` <path>\`${xmlEscape(ws.dir)}\`</path>`,
145
+ ` <role>${xmlEscape(ws.type)} workspace.</role>`,
146
+ ` </node>`,
147
+ ].join("\n");
148
+ }
149
+
150
+ /**
151
+ * Merge missing workspace <node> entries into an existing knowledge-graph.xml.
152
+ * Returns null when the file lacks a </nodes> anchor — caller treats that as
153
+ * a parse failure and leaves bytes untouched.
154
+ */
155
+ function mergeKgNodes(source: string, workspaces: ScaffoldWorkspace[]): string | null {
156
+ const anchor = source.indexOf("</nodes>");
157
+ if (anchor === -1) return null;
158
+ const missing = workspaces.filter((ws) => !source.includes(`id="${ws.id}"`));
159
+ if (missing.length === 0) return source;
160
+ const insertion = missing.map(kgNode).join("\n") + "\n";
161
+ return source.slice(0, anchor) + insertion + source.slice(anchor);
162
+ }
163
+
164
+ function rootPackageJson(root: string): Record<string, unknown> {
165
+ try {
166
+ return JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")) as Record<
167
+ string,
168
+ unknown
169
+ >;
170
+ } catch {
171
+ return {};
172
+ }
173
+ }
174
+
175
+ function docPaths(declared: readonly string[]): Record<CanonicalCorpusDoc, string> {
176
+ const byName = new Map<string, string>();
177
+ for (const p of declared) {
178
+ byName.set(basename(p), p);
179
+ }
180
+ const out = {} as Record<CanonicalCorpusDoc, string>;
181
+ for (const name of CANONICAL_CORPUS_DOCS) {
182
+ out[name] = byName.get(`${name}.xml`) ?? `docs/${name}.xml`;
183
+ }
184
+ return out;
185
+ }
186
+
187
+ export async function runCompassDocsScaffold(
188
+ input: ForgeCommandInput,
189
+ context: ForgeRuntimeContext,
190
+ ): Promise<ForgeCommandResult<CompassDocsScaffoldResult>> {
191
+ const io = resolveIo(context.io);
192
+ const dryRun = context.dryRun || input.flags["dry-run"] === true;
193
+ const { workspaceRoot, logger } = context;
194
+
195
+ let config: ForgeConfig;
196
+ try {
197
+ config = loadForgeConfig(workspaceRoot, context.forgeRoot);
198
+ } catch (err) {
199
+ return {
200
+ data: {
201
+ command: "compass.docs.scaffold",
202
+ status: "fail",
203
+ dryRun,
204
+ schema: COMPASS_DOCS_SCHEMA_ID,
205
+ files: [],
206
+ binding: { declared: [], final: [], written: false, fallback: false },
207
+ },
208
+ exitCode: 1,
209
+ summary: `[compass.docs.scaffold] FAIL — forge.yaml missing or invalid: ${(err as Error).message}`,
210
+ nextSteps: [
211
+ {
212
+ action: "Run `forge init` (or `forge create`) to create forge.yaml first.",
213
+ kind: "required",
214
+ },
215
+ ],
216
+ };
217
+ }
218
+
219
+ const declaredRaw = resolveBinding(config, "paths.compassDocs");
220
+ const declared = (Array.isArray(declaredRaw) ? declaredRaw : []).filter(
221
+ (p): p is string => typeof p === "string",
222
+ );
223
+ const bindingPaths = declared.length > 0 ? declared : DEFAULT_COMPASS_DOCS_BINDING;
224
+ const targets = docPaths(bindingPaths);
225
+ const workspaces = collectWorkspaces(workspaceRoot, config);
226
+ const policy = resolveCompassPolicy(workspaceRoot, context.forgeRoot);
227
+ const rootPkg = rootPackageJson(workspaceRoot);
228
+
229
+ const files: ScaffoldFileAction[] = [];
230
+
231
+ const slotsFor = (name: CanonicalCorpusDoc): Record<string, string> => {
232
+ if (name === "knowledge-graph") {
233
+ return {
234
+ rootLinks: workspaces
235
+ .map((ws) => ` <link rel="delegates-to" target="${xmlEscape(ws.id)}" />`)
236
+ .join("\n"),
237
+ workspaceNodes: workspaces.map(kgNode).join("\n"),
238
+ };
239
+ }
240
+ if (name === "technology") {
241
+ const engines = rootPkg["engines"] as Record<string, unknown> | undefined;
242
+ return {
243
+ nodeRange: xmlEscape(String(engines?.["node"] ?? ">=24 <25")),
244
+ packageManager: xmlEscape(
245
+ String(rootPkg["packageManager"] ?? "pnpm").split("@")[0] || "pnpm",
246
+ ),
247
+ profileId: xmlEscape(config.profile?.id ?? "unknown"),
248
+ workspaceRows: workspaces
249
+ .map(
250
+ (ws) =>
251
+ ` <workspace id="${xmlEscape(ws.id)}" type="${xmlEscape(ws.type)}">\n` +
252
+ ` <name>${xmlEscape(ws.name)}</name>\n` +
253
+ ` <path>\`${xmlEscape(ws.dir)}\`</path>\n` +
254
+ ` </workspace>`,
255
+ )
256
+ .join("\n"),
257
+ };
258
+ }
259
+ if (name === "source-markup") {
260
+ return {
261
+ fileExtensions: itemLines([...policy.fileExtensions]),
262
+ scanRoots: itemLines([...policy.scanRoots]),
263
+ testPatterns: itemLines([...policy.testPatterns]),
264
+ ignoredDirs: itemLines([...policy.ignoredDirs]),
265
+ ignoredDirPrefixes: itemLines([...policy.ignoredDirPrefixes]),
266
+ highRiskPaths: itemLines([...policy.highRiskPaths]),
267
+ excludedPaths: policy.excludedPaths
268
+ .map((e) => ` <item pattern="${xmlEscape(e.pattern)}">${xmlEscape(e.reason)}</item>`)
269
+ .join("\n"),
270
+ idPattern: xmlEscape(policy.idPattern.source),
271
+ layerRules: policy.layerRules
272
+ .map(
273
+ (r) =>
274
+ ` <rule pattern="${xmlEscape(r.pattern)}" layer="${xmlEscape(r.layer)}" risk-class="${xmlEscape(r.risk)}" />`,
275
+ )
276
+ .join("\n"),
277
+ };
278
+ }
279
+ return {};
280
+ };
281
+
282
+ for (const name of CANONICAL_CORPUS_DOCS) {
283
+ const rel = targets[name];
284
+ const abs = resolve(workspaceRoot, rel);
285
+ if (await io.exists(abs)) {
286
+ if (name === "knowledge-graph") {
287
+ const source = await io.readFile(abs);
288
+ const merged = mergeKgNodes(source, workspaces);
289
+ if (merged === null) {
290
+ files.push({
291
+ path: rel,
292
+ action: "failed",
293
+ detail: "no </nodes> anchor — left untouched",
294
+ });
295
+ continue;
296
+ }
297
+ if (merged === source) {
298
+ files.push({ path: rel, action: "skipped", detail: "all workspace nodes present" });
299
+ continue;
300
+ }
301
+ if (!dryRun) {
302
+ await io.writeFile(abs, merged);
303
+ }
304
+ files.push({
305
+ path: rel,
306
+ action: "merged",
307
+ detail: `appended ${workspaces.filter((ws) => !source.includes(`id="${ws.id}"`)).length} workspace node(s)`,
308
+ });
309
+ continue;
310
+ }
311
+ files.push({ path: rel, action: "skipped", detail: "exists — authored content preserved" });
312
+ continue;
313
+ }
314
+ const content = render(loadTemplate(name), slotsFor(name));
315
+ if (!dryRun) {
316
+ await io.mkdir(dirname(abs));
317
+ await io.writeFile(abs, content);
318
+ }
319
+ files.push({ path: rel, action: "created" });
320
+ }
321
+
322
+ // Binding merge: declared set ∪ resolved doc paths (declared order first,
323
+ // canonical order for additions) — subset declarations keep their custom
324
+ // paths and gain only the missing canonical ones.
325
+ const finalBinding = [...new Set([...declared, ...Object.values(targets)])];
326
+ const bindingChanged =
327
+ finalBinding.length !== declared.length || finalBinding.some((p, i) => declared[i] !== p);
328
+ let bindingWritten = false;
329
+ let bindingFallback = false;
330
+ if (bindingChanged) {
331
+ if (!dryRun) {
332
+ const forgeYamlPath = resolve(workspaceRoot, "forge.yaml");
333
+ const raw = await io.readFile(forgeYamlPath).catch(() => null);
334
+ const patched =
335
+ raw === null
336
+ ? null
337
+ : applyForgeYamlPatches(raw, [
338
+ { path: ["bindings", "paths", "compassDocs"], value: finalBinding },
339
+ ]);
340
+ if (patched !== null) {
341
+ await io.writeFile(forgeYamlPath, patched);
342
+ } else {
343
+ bindingFallback = true;
344
+ logger.warn(
345
+ "compass.docs.scaffold: forge.yaml patch failed — falling back to full serialization (schema-unknown keys may be dropped)",
346
+ );
347
+ await io.writeFile(forgeYamlPath, stringifyYaml(serializeForgeConfig(config)));
348
+ }
349
+ }
350
+ bindingWritten = true;
351
+ }
352
+
353
+ const failed = files.filter((f) => f.action === "failed");
354
+ const created = files.filter((f) => f.action === "created").length;
355
+ const merged = files.filter((f) => f.action === "merged").length;
356
+ const skipped = files.filter((f) => f.action === "skipped").length;
357
+ const status = failed.length > 0 ? "partial" : "ok";
358
+
359
+ return {
360
+ data: {
361
+ command: "compass.docs.scaffold",
362
+ status,
363
+ dryRun,
364
+ schema: COMPASS_DOCS_SCHEMA_ID,
365
+ files,
366
+ binding: {
367
+ declared,
368
+ final: finalBinding,
369
+ written: bindingWritten,
370
+ fallback: bindingFallback,
371
+ },
372
+ },
373
+ exitCode: failed.length > 0 ? 1 : 0,
374
+ summary:
375
+ `[compass.docs.scaffold] ${status} — created=${created} merged=${merged} skipped=${skipped}` +
376
+ `${failed.length > 0 ? ` failed=${failed.length}` : ""}` +
377
+ `${bindingWritten ? ` binding=${declared.length === 0 ? "written" : "merged"}` : ""}` +
378
+ `${dryRun ? " (dry-run)" : ""}`,
379
+ nextSteps: [
380
+ {
381
+ action:
382
+ "Author the three draft skeletons (requirements.xml, development-plan.xml, verification-plan.xml) — TODO markers mark the fill-in surface.",
383
+ kind: "optional",
384
+ },
385
+ {
386
+ action: "Run `forge run compass.docs.validate` to check corpus integrity.",
387
+ kind: "optional",
388
+ },
389
+ {
390
+ action:
391
+ "Run `forge agents.generate` to emit the read-first semantic-layer block into AGENTS.md.",
392
+ kind: "optional",
393
+ },
394
+ ],
395
+ };
396
+ }