@warpgogol/forge 6.3.2 → 6.3.5

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 (49) hide show
  1. package/CHANGELOG.md +21 -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/os/spec/spec-schema.d.ts +3 -0
  6. package/dist/os/spec/spec-schema.d.ts.map +1 -1
  7. package/dist/os/spec/spec-schema.js +1 -0
  8. package/dist/os/spec/spec-schema.js.map +1 -1
  9. package/dist/os/spec/spec-validate.d.ts.map +1 -1
  10. package/dist/os/spec/spec-validate.js +17 -0
  11. package/dist/os/spec/spec-validate.js.map +1 -1
  12. package/dist/os/spec/spec.module.d.ts.map +1 -1
  13. package/dist/os/spec/spec.module.js +4 -1
  14. package/dist/os/spec/spec.module.js.map +1 -1
  15. package/dist/src/onboarding/agents-generate.d.ts +2 -0
  16. package/dist/src/onboarding/agents-generate.d.ts.map +1 -1
  17. package/dist/src/onboarding/agents-generate.js +33 -14
  18. package/dist/src/onboarding/agents-generate.js.map +1 -1
  19. package/dist/src/onboarding/compass-docs/semantic-layer-block.d.ts +40 -0
  20. package/dist/src/onboarding/compass-docs/semantic-layer-block.d.ts.map +1 -0
  21. package/dist/src/onboarding/compass-docs/semantic-layer-block.js +116 -0
  22. package/dist/src/onboarding/compass-docs/semantic-layer-block.js.map +1 -0
  23. package/dist/src/onboarding/doctor.d.ts.map +1 -1
  24. package/dist/src/onboarding/doctor.js +3 -5
  25. package/dist/src/onboarding/doctor.js.map +1 -1
  26. package/dist/src/onboarding/nested-agents-generate.d.ts +2 -0
  27. package/dist/src/onboarding/nested-agents-generate.d.ts.map +1 -1
  28. package/dist/src/onboarding/nested-agents-generate.js +31 -6
  29. package/dist/src/onboarding/nested-agents-generate.js.map +1 -1
  30. package/dist/src/onboarding/nested-agents-templates.d.ts +6 -1
  31. package/dist/src/onboarding/nested-agents-templates.d.ts.map +1 -1
  32. package/dist/src/onboarding/nested-agents-templates.js +19 -4
  33. package/dist/src/onboarding/nested-agents-templates.js.map +1 -1
  34. package/docs/reference/compass-docs.md +57 -39
  35. package/os/compass/handlers/compass-docs-scaffold.ts +26 -3
  36. package/os/spec/spec-schema.ts +4 -0
  37. package/os/spec/spec-validate.test.ts +62 -13
  38. package/os/spec/spec-validate.ts +17 -0
  39. package/os/spec/spec.module.ts +4 -1
  40. package/package.json +1 -1
  41. package/src/onboarding/agents-generate.ts +36 -18
  42. package/src/onboarding/compass-docs/semantic-layer-block.test.ts +137 -0
  43. package/src/onboarding/compass-docs/semantic-layer-block.ts +132 -0
  44. package/src/onboarding/doctor.ts +3 -5
  45. package/src/onboarding/nested-agents-generate.ts +40 -6
  46. package/src/onboarding/nested-agents-templates.ts +24 -4
  47. package/src/tests/agents-generate.test.ts +128 -0
  48. package/src/tests/compass-docs-scaffold.test.ts +67 -0
  49. package/src/tests/fixtures/agents-generate-business-before.txt +4 -0
@@ -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 };
@@ -10,7 +10,6 @@ runAgentsGenerate, runUpgrade, and runDoctor (staleness check via dryRun).</purp
10
10
  </non-goals>
11
11
  </MODULE_CONTRACT>
12
12
  <CHANGE_SUMMARY>
13
- <item>RFC-0640: accept optional workspaceTypes from profile and pass to discoverWorkspaces for profile-driven detection.</item>
14
13
  <item>RFC-0643: return workspaceTypeMap for per-file workspace type metadata in details field.</item>
15
14
  <item>RFC-0643: use selectNestedTemplate for profile-driven nested templates with terminology substitution.</item>
16
15
  <item>RFC-1097: step 6 — compass.migrate codemod run
@@ -19,7 +18,8 @@ Mechanical v1 to v2 header migration across the workspace: 942 files rewritten
19
18
  <item>RFC-1097: sweep — werkstatt-engine clean
20
19
 
21
20
  Sweep batch 4: 73 Compass headers on headerless engine files (certification, component-runtime, isolation, evolution, testing), real KEY_DECISIONS on 75 files (kernel, cache, dht, swim, gitmesh, runtime), ~80 purpose expansions (CONTRACT-02/PURPOSE-02), non-goals on 13 CONTRACT-03 files, CS-07 history literal fix repo-wide (253 files). Policy: .template.ts/.template.astro excludedPaths. werkstatt-engine now 0 diagnostics.</item>
22
- <history>RFC-0611</history>
21
+ <item>Result gains injected[]: hand-written nested guides carrying the forge:semantic-layer sentinel or a pasted marked region get the read-first block refreshed in place; ensureSemanticLayerBlock guards renders that bypass the fallback template, e.g. profile-authored nested templates (consumer field report follow-up to RFC-1253).</item>
22
+ <history>RFC-0611, RFC-0640</history>
23
23
  </CHANGE_SUMMARY>
24
24
  */
25
25
 
@@ -34,7 +34,9 @@ import {
34
34
  } from "../utils/index.ts";
35
35
  import { resolveIo } from "../utils/io.ts";
36
36
  import { discoverWorkspaces } from "./workspace-discovery.ts";
37
- import { buildNestedAgentsMd, selectNestedTemplate, type PackageInfo } from "./nested-agents-templates.ts";
37
+ import { buildNestedAgentsMd, NESTED_AGENTS_FOOTER, selectNestedTemplate, type PackageInfo } from "./nested-agents-templates.ts";
38
+ import { ensureSemanticLayerBlock, injectSemanticLayerBlock, semanticLayerLines } from "./compass-docs/semantic-layer-block.ts";
39
+ import { resolveBinding } from "../config/forge-config.ts";
38
40
  import type { ForgeConfig } from "../config/forge-config.ts";
39
41
  import type { ProfileWorkspaceType } from "../profiles/profile-schema.ts";
40
42
  import type { StackProfile } from "../profiles/stack-profile.ts";
@@ -46,6 +48,8 @@ export interface NestedGenerateResult {
46
48
  skipped: string[];
47
49
  /** RFC-1153: files merged with a carried custom tail below the boundary. */
48
50
  preserved: string[];
51
+ /** Hand-written files that accepted the marker-guarded semantic-layer block. */
52
+ injected: string[];
49
53
  renderedFiles: { [relPath: string]: string };
50
54
  workspaceTypeMap?: { [relPath: string]: string };
51
55
  }
@@ -75,6 +79,7 @@ export async function generateNestedAgentsMd(
75
79
  const generated: string[] = [];
76
80
  const skipped: string[] = [];
77
81
  const preserved: string[] = [];
82
+ const injected: string[] = [];
78
83
  const renderedFiles: { [relPath: string]: string } = {};
79
84
  const fio = resolveIo(io);
80
85
  const workspaceTypeMap: { [relPath: string]: string } = {};
@@ -83,6 +88,14 @@ export async function generateNestedAgentsMd(
83
88
  const profile = config.profile as StackProfile | undefined;
84
89
  const terminology = resolveAllTerminology(config, profile);
85
90
 
91
+ // RFC-1253: marker-wrapped read-first block for hand-written opt-in injection.
92
+ const compassDocs = resolveBinding(config, "paths.compassDocs");
93
+ const semanticLayerDocs = (Array.isArray(compassDocs) ? compassDocs : []).filter(
94
+ (d): d is string => typeof d === "string",
95
+ );
96
+ const semanticLayerBlock =
97
+ semanticLayerDocs.length > 0 ? semanticLayerLines(semanticLayerDocs).join("\n") : "";
98
+
86
99
  for (const ws of workspaces) {
87
100
  const agentsMdPath = path.join(workspaceRoot, ws.path, "AGENTS.md");
88
101
  const packageInfo = readPackageInfo(workspaceRoot, ws.path);
@@ -90,7 +103,11 @@ export async function generateNestedAgentsMd(
90
103
 
91
104
  // RFC-0643: use profile-driven template when available
92
105
  const wsType = workspaceTypes?.find((wt) => wt.id === ws.type);
93
- const content = selectNestedTemplate(wsType, profile, terminology, fallback);
106
+ const content = ensureSemanticLayerBlock(
107
+ selectNestedTemplate(wsType, profile, terminology, fallback),
108
+ semanticLayerBlock,
109
+ NESTED_AGENTS_FOOTER,
110
+ );
94
111
  const relPath = path.join(ws.path, "AGENTS.md");
95
112
 
96
113
  if (dryRun) {
@@ -99,7 +116,24 @@ export async function generateNestedAgentsMd(
99
116
  }
100
117
 
101
118
  if (ws.hasAgentsMd && !ws.isGenerated) {
102
- skipped.push(`${relPath} (hand-written)`);
119
+ // Marker-guarded opt-in: a hand-written guide carrying the
120
+ // forge:semantic-layer sentinel (or a pasted marked region) gets the
121
+ // block refreshed — surrounding prose is never touched.
122
+ let injectedHit = false;
123
+ if (semanticLayerBlock) {
124
+ try {
125
+ const existing = await fio.readFile(agentsMdPath);
126
+ const injection = injectSemanticLayerBlock(existing, semanticLayerBlock);
127
+ if (injection.changed) {
128
+ await writeFileIfChanged(agentsMdPath, injection.content, fio);
129
+ injected.push(relPath);
130
+ injectedHit = true;
131
+ }
132
+ } catch {
133
+ // Unreadable — leave the hand-written file alone.
134
+ }
135
+ }
136
+ skipped.push(`${relPath} (hand-written${injectedHit ? " — semantic-layer injected" : ""})`);
103
137
  continue;
104
138
  }
105
139
 
@@ -136,7 +170,7 @@ export async function generateNestedAgentsMd(
136
170
  }
137
171
  }
138
172
 
139
- return { generated, skipped, preserved, renderedFiles, workspaceTypeMap };
173
+ return { generated, skipped, preserved, injected, renderedFiles, workspaceTypeMap };
140
174
  }
141
175
 
142
176
  export { discoverWorkspaces, type WorkspaceDir, type WorkspaceType } from "./workspace-discovery.ts";
@@ -8,7 +8,6 @@ content-rich AGENTS.md for a workspace from its package.json metadata. No I/O.</
8
8
  </non-goals>
9
9
  </MODULE_CONTRACT>
10
10
  <CHANGE_SUMMARY>
11
- <item>RFC-0611: initial minimal stub template for app, package, service workspaces.</item>
12
11
  <item>RFC-0643: selectNestedTemplate() for profile-driven template selection with path traversal guard.</item>
13
12
  <item>RFC-1097: step 6 — compass.migrate codemod run
14
13
 
@@ -17,12 +16,15 @@ Mechanical v1 to v2 header migration across the workspace: 942 files rewritten
17
16
 
18
17
  Sweep batch 4: 73 Compass headers on headerless engine files (certification, component-runtime, isolation, evolution, testing), real KEY_DECISIONS on 75 files (kernel, cache, dht, swim, gitmesh, runtime), ~80 purpose expansions (CONTRACT-02/PURPOSE-02), non-goals on 13 CONTRACT-03 files, CS-07 history literal fix repo-wide (253 files). Policy: .template.ts/.template.astro excludedPaths. werkstatt-engine now 0 diagnostics.</item>
19
18
  <item>Drop the blank line pushed after the generated header — the header ends in a newline so the extra line rendered two blank lines that prettier collapsed, ping-ponging doctor's stale check.</item>
19
+ <item>Emit the marker-wrapped semantic-layer read-first block ahead of the footer when paths.compassDocs is bound; footer literal exported as NESTED_AGENTS_FOOTER (consumer field report follow-up to RFC-1253).</item>
20
+ <history>RFC-0611</history>
20
21
  </CHANGE_SUMMARY>
21
22
  */
22
23
 
23
24
  import { alignMarkdownTable, buildGeneratedHeader } from "../utils/index.ts";
24
- import { resolveForgePackageRoot } from "../config/forge-config.ts";
25
+ import { resolveBinding, resolveForgePackageRoot } from "../config/forge-config.ts";
25
26
  import type { ForgeConfig } from "../config/forge-config.ts";
27
+ import { semanticLayerLines } from "./compass-docs/semantic-layer-block.ts";
26
28
  import type { WorkspaceDir, WorkspaceType } from "./workspace-discovery.ts";
27
29
  import type { ProfileWorkspaceType } from "../profiles/profile-schema.ts";
28
30
  import type { StackProfile } from "../profiles/stack-profile.ts";
@@ -54,6 +56,13 @@ const TYPE_LABEL: Record<WorkspaceType, string> = {
54
56
  service: "Service",
55
57
  };
56
58
 
59
+ /**
60
+ * Canonical nested-guide footer — the last substantive line of every render.
61
+ * Legacy marker-less files merge against this boundary; it must stay last.
62
+ */
63
+ export const NESTED_AGENTS_FOOTER =
64
+ "See the root `AGENTS.md` for project-wide rules, skills, and capabilities.";
65
+
57
66
  interface EntryPoint {
58
67
  name: string;
59
68
  module: string;
@@ -188,7 +197,7 @@ function substituteNestedTemplate(
188
197
 
189
198
  export function buildNestedAgentsMd(
190
199
  workspace: WorkspaceDir,
191
- _config: ForgeConfig,
200
+ config: ForgeConfig,
192
201
  packageInfo?: PackageInfo,
193
202
  ): string {
194
203
  const header = buildGeneratedHeader({
@@ -241,7 +250,18 @@ export function buildNestedAgentsMd(
241
250
  lines.push(...buildScriptsTable(packageInfo?.scripts));
242
251
  lines.push(...buildDependenciesSection(packageInfo?.dependencies));
243
252
 
244
- lines.push("See the root `AGENTS.md` for project-wide rules, skills, and capabilities.");
253
+ // Compass corpus read-first block (RFC-1253): emitted ahead of the footer —
254
+ // the footer line is the canonical merge boundary for legacy marker-less
255
+ // files and must stay the render's last non-empty line.
256
+ const compassDocs = resolveBinding(config, "paths.compassDocs");
257
+ const semanticLayerDocs = (Array.isArray(compassDocs) ? compassDocs : []).filter(
258
+ (d): d is string => typeof d === "string",
259
+ );
260
+ if (semanticLayerDocs.length > 0) {
261
+ lines.push(...semanticLayerLines(semanticLayerDocs), "");
262
+ }
263
+
264
+ lines.push(NESTED_AGENTS_FOOTER);
245
265
  lines.push("");
246
266
 
247
267
  return lines.join("\n");
@@ -532,3 +532,131 @@ test("agents-generate omits the read-first block when compassDocs is absent (RFC
532
532
  const agentsMd = await readFile(join(tempDir, "AGENTS.md"), "utf8");
533
533
  expect(agentsMd).not.toContain("## Semantic layer — read first");
534
534
  });
535
+
536
+ // Consumer field report: the block must reach every surface an agent reads —
537
+ // nested generated guides and opt-in hand-written files, not only generated roots.
538
+
539
+ test("agents-generate emits the read-first block into nested workspace guides", async () => {
540
+ await makeForgeYaml(tempDir);
541
+ await mkdir(join(tempDir, "packages", "my-pkg"), { recursive: true });
542
+ await writeFile(
543
+ join(tempDir, "packages", "my-pkg", "package.json"),
544
+ JSON.stringify({ name: "@test/my-pkg" }),
545
+ );
546
+
547
+ const result = await runAgentsGenerate({ argv: [], flags: {} }, makeContext(tempDir));
548
+ expect(result.exitCode).toBe(0);
549
+
550
+ const nested = await readFile(join(tempDir, "packages", "my-pkg", "AGENTS.md"), "utf8");
551
+ expect(nested).toContain("<!-- forge:begin semantic-layer -->");
552
+ expect(nested).toContain("## Semantic layer — read first");
553
+ expect(nested).toContain("`docs/requirements.xml`");
554
+ expect(nested).toContain("<!-- forge:end semantic-layer -->");
555
+ // the footer stays the last substantive line — it is the merge boundary
556
+ // for legacy marker-less files and must not move below the block
557
+ expect(nested.indexOf("## Semantic layer — read first")).toBeLessThan(
558
+ nested.indexOf("See the root `AGENTS.md`"),
559
+ );
560
+ });
561
+
562
+ test("agents-generate expands the forge:semantic-layer sentinel in a hand-written root", async () => {
563
+ await makeForgeYaml(tempDir);
564
+ await writeFile(
565
+ join(tempDir, "AGENTS.md"),
566
+ "# Hand-written\n\nCustom intro.\n\n<!-- forge:semantic-layer -->\n\nCustom tail.\n",
567
+ "utf8",
568
+ );
569
+
570
+ const result = await runAgentsGenerate({ argv: [], flags: {} }, makeContext(tempDir));
571
+ expect(result.exitCode).toBe(0);
572
+ expect(result.data?.rootSkipped).toBe(true);
573
+ expect(result.data?.injected).toContain("AGENTS.md");
574
+
575
+ const agentsMd = await readFile(join(tempDir, "AGENTS.md"), "utf8");
576
+ expect(agentsMd).toContain("<!-- forge:begin semantic-layer -->");
577
+ expect(agentsMd).toContain("## Semantic layer — read first");
578
+ expect(agentsMd).toContain("`docs/requirements.xml`");
579
+ expect(agentsMd).toContain("<!-- forge:end semantic-layer -->");
580
+ expect(agentsMd).toContain("Custom intro.");
581
+ expect(agentsMd).toContain("Custom tail.");
582
+ expect(agentsMd).not.toContain("<!-- forge:semantic-layer -->");
583
+ expect(agentsMd.match(/## Semantic layer — read first/g)).toHaveLength(1);
584
+ });
585
+
586
+ test("agents-generate refreshes a pasted semantic-layer region in a hand-written root", async () => {
587
+ await makeForgeYaml(tempDir);
588
+ const staleRegion = [
589
+ "<!-- forge:begin semantic-layer -->",
590
+ "",
591
+ "## Semantic layer — read first",
592
+ "",
593
+ "STALE",
594
+ "",
595
+ "<!-- forge:end semantic-layer -->",
596
+ ].join("\n");
597
+ await writeFile(join(tempDir, "AGENTS.md"), `# Hand-written\n\n${staleRegion}\n`, "utf8");
598
+
599
+ const result = await runAgentsGenerate({ argv: [], flags: {} }, makeContext(tempDir));
600
+ const agentsMd = await readFile(join(tempDir, "AGENTS.md"), "utf8");
601
+ expect(agentsMd).not.toContain("STALE");
602
+ expect(agentsMd).toContain("`docs/requirements.xml`");
603
+ expect(result.data?.injected).toContain("AGENTS.md");
604
+
605
+ // idempotent — a current region reports no further injection
606
+ const second = await runAgentsGenerate({ argv: [], flags: {} }, makeContext(tempDir));
607
+ expect(second.data?.injected).toEqual([]);
608
+ });
609
+
610
+ test("agents-generate leaves a hand-written root without the sentinel untouched", async () => {
611
+ await makeForgeYaml(tempDir);
612
+ const original = "# Hand-written\nNo marker, no sentinel — fully authored.\n";
613
+ await writeFile(join(tempDir, "AGENTS.md"), original, "utf8");
614
+
615
+ const result = await runAgentsGenerate({ argv: [], flags: {} }, makeContext(tempDir));
616
+ expect(result.exitCode).toBe(0);
617
+ expect(result.data?.injected).toEqual([]);
618
+
619
+ const agentsMd = await readFile(join(tempDir, "AGENTS.md"), "utf8");
620
+ expect(agentsMd).toBe(original);
621
+ });
622
+
623
+ test("agents-generate expands the sentinel in a hand-written nested guide", async () => {
624
+ await makeForgeYaml(tempDir);
625
+ await mkdir(join(tempDir, "packages", "my-pkg"), { recursive: true });
626
+ await writeFile(
627
+ join(tempDir, "packages", "my-pkg", "package.json"),
628
+ JSON.stringify({ name: "@test/my-pkg" }),
629
+ );
630
+ await writeFile(
631
+ join(tempDir, "packages", "my-pkg", "AGENTS.md"),
632
+ "# Custom\n\n<!-- forge:semantic-layer -->\n",
633
+ "utf8",
634
+ );
635
+
636
+ const result = await runAgentsGenerate({ argv: [], flags: {} }, makeContext(tempDir));
637
+ expect(result.data?.injected).toContain(join("packages", "my-pkg", "AGENTS.md"));
638
+
639
+ const nested = await readFile(join(tempDir, "packages", "my-pkg", "AGENTS.md"), "utf8");
640
+ expect(nested).toContain("## Semantic layer — read first");
641
+ expect(nested).toContain("# Custom");
642
+ });
643
+
644
+ test("agents-generate emits no read-first block in nested guides when compassDocs is absent", async () => {
645
+ await makeForgeYaml(tempDir);
646
+ const yaml = (await readFile(join(tempDir, "forge.yaml"), "utf8")).replace(
647
+ " compassDocs: [docs/requirements.xml]\n",
648
+ "",
649
+ );
650
+ await writeFile(join(tempDir, "forge.yaml"), yaml, "utf8");
651
+ await mkdir(join(tempDir, "packages", "my-pkg"), { recursive: true });
652
+ await writeFile(
653
+ join(tempDir, "packages", "my-pkg", "package.json"),
654
+ JSON.stringify({ name: "@test/my-pkg" }),
655
+ );
656
+
657
+ const result = await runAgentsGenerate({ argv: [], flags: {} }, makeContext(tempDir));
658
+ expect(result.exitCode).toBe(0);
659
+
660
+ const nested = await readFile(join(tempDir, "packages", "my-pkg", "AGENTS.md"), "utf8");
661
+ expect(nested).not.toContain("## Semantic layer — read first");
662
+ });