@warpgogol/forge 6.3.2 → 6.3.3

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 (35) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/os/compass/handlers/compass-docs-scaffold.d.ts.map +1 -1
  3. package/dist/os/compass/handlers/compass-docs-scaffold.js +26 -3
  4. package/dist/os/compass/handlers/compass-docs-scaffold.js.map +1 -1
  5. package/dist/src/onboarding/agents-generate.d.ts +2 -0
  6. package/dist/src/onboarding/agents-generate.d.ts.map +1 -1
  7. package/dist/src/onboarding/agents-generate.js +33 -14
  8. package/dist/src/onboarding/agents-generate.js.map +1 -1
  9. package/dist/src/onboarding/compass-docs/semantic-layer-block.d.ts +40 -0
  10. package/dist/src/onboarding/compass-docs/semantic-layer-block.d.ts.map +1 -0
  11. package/dist/src/onboarding/compass-docs/semantic-layer-block.js +116 -0
  12. package/dist/src/onboarding/compass-docs/semantic-layer-block.js.map +1 -0
  13. package/dist/src/onboarding/doctor.d.ts.map +1 -1
  14. package/dist/src/onboarding/doctor.js +3 -5
  15. package/dist/src/onboarding/doctor.js.map +1 -1
  16. package/dist/src/onboarding/nested-agents-generate.d.ts +2 -0
  17. package/dist/src/onboarding/nested-agents-generate.d.ts.map +1 -1
  18. package/dist/src/onboarding/nested-agents-generate.js +31 -6
  19. package/dist/src/onboarding/nested-agents-generate.js.map +1 -1
  20. package/dist/src/onboarding/nested-agents-templates.d.ts +6 -1
  21. package/dist/src/onboarding/nested-agents-templates.d.ts.map +1 -1
  22. package/dist/src/onboarding/nested-agents-templates.js +19 -4
  23. package/dist/src/onboarding/nested-agents-templates.js.map +1 -1
  24. package/docs/reference/compass-docs.md +57 -39
  25. package/os/compass/handlers/compass-docs-scaffold.ts +26 -3
  26. package/package.json +1 -1
  27. package/src/onboarding/agents-generate.ts +36 -18
  28. package/src/onboarding/compass-docs/semantic-layer-block.test.ts +137 -0
  29. package/src/onboarding/compass-docs/semantic-layer-block.ts +132 -0
  30. package/src/onboarding/doctor.ts +3 -5
  31. package/src/onboarding/nested-agents-generate.ts +40 -6
  32. package/src/onboarding/nested-agents-templates.ts +24 -4
  33. package/src/tests/agents-generate.test.ts +128 -0
  34. package/src/tests/compass-docs-scaffold.test.ts +67 -0
  35. package/src/tests/fixtures/agents-generate-business-before.txt +4 -0
@@ -1,19 +1,17 @@
1
1
  # Compass docs corpus
2
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.
3
+ The Compass docs corpus is a small set of machine-readable XML documents that gives AI agents a semantic layer over the repository: _what reads X, what breaks if I change Y_ — without a full re-scan.
6
4
 
7
5
  Canonical documents (default layout, all under `docs/`):
8
6
 
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) |
7
+ | Document | Status on scaffold | Content |
8
+ | --- | --- | --- |
9
+ | `requirements.xml` | draft (TODOs) | What the repository exists to do; what "correct" is |
10
+ | `technology.xml` | active | Stack, toolchain, workspace inventory (from state) |
11
+ | `development-plan.xml` | draft (TODOs) | Durable principles and change workflow |
12
+ | `knowledge-graph.xml` | active | Workspace nodes + links (generated, merge-only) |
13
+ | `verification-plan.xml` | draft (TODOs) | Gates, commands, evidence standards |
14
+ | `source-markup.xml` | active | Compass source-markup contract (resolved policy) |
17
15
 
18
16
  ## Format contract
19
17
 
@@ -28,13 +26,9 @@ Every corpus document declares the schema marker inside its `<meta>` block:
28
26
  </meta>
29
27
  ```
30
28
 
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.
29
+ `forge/compass-docs@1` identifies the corpus format generation. Documents without the marker — or with a different schema id — still validate but earn a `COMPASS-DOC-04` warning so migration drift stays visible.
34
30
 
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.
31
+ Corpus membership for that check: the six canonical basenames plus every path listed in `bindings.paths.compassDocs`. Generated non-corpus XML such as `docs/compass-inventory.xml` is never expected to carry the marker.
38
32
 
39
33
  ## Binding
40
34
 
@@ -52,11 +46,7 @@ bindings:
52
46
  - docs/source-markup.xml
53
47
  ```
54
48
 
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.
49
+ Paths may point anywhere in the workspace; `compass.docs.scaffold` maps the canonical documents onto declared paths by basename (custom layouts are honored, never rewritten). `forge doctor` reports declared-but-missing paths as invalid and emits a scaffold remediation notice; paths outside `docs/` get a convention notice.
60
50
 
61
51
  ## Commands
62
52
 
@@ -65,28 +55,38 @@ forge compass.docs.scaffold [--dry-run] # materialize/merge the corpus
65
55
  forge compass.docs.validate # corpus integrity gate
66
56
  ```
67
57
 
68
- `compass.docs.scaffold` reads the real repository state — workspace discovery,
69
- stack profile, resolved Compass policy — and:
58
+ `compass.docs.scaffold` reads the real repository state — workspace discovery, stack profile, resolved Compass policy — and:
70
59
 
71
60
  - creates missing corpus documents from templates,
72
- - merges **only missing workspace nodes** into an existing
73
- `knowledge-graph.xml` (authored content is never overwritten),
61
+ - merges **only missing workspace nodes** into an existing `knowledge-graph.xml` (authored content is never overwritten),
74
62
  - writes/merges `bindings.paths.compassDocs` in `forge.yaml`,
75
63
  - stays byte-stable on reruns; `--dry-run` prints the action manifest.
76
64
 
77
- `compass.docs.validate` scans `docs/*.xml` ∪ the bound paths (deduplicated)
78
- and enforces:
65
+ `compass.docs.validate` scans `docs/*.xml` ∪ the bound paths (deduplicated) and enforces:
79
66
 
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 |
67
+ | Rule | Severity | Check |
68
+ | ---------------- | -------- | ---------------------------------------------------- |
69
+ | `COMPASS-DOC-00` | error | well-formed XML (tag balance) |
70
+ | `COMPASS-DOC-01` | error | `<path>` references resolve under the workspace root |
71
+ | `COMPASS-DOC-02` | error | workspace ids (`pkg-*`, `svc-*`, `app-*`) exist |
72
+ | `COMPASS-DOC-03` | warning | `<link>` targets resolve to nodes or files |
73
+ | `COMPASS-DOC-04` | warning | corpus docs carry the `forge/compass-docs@1` marker |
74
+
75
+ `forge validate` runs the corpus validator automatically when the binding resolves non-empty and feeds errors into `allPassed`.
76
+
77
+ ### Workspace id convention
78
+
79
+ Workspace node ids follow the **location** convention `COMPASS-DOC-02` enforces — the prefix names the top-level directory, not the detected workspace type:
80
+
81
+ | Location | Emitted id | Example |
82
+ | ----------------------------- | ------------------------- | -------------------------- |
83
+ | `apps/<name>` | `app-<name>` | `apps/api` → `app-api` |
84
+ | `packages/<name>` | `pkg-<name>` | `packages/foo` → `pkg-foo` |
85
+ | `services/<name>` | `svc-<name>` | `services/x` → `svc-x` |
86
+ | anywhere else / nested deeper | `<dir>.<…>.<name>` dotted | `tools/x` → `tools.x` |
87
+
88
+ The prefix never comes from content detection — a worker under `apps/` still gets `app-*`, so scaffold output always validates clean. Dotted ids outside `apps`/`packages`/`services` are semantic handles: `COMPASS-DOC-02` resolves only their first two segments (or leaves unmapped prefixes unchecked), while the node's `<path>` still pins the real directory via `COMPASS-DOC-01`.
87
89
 
88
- `forge validate` runs the corpus validator automatically when the binding
89
- resolves non-empty and feeds errors into `allPassed`.
90
90
 
91
91
  ## Lifecycle opt-in
92
92
 
@@ -98,5 +98,23 @@ forge upgrade --compass-docs
98
98
 
99
99
  `--compass-docs` runs `compass.docs.scaffold` after the primary operation.
100
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.
101
+ "Semantic layer — read first" block — marker-wrapped in
102
+ `<!-- forge:begin semantic-layer -->` / `<!-- forge:end semantic-layer -->` —
103
+ into the generated root `AGENTS.md` and every generated nested workspace
104
+ guide, so agents read the corpus before planning or editing code.
105
+
106
+ ### Discoverability in hand-written AGENTS.md
107
+
108
+ Hand-written files are never overwritten — but they can opt in to the block.
109
+ Drop the sentinel anywhere in the file:
110
+
111
+ ```md
112
+ <!-- forge:semantic-layer -->
113
+ ```
114
+
115
+ The next `agents.generate` (or `upgrade`, or `doctor --fix`) expands it into
116
+ a full marker-wrapped region listing the bound corpus docs. Regions already
117
+ present are refreshed in place — a block pasted from generated output keeps
118
+ updating when `paths.compassDocs` changes. Files without the sentinel are
119
+ left untouched.
120
+
@@ -14,6 +14,7 @@
14
14
  </KEY_DECISIONS>
15
15
  <CHANGE_SUMMARY>
16
16
  <item>RFC-1253: created — six-doc scaffold, KG node merge, binding patch, dry-run manifest.</item>
17
+ <item>Derive workspace node id prefixes from directory location (apps/→app-, packages/→pkg-, services/→svc-, dotted elsewhere) — COMPASS-DOC-02 resolves prefixes to paths, so type-derived ids failed validation on apps/ repos (consumer field report).</item>
17
18
  </CHANGE_SUMMARY>
18
19
  */
19
20
 
@@ -97,10 +98,32 @@ interface ScaffoldWorkspace {
97
98
  name: string;
98
99
  }
99
100
 
101
+ /**
102
+ * COMPASS-DOC-02 resolves workspace ids by top-level-directory convention:
103
+ * app-* names apps/<rest>, pkg-* names packages/<rest>, svc-* names
104
+ * services/<rest>. Deriving the prefix from the detected workspace type breaks
105
+ * that contract on repos whose apps/ workspaces miss content detection — a
106
+ * non-astro, non-docker workspace under apps/ detects as "package" and would
107
+ * emit pkg-<name>, which the validator resolves to a packages/<name> path that
108
+ * does not exist. Derive the prefix from the location instead; locations the
109
+ * prefixed convention cannot express (nested deeper than <dir>/<name>, or
110
+ * outside apps/packages/services) fall back to the dotted semantic-id form —
111
+ * DOC-02 resolves it through its first two segments or leaves unmapped
112
+ * prefixes unchecked, and DOC-01 still verifies the real path via <path>.
113
+ */
114
+ const WORKSPACE_ID_PREFIX: Record<string, string> = {
115
+ apps: "app",
116
+ packages: "pkg",
117
+ services: "svc",
118
+ };
119
+
100
120
  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}`;
121
+ const segments = dir.path.replace(/\\/g, "/").split("/").filter(Boolean);
122
+ if (segments.length === 2) {
123
+ const prefix = WORKSPACE_ID_PREFIX[segments[0]!];
124
+ if (prefix) return `${prefix}-${segments[1]}`;
125
+ }
126
+ return segments.join(".");
104
127
  }
105
128
 
106
129
  function readPackageName(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warpgogol/forge",
3
- "version": "6.3.2",
3
+ "version": "6.3.3",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -7,7 +7,6 @@
7
7
  </non-goals>
8
8
  </MODULE_CONTRACT>
9
9
  <CHANGE_SUMMARY>
10
- <item>RFC-0664: added project memory layer read discipline section to generated AGENTS.md.</item>
11
10
  <item>RFC-1253: emit "Semantic layer — read first" block listing bound paths.compassDocs before the Skills table when the binding resolves non-empty.</item>
12
11
  <item>RFC-1097: step 6 — compass.migrate codemod run
13
12
 
@@ -16,7 +15,8 @@ Mechanical v1 to v2 header migration across the workspace: 942 files rewritten
16
15
 
17
16
  Sweep batch 2: real KEY_DECISIONS on 10 files, expanded purposes (CONTRACT-02/PURPOSE-02), headers on mission/index + gen-upstreams, sanitizeItemText in summary.record (literal Compass tags corrupted history), excludedPaths for wrangler types, test-fixtures testPattern. forge+services now 0 diagnostics under --mode error.</item>
18
17
  <item>Single blank line after the generated header — header ends in a newline so "\n\n" produced two blank lines that prettier collapsed, ping-ponging doctor's stale check. wsTypes resolution moved to shared resolveWorkspaceTypes.</item>
19
- <history>RFC-0391, RFC-0393, RFC-0548, RFC-0549, RFC-0551, RFC-0611, RFC-0640, RFC-0643</history>
18
+ <item>Semantic-layer block rendered marker-wrapped via shared semantic-layer-block module and injected/refreshed inside hand-written roots carrying the sentinel or a pasted region; result gains injected[] (consumer field report follow-up to RFC-1253).</item>
19
+ <history>RFC-0391, RFC-0393, RFC-0548, RFC-0549, RFC-0551, RFC-0611, RFC-0640, RFC-0643, RFC-0664</history>
20
20
  </CHANGE_SUMMARY>
21
21
  */
22
22
 
@@ -29,6 +29,7 @@ import { resolveAllTerminology } from "../profiles/terminology-utils.ts";
29
29
  import { FORGE_SKILLS } from "../registry.ts";
30
30
  import { alignMarkdownTable, buildGeneratedHeader, hasEditableGeneratedMarker, hasGeneratedMarker, mergeEditableGenerated, writeFileIfChanged } from "../utils/index.ts";
31
31
  import { generateNestedAgentsMd } from "./nested-agents-generate.ts";
32
+ import { injectSemanticLayerBlock, semanticLayerLines } from "./compass-docs/semantic-layer-block.ts";
32
33
  import { resolveWorkspaceTypes } from "./workspace-discovery.ts";
33
34
  import type { StackProfile } from "../profiles/stack-profile.ts";
34
35
  import type {
@@ -235,6 +236,8 @@ interface AgentsGenerateResult {
235
236
  configPath: string;
236
237
  generated: string[];
237
238
  skipped: string[];
239
+ /** Hand-written files that accepted the marker-guarded semantic-layer block. */
240
+ injected: string[];
238
241
  errors: string[];
239
242
  renderedFiles?: { [relPath: string]: string };
240
243
  details?: Array<{ path: string; domain?: string; register?: string; workspaceType?: string }>;
@@ -265,6 +268,7 @@ export async function runAgentsGenerate(
265
268
  configPath: "forge.yaml",
266
269
  generated: [],
267
270
  skipped: [],
271
+ injected: [],
268
272
  errors: [msg],
269
273
  },
270
274
  exitCode: 1,
@@ -305,21 +309,15 @@ export async function runAgentsGenerate(
305
309
 
306
310
  // RFC-1253: Compass corpus read-first block — only when the binding
307
311
  // resolves non-empty (DNA-90: instructions live where agents read them).
312
+ // Marker-wrapped so hand-written files that pasted it stay refreshable.
308
313
  const compassDocsReadFirst = resolveBinding(config, "paths.compassDocs");
309
- if (Array.isArray(compassDocsReadFirst) && compassDocsReadFirst.length > 0) {
310
- dynamicLines.push("## Semantic layer — read first");
311
- dynamicLines.push("");
312
- dynamicLines.push(
313
- "This repository carries a machine-readable Compass corpus — the semantic layer that answers \u201cwhat reads X, what breaks if I change Y\u201d without a full repository re-scan. For repository-wide, cross-workspace, architectural, shared-package, or high-risk tasks, read these documents before planning or editing code:",
314
- );
315
- dynamicLines.push("");
316
- for (const doc of compassDocsReadFirst) {
317
- dynamicLines.push(`- \`${doc}\``);
318
- }
319
- dynamicLines.push("");
320
- dynamicLines.push(
321
- "Treat these XML documents as the primary semantic layer for AI work and keep them synchronized with code, architecture, and verification changes.",
322
- );
314
+ const semanticLayerDocs = (Array.isArray(compassDocsReadFirst) ? compassDocsReadFirst : []).filter(
315
+ (d): d is string => typeof d === "string",
316
+ );
317
+ const semanticLayerBlock =
318
+ semanticLayerDocs.length > 0 ? semanticLayerLines(semanticLayerDocs).join("\n") : "";
319
+ if (semanticLayerBlock) {
320
+ dynamicLines.push(semanticLayerBlock);
323
321
  dynamicLines.push("");
324
322
  }
325
323
 
@@ -417,6 +415,7 @@ export async function runAgentsGenerate(
417
415
 
418
416
  const generated: string[] = [];
419
417
  const skipped: string[] = [];
418
+ const injected: string[] = [];
420
419
  const renderedFiles: { [relPath: string]: string } = {};
421
420
  const details: Array<{ path: string; domain?: string; register?: string; workspaceType?: string }> = [];
422
421
  details.push({
@@ -429,7 +428,24 @@ export async function runAgentsGenerate(
429
428
  renderedFiles["AGENTS.md"] = content;
430
429
  generated.push("AGENTS.md");
431
430
  } else if (rootSkipped) {
432
- skipped.push("AGENTS.md (hand-written)");
431
+ // Marker-guarded opt-in: a hand-written root carrying the semantic-layer
432
+ // sentinel (or a pasted marked region) gets the block refreshed —
433
+ // surrounding prose is never touched.
434
+ let rootInjected = false;
435
+ if (semanticLayerBlock) {
436
+ try {
437
+ const existing = await fio.readFile(agentsMdPath);
438
+ const injection = injectSemanticLayerBlock(existing, semanticLayerBlock);
439
+ if (injection.changed) {
440
+ await writeFileIfChanged(agentsMdPath, injection.content, fio);
441
+ rootInjected = true;
442
+ }
443
+ } catch {
444
+ // Unreadable — leave the hand-written file alone.
445
+ }
446
+ }
447
+ skipped.push(`AGENTS.md (hand-written${rootInjected ? " — semantic-layer injected" : ""})`);
448
+ if (rootInjected) injected.push("AGENTS.md");
433
449
  } else {
434
450
  // RFC-1153: merge instead of overwrite — preserve the custom tail below
435
451
  // the forge:custom boundary; fail-closed skip when no boundary resolves.
@@ -478,6 +494,7 @@ export async function runAgentsGenerate(
478
494
  const nestedResult = await generateNestedAgentsMd(workspaceRoot, config, dryRun, workspaceTypes, fio);
479
495
  generated.push(...nestedResult.generated);
480
496
  skipped.push(...nestedResult.skipped);
497
+ injected.push(...nestedResult.injected);
481
498
  Object.assign(renderedFiles, nestedResult.renderedFiles);
482
499
 
483
500
  // RFC-0643: add details for nested files
@@ -505,6 +522,7 @@ export async function runAgentsGenerate(
505
522
  configPath: "forge.yaml",
506
523
  generated,
507
524
  skipped,
525
+ injected,
508
526
  errors: [],
509
527
  details,
510
528
  ...(rootSkipped ? { rootSkipped: true, rootSkipReason: "hand-written" } : {}),
@@ -513,6 +531,6 @@ export async function runAgentsGenerate(
513
531
  exitCode: 0,
514
532
  summary: dryRun
515
533
  ? `forge.agents.generate: [dry-run] would generate ${generated.length} file(s), skip ${skipped.length}`
516
- : `forge.agents.generate: OK — ${generated.length} file(s) generated, ${skipped.length} skipped${rootSkipped ? " (root AGENTS.md hand-written — skipped)" : ""}`,
534
+ : `forge.agents.generate: OK — ${generated.length} file(s) generated, ${skipped.length} skipped${injected.length > 0 ? `, ${injected.length} semantic-layer injected` : ""}${rootSkipped ? " (root AGENTS.md hand-written — skipped)" : ""}`,
517
535
  };
518
536
  }
@@ -0,0 +1,137 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Unit tests for the shared semantic-layer block — marker-wrapped render shape
5
+ and the opt-in/refresh injection contract for hand-written AGENTS.md files
6
+ (consumer field report follow-up to RFC-1253).
7
+ </purpose>
8
+ </MODULE_CONTRACT>
9
+ */
10
+
11
+ import { describe, it, expect } from "vitest";
12
+ import {
13
+ SEMANTIC_LAYER_BEGIN,
14
+ SEMANTIC_LAYER_END,
15
+ SEMANTIC_LAYER_OPT_IN,
16
+ ensureSemanticLayerBlock,
17
+ injectSemanticLayerBlock,
18
+ semanticLayerLines,
19
+ } from "./semantic-layer-block.ts";
20
+
21
+ const DOCS = ["docs/requirements.xml", "docs/technology.xml"];
22
+
23
+ describe("semanticLayerLines", () => {
24
+ it("wraps the block in forge:begin/forge:end semantic-layer markers", () => {
25
+ const lines = semanticLayerLines(DOCS);
26
+ expect(lines[0]).toBe(SEMANTIC_LAYER_BEGIN);
27
+ expect(lines[lines.length - 1]).toBe(SEMANTIC_LAYER_END);
28
+ const text = lines.join("\n");
29
+ expect(text).toContain("## Semantic layer — read first");
30
+ expect(text).toContain("- `docs/requirements.xml`");
31
+ expect(text).toContain("- `docs/technology.xml`");
32
+ });
33
+ });
34
+
35
+ describe("injectSemanticLayerBlock", () => {
36
+ const block = semanticLayerLines(DOCS).join("\n");
37
+
38
+ it("expands the first bare opt-in sentinel into a full marked region", () => {
39
+ const source = ["# Guide", "", "Intro.", "", SEMANTIC_LAYER_OPT_IN, "", "Tail.", ""].join("\n");
40
+ const res = injectSemanticLayerBlock(source, block);
41
+ expect(res.region).toBe("expanded");
42
+ expect(res.changed).toBe(true);
43
+ expect(res.content).toContain(SEMANTIC_LAYER_BEGIN);
44
+ expect(res.content).toContain("## Semantic layer — read first");
45
+ expect(res.content).toContain("`docs/technology.xml`");
46
+ expect(res.content).not.toContain(SEMANTIC_LAYER_OPT_IN);
47
+ expect(res.content).toContain("Intro.");
48
+ expect(res.content).toContain("Tail.");
49
+ });
50
+
51
+ it("refreshes an existing region in place — stale content replaced, prose kept", () => {
52
+ const stale = [
53
+ SEMANTIC_LAYER_BEGIN,
54
+ "",
55
+ "## Semantic layer — read first",
56
+ "",
57
+ "STALE",
58
+ "",
59
+ SEMANTIC_LAYER_END,
60
+ ].join("\n");
61
+ const source = `before\n\n${stale}\n\nafter\n`;
62
+ const res = injectSemanticLayerBlock(source, block);
63
+ expect(res.region).toBe("refreshed");
64
+ expect(res.changed).toBe(true);
65
+ expect(res.content).not.toContain("STALE");
66
+ expect(res.content).toBe(`before\n\n${block}\n\nafter\n`);
67
+ });
68
+
69
+ it("is idempotent — an up-to-date region reports no change", () => {
70
+ const source = `before\n${block}\nafter\n`;
71
+ const res = injectSemanticLayerBlock(source, block);
72
+ expect(res.region).toBe("refreshed");
73
+ expect(res.changed).toBe(false);
74
+ expect(res.content).toBe(source);
75
+ });
76
+
77
+ it("leaves files without markers untouched", () => {
78
+ const source = "# Guide\n\nNo markers here.\n";
79
+ const res = injectSemanticLayerBlock(source, block);
80
+ expect(res.region).toBe("none");
81
+ expect(res.changed).toBe(false);
82
+ expect(res.content).toBe(source);
83
+ });
84
+
85
+ it("refreshes every complete region when several exist", () => {
86
+ const stale = `${SEMANTIC_LAYER_BEGIN}\nstale\n${SEMANTIC_LAYER_END}`;
87
+ const source = `${stale}\nmiddle\n${stale}\n`;
88
+ const res = injectSemanticLayerBlock(source, block);
89
+ expect(res.region).toBe("refreshed");
90
+ expect(res.content).toBe(`${block}\nmiddle\n${block}\n`);
91
+ });
92
+
93
+ it("ignores an unbalanced begin marker and still expands the opt-in sentinel", () => {
94
+ const source = `${SEMANTIC_LAYER_BEGIN}\nnever closed\n\n${SEMANTIC_LAYER_OPT_IN}\n`;
95
+ const res = injectSemanticLayerBlock(source, block);
96
+ expect(res.region).toBe("expanded");
97
+ // The dangling begin line is preserved verbatim above the new region.
98
+ expect(res.content).toBe(`${SEMANTIC_LAYER_BEGIN}\nnever closed\n\n${block}\n`);
99
+ });
100
+
101
+ it("normalizes CRLF input to LF", () => {
102
+ const source = `intro\r\n${SEMANTIC_LAYER_OPT_IN}\r\ntail\r\n`;
103
+ const res = injectSemanticLayerBlock(source, block);
104
+ expect(res.changed).toBe(true);
105
+ expect(res.content).not.toContain("\r\n");
106
+ expect(res.content).toContain(block);
107
+ });
108
+ });
109
+
110
+ describe("ensureSemanticLayerBlock", () => {
111
+ const block = semanticLayerLines(DOCS).join("\n");
112
+ const FOOTER = "See the root `AGENTS.md` for project-wide rules, skills, and capabilities.";
113
+
114
+ it("inserts the block before the footer so the footer stays last", () => {
115
+ const source = `# Guide\n\nbody\n\n${FOOTER}\n`;
116
+ const out = ensureSemanticLayerBlock(source, block, FOOTER);
117
+ expect(out.indexOf("## Semantic layer — read first")).toBeLessThan(out.indexOf(FOOTER));
118
+ expect(out.trimEnd().endsWith(FOOTER)).toBe(true);
119
+ expect(out).toContain("body");
120
+ });
121
+
122
+ it("appends the block at the end when no footer is found", () => {
123
+ const source = `# Guide\n\nbody\n`;
124
+ const out = ensureSemanticLayerBlock(source, block, FOOTER);
125
+ expect(out).toBe(`# Guide\n\nbody\n\n${block}\n`);
126
+ });
127
+
128
+ it("returns content that already carries the region unchanged", () => {
129
+ const source = `# Guide\n\n${block}\n\n${FOOTER}\n`;
130
+ expect(ensureSemanticLayerBlock(source, block, FOOTER)).toBe(source);
131
+ });
132
+
133
+ it("returns content unchanged when the block is empty", () => {
134
+ const source = `# Guide\n\n${FOOTER}\n`;
135
+ expect(ensureSemanticLayerBlock(source, "", FOOTER)).toBe(source);
136
+ });
137
+ });
@@ -0,0 +1,132 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>Canonical "Semantic layer — read first" AGENTS.md block for the Compass docs corpus: one renderer shared by the generated root, nested workspace guides, and the marker-guarded injection path for hand-written AGENTS.md files. Keeps the read-first contract identical on every surface it lands on.</purpose>
4
+ <non-goals>
5
+ <item>Do not read forge.yaml, resolve bindings, or touch the filesystem — pure string functions only; callers resolve paths.compassDocs and perform I/O.</item>
6
+ <item>Do not merge or preserve authored content — injection only refreshes the marker-guarded region; everything outside the markers stays verbatim.</item>
7
+ </non-goals>
8
+ </MODULE_CONTRACT>
9
+ <KEY_DECISIONS>
10
+ <item>Markers are the contract — a region pasted into a hand-written file stays refreshable through the same injection path.</item>
11
+ <item>forge:semantic-layer sentinel opts hand-written files in; the marked region refreshes in place thereafter.</item>
12
+ <item>Regions beat stray sentinels — the block appears at most once per file.</item>
13
+ </KEY_DECISIONS>
14
+ <CHANGE_SUMMARY>
15
+ <item>created — shared read-first block renderer, marker-guarded injection for hand-written AGENTS.md, and ensureSemanticLayerBlock for renders that bypass the fallback template (consumer field report follow-up to RFC-1253).</item>
16
+ </CHANGE_SUMMARY>
17
+ */
18
+
19
+ /** Opt-in sentinel for hand-written AGENTS.md files — expands into a full marked region. */
20
+ export const SEMANTIC_LAYER_OPT_IN = "<!-- forge:semantic-layer -->";
21
+ /** Region markers emitted around the generated block and matched by injection. */
22
+ export const SEMANTIC_LAYER_BEGIN = "<!-- forge:begin semantic-layer -->";
23
+ export const SEMANTIC_LAYER_END = "<!-- forge:end semantic-layer -->";
24
+
25
+ /**
26
+ * The canonical read-first block, marker-wrapped. `compassDocs` is the bound
27
+ * `paths.compassDocs` list — callers filter non-string entries before calling.
28
+ */
29
+ export function semanticLayerLines(compassDocs: readonly string[]): string[] {
30
+ const lines = [
31
+ SEMANTIC_LAYER_BEGIN,
32
+ "",
33
+ "## Semantic layer — read first",
34
+ "",
35
+ "This repository carries a machine-readable Compass corpus — the semantic layer that answers “what reads X, what breaks if I change Y” without a full repository re-scan. For repository-wide, cross-workspace, architectural, shared-package, or high-risk tasks, read these documents before planning or editing code:",
36
+ "",
37
+ ];
38
+ for (const doc of compassDocs) lines.push(`- \`${doc}\``);
39
+ lines.push(
40
+ "",
41
+ "Treat these XML documents as the primary semantic layer for AI work and keep them synchronized with code, architecture, and verification changes.",
42
+ "",
43
+ SEMANTIC_LAYER_END,
44
+ );
45
+ return lines;
46
+ }
47
+
48
+ export interface SemanticLayerInjection {
49
+ content: string;
50
+ changed: boolean;
51
+ /** How the block landed: existing region refreshed, opt-in expanded, or no anchor found. */
52
+ region: "refreshed" | "expanded" | "none";
53
+ }
54
+
55
+ /**
56
+ * Guarantee the block is present in generated render output — a safety net for
57
+ * content paths that bypass {@link semanticLayerLines} (e.g. a profile-authored
58
+ * nested template selected over the fallback render). Content already carrying
59
+ * the region is returned as-is; otherwise the block is inserted before
60
+ * `footerLine` (the canonical merge boundary stays the last substantive line)
61
+ * or appended when no footer is found.
62
+ */
63
+ export function ensureSemanticLayerBlock(
64
+ content: string,
65
+ block: string,
66
+ footerLine?: string,
67
+ ): string {
68
+ if (!block || content.includes(SEMANTIC_LAYER_BEGIN)) return content;
69
+ const lines = content.replace(/\r\n/g, "\n").split("\n");
70
+ const blockLines = block.split("\n");
71
+ const footerIdx = footerLine
72
+ ? lines.findIndex((line) => line.trim() === footerLine)
73
+ : -1;
74
+ if (footerIdx === -1) {
75
+ while (lines.length > 0 && lines[lines.length - 1]!.trim() === "") lines.pop();
76
+ return [...lines, "", ...blockLines, ""].join("\n");
77
+ }
78
+ const lead = footerIdx > 0 && lines[footerIdx - 1]!.trim() !== "" ? [""] : [];
79
+ lines.splice(footerIdx, 0, ...lead, ...blockLines, "");
80
+ return lines.join("\n");
81
+ }
82
+
83
+ /**
84
+ * Inject or refresh the marker-guarded semantic-layer region in file content.
85
+ * `block` is the marker-wrapped render ({@link semanticLayerLines} joined).
86
+ *
87
+ * - Every complete `forge:begin semantic-layer` … `forge:end semantic-layer`
88
+ * region is replaced with the current block (content refresh is free).
89
+ * - When no region exists, the first bare `forge:semantic-layer` sentinel line
90
+ * expands into a full region.
91
+ * - Files carrying neither anchor return unchanged — injection is opt-in only.
92
+ *
93
+ * Matching normalizes CRLF to LF (the DNA-58 convention shared with
94
+ * editable-region.ts); marker lines match on trimmed equality.
95
+ */
96
+ export function injectSemanticLayerBlock(content: string, block: string): SemanticLayerInjection {
97
+ const text = content.replace(/\r\n/g, "\n");
98
+ const lines = text.split("\n");
99
+
100
+ // Pass 1: refresh complete begin..end regions.
101
+ const out: string[] = [];
102
+ let changed = false;
103
+ let refreshed = false;
104
+ let i = 0;
105
+ while (i < lines.length) {
106
+ if (lines[i]!.trim() === SEMANTIC_LAYER_BEGIN) {
107
+ let j = i + 1;
108
+ while (j < lines.length && lines[j]!.trim() !== SEMANTIC_LAYER_END) j++;
109
+ if (j < lines.length) {
110
+ if (lines.slice(i, j + 1).join("\n") !== block) changed = true;
111
+ out.push(block);
112
+ refreshed = true;
113
+ i = j + 1;
114
+ continue;
115
+ }
116
+ // Unbalanced begin (no matching end) — fall through, leave the line alone.
117
+ }
118
+ out.push(lines[i]!);
119
+ i++;
120
+ }
121
+ if (refreshed) {
122
+ return { content: out.join("\n"), changed, region: "refreshed" };
123
+ }
124
+
125
+ // Pass 2: no region — expand the first bare opt-in sentinel.
126
+ const idx = out.findIndex((line) => line.trim() === SEMANTIC_LAYER_OPT_IN);
127
+ if (idx === -1) {
128
+ return { content: text, changed: false, region: "none" };
129
+ }
130
+ out[idx] = block;
131
+ return { content: out.join("\n"), changed: true, region: "expanded" };
132
+ }
@@ -8,13 +8,11 @@ Checks for forge.yaml, AGENTS.md, PREFERENCES.md, .agents/skills/, docs/rfcs/,
8
8
  </non-goals>
9
9
  </MODULE_CONTRACT>
10
10
  <CHANGE_SUMMARY>
11
- <item>RFC-1097: sweep — packages/forge + services clean
12
-
13
- Sweep batch 2: real KEY_DECISIONS on 10 files, expanded purposes (CONTRACT-02/PURPOSE-02), headers on mission/index + gen-upstreams, sanitizeItemText in summary.record (literal Compass tags corrupted history), excludedPaths for wrangler types, test-fixtures testPattern. forge+services now 0 diagnostics under --mode error.</item>
14
11
  <item>RFC-1224: preserve operator forge.yaml content on upgrade, promote adrImplementStamp binding</item>
15
12
  <item>RFC-1226: skills-unmanaged check — warn on SKILL.md-bearing dirs without .forge-managed marker</item>
16
13
  <item>RFC-1249: wire werkstatt.commands.validate into packages.check + retire CMD-OUTPUT debt</item>
17
14
  <item>forge-version-sync check — warns when the installed @warpgogol/forge version diverges from forge.yaml syncedVersion (pnpm up drifts it silently); nested wsTypes resolution moved to shared resolveWorkspaceTypes.</item>
15
+ <item>agents.generate remediation counts marker-guarded semantic-layer injections as fixes — a hand-written file that only gained the region reports fixed instead of skipped (consumer field report follow-up to RFC-1253).</item>
18
16
  <history>RFC-0391, RFC-0393, RFC-0524, RFC-0539, RFC-0540, RFC-0611, RFC-0640, RFC-0660, RFC-0661, RFC-0663, RFC-0664, RFC-0675, RFC-0704, RFC-0941, RFC-1097, RFC-1224</history>
19
17
  </CHANGE_SUMMARY>
20
18
  */
@@ -1708,8 +1706,8 @@ async function applyDoctorRemediation(
1708
1706
  const res = await generateNestedAgentsMd(workspaceRoot, config, dryRun, workspaceTypes, io);
1709
1707
  return {
1710
1708
  check: check.name,
1711
- action: res.generated.length > 0 ? "fixed" : "skipped",
1712
- detail: `${res.generated.length} file(s) ${dryRun ? "would be " : ""}regenerated, ${res.skipped.length} skipped`,
1709
+ action: res.generated.length > 0 || res.injected.length > 0 ? "fixed" : "skipped",
1710
+ detail: `${res.generated.length} file(s) ${dryRun ? "would be " : ""}regenerated, ${res.skipped.length} skipped${res.injected.length > 0 ? `, ${res.injected.length} semantic-layer injected` : ""}`,
1713
1711
  };
1714
1712
  } catch (err) {
1715
1713
  return { check: check.name, action: "failed", detail: (err as Error).message };