forgedock 1.55.1 → 1.57.0

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 (133) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +58 -10
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +3 -1
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +88 -17
  14. package/bin/lean/conformance.test.mjs +98 -3
  15. package/bin/lean/decisions.mjs +86 -1
  16. package/bin/lean/decisions.test.mjs +21 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +12 -2
  32. package/bin/lean/issuewatch-parity.test.mjs +26 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +80 -25
  39. package/bin/lean/lean.test.mjs +149 -3
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +125 -0
  44. package/bin/lean/orphan-pr.test.mjs +145 -0
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +25 -0
  52. package/bin/lean/release-config.mjs +158 -0
  53. package/bin/lean/release-config.test.mjs +109 -0
  54. package/bin/lean/release-control.mjs +148 -0
  55. package/bin/lean/release-control.test.mjs +143 -0
  56. package/bin/lean/release-fence.mjs +50 -0
  57. package/bin/lean/release-fence.test.mjs +105 -0
  58. package/bin/lean/release-flakes.mjs +139 -0
  59. package/bin/lean/release-flakes.test.mjs +116 -0
  60. package/bin/lean/release-ledger.mjs +160 -0
  61. package/bin/lean/release-ledger.test.mjs +226 -0
  62. package/bin/lean/release-minutes.mjs +92 -0
  63. package/bin/lean/release-minutes.test.mjs +99 -0
  64. package/bin/lean/release-nightly.mjs +75 -0
  65. package/bin/lean/release-nightly.test.mjs +48 -0
  66. package/bin/lean/release-postmerge.mjs +45 -21
  67. package/bin/lean/release-review.e2e.test.mjs +1 -0
  68. package/bin/lean/release-review.mjs +54 -7
  69. package/bin/lean/release-review.test.mjs +76 -7
  70. package/bin/lean/release-unitmap.mjs +35 -0
  71. package/bin/lean/release-unitmap.test.mjs +41 -0
  72. package/bin/lean/release.mjs +177 -19
  73. package/bin/lean/release.test.mjs +80 -16
  74. package/bin/lean/render.mjs +3 -1
  75. package/bin/lean/run-issue-placement.test.mjs +82 -0
  76. package/bin/lean/sandbox-remote.mjs +16 -0
  77. package/bin/lean/schedd.mjs +1 -1
  78. package/bin/lean/seam.mjs +115 -0
  79. package/bin/lean/seam.test.mjs +118 -0
  80. package/bin/lean/selftest-journey.mjs +40 -2
  81. package/bin/lean/selftest-journey.test.mjs +43 -3
  82. package/bin/lean/statuscomment.mjs +168 -0
  83. package/bin/lean/statuscomment.test.mjs +133 -0
  84. package/bin/lean/ui-quality.mjs +57 -0
  85. package/bin/lean/ui-quality.test.mjs +55 -0
  86. package/bin/lean/visual-gate.test.mjs +63 -0
  87. package/bin/pool/agent.mjs +16 -2
  88. package/bin/pool/router.mjs +5 -1
  89. package/bin/review-staging.mjs +8 -5
  90. package/bin/stats/card.mjs +117 -0
  91. package/bin/stats/card.test.mjs +109 -0
  92. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  93. package/bin/stats/depth.mjs +1 -1
  94. package/bin/stats/gh-retry.test.mjs +152 -0
  95. package/bin/stats/github-source.mjs +147 -14
  96. package/bin/stats/index.mjs +35 -2
  97. package/bin/stats/stats.test.mjs +31 -3
  98. package/bin/vendor/js-yaml/LICENSE +21 -0
  99. package/bin/vendor/js-yaml/PIN.md +7 -0
  100. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  101. package/commands/design-render-critique-loop.md +2 -0
  102. package/commands/design.md +2 -0
  103. package/commands/incident-response.md +4 -0
  104. package/commands/issue.md +1 -1
  105. package/commands/milestone.md +1 -1
  106. package/commands/pipeline-status.md +13 -0
  107. package/commands/review-pr-agents/frontend.md +1 -0
  108. package/commands/review-pr-staging.md +5 -0
  109. package/docs/CONFIG.md +75 -1
  110. package/docs/ISSUE-WATCH.md +7 -0
  111. package/docs/OUTCOME-CODES.md +1 -0
  112. package/docs/STATS.md +10 -0
  113. package/docs/design/visual-gate.md +25 -0
  114. package/docs/eval/adversarial-bench.md +2 -2
  115. package/docs/eval/corpus/adversarial-v1.json +3 -3
  116. package/docs/site/start-a-new-project.md +7 -0
  117. package/docs/spec/forge-protocol-v1.md +31 -0
  118. package/package.json +1 -1
  119. package/pool/README.md +2 -0
  120. package/scripts/acceptance-red-green.sh +15 -1
  121. package/scripts/acceptance-red-green.test.sh +12 -0
  122. package/scripts/bench-adversarial.mjs +4 -0
  123. package/scripts/bench-lightlane.mjs +4 -1
  124. package/scripts/bootstrap-create.mjs +8 -2
  125. package/scripts/ci-local.test.sh +3 -3
  126. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  127. package/scripts/plan-validate-live.mjs +9 -6
  128. package/scripts/review-prepare.sh +7 -1
  129. package/scripts/review-roster.sh +5 -2
  130. package/scripts/review-roster.test.sh +9 -0
  131. package/scripts/visual-gate.mjs +64 -0
  132. package/templates/bootstrap/technical-spike.md +17 -0
  133. package/templates/contracts/seam-check.mjs +236 -0
@@ -0,0 +1,181 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5338: architecture and interface contracts bound into the decision register. One module for the four engine seams:
5
+ * - validation: a spike or feature epic with two or more slices needs an `## Interfaces` section (rationale line plus at
6
+ * least one boundary row with anchors); `checkInterfaces` is the pure check, `forgedock interfaces check` the gate
7
+ * (`/milestone` and `/issue` run it before creating an epic, `bootstrap-create` before creating a backlog);
8
+ * - registration: `seedDecisions` writes each Interfaces row and each anchored architecture choice into the register
9
+ * (FORGE:DECISION comment on the spike/epic issue + the local index), once per id; the lane contract then carries
10
+ * them as preserve rows (decisions.mjs withDecisionRows) and conformance fails a change under their anchors that
11
+ * neither reports the row intact nor supersedes it (conformance.mjs interfaceDecisionFailures);
12
+ * - contract tests: `writeContracts` generates one seam contract test per row with a machine form (seam.mjs);
13
+ * - consumers: `consumerNotices` / `notifyConsumers` reopen (or notify) the consumer issues, or file one issue per
14
+ * named consumer, when a lane's `supersedes` decision lands.
15
+ * Pure except the injected gh/fs; no LLM.
16
+ */
17
+ import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
18
+ import { dirname, join } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { interfaceDecisions, interfaceRows, parseDecisionComment, renderDecision, readDecisionIndex, writeDecisionIndex } from "./decisions.mjs";
21
+ import { renderSeamTest } from "./seam.mjs";
22
+
23
+ export const INTERFACES_SECTION = "Interfaces";
24
+ export const INTERFACE_CHANGED_MARKER = "FORGE:INTERFACE_CHANGED";
25
+ const SEAM_CHECK = fileURLToPath(new URL("../../templates/contracts/seam-check.mjs", import.meta.url));
26
+
27
+ const h2 = (text) => {
28
+ const secs = [];
29
+ let fence = null;
30
+ for (const line of String(text ?? "").replace(/\r\n/g, "\n").split("\n")) {
31
+ const f = /^[ \t]*(`{3,}|~{3,})/.exec(line);
32
+ if (f) { fence = fence ? (f[1][0] === fence ? null : fence) : f[1][0]; if (secs.length) secs.at(-1).lines.push(line); continue; }
33
+ const h = fence ? null : /^##(?!#)[ \t]+(.+?)[ \t]*$/.exec(line);
34
+ if (h) secs.push({ heading: h[1], lines: [] }); else if (secs.length) secs.at(-1).lines.push(line);
35
+ }
36
+ return secs;
37
+ };
38
+
39
+ const SLICE_HEADING = /^(slices?|children|sub-?issues|waves?|work items|issues|milestone plan|plan)\b/i;
40
+ const LIST_ITEM = /^\s*(?:[-*+]\s+(?:\[[ xX]\]\s+)?|\d+[.)]\s+)\S/;
41
+
42
+ /** Slices of a spike (numbered items of its Milestone plan) or of an epic (list items of its Slices/Children/... section). */
43
+ export function sliceCount(text, kind = "auto") {
44
+ const secs = h2(text), plan = secs.find((x) => /^milestone plan/i.test(x.heading));
45
+ if (kind === "spike" || (kind === "auto" && plan)) return (plan?.lines.join("\n").match(/(?:^|\s)\d+\.\s/g) ?? []).length;
46
+ const listed = secs.filter((x) => SLICE_HEADING.test(x.heading)).flatMap((x) => x.lines.filter((l) => LIST_ITEM.test(l)));
47
+ if (listed.length) return listed.length;
48
+ return String(text ?? "").split("\n").filter((l) => /^\s*[-*]\s+\[[ xX]\]\s+#\d+/.test(l)).length;
49
+ }
50
+
51
+ /**
52
+ * Pure check of the Interfaces section. `required` once the body has two or more slices; then the section, its
53
+ * `**Rationale**:` line are needed, and for an epic (the spike template ships a placeholder row) at least one boundary row
54
+ * with anchors. `kind` is "spike", "epic" or "auto" (a body with a Milestone plan section is a spike).
55
+ * Also lists rows whose signature has a machine form but whose Anchors cell declares no provider/consumer sides
56
+ * (`unchecked`: no contract test can be generated for them).
57
+ */
58
+ export function checkInterfaces(text, { kind = "auto" } = {}) {
59
+ const slices = sliceCount(text, kind), required = slices >= 2;
60
+ const spike = kind === "spike" || (kind === "auto" && h2(text).some((x) => /^milestone plan/i.test(x.heading)));
61
+ const sec = h2(text).find((x) => x.heading.toLowerCase().startsWith(INTERFACES_SECTION.toLowerCase()));
62
+ const rows = interfaceRows(text);
63
+ const problems = [];
64
+ if (required && !sec) problems.push(`no \`## ${INTERFACES_SECTION}\` section: ${slices} slices need one row per boundary (signature or schema, auth mode, owner issue, anchors)`);
65
+ else if (required && !sec.lines.some((l) => /\*\*Rationale\*\*:/.test(l))) problems.push(`\`## ${INTERFACES_SECTION}\` has no **Rationale**: line`);
66
+ else if (required && !spike && !rows.length) problems.push(`\`## ${INTERFACES_SECTION}\` has no boundary row with an anchor (a row of the template's {placeholders} does not count)`);
67
+ const unchecked = rows.filter((r) => !r.seam && /^(?:(?:GET|POST|PUT|PATCH|DELETE)\s+\/|[\w.$]+\s*\(|(?:queue|topic|message|payload|event)\s|\{)/i.test(String(r.signature).replace(/`/g, "").trim())).map((r) => r.boundary);
68
+ return { ok: problems.length === 0, required, slices, hasSection: Boolean(sec), rows: rows.length, problems, unchecked };
69
+ }
70
+
71
+ /** The records of `text` not yet posted on the issue (`comments` are its comment bodies): once per id. */
72
+ export function freshDecisions({ text, issue, comments = [] }) {
73
+ const posted = new Set(comments.map((b) => parseDecisionComment(b, { issue })?.id).filter(Boolean));
74
+ return interfaceDecisions(text, { issue }).filter((d) => !posted.has(d.id));
75
+ }
76
+
77
+ /** The comment body (marker line first) that registers one record. */
78
+ export const decisionComment = (rec) => { const m = renderDecision(rec); return `<!-- ${m.marker} -->\n${m.body}`; };
79
+
80
+ /** Synchronous registration (bootstrap-create): posts each fresh record via `post(body)`, then updates the index. Returns the records posted. */
81
+ export function seedDecisions({ text, issue, repo, comments = [], post, index = { read: readDecisionIndex, write: writeDecisionIndex } }) {
82
+ const fresh = freshDecisions({ text, issue, comments });
83
+ for (const d of fresh) post(decisionComment(d));
84
+ if (fresh.length) index.write(repo, [...index.read(repo), ...fresh]);
85
+ return fresh;
86
+ }
87
+
88
+ /** Writes `<outDir>/<id>.contract.test.mjs` for every row with a machine form, plus seam-check.mjs. Returns {written, skipped}. */
89
+ export function writeContracts({ text, issue, outDir, fs = { mkdirSync, writeFileSync, copyFileSync } }) {
90
+ const recs = interfaceDecisions(text, { issue }), written = [];
91
+ const wanted = recs.filter((r) => r.seam);
92
+ if (wanted.length) {
93
+ fs.mkdirSync(outDir, { recursive: true });
94
+ fs.copyFileSync(SEAM_CHECK, join(outDir, "seam-check.mjs"));
95
+ for (const r of wanted) {
96
+ const file = join(outDir, `${r.id}.contract.test.mjs`);
97
+ fs.writeFileSync(file, renderSeamTest({ v: 1, id: r.id, kind: r.seam.kind, boundary: r.choice.slice(0, 160), auth: r.seam.auth, [r.seam.kind]: r.seam[r.seam.kind], provider: r.seam.provider, consumer: r.seam.consumer }));
98
+ written.push(file);
99
+ }
100
+ }
101
+ return { written, skipped: recs.filter((r) => !r.seam).map((r) => r.id) };
102
+ }
103
+
104
+ const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "consumer";
105
+ const REF = /^#?(\d+)$/;
106
+
107
+ /** What a landed `supersedes` decision owes its consumers: [{consumer, issue|null, key}] (`#N` reopens/notifies, a name files an issue). */
108
+ export function consumerNotices(rec) {
109
+ if (!rec?.supersedes || !rec.consumers?.length) return [];
110
+ return rec.consumers.map((c) => { const m = REF.exec(String(c).trim()); return m ? { consumer: `#${m[1]}`, issue: Number(m[1]), key: `${rec.id}:${m[1]}` } : { consumer: String(c), issue: null, key: `${rec.id}:${slug(c)}` }; });
111
+ }
112
+
113
+ const noticeBody = (rec, n, { pr, tag }) => `<!-- ${INTERFACE_CHANGED_MARKER} decision=${rec.id} consumer=${tag} -->\n## Interface changed: ${rec.choice}\n\nDecision \`${rec.id}\` supersedes \`${rec.supersedes}\`${pr ? ` (PR #${pr})` : ""}${rec.issue ? `, recorded on #${rec.issue}` : ""}. ${n.consumer} builds against this interface: re-check it against the new contract${rec.why ? ` (${rec.why})` : ""}.\n\nGoverns: ${(rec.anchors ?? []).map((a) => `\`${a}\``).join(", ")}`;
114
+
115
+ /**
116
+ * Tells the consumers of a superseded interface. `gh(args)` runs gh and resolves stdout. A `#N` consumer that is closed is
117
+ * reopened (best-effort `workflow:merged` removal so it is picked up as work, not as a merge to verify) and every `#N`
118
+ * consumer gets one FORGE:INTERFACE_CHANGED comment; a named consumer gets one new issue. Idempotent: an existing
119
+ * comment/issue carrying the same decision+consumer marker is reused. Returns [{consumer, action, issue?}]; a failed
120
+ * consumer is {action:"failed", error} and never throws.
121
+ */
122
+ export async function notifyConsumers({ rec, pr = null, repo, gh }) {
123
+ const out = [];
124
+ for (const n of consumerNotices(rec)) {
125
+ const tag = n.issue ? `#${n.issue}` : slug(n.consumer), marker = `${INTERFACE_CHANGED_MARKER} decision=${rec.id} consumer=${tag}`;
126
+ try {
127
+ if (n.issue) {
128
+ const v = JSON.parse(String(await gh(["issue", "view", String(n.issue), "-R", repo, "--json", "state,comments"])) || "{}");
129
+ if (String(v.state).toUpperCase() === "CLOSED") {
130
+ await gh(["issue", "reopen", String(n.issue), "-R", repo]);
131
+ try { await gh(["issue", "edit", String(n.issue), "-R", repo, "--remove-label", "workflow:merged"]); } catch { /* the label may not exist */ }
132
+ out.push({ consumer: n.consumer, action: "reopened", issue: n.issue });
133
+ } else out.push({ consumer: n.consumer, action: "notified", issue: n.issue });
134
+ if (!(v.comments ?? []).some((c) => String(c?.body ?? "").includes(marker))) await gh(["issue", "comment", String(n.issue), "-R", repo, "--body", noticeBody(rec, n, { pr, tag })]);
135
+ continue;
136
+ }
137
+ const found = JSON.parse(String(await gh(["issue", "list", "-R", repo, "--state", "all", "--search", `"${marker}" in:body`, "--json", "number", "--limit", "5"])) || "[]");
138
+ if (found.length) { out.push({ consumer: n.consumer, action: "exists", issue: found[0].number }); continue; }
139
+ const url = String(await gh(["issue", "create", "-R", repo, "--title", `Adapt ${n.consumer} to interface change ${rec.id}`.slice(0, 120), "--body", noticeBody(rec, n, { pr, tag })])).trim();
140
+ out.push({ consumer: n.consumer, action: "filed", issue: Number(/\/issues\/(\d+)/.exec(url)?.[1]) || null });
141
+ } catch (e) { out.push({ consumer: n.consumer, action: "failed", error: String(e?.message ?? e).slice(0, 160) }); }
142
+ }
143
+ return out;
144
+ }
145
+
146
+ /** `forgedock interfaces check|register|contract`. Resolves the exit code (1: invalid). */
147
+ export async function interfacesFromCli(argv, deps = {}) {
148
+ const val = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : null; };
149
+ const print = deps.print ?? ((t) => console.log(t));
150
+ const usage = "usage: forgedock interfaces check --body-file F [--kind spike|epic] | register --issue N --body-file F [--repo o/r] | contract --issue N --body-file F [--out contracts]";
151
+ const sub = argv[0], file = val("--body-file");
152
+ if (!["check", "register", "contract"].includes(sub) || !file) throw new Error(usage);
153
+ const text = deps.readFile ? deps.readFile(file) : readFileSync(file, "utf8");
154
+ if (sub === "check") {
155
+ const kind = val("--kind") ?? "auto";
156
+ if (!["auto", "spike", "epic"].includes(kind)) throw new Error(usage);
157
+ const r = checkInterfaces(text, { kind });
158
+ for (const p of r.problems) print(`interfaces: ${p}`);
159
+ for (const u of r.unchecked) print(`interfaces: note: "${u}" has a machine-form signature but no provider:/consumer: anchors, so no contract test is generated`);
160
+ if (r.ok) print(`interfaces: ok (${r.slices} slice(s), ${r.rows} boundary row(s))`);
161
+ return r.ok ? 0 : 1;
162
+ }
163
+ const issue = Number(val("--issue"));
164
+ if (!Number.isSafeInteger(issue) || issue < 1) throw new Error(usage);
165
+ if (sub === "contract") {
166
+ const r = writeContracts({ text, issue, outDir: val("--out") ?? "contracts", ...(deps.fs ? { fs: deps.fs } : {}) });
167
+ for (const f of r.written) print(`interfaces: wrote ${f}`);
168
+ if (!r.written.length) print("interfaces: no row has a machine-form signature with provider: and consumer: anchors; nothing generated");
169
+ return 0;
170
+ }
171
+ const repo = val("--repo") ?? deps.repo;
172
+ if (!repo) throw new Error("interfaces register needs the repo: pass --repo owner/repo");
173
+ const gh = deps.gh ?? (async (args, input) => (await import("node:child_process")).execFileSync("gh", args, { encoding: "utf8", input, maxBuffer: 64 * 1024 * 1024 }));
174
+ const comments = JSON.parse(String(await gh(["issue", "view", String(issue), "-R", repo, "--json", "comments"])) || "{}").comments?.map((c) => c?.body) ?? [];
175
+ const index = deps.index ?? { read: readDecisionIndex, write: writeDecisionIndex };
176
+ const fresh = freshDecisions({ text, issue, comments });
177
+ for (const d of fresh) await gh(["issue", "comment", String(issue), "-R", repo, "--body-file", "-"], decisionComment(d));
178
+ if (fresh.length) index.write(repo, [...index.read(repo), ...fresh]);
179
+ print(`interfaces: registered ${fresh.length} decision(s) on #${issue}${fresh.length ? `: ${fresh.map((d) => d.id).join(", ")}` : " (all already present)"}`);
180
+ return 0;
181
+ }
@@ -0,0 +1,192 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpDir } from "../tests/_tmp.mjs";
8
+ import { sliceCount, checkInterfaces, freshDecisions, seedDecisions, writeContracts, consumerNotices, notifyConsumers, interfacesFromCli, decisionComment } from "./interfaces.mjs";
9
+ import { interfaceDecisions, interfaceRows, withDecisionRows, supersede, normaliseDecision, readDecisionIndex } from "./decisions.mjs";
10
+ import { precheck, applyAmendments } from "./conformance.mjs";
11
+ import { seamFailures } from "./seam.mjs";
12
+
13
+ const TABLE = (rows) => ["| Boundary | Signature or schema | Auth mode | Owner issue | Anchors | Consumers |", "|---|---|---|---|---|---|", ...rows].join("\n");
14
+ const SPIKE = (extra = "") => `## Stack\n**Rationale**: x\n\n## Milestone plan\n1. api\n2. web\n\n${extra}`;
15
+ const EPIC = (extra = "") => `## Goal\nShip search.\n\n## Slices\n- [ ] #11 api\n- [ ] #12 web\n\n${extra}`;
16
+ const IFACE = `## Interfaces\n\n${TABLE(["| web -> api | POST /v1/search | API key only, no session cookie | #11 | `provider:api/`, `consumer:web/` | #12, search-sdk |"])}\n\n**Rationale**: one boundary\n`;
17
+
18
+ describe("Interfaces section validation (#5338)", () => {
19
+ it("counts slices: a spike's numbered Milestone plan, an epic's list items", () => {
20
+ assert.equal(sliceCount(SPIKE()), 2);
21
+ assert.equal(sliceCount(EPIC()), 2);
22
+ assert.equal(sliceCount(`## Slices\n1. one\n2. two\n3. three\n`), 3);
23
+ assert.equal(sliceCount("## Goal\n- [ ] #1 a\n- [ ] #2 b\n"), 2);
24
+ assert.equal(sliceCount("## Goal\nno list"), 0);
25
+ });
26
+ it("a spike or an epic with two or more slices and no Interfaces section fails; one slice, or a section, passes", () => {
27
+ for (const [body, kind] of [[SPIKE(), "spike"], [EPIC(), "epic"]]) {
28
+ const r = checkInterfaces(body, { kind });
29
+ assert.equal(r.ok, false, kind);
30
+ assert.match(r.problems[0], /no `## Interfaces` section: 2 slices/);
31
+ assert.equal(checkInterfaces(body + IFACE, { kind }).ok, true, kind);
32
+ assert.equal(checkInterfaces(body, { kind: "auto" }).ok, false);
33
+ }
34
+ assert.equal(checkInterfaces("## Slices\n- [ ] #1 only\n", { kind: "epic" }).ok, true);
35
+ assert.equal(checkInterfaces("## Goal\nx").required, false);
36
+ });
37
+ it("the section needs a Rationale line, and an epic needs a real boundary row (a placeholder row does not count)", () => {
38
+ assert.match(checkInterfaces(EPIC("## Interfaces\n" + TABLE(["| a -> b | f(x) | key | #1 | `p/` | |"])), { kind: "epic" }).problems[0], /no \*\*Rationale\*\*/);
39
+ const ph = EPIC(`## Interfaces\n${TABLE(["| {web -> api} | {POST /x} | {key} | {issue} | `{provider:a/}` | {#n} |"])}\n\n**Rationale**: r\n`);
40
+ assert.match(checkInterfaces(ph, { kind: "epic" }).problems[0], /no boundary row/);
41
+ assert.equal(checkInterfaces(SPIKE(`## Interfaces\n${TABLE(["| {a} | {b} | {c} | {d} | `{e}` | |"])}\n\n**Rationale**: r\n`), { kind: "spike" }).ok, true, "the spike template ships a placeholder row");
42
+ });
43
+ it("notes a machine-form signature that declares no sides (no contract test can be generated)", () => {
44
+ const body = EPIC(`## Interfaces\n${TABLE(["| a -> b | POST /v1/x | key | #1 | `api/` | |"])}\n\n**Rationale**: r\n`);
45
+ assert.deepEqual(checkInterfaces(body, { kind: "epic" }).unchecked, ["a -> b"]);
46
+ assert.deepEqual(checkInterfaces(EPIC(IFACE), { kind: "epic" }).unchecked, []);
47
+ });
48
+ it("rows are read by header name: a five-column table without Consumers still parses", () => {
49
+ const rows = interfaceRows(`## Interfaces\n| Boundary | Signature or schema | Auth mode | Owner issue | Anchors |\n|--|--|--|--|--|\n| a -> b | refund(id) | key | #3 | \`provider:w/\`, \`consumer:a/\` |\n`);
50
+ assert.equal(rows.length, 1);
51
+ assert.deepEqual(rows[0].consumers, []);
52
+ assert.equal(rows[0].seam.kind, "symbol");
53
+ assert.deepEqual(interfaceRows(EPIC(IFACE))[0].consumers, ["#12", "search-sdk"]);
54
+ });
55
+ });
56
+
57
+ describe("registering a spike or epic's interfaces in the decision register (#5338)", () => {
58
+ const idx = () => { const dir = tmpDir("ifc-"); process.env.FORGEDOCK_DECISIONS_DIR = dir; return dir; };
59
+ it("an epic's Interfaces row and anchored architecture choice are posted once per id and indexed; a lane on the anchors gets the preserve row", () => {
60
+ idx();
61
+ const body = EPIC(`## Auth\n**Rationale**: keys everywhere\n**Anchors**: \`api/auth/\`\n\n${IFACE}`);
62
+ const posts = [];
63
+ const first = seedDecisions({ text: body, issue: 40, repo: "o/r", comments: [], post: (b) => posts.push(b) });
64
+ assert.deepEqual(first.map((d) => d.id), ["i40-1", "i40-2"]);
65
+ assert.match(posts[0], /^<!-- FORGE:DECISION \{/);
66
+ assert.match(posts[1], /Interface web -> api: POST \/v1\/search; auth API key only, no session cookie; owner #11/);
67
+ const again = seedDecisions({ text: body, issue: 40, repo: "o/r", comments: posts, post: (b) => posts.push(b) });
68
+ assert.deepEqual(again, [], "idempotent on resume");
69
+ assert.equal(posts.length, 2);
70
+ const recs = readDecisionIndex("o/r");
71
+ assert.equal(recs.length, 2);
72
+ assert.deepEqual(recs[1].consumers, ["#12", "search-sdk"]);
73
+ assert.equal(recs[1].seam.kind, "route");
74
+ const lane = withDecisionRows({ deliverables: [{ id: "D1", path: "web/app/api/search/route.ts" }], preserve: [] }, recs);
75
+ assert.deepEqual(lane.preserve.map((p) => [p.source, p.decision]), [["decision", "i40-2"]]);
76
+ assert.match(lane.preserve[0].what, /POST \/v1\/search/);
77
+ assert.deepEqual(freshDecisions({ text: body, issue: 40, comments: [decisionComment(first[0])] }).map((d) => d.id), ["i40-2"]);
78
+ });
79
+ it("CLI: check exits 1 for the missing section and 0 with it; register posts via gh once; contract writes the test for machine-form rows", async () => {
80
+ const dir = idx(); const out = [];
81
+ const files = { "epic.md": EPIC(), "ok.md": EPIC(IFACE) };
82
+ const deps = { print: (t) => out.push(t), readFile: (f) => files[f] };
83
+ assert.equal(await interfacesFromCli(["check", "--body-file", "epic.md", "--kind", "epic"], deps), 1);
84
+ assert.match(out.at(-1), /interfaces: no `## Interfaces` section/);
85
+ assert.equal(await interfacesFromCli(["check", "--body-file", "ok.md", "--kind", "epic"], deps), 0);
86
+ const calls = [];
87
+ const gh = async (a, input) => { calls.push([a, input]); return a[1] === "view" ? JSON.stringify({ comments: calls.filter((c) => c[0][1] === "comment").map((c) => ({ body: c[1] })) }) : ""; };
88
+ assert.equal(await interfacesFromCli(["register", "--issue", "40", "--body-file", "ok.md", "--repo", "o/r"], { ...deps, gh }), 0);
89
+ assert.equal(calls.filter((c) => c[0][1] === "comment").length, 1);
90
+ assert.match(out.at(-1), /registered 1 decision\(s\) on #40: i40-1/);
91
+ await interfacesFromCli(["register", "--issue", "40", "--body-file", "ok.md", "--repo", "o/r"], { ...deps, gh });
92
+ assert.equal(calls.filter((c) => c[0][1] === "comment").length, 1, "re-run posts nothing");
93
+ assert.match(out.at(-1), /already present/);
94
+ await assert.rejects(() => interfacesFromCli(["register", "--body-file", "ok.md"], deps), /usage/);
95
+ const o = join(dir, "contracts");
96
+ assert.equal(await interfacesFromCli(["contract", "--issue", "40", "--body-file", "ok.md", "--out", o], deps), 0);
97
+ assert.ok(existsSync(join(o, "seam-check.mjs")) && existsSync(join(o, "i40-1.contract.test.mjs")));
98
+ assert.match(readFileSync(join(o, "i40-1.contract.test.mjs"), "utf8"), /"kind": "route"/);
99
+ assert.deepEqual(writeContracts({ text: EPIC(), issue: 1, outDir: join(dir, "none") }), { written: [], skipped: [] });
100
+ });
101
+ });
102
+
103
+ describe("a superseded interface tells its consumers (#5338)", () => {
104
+ const old = normaliseDecision({ id: "i40-1", choice: "Interface web -> api: POST /v1/search", anchors: ["api/", "web/"], issue: 40, consumers: ["#12", "#13", "search-sdk"] });
105
+ const rec = supersede(old, normaliseDecision({ id: "d41-1", choice: "Interface web -> api: POST /v2/search", why: "v2", anchors: ["api/", "web/"], issue: 41 })).next;
106
+ it("the new record inherits the consumers; none for a decision that supersedes nothing", () => {
107
+ assert.deepEqual(rec.consumers, ["#12", "#13", "search-sdk"]);
108
+ assert.deepEqual(consumerNotices(rec).map((n) => [n.consumer, n.issue]), [["#12", 12], ["#13", 13], ["search-sdk", null]]);
109
+ assert.deepEqual(consumerNotices({ ...rec, supersedes: undefined }), []);
110
+ });
111
+ it("closed consumers are reopened, open ones commented, a named consumer gets one new issue; idempotent on a re-run", async () => {
112
+ const calls = [], comments = { 12: [], 13: [] };
113
+ const gh = async (a) => {
114
+ calls.push(a.join(" "));
115
+ if (a[0] === "issue" && a[1] === "view") return JSON.stringify({ state: a[2] === "12" ? "CLOSED" : "OPEN", comments: (comments[a[2]] ?? []).map((body) => ({ body })) });
116
+ if (a[0] === "issue" && a[1] === "comment") { comments[a[2]].push(a[a.indexOf("--body") + 1]); return ""; }
117
+ if (a[0] === "issue" && a[1] === "list") return JSON.stringify(calls.some((c) => c.startsWith("issue create")) ? [{ number: 99 }] : []);
118
+ if (a[0] === "issue" && a[1] === "create") return "https://github.com/o/r/issues/99\n";
119
+ return "";
120
+ };
121
+ const first = await notifyConsumers({ rec, pr: 77, repo: "o/r", gh });
122
+ assert.deepEqual(first.map((x) => [x.consumer, x.action, x.issue]), [["#12", "reopened", 12], ["#13", "notified", 13], ["search-sdk", "filed", 99]]);
123
+ assert.ok(calls.includes("issue reopen 12 -R o/r") && !calls.includes("issue reopen 13 -R o/r"));
124
+ assert.ok(calls.some((c) => c.startsWith("issue edit 12") && c.includes("--remove-label workflow:merged")));
125
+ assert.match(comments[12][0], /FORGE:INTERFACE_CHANGED decision=d41-1 consumer=#12/);
126
+ assert.match(comments[12][0], /supersedes `i40-1` \(PR #77\)/);
127
+ const second = await notifyConsumers({ rec, pr: 77, repo: "o/r", gh });
128
+ assert.deepEqual(second.map((x) => x.action), ["reopened", "notified", "exists"]);
129
+ assert.equal(comments[12].length, 1, "one notice per consumer");
130
+ assert.equal(calls.filter((c) => c.startsWith("issue create")).length, 1);
131
+ });
132
+ it("a failing consumer is reported, never thrown", async () => {
133
+ const r = await notifyConsumers({ rec, repo: "o/r", gh: async () => { throw new Error("HTTP 500"); } });
134
+ assert.deepEqual(r.map((x) => x.action), ["failed", "failed", "failed"]);
135
+ });
136
+ });
137
+
138
+ describe("replay: the audit's interface mismatches are flagged at lane review, not at release review (#5338)", () => {
139
+ // The spike rows the architecture would have carried (AlterLab Search/Hands): the refund primitive, the web proxy auth
140
+ // mode (#39210, #39569) and the device/city/uule payload (worker BUG-1).
141
+ const spike = `${SPIKE()}## Interfaces\n\n${TABLE([
142
+ "| research -> refund primitive | refund(job_id, amount_micro) | internal | #101 | `provider:worker/refund.py`, `consumer:api/research/` | #102 |",
143
+ "| web proxy -> API | POST /v1/search | API key only, no session cookie or JWT | #103 | `provider:api/routes/`, `consumer:web/app/api/` | #104 |",
144
+ "| API -> worker | queue search.jobs {query, device, city, uule} | internal | #105 | `provider:worker/handlers/`, `consumer:api/search/` | |",
145
+ ])}\n\n**Rationale**: each boundary is a contract\n`;
146
+ const recs = interfaceDecisions(spike, { issue: 100 });
147
+ const base = {
148
+ "worker/refund.py": "async def refund(job_id: str, amount_micro: int) -> None:\n ...\n",
149
+ "api/research/run.py": "await refund(job.id, amount_micro=cost)\n",
150
+ "api/routes/search.py": "@router.post('/v1/search')\nasync def search(): ...\n",
151
+ "web/app/api/search/route.ts": "export async function POST() { return fetch(`${API}/v1/search`, { headers: { 'x-api-key': KEY } }); }\n",
152
+ "worker/handlers/search.py": "def handle(j): return j['query'], j['device'], j['city'], j['uule']\n",
153
+ "api/search/enqueue.py": "enqueue({'query': q, 'device': d, 'city': c, 'uule': u})\n",
154
+ };
155
+ const lane = (changes) => {
156
+ const files = { ...base, ...changes };
157
+ const changed = Object.keys(changes);
158
+ const contract = withDecisionRows({ requirements: [], deliverables: changed.map((p, i) => ({ id: `D${i + 1}`, path: p })), preserve: [] }, recs);
159
+ const seam = seamFailures({ records: recs, changedFiles: changed, list: () => Object.keys(files), read: (p) => files[p] });
160
+ return { contract, seam, pc: precheck({ contract: { ...contract, deliverables: [] }, result: { requirements: [], validation: [], preserve: [] }, changedFiles: changed, ignore: changed, seamFailures: seam }) };
161
+ };
162
+ it("the baseline repo is clean: every seam row has a contract", () => {
163
+ assert.equal(recs.filter((r) => r.seam).length, 3);
164
+ assert.deepEqual(lane({ "worker/refund.py": base["worker/refund.py"] }).seam, []);
165
+ });
166
+ it("refund signature drift: flagged on the lane that changes the primitive, with the row as a preserve item", () => {
167
+ const l = lane({ "worker/refund.py": "async def refund(job_id: str) -> None:\n ...\n" });
168
+ assert.ok(l.contract.preserve.some((p) => p.source === "decision" && /refund\(job_id, amount_micro\)/.test(p.what)));
169
+ assert.deepEqual(l.seam.map((f) => f.kind), ["interface_seam"]);
170
+ assert.match(l.seam[0].detail, /refund\(job_id\) does not match the declared refund\(job_id, amount_micro\)/);
171
+ assert.equal(l.pc.ok, false);
172
+ assert.ok(l.pc.failures.some((f) => f.kind === "interface_seam"));
173
+ });
174
+ it("cookie vs API key: a web proxy that forwards the session cookie to the API-key-only route is flagged at lane review", () => {
175
+ const l = lane({ "web/app/api/search/route.ts": "export async function POST(req) { return fetch(`${API}/v1/search`, { headers: { cookie: req.headers.get('cookie') ?? '' } }); }\n" });
176
+ assert.ok(l.seam.length >= 1);
177
+ assert.match(l.seam[0].detail, /web\/app\/api\/search\/route\.ts:1.*Cookie header/);
178
+ assert.ok(l.pc.failures.some((f) => f.kind === "interface_seam" && f.code === "conformance.preserve_violated"));
179
+ });
180
+ it("dropped payload fields: the handler that stops reading device/city/uule is flagged", () => {
181
+ const l = lane({ "worker/handlers/search.py": "def handle(j): return j['query']\n" });
182
+ assert.deepEqual(l.seam.map((f) => /field "(\w+)"/.exec(f.detail)[1]), ["device", "city", "uule"]);
183
+ });
184
+ it("changing an interface on purpose needs a supersedes decision, which retires the row and the seam check", () => {
185
+ const changes = { "worker/refund.py": "async def refund(job_id: str) -> None:\n ...\n" };
186
+ const files = { ...base, ...changes };
187
+ const a = applyAmendments({ requirements: [{ id: "R1", quote: "q", disposition: "deliver" }], deliverables: [{ id: "D1", path: "worker/refund.py" }], preserve: withDecisionRows({ deliverables: [{ id: "D1", path: "worker/refund.py" }], preserve: [] }, recs).preserve }, [{ kind: "decision", why: "refund is job-scoped now", decision: { choice: "Interface research -> refund: refund(job_id)", anchors: ["worker/refund.py"], supersedes: "i100-1" } }], "q", { baseFiles: Object.keys(files) });
188
+ assert.deepEqual(a.problems, []);
189
+ assert.equal(a.contract.preserve.some((p) => p.decision === "i100-1"), false);
190
+ assert.deepEqual(seamFailures({ records: recs, changedFiles: Object.keys(changes), list: () => Object.keys(files), read: (p) => files[p], superseded: a.decisions.map((d) => d.supersedes).filter(Boolean) }), []);
191
+ });
192
+ });
@@ -4,28 +4,65 @@
4
4
  * `forgedock issue-watch install` (#5465): run one watch as a supervised unit, like `forgedock-schedd` (pool/install/install-schedd.sh).
5
5
  * systemd user unit with `Restart=on-failure` (a finished watch exits 0 and stays down) plus a watchdog timer that runs
6
6
  * `issue-watch watchdog` to alert on a dead heartbeat; launchd agent with `KeepAlive.SuccessfulExit=false` on macOS. No LLM calls.
7
+ * #5529: the unit carries the lane environment (PATH with claude first, TMPDIR, TOKENBATON_*, no CLAUDE_CONFIG_DIR) and reads the
8
+ * computeshare token when it starts; the token value is never written into the unit.
7
9
  */
8
- import { mkdirSync, writeFileSync } from "node:fs";
10
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
11
  import { spawnSync } from "node:child_process";
10
12
  import { homedir } from "node:os";
11
- import { join } from "node:path";
13
+ import { dirname, join } from "node:path";
14
+ import { resolveOnPath } from "./issuewatch-parity.mjs";
15
+ import { isShim } from "./rotator.mjs";
12
16
 
13
17
  const safe = (s) => String(s).replace(/[^\w.-]/g, "_");
14
18
  const quote = (s) => (/[\s"\\]/.test(s) ? `"${s.replace(/(["\\])/g, "\\$1")}"` : s);
15
19
 
16
20
  export const watchUnitName = (name) => `forgedock-issue-watch-${safe(name)}`;
17
21
 
22
+ /** The router's token *file path* (never its value): `forgedock_token_file` of the computeshare router config, else its sibling `forgedock.token`. */
23
+ export function routerTokenFile({ env = process.env, home = homedir(), read = (p) => readFileSync(p, "utf8") } = {}) {
24
+ const conf = env.COMPUTESHARE_CONFIG || join(home, ".config", "computeshare", "router.json");
25
+ try { const p = JSON.parse(read(conf))?.forgedock_token_file; if (typeof p === "string" && p) return p; } catch { /* no router config: the sibling path */ }
26
+ return join(dirname(conf), "forgedock.token");
27
+ }
28
+
29
+ /**
30
+ * #5529: the lane environment a supervised watch needs (systemd and launchd start it with almost none, so its lanes failed
31
+ * `Failed to find executable claude`): PATH with the tokenbaton shim and the resolved `claude` dirs first, then the installer's PATH;
32
+ * TMPDIR; TOKENBATON_HOME / TOKENBATON_SWITCH_AT when set. `tokenFile` is where the computeshare token is read at start (a path only).
33
+ * @returns {{vars: Record<string,string>, unset: string[], tokenFile: string, claude: string|null}}
34
+ */
35
+ export function resolveLaneEnv({ env = process.env, home = homedir(), exists = existsSync } = {}) {
36
+ const claude = resolveOnPath("claude", env.PATH);
37
+ const shims = [env.TOKENBATON_HOME && join(env.TOKENBATON_HOME, "shim"), join(home, ".tokenbaton", "shim")].filter((d) => d && exists(join(d, "claude")));
38
+ const dirs = [...(claude && isShim(claude) ? [dirname(claude)] : []), ...shims, ...(claude ? [dirname(claude)] : []), ...String(env.PATH ?? "").split(":"), "/usr/local/bin", "/usr/bin", "/bin"];
39
+ const vars = { PATH: [...new Set(dirs.filter(Boolean))].join(":"), TMPDIR: env.TMPDIR || "/tmp" };
40
+ for (const k of ["TOKENBATON_HOME", "TOKENBATON_SWITCH_AT"]) if (env[k]) vars[k] = env[k];
41
+ return { vars, unset: ["CLAUDE_CONFIG_DIR"], tokenFile: routerTokenFile({ env, home }), claude };
42
+ }
43
+
44
+ const shq = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
45
+ /** sh run at unit start: COMPUTESHARE_TOKEN from the keychain (pool/install/install-router.sh), else the router token file, then exec the watch. */
46
+ export const tokenStartScript = (tokenFile) =>
47
+ 't="${COMPUTESHARE_TOKEN:-}"; [ -n "$t" ] || t=$(secret-tool lookup service forgedock account COMPUTESHARE_TOKEN 2>/dev/null) || t=; ' +
48
+ '[ -n "$t" ] || t=$(cat ' + shq(tokenFile) + ' 2>/dev/null) || t=; [ -n "$t" ] && export COMPUTESHARE_TOKEN="$t"; exec "$@"';
49
+ /** One systemd word in double quotes; `$` and `%` are doubled so systemd passes them through verbatim. */
50
+ const sdArg = (s) => '"' + String(s).replace(/(["\\])/g, "\\$1").replace(/[$%]/g, (c) => c + c) + '"';
51
+
18
52
  /** The argv after `forgedock.mjs` that runs the watch. */
19
53
  const runArgs = ({ name, repo, interval }) => ["issue-watch", "run", "--name", name, ...(repo ? ["--repo", repo] : []), ...(interval ? ["--interval", String(interval)] : [])];
20
54
 
21
- export function renderSystemdUnit({ node, cli, name, repo, interval, cwd }) {
55
+ export function renderSystemdUnit({ node, cli, name, repo, interval, cwd, laneEnv = null }) {
56
+ const argv = [node, cli, ...runArgs({ name, repo, interval })].map(quote).join(" ");
57
+ const env = laneEnv ? [...Object.entries(laneEnv.vars).map(([k, v]) => `Environment=${sdArg(`${k}=${v}`)}`), `UnsetEnvironment=${laneEnv.unset.join(" ")}`, ""].join("\n") : "";
58
+ const exec = laneEnv ? `/bin/sh -c ${sdArg(tokenStartScript(laneEnv.tokenFile))} forgedock-issue-watch ${argv}` : argv;
22
59
  return `[Unit]
23
60
  Description=forgedock issue-watch ${name}
24
61
  StartLimitIntervalSec=0
25
62
 
26
63
  [Service]
27
64
  WorkingDirectory=${cwd}
28
- ExecStart=${[node, cli, ...runArgs({ name, repo, interval })].map(quote).join(" ")}
65
+ ${env}ExecStart=${exec}
29
66
  Restart=on-failure
30
67
  RestartSec=30
31
68
 
@@ -56,8 +93,11 @@ WantedBy=timers.target
56
93
  return { service, timer };
57
94
  }
58
95
 
59
- export function renderLaunchdPlist({ node, cli, name, repo, interval, cwd }) {
60
- const args = [node, cli, ...runArgs({ name, repo, interval })].map((a) => ` <string>${String(a).replace(/&/g, "&amp;").replace(/</g, "&lt;")}</string>`).join("\n");
96
+ export function renderLaunchdPlist({ node, cli, name, repo, interval, cwd, laneEnv = null }) {
97
+ const x = (a) => String(a).replace(/&/g, "&amp;").replace(/</g, "&lt;");
98
+ const args = [node, cli, ...runArgs({ name, repo, interval })].map((a) => ` <string>${x(a)}</string>`).join("\n");
99
+ // launchd agents run in the login session, so the lane reads the token from the keychain itself; no value here
100
+ const env = laneEnv ? ` <key>EnvironmentVariables</key><dict>${Object.entries(laneEnv.vars).map(([k, v]) => `<key>${x(k)}</key><string>${x(v)}</string>`).join("")}</dict>\n` : "";
61
101
  return `<?xml version="1.0" encoding="UTF-8"?>
62
102
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
63
103
  <plist version="1.0"><dict>
@@ -66,21 +106,21 @@ export function renderLaunchdPlist({ node, cli, name, repo, interval, cwd }) {
66
106
  ${args}
67
107
  </array>
68
108
  <key>WorkingDirectory</key><string>${cwd}</string>
69
- <key>RunAtLoad</key><true/>
109
+ ${env} <key>RunAtLoad</key><true/>
70
110
  <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
71
111
  <key>ThrottleInterval</key><integer>30</integer>
72
112
  </dict></plist>
73
113
  `;
74
114
  }
75
115
 
76
- /** Writes and starts the unit; `{files, platform}`. `run(cmd, args)` and `write(path, text)` are injectable. */
77
- export function installWatchUnit({ name, repo, interval, cwd = process.cwd(), node = process.execPath, cli, platform = process.platform, home = homedir(), run = (c, a) => spawnSync(c, a, { stdio: "ignore" }), write = (p, t) => { mkdirSync(join(p, ".."), { recursive: true }); writeFileSync(p, t); } }) {
78
- const o = { node, cli, name, repo, interval, cwd }, files = [];
116
+ /** Writes and starts the unit; `{files, platform, claude}`. `run(cmd, args)` and `write(path, text)` are injectable; `env` is the installer's environment. */
117
+ export function installWatchUnit({ name, repo, interval, cwd = process.cwd(), node = process.execPath, cli, platform = process.platform, home = homedir(), env = process.env, run = (c, a) => spawnSync(c, a, { stdio: "ignore" }), write = (p, t) => { mkdirSync(join(p, ".."), { recursive: true }); writeFileSync(p, t); } }) {
118
+ const laneEnv = resolveLaneEnv({ env, home }), o = { node, cli, name, repo, interval, cwd, laneEnv }, files = [];
79
119
  if (platform === "darwin") {
80
120
  const f = join(home, "Library", "LaunchAgents", `com.forgedock.issue-watch.${safe(name)}.plist`);
81
121
  write(f, renderLaunchdPlist(o)); files.push(f);
82
122
  run("launchctl", ["unload", f]); run("launchctl", ["load", "-w", f]);
83
- return { files, platform };
123
+ return { files, platform, claude: laneEnv.claude };
84
124
  }
85
125
  if (platform !== "linux") throw new Error(`issue-watch install: unsupported platform ${platform} (systemd or launchd only)`);
86
126
  const dir = join(home, ".config", "systemd", "user"), u = watchUnitName(name), w = renderWatchdog(o);
@@ -88,5 +128,5 @@ export function installWatchUnit({ name, repo, interval, cwd = process.cwd(), no
88
128
  run("systemctl", ["--user", "daemon-reload"]);
89
129
  run("systemctl", ["--user", "enable", "--now", `${u}.service`]);
90
130
  run("systemctl", ["--user", "enable", "--now", `${u}-watchdog.timer`]);
91
- return { files, platform };
131
+ return { files, platform, claude: laneEnv.claude };
92
132
  }
@@ -29,3 +29,53 @@ test("#5465 installWatchUnit writes three systemd files and enables them; other
29
29
  assert.ok(ran.some((l) => /enable --now forgedock-issue-watch-nomilestone\.service/.test(l)));
30
30
  assert.throws(() => installWatchUnit({ ...o, platform: "win32" }), /unsupported platform/);
31
31
  });
32
+
33
+ // #5529: the unit the real installer writes must let a lane find claude; nothing in the install/render path is replaced
34
+ import { mkdirSync, writeFileSync, readFileSync, chmodSync, symlinkSync } from "node:fs";
35
+ import { join } from "node:path";
36
+ import { execFileSync } from "node:child_process";
37
+ import { tmpDir } from "../tests/_tmp.mjs";
38
+
39
+ const exe = (p) => { mkdirSync(join(p, ".."), { recursive: true }); writeFileSync(p, "#!/bin/sh\nexit 0\n"); chmodSync(p, 0o755); return p; };
40
+ /** systemd unquoting of one double-quoted word (`\x` escapes, doubled `$`/`%`). */
41
+ const sdWord = (w) => w.replace(/\\(.)/g, "$1").replace(/\$\$/g, "$").replace(/%%/g, "%");
42
+
43
+ test("#5529 the installed unit's PATH resolves the staged claude shim and carries the lane environment without the token value", () => {
44
+ const root = tmpDir("iw5529-"), home = join(root, "home"), bin = join(root, "opt", "claude-bin"), tb = join(root, "tb");
45
+ const claude = exe(join(bin, "claude"));
46
+ const tokenFile = join(home, ".config", "computeshare", "forgedock.token");
47
+ mkdirSync(join(tokenFile, ".."), { recursive: true }); writeFileSync(tokenFile, "file-token-xyz\n");
48
+ const env = { PATH: `${bin}:/usr/bin:/bin`, TMPDIR: "/tmp", TOKENBATON_HOME: tb, TOKENBATON_SWITCH_AT: "90", COMPUTESHARE_TOKEN: "secret-value-123", CLAUDE_CONFIG_DIR: "/x/claude" };
49
+ const ran = [];
50
+ const r = installWatchUnit({ ...o, platform: "linux", home, env, run: (c, a) => ran.push([c, ...a].join(" ")) });
51
+ const unit = readFileSync(r.files[0], "utf8");
52
+ // the observable: a shell started with the unit's PATH finds claude (the systemd default /usr/local/bin:/usr/bin did not)
53
+ const envLine = (k) => { const m = new RegExp(`^Environment="${k}=((?:[^"\\\\]|\\\\.)*)"$`, "m").exec(unit); return m ? sdWord(m[1]) : null; };
54
+ const path = envLine("PATH");
55
+ assert.ok(path, "unit sets PATH");
56
+ assert.equal(execFileSync("/bin/sh", ["-c", "command -v claude"], { env: { PATH: path }, encoding: "utf8" }).trim(), claude);
57
+ assert.equal(path.split(":")[0], bin, "the resolved claude dir comes first");
58
+ assert.equal(envLine("TMPDIR"), "/tmp");
59
+ assert.equal(envLine("TOKENBATON_HOME"), tb);
60
+ assert.equal(envLine("TOKENBATON_SWITCH_AT"), "90");
61
+ assert.match(unit, /^UnsetEnvironment=CLAUDE_CONFIG_DIR$/m);
62
+ assert.doesNotMatch(unit, /secret-value-123|file-token-xyz/, "the token value is never written into the unit");
63
+ // the token is sourced when the unit starts: run the ExecStart wrapper with a PATH that has only cat (no secret-tool)
64
+ const m = /^ExecStart=\/bin\/sh -c "((?:[^"\\]|\\.)*)" forgedock-issue-watch (.*)$/m.exec(unit);
65
+ assert.ok(m, "ExecStart wraps the watch in a token-sourcing sh");
66
+ assert.match(m[2], /forgedock\.mjs issue-watch run --name nomilestone --repo o\/r$/);
67
+ const catOnly = join(root, "catbin"); mkdirSync(catOnly); symlinkSync(execFileSync("/bin/sh", ["-c", "command -v cat"], { encoding: "utf8" }).trim(), join(catOnly, "cat"));
68
+ const out = execFileSync("/bin/sh", ["-c", sdWord(m[1]), "forgedock-issue-watch", "/bin/sh", "-c", 'printf %s "$COMPUTESHARE_TOKEN"'], { env: { PATH: catOnly }, encoding: "utf8" });
69
+ assert.equal(out, "file-token-xyz");
70
+ assert.ok(ran.some((l) => /enable --now forgedock-issue-watch-nomilestone\.service/.test(l)));
71
+ });
72
+
73
+ test("#5529 launchd plist carries the lane PATH/TMPDIR, never the token", () => {
74
+ const root = tmpDir("iw5529-"), bin = join(root, "b"); exe(join(bin, "claude"));
75
+ const written = {};
76
+ installWatchUnit({ ...o, platform: "darwin", home: join(root, "h"), env: { PATH: `${bin}:/usr/bin`, COMPUTESHARE_TOKEN: "secret-value-123" }, run: () => {}, write: (p, t) => { written[p] = t; } });
77
+ const p = Object.values(written)[0];
78
+ assert.match(p, new RegExp(`<key>EnvironmentVariables</key><dict><key>PATH</key><string>${bin}:`));
79
+ assert.match(p, /<key>TMPDIR<\/key><string>\/tmp<\/string>/);
80
+ assert.doesNotMatch(p, /secret-value-123/);
81
+ });
@@ -5,9 +5,9 @@
5
5
  * the default skip labels, issues with an open closing PR, release awareness (pause while a `forgedock release` job runs)
6
6
  * and the heartbeat liveness read by `issue-watch status` and doctor. No LLM calls; gh and the clock are injected.
7
7
  */
8
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
8
+ import { accessSync, constants, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
9
9
  import { writeAtomic } from "./batch.mjs";
10
- import { join } from "node:path";
10
+ import { delimiter, join } from "node:path";
11
11
  import { RELEASE_STEPS } from "./release.mjs";
12
12
 
13
13
  export const DEFAULT_SKIP_LABELS = ["epic", "needs-human", "post-deploy", "workflow:merged", "awaiting-promotion", "host-task"];
@@ -92,3 +92,13 @@ export async function alertDeadWatches({ root, now = Date.now(), emit }) {
92
92
  }
93
93
  return dead;
94
94
  }
95
+
96
+ /** #5529: the first executable `name` on `PATH` (a PATH string), or null. `isExec` defaults to a real X_OK check. */
97
+ export function resolveOnPath(name, PATH, { isExec = (p) => { try { accessSync(p, constants.X_OK); return statSync(p).isFile(); } catch { return false; } } } = {}) {
98
+ for (const d of String(PATH ?? "").split(delimiter)) if (d && isExec(join(d, name))) return join(d, name);
99
+ return null;
100
+ }
101
+
102
+ /** #5529: one warning per watch whose running watcher recorded that it cannot resolve `claude` (status.json `claude: null`). */
103
+ export const watchEnvWarnings = (rows) => rows.filter((w) => w.status && "claude" in w.status && w.status.claude === null && !["done", "exited"].includes(w.live?.state))
104
+ .map((w) => `watch ${w.name} (${w.repo}): cannot resolve claude on the watcher PATH; its lanes fail 'Failed to find executable claude' (reinstall: forgedock issue-watch install --name ${w.name})`);
@@ -150,3 +150,29 @@ test("#5465 a killed watch shows DEAD within 3 heartbeats and the watchdog alert
150
150
  writeFileSync(join(dir, "status.json"), JSON.stringify({ ...state(), heartbeat: beat(1000), heartbeatEveryMs: 300000 }));
151
151
  assert.equal((await alertDeadWatches({ root, now, emit })).length, 0);
152
152
  });
153
+
154
+ // #5529: claude resolution of the running watcher and the status/doctor warning rows, on a real temp filesystem
155
+ import { chmodSync } from "node:fs";
156
+ import { resolveOnPath, watchEnvWarnings } from "./issuewatch-parity.mjs";
157
+
158
+ test("#5529 resolveOnPath finds an executable claude and ignores a non-executable one", () => {
159
+ const d = tmpDir("iw5529-"), a = join(d, "a"), b = join(d, "b");
160
+ mkdirSync(a); mkdirSync(b);
161
+ writeFileSync(join(a, "claude"), "x"); // not executable
162
+ writeFileSync(join(b, "claude"), "#!/bin/sh\n"); chmodSync(join(b, "claude"), 0o755);
163
+ assert.equal(resolveOnPath("claude", `${a}:${b}`), join(b, "claude"));
164
+ assert.equal(resolveOnPath("claude", a), null);
165
+ assert.equal(resolveOnPath("claude", undefined), null);
166
+ });
167
+
168
+ test("#5529 watchEnvWarnings warns only for a live watcher that recorded it cannot resolve claude", () => {
169
+ const root = tmpDir("iw5529-"), beat = new Date(NOW).toISOString();
170
+ const put = (name, s) => { mkdirSync(join(root, "o__r", name), { recursive: true }); writeFileSync(join(root, "o__r", name, "status.json"), JSON.stringify({ name, repo: "o/r", phase: "running", heartbeat: beat, ...s })); };
171
+ put("bare", { claude: null });
172
+ put("ok", { claude: "/u/bin/claude" });
173
+ put("old", {}); // written before #5529: unknown, no warning
174
+ put("gone", { claude: null, phase: "exited" });
175
+ const lines = watchEnvWarnings(listWatches(root, NOW));
176
+ assert.equal(lines.length, 1);
177
+ assert.match(lines[0], /watch bare \(o\/r\): cannot resolve claude/);
178
+ });