@codyswann/lisa 4.101.5 → 4.101.7

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 (127) hide show
  1. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  2. package/dist/core/upstream-evidence-manifest.d.ts.map +1 -1
  3. package/dist/core/upstream-evidence-manifest.js +23 -7
  4. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  5. package/package.json +4 -4
  6. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  7. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  8. package/plugins/lisa/.codex-plugin/scripts/automation-run-record.mjs +678 -0
  9. package/plugins/lisa/.codex-plugin/scripts/blocker-edge-resolution.mjs +150 -0
  10. package/plugins/lisa/.codex-plugin/scripts/intake-blocker-reprobe.mjs +1379 -0
  11. package/plugins/lisa/.codex-plugin/scripts/intake-prework-denominator.mjs +249 -0
  12. package/plugins/lisa/.codex-plugin/scripts/operator-id-kinds.mjs +120 -0
  13. package/plugins/lisa/.codex-plugin/scripts/qa-signal-lifecycle.mjs +523 -0
  14. package/plugins/lisa/.codex-plugin/scripts/ready-queue-order.mjs +549 -0
  15. package/plugins/lisa/.codex-plugin/scripts/resolve-lifecycle-role.mjs +347 -0
  16. package/plugins/lisa/.codex-plugin/skills/lisa-jira-evidence/SKILL.md +10 -5
  17. package/plugins/lisa/.codex-plugin/skills/lisa-jira-journey/SKILL.md +14 -11
  18. package/plugins/lisa/.codex-plugin/skills/lisa-tracker-evidence/references/completion-authorization.md +7 -3
  19. package/plugins/lisa/skills/lisa-jira-evidence/SKILL.md +10 -5
  20. package/plugins/lisa/skills/lisa-jira-journey/SKILL.md +14 -11
  21. package/plugins/lisa/skills/lisa-tracker-evidence/references/completion-authorization.md +7 -3
  22. package/plugins/lisa-agy/plugin.json +1 -1
  23. package/plugins/lisa-agy/skills/lisa-jira-evidence/SKILL.md +10 -5
  24. package/plugins/lisa-agy/skills/lisa-jira-journey/SKILL.md +14 -11
  25. package/plugins/lisa-agy/skills/lisa-tracker-evidence/references/completion-authorization.md +7 -3
  26. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  27. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  28. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  29. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  30. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  31. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  32. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  33. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  34. package/plugins/lisa-copilot/skills/lisa-jira-evidence/SKILL.md +10 -5
  35. package/plugins/lisa-copilot/skills/lisa-jira-journey/SKILL.md +14 -11
  36. package/plugins/lisa-copilot/skills/lisa-tracker-evidence/references/completion-authorization.md +7 -3
  37. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  38. package/plugins/lisa-cursor/skills/lisa-jira-evidence/SKILL.md +10 -5
  39. package/plugins/lisa-cursor/skills/lisa-jira-journey/SKILL.md +14 -11
  40. package/plugins/lisa-cursor/skills/lisa-tracker-evidence/references/completion-authorization.md +7 -3
  41. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  42. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  43. package/plugins/lisa-devin/skills/lisa-jira-evidence/SKILL.md +10 -5
  44. package/plugins/lisa-devin/skills/lisa-jira-journey/SKILL.md +14 -11
  45. package/plugins/lisa-devin/skills/lisa-tracker-evidence/references/completion-authorization.md +7 -3
  46. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  47. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  48. package/plugins/lisa-expo/.codex-plugin/skills/jira-evidence/SKILL.md +10 -5
  49. package/plugins/lisa-expo/.codex-plugin/skills/jira-journey/SKILL.md +14 -11
  50. package/plugins/lisa-expo/skills/jira-evidence/SKILL.md +10 -5
  51. package/plugins/lisa-expo/skills/jira-journey/SKILL.md +14 -11
  52. package/plugins/lisa-expo-agy/plugin.json +1 -1
  53. package/plugins/lisa-expo-agy/skills/jira-evidence/SKILL.md +10 -5
  54. package/plugins/lisa-expo-agy/skills/jira-journey/SKILL.md +14 -11
  55. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  56. package/plugins/lisa-expo-copilot/skills/jira-evidence/SKILL.md +10 -5
  57. package/plugins/lisa-expo-copilot/skills/jira-journey/SKILL.md +14 -11
  58. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  59. package/plugins/lisa-expo-cursor/skills/jira-evidence/SKILL.md +10 -5
  60. package/plugins/lisa-expo-cursor/skills/jira-journey/SKILL.md +14 -11
  61. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  62. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  63. package/plugins/lisa-expo-devin/skills/jira-evidence/SKILL.md +10 -5
  64. package/plugins/lisa-expo-devin/skills/jira-journey/SKILL.md +14 -11
  65. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  67. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  68. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  69. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  70. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  71. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  72. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  73. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  74. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  75. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  77. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  78. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  79. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  80. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  81. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  82. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  83. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  84. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  85. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  86. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  87. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  88. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  89. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  90. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  91. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  92. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  93. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  94. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  95. package/plugins/lisa-rails/.codex-plugin/skills/jira-evidence/SKILL.md +10 -5
  96. package/plugins/lisa-rails/skills/jira-evidence/SKILL.md +10 -5
  97. package/plugins/lisa-rails-agy/plugin.json +1 -1
  98. package/plugins/lisa-rails-agy/skills/jira-evidence/SKILL.md +10 -5
  99. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  100. package/plugins/lisa-rails-copilot/skills/jira-evidence/SKILL.md +10 -5
  101. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  102. package/plugins/lisa-rails-cursor/skills/jira-evidence/SKILL.md +10 -5
  103. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  104. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  105. package/plugins/lisa-rails-devin/skills/jira-evidence/SKILL.md +10 -5
  106. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  107. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  108. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  109. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  110. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  111. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  112. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  113. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  114. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  115. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  116. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  117. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  118. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  119. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  120. package/plugins/src/base/skills/lisa-jira-evidence/SKILL.md +10 -5
  121. package/plugins/src/base/skills/lisa-jira-journey/SKILL.md +14 -11
  122. package/plugins/src/base/skills/lisa-tracker-evidence/references/completion-authorization.md +7 -3
  123. package/plugins/src/expo/skills/jira-evidence/SKILL.md +10 -5
  124. package/plugins/src/expo/skills/jira-journey/SKILL.md +14 -11
  125. package/plugins/src/rails/skills/jira-evidence/SKILL.md +10 -5
  126. package/scripts/generate-codex-plugin-artifacts.mjs +6 -0
  127. package/scripts/lib/codex-shared-scripts.mjs +156 -0
@@ -0,0 +1,1379 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Blocker re-probe gate for pre-work build-intake candidates.
4
+ *
5
+ * A blocker is a claim with a timestamp, not a fact. It is written once, and it
6
+ * decays the moment its condition goes true — a dependency lands on trunk, a
7
+ * CVE gets patched, a package publishes. Nothing in the old intake loop ever
8
+ * re-read one, so a discharged blocker held its item out of the queue forever.
9
+ *
10
+ * This module decides, per candidate, whether intake may select it. It never
11
+ * probes anything itself: the caller runs the probe and hands back the result,
12
+ * which keeps the decision auditable and testable apart from the network.
13
+ */
14
+
15
+ import { isPreWorkLaneType } from "./intake-prework-denominator.mjs";
16
+
17
+ /** Marker a writer stamps on an item a human deliberately parked. */
18
+ export const HUMAN_GATE_MARKER = "[lisa-human-gate]";
19
+
20
+ /** Default label naming a block only a human can clear. */
21
+ export const DEFAULT_HUMAN_NEEDED_LABEL = "human-needed";
22
+
23
+ /**
24
+ * @param {unknown} labels
25
+ * @returns {readonly string[]}
26
+ */
27
+ function normalizeLabels(labels) {
28
+ return (Array.isArray(labels) ? labels : [])
29
+ .map(label =>
30
+ typeof label === "string"
31
+ ? label
32
+ : typeof label?.name === "string"
33
+ ? label.name
34
+ : ""
35
+ )
36
+ .map(label => label.trim().toLowerCase())
37
+ .filter(label => label.length > 0);
38
+ }
39
+
40
+ /**
41
+ * Decoration a declaration may sit behind, and nothing more.
42
+ *
43
+ * Whitespace, blockquote arrows, list bullets or numbers, emphasis, a comment
44
+ * hash, and an opening HTML comment. `#` is there on EVIDENCE rather than
45
+ * taste: a shell script declares a hold as `# <marker> reason=…` — a bare
46
+ * marker behind a SHELL comment, with no HTML comment anywhere — and that form
47
+ * is in this repository's own guard fixtures. A single character class plus two
48
+ * optional groups —
49
+ * deliberately not a nested-quantifier pattern, because this runs over
50
+ * untrusted work-item bodies and `sonarjs/slow-regex` is right about that
51
+ * shape.
52
+ */
53
+ const LEADING_DECORATION =
54
+ /^[ \t>*_+#-]*(?:\d+[.)][ \t]*)?(?:<!--[ \t]*)?[ \t]*/u;
55
+
56
+ /**
57
+ * Decode one stored Markdown escape layer without changing the provider record.
58
+ * Linear escapes marker brackets and punctuation in reason keys. A single pass
59
+ * keeps literal backslash pairs intact instead of recursively inventing markers.
60
+ * Callers doing bookkeeping-marker searches use this same projection; hold and
61
+ * release parsers receive original bodies and apply it after excluding code.
62
+ * @param {unknown} body - Original provider text
63
+ * @returns {string} One-pass Markdown punctuation projection
64
+ */
65
+ export function normalizeProviderMarkdown(body) {
66
+ return String(body ?? "").replace(
67
+ /\\([\u0021-\u002f\u003a-\u0040\u005b-\u0060\u007b-\u007e])/gu,
68
+ "$1"
69
+ );
70
+ }
71
+
72
+ /**
73
+ * The body with fenced blocks and inline code spans removed.
74
+ *
75
+ * Documentation of a declaration is not a declaration, and a fenced example is
76
+ * how the declaration form gets written ABOUT. The same move
77
+ * `pr-arming-sweep.mjs` makes for the auto-merge-off marker
78
+ * (CodySwannGT/lisa#3986), and the same one `block-direct-issue-create.sh`
79
+ * makes when it strips heredoc bodies before tokenising argv.
80
+ * @param {unknown} body - The raw item body
81
+ * @returns {string} The body with quoted and code regions blanked out
82
+ */
83
+ function declarativeText(body) {
84
+ const withoutCode = String(body ?? "")
85
+ .replace(/```[\s\S]*?```/gu, "")
86
+ .replace(/`[^`\n]*`/gu, "");
87
+ return normalizeProviderMarkdown(withoutCode);
88
+ }
89
+
90
+ /**
91
+ * Whether an HTML comment on this line carries the given marker.
92
+ *
93
+ * The second declaration form, and it is not a concession: an HTML comment is
94
+ * invisible when the body is rendered, so nobody writes one to TALK about the
95
+ * marker — a quotation has to be visible to be a quotation. Prose about the
96
+ * marker is written in sentences, code spans and fenced examples, all of which
97
+ * this rule already excludes.
98
+ *
99
+ * Scanned rather than pattern-matched. A regular expression with two lazy
100
+ * `[^\n]*?` runs around a literal is the ambiguous shape this module avoids
101
+ * elsewhere, and an indexOf walk is both linear and easier to be sure about.
102
+ * @param {string} line - One line of the body
103
+ * @param {string} marker - The literal marker to look for
104
+ * @returns {boolean} True when a comment on this line contains the marker
105
+ */
106
+ function commentCarriesMarker(line, marker) {
107
+ const segments = line.split("<!--");
108
+ for (let index = 1; index < segments.length; index += 1) {
109
+ const close = segments[index].indexOf("-->");
110
+ const inside =
111
+ close === -1 ? segments[index] : segments[index].slice(0, close);
112
+ if (inside.includes(marker)) return true;
113
+ }
114
+ return false;
115
+ }
116
+
117
+ /**
118
+ * Whether one line DECLARES a hold rather than mentioning one.
119
+ *
120
+ * Two accepted forms, and the corpus says they cost nothing to combine:
121
+ * measured over this repository's 42 matching bodies, line-leading alone and
122
+ * line-leading-or-comment hold the SAME 29. The comment branch exists because
123
+ * the filing guard reads inputs that are not markdown documents — a one-line
124
+ * `--body` string and a shell script — where a declaration legitimately sits
125
+ * after other text on its line.
126
+ * @param {string} line - One line of the body
127
+ * @param {string} [marker] - The declaration marker to test for
128
+ * @returns {boolean} True when the line declares with that marker
129
+ */
130
+ function declaresOnLine(line, marker = HUMAN_GATE_MARKER) {
131
+ if (line.replace(LEADING_DECORATION, "").startsWith(marker)) {
132
+ return true;
133
+ }
134
+ return commentCarriesMarker(line, marker);
135
+ }
136
+
137
+ /**
138
+ * Count what a body says about the hold marker, split by what it MEANS.
139
+ *
140
+ * ## Why the substring test had to go
141
+ *
142
+ * `isHumanGated` asked one question — does the body contain the marker
143
+ * anywhere — and that form was deliberate, documented, and correct when it was
144
+ * written: *"it is a marker with no other meaning, so its presence IS the
145
+ * declaration."* The premise expired. The marker acquired a second meaning —
146
+ * **being discussed** — the moment the feature became something people file
147
+ * tickets about, so a sentence quoting it, a Gherkin line naming it, and a
148
+ * ticket about it all read as declared holds (CodySwannGT/lisa#3815).
149
+ *
150
+ * The consequence is not one skipped cycle. `planHumanGateReconciliation`
151
+ * removes the ready role and applies the human-needed label, so a false
152
+ * positive rewrites the item's own metadata and every later sweep agrees with
153
+ * the first. And the affected population GROWS with the documentation: 38
154
+ * matching bodies measured 2026-09-04, 42 on 2026-09-05.
155
+ *
156
+ * ## The rule
157
+ *
158
+ * A declaration is POSITIONAL — the marker leads its line, behind at most
159
+ * blockquote, list, emphasis or opening-comment decoration — evaluated after
160
+ * code regions are removed. Measured over this repository's 42 matching bodies:
161
+ * this holds 29 of them and correctly releases the two live ready-lane items
162
+ * that only discussed the marker.
163
+ *
164
+ * The stricter HTML-comment-only rule was measured and REJECTED: it holds only
165
+ * 18, dropping declarations that carry `human-needed` today. Losing a real hold
166
+ * is the unsafe direction and would need a retrofit of the tracker.
167
+ *
168
+ * ## Why it counts rather than answering yes or no
169
+ *
170
+ * A heuristic that silently drops candidates is indistinguishable from one that
171
+ * found none. Every occurrence this rule declines to honour is counted and
172
+ * reported, so "the rule demoted 33 mentions" is a fact an operator can read
173
+ * rather than an absence they must infer.
174
+ * @param {unknown} body - The item body
175
+ * @returns {{ total: number, declared: number, demoted: number }} Occurrences,
176
+ * those that declare a hold, and those demoted to mentions
177
+ */
178
+ export function humanGateMentions(body) {
179
+ const raw = String(body ?? "");
180
+ const total =
181
+ normalizeProviderMarkdown(raw).split(HUMAN_GATE_MARKER).length - 1;
182
+ const declared = declarativeText(raw)
183
+ .split("\n")
184
+ .filter(line => declaresOnLine(line)).length;
185
+ return { total, declared, demoted: total - declared };
186
+ }
187
+
188
+ /**
189
+ * Whether a body declares a hold, as opposed to discussing one.
190
+ * @param {unknown} body - The item body
191
+ * @returns {boolean} True when at least one line declares a hold
192
+ */
193
+ export function bodyDeclaresHold(body) {
194
+ return humanGateMentions(body).declared > 0;
195
+ }
196
+
197
+ /**
198
+ * Marker a comment carries to DISCHARGE a hold.
199
+ *
200
+ * ## Why a comment and not the body
201
+ *
202
+ * The hold lives in the description, and the only description write this plugin
203
+ * has is a whole-body replacement — re-read everything, change one line, write
204
+ * it all back. On an item carrying acceptance criteria, a validation journey
205
+ * and a managed usage section, "delete one HTML comment" is therefore "rewrite
206
+ * the record and hope nothing was dropped". A release procedure whose only
207
+ * implementation risks destroying what it releases is not a release procedure:
208
+ * the rational move is always to leave the hold, so holds only accumulate
209
+ * (CodySwannGT/lisa#3852).
210
+ *
211
+ * A comment is append-only. It cannot drop a section it never held, and the
212
+ * same reader that reads the hold reads the discharge.
213
+ *
214
+ * ## Why it is not a superstring of the hold marker
215
+ *
216
+ * `HUMAN_GATE_MARKER` closes with `]`, so `[lisa-human-gate-release]` does not
217
+ * contain it. That is load-bearing rather than incidental: a release record
218
+ * that matched the hold test would declare a fresh hold every time one was
219
+ * lifted, which is the same trap `NORMALIZATION_HOLD_NOTE_MARKER` documents.
220
+ */
221
+ export const HUMAN_GATE_RELEASE_MARKER = "[lisa-human-gate-release]";
222
+
223
+ /** Structured key a hold and its release both name, so they pair up. */
224
+ const REASON_KEY = "reason=";
225
+
226
+ /**
227
+ * The comparable form of a hold reason.
228
+ *
229
+ * Case and internal whitespace drift between the hand that writes the hold and
230
+ * the hand that writes the release; the identity of the question does not.
231
+ * @param {unknown} value - A raw reason string
232
+ * @returns {string} Its comparable form, empty when there is none
233
+ */
234
+ function normalizeReason(value) {
235
+ return String(value ?? "")
236
+ .replace(/\s+/gu, " ")
237
+ .trim()
238
+ .toLowerCase();
239
+ }
240
+
241
+ /**
242
+ * The reason a declaring line names, or the empty key when it names none.
243
+ *
244
+ * A keyless declaration is not a defect to be rejected — markers in the wild
245
+ * carry no `reason=` at all, which is why the hold test is not keyed on one.
246
+ * The empty string is a real key here: a keyless hold is discharged by a
247
+ * keyless release and by nothing else, so the two surfaces stay symmetric
248
+ * whether or not a reason was ever written.
249
+ * @param {string} line - A line already known to declare
250
+ * @param {string} marker - The declaration marker it carries
251
+ * @returns {string} The normalized reason key
252
+ */
253
+ function reasonOnLine(line, marker) {
254
+ const at = line.indexOf(marker);
255
+ if (at === -1) return "";
256
+ const tail = line.slice(at + marker.length).split("-->")[0];
257
+ const key = tail.indexOf(REASON_KEY);
258
+ if (key === -1) return "";
259
+ return normalizeReason(tail.slice(key + REASON_KEY.length));
260
+ }
261
+
262
+ /**
263
+ * The reason keys of every hold a body DECLARES, deduplicated.
264
+ *
265
+ * Reuses the precision rule rather than restating it, so a body that merely
266
+ * discusses the marker yields no holds here for the same reason it reads as
267
+ * unheld in {@link bodyDeclaresHold}.
268
+ * @param {unknown} body - The item body
269
+ * @returns {string[]} One key per declared hold
270
+ */
271
+ export function humanGateHolds(body) {
272
+ const keys = declarativeText(body)
273
+ .split("\n")
274
+ .filter(line => declaresOnLine(line))
275
+ .map(line => reasonOnLine(line, HUMAN_GATE_MARKER));
276
+ return [...new Set(keys)];
277
+ }
278
+
279
+ /**
280
+ * What a `human_gate` must name: an ACT an agent cannot perform
281
+ * (CodySwannGT/lisa#4658). A reason is legitimate only when it names one of
282
+ * the acts below, or a decision class the project declared human-only
283
+ * (`humanGate.humanOnly`). Anything else is a decision the agent makes and
284
+ * records. The writer-side CLI is `human-gate-act.mjs`; the sweep is
285
+ * `human-gate-lift.mjs`. It lives here so the hold verdict can judge a lift
286
+ * without a new dependency edge (the npm updater pins this file's dependency graph).
287
+ */
288
+
289
+ /**
290
+ * The acts an agent cannot perform. Each `label` is phrased so it completes
291
+ * "Held for a person to …", which is how the writers render the visible line.
292
+ *
293
+ * The patterns run over a normalized reason (lower case, hyphens and
294
+ * underscores read as spaces) so a slug and its prose spelling match alike.
295
+ * They are intentionally narrow: a word that is also an everyday topic
296
+ * ("token", "login", "billing page") is left out, because a pattern that
297
+ * matches a topic re-opens the gate this module closes.
298
+ */
299
+ export const HUMAN_GATE_ACTS = Object.freeze([
300
+ Object.freeze({
301
+ act: "credential",
302
+ label: "supply a credential only a person holds",
303
+ pattern:
304
+ /\b(credentials?|secrets?|passwords?|passphrases?|api keys?|access keys?|private keys?|deploy keys?|ssh keys?|signing keys?|auth tokens?|oauth|2fa|mfa|otp|one time codes?)\b/u,
305
+ }),
306
+ Object.freeze({
307
+ act: "spend",
308
+ label: "approve spending money",
309
+ pattern:
310
+ /\b(spend|spending|payments?|pay for|pay (a|an|the)|pay ([a-z0-9]+ ){0,3}fees?|purchase|purchasing|buy|budget approval|credit card|money|paid (plan|tier|seat|account)s?)\b/u,
311
+ }),
312
+ Object.freeze({
313
+ act: "external-account",
314
+ label: "open an external account",
315
+ pattern:
316
+ /\b((open|opening|create|creating|register|registering|sign up for|signing up for)( (a|an|the|new))?( [a-z0-9]+){0,3} accounts?|(vendor|provider|third party|external) accounts?|accounts? in (a|an|the|our) [a-z]+ name|signup)\b/u,
317
+ }),
318
+ Object.freeze({
319
+ act: "legal-signoff",
320
+ label: "give a legal or compliance sign-off",
321
+ pattern:
322
+ /\b(baa|business associate agreement|sign (a|an|the) [a-z ]{0,30}(agreement|contract|baa|dpa)|legal|lawyer|counsel|compliance|regulatory|hipaa|gdpr|soc ?2|contracts?|terms of service|licen[cs]e agreements?|protected (deploy|deployment|environment)s?)\b/u,
323
+ }),
324
+ Object.freeze({
325
+ act: "accountable-person",
326
+ label: "name an accountable person",
327
+ pattern:
328
+ /\b(accountable (person|owner|party)|name (an|the) (owner|approver|accountable)|(owner|approver) who answers|answers for)\b/u,
329
+ }),
330
+ Object.freeze({
331
+ act: "unreachable-system",
332
+ label: "act in a system the agent cannot reach",
333
+ pattern:
334
+ /\b(admin (rights|access|permissions?|role)|grant admin|physically|invite ([a-z]+ ){0,4}to (the |a |our )?([a-z]+ )?(workspace|org|organization|team|repo|repository|project)|add (the |a |our )?(bot|app|agent|integration) to|workspace admin|physical|hardware|on site|in person|unreachable|cannot reach|can ?not reach|cant reach|no access|outside (the )?agent|grant(s|ed|ing)? ([a-z]+ ){0,3}(access|permissions?|roles?)|give (the )?agent ([a-z]+ ){0,3}access|access (the )?agent (lacks|does not have|doesnt have|cannot get)|agent (lacks|does not have|doesnt have) ([a-z]+ ){0,4}access|tool access|missing access|access grant|provision(ing)? access|phone call)\b/u,
335
+ }),
336
+ Object.freeze({
337
+ act: "lisa-policy",
338
+ label: "make a call Lisa's own policy reserves for a person",
339
+ // Lisa's own human-only gates: exploratory-QA findings (the named exception
340
+ // in `ready-role-filing`), learnings promotion/demotion, harness
341
+ // interventions, automation retirement, and a hold the operator explicitly
342
+ // asked for. Each is a gate the factory model places outside the factory.
343
+ pattern:
344
+ /\b(exploratory (finding|qa)|harness intervention|(promot|demot|retir)\w*\b.{0,80}?\b(knowledge|learnings?)|(knowledge|learnings?)\b.{0,80}?\b(promot|demot|retir)\w*|automation retirement|retire (an |the )?automations?|operator (prioriti[sz]ation|requested)|operator (explicitly )?(asked|requested)|explicitly asked for|requested by (the )?operator)\b/u,
345
+ }),
346
+ ]);
347
+
348
+ /**
349
+ * Acts whose keyword alone could be a topic. A slug such as
350
+ * `compliance-dashboard-triage` or `oauth-provider-choice` carries an act
351
+ * keyword but names a decision about a topic, so for these acts a topic word
352
+ * with no act verb beside it is refused. Lisa's own policy gates and
353
+ * project-declared classes are exempt: they are already named decisions.
354
+ */
355
+ const KEYWORD_ACTS = new Set([
356
+ "credential",
357
+ "spend",
358
+ "external-account",
359
+ "legal-signoff",
360
+ "accountable-person",
361
+ "unreachable-system",
362
+ ]);
363
+
364
+ /** Words that mark a reason as being about a topic, not an act. */
365
+ const TOPIC_WORDS =
366
+ /\b(triage|dispatch|naming|rename|choice|choose|design|copy|colou?r|layout|wording|migration|refactor|classification|classify|cleanup|dashboard|page|button|ui|ux|docs?|documentation|schema|decision|selection|split|labels?|error message|policy|strategy|approach|format|field|template|structure|flag|adoption|list|pagination|conversion|settings|framework|pick|banner|placement|table|flow|storage|rotation|scope|folder|report|logging|tests?)\b/u;
367
+
368
+ /** Verbs that say what a person must actually do. */
369
+ const ACT_VERBS =
370
+ /\b(supply|supplies|provide|provides|enter|holds?|held by|approv\w*|sign(s|ed|ing)?|signoff|grant\w*|give|gives|open|opens|register\w*|attest\w*|pay|pays|only (a|the) (person|founder|owner|operator|human|admin)|lacks?|does not have|doesnt have|cannot|can not|physically|in person|on site)\b/u;
371
+
372
+ /** The path a refused gate is pointed at. One string, so writers cannot drift. */
373
+ export const DECIDE_AND_RECORD =
374
+ "This is a decision, not an act a person must perform. Decide and record: " +
375
+ "pick the reasonable default, write the decision on the item (a `Decision:` " +
376
+ "line saying what was chosen and why), and file it with `build_ready: true`.";
377
+
378
+ /**
379
+ * The comparable form of a reason: lower case, slug separators read as spaces.
380
+ * @param {unknown} value - A raw reason, slug, or line of text
381
+ * @returns {string} Normalized text
382
+ */
383
+ export function normalizeGateText(value) {
384
+ return String(value ?? "")
385
+ .toLowerCase()
386
+ .replace(/[-_/]+/gu, " ")
387
+ .replace(/[^a-z0-9' ]+/gu, " ")
388
+ .replace(/'/gu, "")
389
+ .replace(/\s+/gu, " ")
390
+ .trim();
391
+ }
392
+
393
+ /**
394
+ * The project's declared human-only decision classes, normalized.
395
+ * @param {unknown} classes - `humanGate.humanOnly` from config
396
+ * @returns {string[]} Non-empty normalized phrases
397
+ */
398
+ function normalizeClasses(classes) {
399
+ return (Array.isArray(classes) ? classes : [])
400
+ .map(normalizeGateText)
401
+ .filter(phrase => phrase.length > 0);
402
+ }
403
+
404
+ /**
405
+ * Classify a `human_gate` reason.
406
+ * @param {unknown} reason - The reason (slug or prose) a filing gives
407
+ * @param {{ humanOnly?: unknown }} [options] - `humanOnly`: project-declared
408
+ * human-only decision classes (`humanGate.humanOnly`)
409
+ * @returns {{ valid: boolean, act: string | null, label: string | null, matched: string | null, remedy: string | null }} Verdict
410
+ */
411
+ export function classifyHumanGateReason(reason, options = {}) {
412
+ const text = normalizeGateText(reason);
413
+ if (text.length > 0) {
414
+ // The topic veto applies to a SLUG only (one hyphenated token, no spaces).
415
+ // A prose reason describes the act in its own words ("the Stripe API key
416
+ // for the payments dashboard"), and refusing it for mentioning a topic
417
+ // would refuse real acts; a keyword in prose stays accepted, which keeps a
418
+ // hold rather than lifting one.
419
+ const slug = !/\s/u.test(String(reason ?? "").trim());
420
+ const topicOnly = slug && TOPIC_WORDS.test(text) && !ACT_VERBS.test(text);
421
+ for (const entry of HUMAN_GATE_ACTS) {
422
+ const match = entry.pattern.exec(text);
423
+ // A secret is never a topic: a credential match always wins.
424
+ const vetoed =
425
+ topicOnly && entry.act !== "credential" && KEYWORD_ACTS.has(entry.act);
426
+ if (match && !vetoed) {
427
+ return {
428
+ valid: true,
429
+ act: entry.act,
430
+ label: entry.label,
431
+ matched: match[0],
432
+ remedy: null,
433
+ };
434
+ }
435
+ }
436
+ const declared = normalizeClasses(options.humanOnly).find(phrase =>
437
+ ` ${text} `.includes(` ${phrase} `)
438
+ );
439
+ if (declared) {
440
+ return {
441
+ valid: true,
442
+ act: "project-policy",
443
+ label: `make a ${declared} decision this project reserves for a person`,
444
+ matched: declared,
445
+ remedy: null,
446
+ };
447
+ }
448
+ }
449
+ return {
450
+ valid: false,
451
+ act: null,
452
+ label: null,
453
+ matched: null,
454
+ remedy: DECIDE_AND_RECORD,
455
+ };
456
+ }
457
+
458
+ /**
459
+ * Marker on the machine-authored comment that LIFTS an invalid hold.
460
+ *
461
+ * Not a release, and deliberately not spelled like one. A release records a
462
+ * person's answer and so must come from a trusted human. A lift records that
463
+ * the hold was never valid under `ready-role-filing`: it names no act an agent
464
+ * cannot perform, so there is nothing for a person to authorize
465
+ * (CodySwannGT/lisa#4658). Its authority therefore comes from re-classifying
466
+ * the hold, not from who wrote the comment: a lift discharges a reason only
467
+ * while {@link invalidHumanGateHolds} still treats that hold as liftable. A
468
+ * lift naming a valid hold (a credential, spend, a sign-off) discharges
469
+ * nothing, whoever posts it.
470
+ *
471
+ * Like the release marker it closes with its own `]`, so it never contains
472
+ * {@link HUMAN_GATE_MARKER} and never reads as a fresh hold.
473
+ */
474
+ export const HUMAN_GATE_LIFTED_MARKER = "[lisa-human-gate-lifted]";
475
+
476
+ /** Longest slice of any one line the lift rule reads. */
477
+ const HOLD_TEXT_CAP = 2000;
478
+
479
+ /**
480
+ * Tokens that keep a hold no matter how it is worded or laid out.
481
+ *
482
+ * A wrongly kept hold costs one interruption; a wrongly lifted credential hold
483
+ * dispatches work that cannot succeed. So the sweep never lifts an item whose
484
+ * hold text mentions any of these anywhere, even when the reason itself reads
485
+ * as a topic. The list is about safety, not about classification: it is
486
+ * deliberately broader than the act patterns.
487
+ */
488
+ const HOLD_SAFETY_TOKENS =
489
+ /\b(credentials?|passwords?|passphrases?|passcodes?|mfa|2fa|otp|one time codes?|api keys?|keys?|tokens?|secrets?|oauth|sign|signs|signed|signing|signatures?|signoff|sign off|baa|contracts?|agreements?|admin|administrator|access|accounts?|spend\w*|budgets?|payments?|pay|paid|money|purchase|buy|billing|invoice|legal|lawyer|counsel|compliance|regulatory|hipaa|gdpr|soc ?2|physical|hardware|device)\b/u;
490
+
491
+ /**
492
+ * Every line of a body that belongs to a hold: each declaring marker line and
493
+ * each visible "Held for …" line, wherever they sit, plus the nearest
494
+ * non-blank neighbour of each.
495
+ * @param {unknown} body - The item body
496
+ * @returns {string[]} Hold-related lines, each capped
497
+ */
498
+ function holdRelatedLines(body) {
499
+ const lines = declarativeText(body).split("\n");
500
+ const isHoldLine = line =>
501
+ declaresOnLine(line) || /^\s*held for\b/iu.test(line);
502
+ const related = new Set();
503
+ lines.forEach((line, index) => {
504
+ if (!isHoldLine(line)) return;
505
+ related.add(index);
506
+ // The nearest non-blank neighbour on each side, so a hand-written hold
507
+ // that explains itself next to its marker is read too. More text can
508
+ // only keep a hold under this rule, never lift one.
509
+ for (const step of [-1, 1]) {
510
+ let at = index + step;
511
+ while (at >= 0 && at < lines.length && lines[at].trim() === "")
512
+ at += step;
513
+ if (at >= 0 && at < lines.length) related.add(at);
514
+ }
515
+ });
516
+ return (
517
+ [...related]
518
+ .sort((a, b) => a - b)
519
+ // A marker line's own `reason=` slug is judged once, as a slug, by the
520
+ // caller; read as prose here it would dodge the topic veto and re-hold a
521
+ // lifted decision (a `fee-label-copy` slug reading as spend).
522
+ .map(index => lines[index].replace(/reason=\S*/gu, " "))
523
+ .map(line => line.slice(0, HOLD_TEXT_CAP))
524
+ );
525
+ }
526
+
527
+ /**
528
+ * The reasons of every declared hold the sweep may lift.
529
+ *
530
+ * Structural rather than positional, on purpose: layout heuristics (which line
531
+ * is "this hold's" visible line) kept finding layouts that lifted a credential
532
+ * hold. A hold is liftable only when ALL of these hold for the item as a whole:
533
+ *
534
+ * 1. its reason slug classifies as topic-only;
535
+ * 2. no hold-related line (any marker line, any "Held for …" line) names an
536
+ * act, judged one line at a time;
537
+ * 3. no {@link HOLD_SAFETY_TOKENS} token appears anywhere in the reasons or
538
+ * the hold-related lines, judged as one set.
539
+ *
540
+ * Any doubt keeps the hold. A topic hold that shares an item with a real one,
541
+ * or sits beside a line mentioning a budget, stays held; that conservatism is
542
+ * the intended trade.
543
+ * @param {unknown} body - The item body
544
+ * @param {unknown} humanOnly - Project-declared human-only decision classes
545
+ * @returns {string[]} Reason keys whose hold may be lifted
546
+ */
547
+ export function invalidHumanGateHolds(body, humanOnly) {
548
+ const holds = humanGateHolds(body);
549
+ if (holds.length === 0) return [];
550
+ const lines = holdRelatedLines(body);
551
+ const anyLineValid = lines.some(
552
+ line => classifyHumanGateReason(line, { humanOnly }).valid
553
+ );
554
+ const everything = normalizeGateText([...holds, ...lines].join(" "));
555
+ if (anyLineValid || HOLD_SAFETY_TOKENS.test(everything)) return [];
556
+ return holds.filter(
557
+ reason => !classifyHumanGateReason(reason, { humanOnly }).valid
558
+ );
559
+ }
560
+
561
+ /**
562
+ * The reasons a lift comment discharges: named by a lift AND still invalid.
563
+ * @param {unknown} comments - Comments, structured or raw, any author
564
+ * @param {unknown} body - The item body
565
+ * @param {unknown} humanOnly - Project-declared human-only decision classes
566
+ * @returns {string[]} Reason keys lifted
567
+ */
568
+ export function humanGateLifts(comments, body, humanOnly) {
569
+ const invalid = new Set(invalidHumanGateHolds(body, humanOnly));
570
+ const named = (Array.isArray(comments) ? comments : [])
571
+ .map(entry => (typeof entry === "string" ? entry : (entry?.body ?? "")))
572
+ .flatMap(text =>
573
+ declarativeText(text)
574
+ .split("\n")
575
+ .filter(line => declaresOnLine(line, HUMAN_GATE_LIFTED_MARKER))
576
+ .map(line => reasonOnLine(line, HUMAN_GATE_LIFTED_MARKER))
577
+ );
578
+ return [...new Set(named)].filter(reason => invalid.has(reason));
579
+ }
580
+
581
+ /**
582
+ * Normalize stable provider IDs without case folding or trusting display names.
583
+ * @param {unknown} value - Provider actor ID
584
+ * @returns {string} Stable comparison key, or empty when invalid
585
+ */
586
+ function stableActorId(value) {
587
+ if (typeof value === "string") return value.trim();
588
+ return Number.isSafeInteger(value) && value > 0 ? String(value) : "";
589
+ }
590
+
591
+ /**
592
+ * Recognize explicit provider bot metadata even for an allowlisted identity.
593
+ * @param {unknown} actor - Provider or normalized author metadata
594
+ * @returns {boolean} Whether the metadata identifies automation
595
+ */
596
+ function isKnownBot(actor) {
597
+ if (!actor || typeof actor !== "object") return false;
598
+ const kinds = [
599
+ actor.type,
600
+ actor.__typename,
601
+ actor.accountType,
602
+ actor.authorType,
603
+ ];
604
+ return (
605
+ actor.botActor != null ||
606
+ actor.isBot === true ||
607
+ actor.bot === true ||
608
+ kinds.some(kind => /^(?:bot|app)$/i.test(String(kind ?? "").trim()))
609
+ );
610
+ }
611
+
612
+ /**
613
+ * Require authenticated provider identity and separately supplied human trust.
614
+ * Adapters may normalize the ID to authorId, but must preserve bot metadata.
615
+ * Names, body text and self-asserted authorization flags never confer trust.
616
+ * @param {unknown} comment - Structured provider comment
617
+ * @param {ReadonlySet<string>} trustedIds - Explicitly trusted human actor IDs
618
+ * @returns {boolean} Whether the comment may discharge a human hold
619
+ */
620
+ function isTrustedHumanComment(comment, trustedIds) {
621
+ if (!comment || typeof comment !== "object" || Array.isArray(comment))
622
+ return false;
623
+ if ([comment, comment.user, comment.author].some(isKnownBot)) return false;
624
+ const id = stableActorId(
625
+ comment.authorId ??
626
+ comment.user?.id ??
627
+ comment.author?.id ??
628
+ comment.author?.accountId
629
+ );
630
+ return id.length > 0 && trustedIds.has(id);
631
+ }
632
+
633
+ /**
634
+ * The reason keys released by explicitly trusted human authors, deduplicated.
635
+ *
636
+ * Comments must retain authenticated provider authorship: normalized authorId,
637
+ * user.id, author.id or author.accountId. The caller supplies trusted human IDs
638
+ * independently of comment content. Raw strings, missing IDs, known bots and
639
+ * an absent or empty allowlist fail closed and cannot discharge a hold.
640
+ * @param {unknown} comments - Structured comments, any order
641
+ * @param {unknown} trustedHumanActorIds - Explicit trusted human provider IDs
642
+ * @returns {string[]} One key per authorized recorded release
643
+ */
644
+ export function humanGateReleases(comments, trustedHumanActorIds = []) {
645
+ const trustedIds = new Set(
646
+ (Array.isArray(trustedHumanActorIds) ? trustedHumanActorIds : [])
647
+ .map(stableActorId)
648
+ .filter(Boolean)
649
+ );
650
+ const bodies = (Array.isArray(comments) ? comments : [])
651
+ .filter(entry => isTrustedHumanComment(entry, trustedIds))
652
+ .map(entry => entry.body ?? "");
653
+ const keys = bodies.flatMap(body =>
654
+ declarativeText(body)
655
+ .split("\n")
656
+ .filter(line => declaresOnLine(line, HUMAN_GATE_RELEASE_MARKER))
657
+ .map(line => reasonOnLine(line, HUMAN_GATE_RELEASE_MARKER))
658
+ );
659
+ return [...new Set(keys)];
660
+ }
661
+
662
+ /**
663
+ * Whether every hold on this item has a release recorded against it.
664
+ *
665
+ * Matching is per-reason on purpose. A blanket "any release clears everything"
666
+ * rule would make a hold declared AFTER a release be born discharged, which is
667
+ * the unsafe direction — the one this fix must not introduce while correcting
668
+ * the safe one. An item with no declared body hold is discharged only by a
669
+ * keyless release, which is the form that pairs with a label-only hold.
670
+ * @param {{ body?: unknown, comments?: unknown, trustedHumanActorIds?: unknown }} input - The item's surfaces
671
+ * @returns {boolean} True when nothing is left outstanding
672
+ */
673
+ export function humanGateDischarged(input = {}) {
674
+ const released = new Set(
675
+ humanGateReleases(input.comments, input.trustedHumanActorIds)
676
+ );
677
+ const holds = humanGateHolds(input.body);
678
+ if (holds.length === 0) return released.has("");
679
+ return holds.every(reason => released.has(reason));
680
+ }
681
+
682
+ /**
683
+ * The full held-ness verdict for an item, on every surface that carries a hold.
684
+ *
685
+ * Split out of {@link isHumanGated} because the release path needs to know more
686
+ * than yes-or-no: whether a hold existed at all, which reasons are still
687
+ * outstanding, and whether the durable label needs removing. A caller that only
688
+ * wants the boolean still gets exactly the boolean.
689
+ *
690
+ * The label is treated as a MIRROR of a declared body hold, never as a second
691
+ * independent hold, because that is how it is written: the vendor writers stamp
692
+ * both surfaces for one hold, and `planHumanGateReconciliation` adds the label
693
+ * to an item already carrying the marker. Counting it separately would leave
694
+ * every mirrored hold permanently outstanding under a keyed release — the exact
695
+ * defect this function exists to end, one layer down. Only when the body
696
+ * declares nothing does the label stand as a hold in its own right, and then it
697
+ * is a keyless one.
698
+ *
699
+ * Fails CLOSED on an unreadable discharge: with no comments supplied there are
700
+ * no releases, so a held item stays held. Holding a gate that may be stale
701
+ * beats releasing one that is not, and every caller that never passes comments
702
+ * keeps its current behaviour by construction.
703
+ * @param {{ labels?: unknown, body?: unknown, comments?: unknown, trustedHumanActorIds?: unknown, humanNeededLabel?: unknown, humanOnly?: unknown }} input - Candidate surfaces
704
+ * @returns {{ held: boolean, reason: string, declared: number, outstanding: string[], released: string[], lifted: string[], labelPresent: boolean }} Held-ness verdict
705
+ */
706
+ export function humanGateVerdict(input = {}) {
707
+ const configured = String(
708
+ input.humanNeededLabel ?? DEFAULT_HUMAN_NEEDED_LABEL
709
+ )
710
+ .trim()
711
+ .toLowerCase();
712
+ const labelPresent =
713
+ configured.length > 0 && normalizeLabels(input.labels).includes(configured);
714
+ const released = humanGateReleases(
715
+ input.comments,
716
+ input.trustedHumanActorIds
717
+ );
718
+ const releasedSet = new Set(released);
719
+ const holds = humanGateHolds(input.body);
720
+ // A lift discharges only a declared body hold that is still invalid; it can
721
+ // never discharge a label-only hold (access blocks, blocked verdicts), which
722
+ // is why it is applied here and not in the label-only branch below.
723
+ const lifted = humanGateLifts(input.comments, input.body, input.humanOnly);
724
+ const liftedSet = new Set(lifted);
725
+ const outstanding = holds.filter(
726
+ reason => !releasedSet.has(reason) && !liftedSet.has(reason)
727
+ );
728
+ const base = {
729
+ declared: holds.length,
730
+ released,
731
+ lifted,
732
+ labelPresent,
733
+ };
734
+
735
+ if (outstanding.length > 0) {
736
+ return { held: true, reason: "hold-outstanding", outstanding, ...base };
737
+ }
738
+ if (holds.length > 0) {
739
+ return { held: false, reason: "hold-released", outstanding: [], ...base };
740
+ }
741
+ if (labelPresent) {
742
+ return releasedSet.has("")
743
+ ? { held: false, reason: "hold-released", outstanding: [], ...base }
744
+ : { held: true, reason: "hold-outstanding", outstanding: [""], ...base };
745
+ }
746
+
747
+ return { held: false, reason: "no-hold", outstanding: [], ...base };
748
+ }
749
+
750
+ /**
751
+ * Whether an item is held for a person, on either surface.
752
+ *
753
+ * Exported deliberately, and it is the ONLY answer to that question anywhere in
754
+ * the intake machinery. Every selection and promotion path calls this rather
755
+ * than inspecting labels itself, because the label surface alone is a partial
756
+ * answer: the vendor writers stamp the body marker on a deliberate hold, so an
757
+ * item held exactly as the filing contract instructs carries no label at all.
758
+ * A path that read labels alone judged such an item unheld and promoted it —
759
+ * which is #3805, and is why this is a shared function rather than a shared
760
+ * convention.
761
+ *
762
+ * It is also the only place a hold ENDS, which is why the release lives behind
763
+ * the same call rather than beside it: a reader that could see the hold but not
764
+ * its discharge is how the gate became one-way in the first place. Pass the
765
+ * item's structured comments and trustedHumanActorIds to honor an authorized
766
+ * release; omit either and the item stays held.
767
+ * @param {{ labels?: unknown, body?: unknown, comments?: unknown, trustedHumanActorIds?: unknown, humanNeededLabel?: unknown, humanOnly?: unknown }} input - Candidate surfaces
768
+ * @returns {boolean} True when a person is holding this item
769
+ */
770
+ export function isHumanGated(input) {
771
+ return humanGateVerdict(input).held;
772
+ }
773
+
774
+ /**
775
+ * @param {unknown} value
776
+ * @returns {string}
777
+ */
778
+ function trimmedString(value) {
779
+ return typeof value === "string" ? value.trim() : "";
780
+ }
781
+
782
+ /**
783
+ * @param {{ discharged?: unknown, evidence?: unknown }} probe
784
+ * @returns {{ selectable: boolean, reason: string, evidence: string }}
785
+ */
786
+ function judgeProbe(probe) {
787
+ const evidence = trimmedString(probe.evidence);
788
+
789
+ if (probe.discharged !== true) {
790
+ return {
791
+ selectable: false,
792
+ reason: "blocker-holds",
793
+ evidence,
794
+ };
795
+ }
796
+ if (evidence.length === 0) {
797
+ return {
798
+ selectable: false,
799
+ reason: "blocker-discharge-unevidenced",
800
+ evidence,
801
+ };
802
+ }
803
+
804
+ return { selectable: true, reason: "blocker-discharged", evidence };
805
+ }
806
+
807
+ /**
808
+ * Decide whether a pre-work item may be selected as a build candidate.
809
+ *
810
+ * Order is load-bearing. The human gate is checked before anything else, so no
811
+ * probe result — however conclusive — can promote an item a human parked.
812
+ *
813
+ * @param {{
814
+ * laneType?: unknown
815
+ * labels?: unknown
816
+ * body?: unknown
817
+ * comments?: unknown
818
+ * trustedHumanActorIds?: unknown
819
+ * humanNeededLabel?: unknown
820
+ * humanOnly?: unknown
821
+ * statedBlocker?: unknown
822
+ * probe?: { discharged?: unknown, evidence?: unknown } | null
823
+ * }} input
824
+ * @returns {{ selectable: boolean, reason: string, humanGated: boolean, evidence: string }}
825
+ */
826
+ export function classifyPreWorkCandidate(input = {}) {
827
+ if (isHumanGated(input)) {
828
+ return {
829
+ selectable: false,
830
+ reason: "human-gate",
831
+ humanGated: true,
832
+ evidence: "",
833
+ };
834
+ }
835
+ if (!isPreWorkLaneType(input.laneType)) {
836
+ return {
837
+ selectable: false,
838
+ reason: "not-pre-work",
839
+ humanGated: false,
840
+ evidence: "",
841
+ };
842
+ }
843
+ if (trimmedString(input.statedBlocker).length === 0) {
844
+ return {
845
+ selectable: true,
846
+ reason: "no-blocker",
847
+ humanGated: false,
848
+ evidence: "",
849
+ };
850
+ }
851
+ if (!input.probe || typeof input.probe !== "object") {
852
+ return {
853
+ selectable: false,
854
+ reason: "blocker-unprobed",
855
+ humanGated: false,
856
+ evidence: "",
857
+ };
858
+ }
859
+
860
+ return { ...judgeProbe(input.probe), humanGated: false };
861
+ }
862
+
863
+ /** Plain-English wording for each verdict, for the note left on the item. */
864
+ const REASON_COPY = Object.freeze({
865
+ "human-gate": "A person parked this one on purpose, so intake left it alone.",
866
+ "not-pre-work": "This item is not sitting in a not-yet-started lane.",
867
+ "no-blocker": "No blocker was written on this item, so it is buildable.",
868
+ "blocker-unprobed":
869
+ "This item states a blocker that was not re-checked this cycle, so it stays put.",
870
+ "blocker-holds":
871
+ "The blocker was re-checked and still holds, so it stays put.",
872
+ "blocker-discharge-unevidenced":
873
+ "The blocker looked clear but no proof was recorded, so it stays put.",
874
+ "blocker-discharged":
875
+ "The blocker was re-checked and no longer applies, so this item is buildable again.",
876
+ });
877
+
878
+ /**
879
+ * Render the re-probe result to leave on the item, so the next cycle reads the
880
+ * answer instead of deriving it again.
881
+ *
882
+ * @param {{
883
+ * statedBlocker?: unknown
884
+ * checkedAt?: string | Date
885
+ * }} candidate
886
+ * @param {{ reason: string, evidence?: string }} verdict
887
+ * @returns {string}
888
+ */
889
+ export function formatReprobeNote(candidate = {}, verdict) {
890
+ const checkedAt =
891
+ candidate.checkedAt instanceof Date
892
+ ? candidate.checkedAt.toISOString()
893
+ : trimmedString(candidate.checkedAt) || new Date().toISOString();
894
+ const lines = [
895
+ "**Blocker re-check**",
896
+ "",
897
+ `- What has to be true: ${trimmedString(candidate.statedBlocker) || "(none written on this item)"}`,
898
+ `- What we found: ${REASON_COPY[verdict.reason] ?? verdict.reason}`,
899
+ ];
900
+ const evidence = trimmedString(verdict.evidence);
901
+ if (evidence.length > 0) {
902
+ lines.push(`- Proof: ${evidence}`);
903
+ }
904
+ lines.push(`- Checked at: ${checkedAt}`);
905
+
906
+ return lines.join("\n");
907
+ }
908
+
909
+ /**
910
+ * Marker on the note this module leaves, so a later cycle recognises its own
911
+ * work instead of commenting again.
912
+ */
913
+ export const HUMAN_GATE_NOTE_MARKER = "<!-- [lisa-human-gate-reconciled] -->";
914
+
915
+ /**
916
+ * Decide whether a candidate ALREADY IN THE READY LANE may be claimed.
917
+ *
918
+ * `classifyPreWorkCandidate` was the only caller of the human-gate test, and it
919
+ * runs on candidates outside the ready lane. An item that reached the ready
920
+ * lane was therefore claimed with the gate never consulted — the check was
921
+ * correct and simply unreachable from the path that matters.
922
+ *
923
+ * This shares `isHumanGated` with the pre-work classifier deliberately. Two
924
+ * copies of a substring test drift, and a drifted gate fails silently: it stops
925
+ * matching, and nothing reports that it stopped.
926
+ *
927
+ * The test stays a plain literal-substring match and is NOT keyed on `reason=`.
928
+ * Markers in the wild carry no `reason=` at all and sit anywhere in the body, so
929
+ * a parser keyed on the structured field would miss those while appearing to
930
+ * work on every item that happens to have one — reproducing this defect one
931
+ * layer down.
932
+ * @param {{ labels?: unknown, body?: unknown, comments?: unknown, trustedHumanActorIds?: unknown, humanNeededLabel?: unknown, humanOnly?: unknown }} input - Candidate surfaces
933
+ * @returns {{ claimable: boolean, reason: string, humanGated: boolean }} Claim verdict
934
+ */
935
+ export function classifyReadyCandidate(input = {}) {
936
+ if (isHumanGated(input)) {
937
+ return { claimable: false, reason: "human-gate", humanGated: true };
938
+ }
939
+ return { claimable: true, reason: "ready-eligible", humanGated: false };
940
+ }
941
+
942
+ /**
943
+ * Plan the state repair for a ready-lane item that is held for a person.
944
+ *
945
+ * Skipping such an item is not enough. `lisa-repair-intake` sweeps items that
946
+ * are NOT in the ready role and excludes gated ones outright, so a ready AND
947
+ * gated item falls outside its filter twice over. Skipping alone would leave it
948
+ * re-evaluated and re-rejected every cycle forever, seen by nothing — trading a
949
+ * loud failure for a silent one.
950
+ *
951
+ * So the lane is reconciled to match the hold: the item leaves the pickup queue
952
+ * and gains the human-needed marker. That is the same repair the leaf-only gate
953
+ * already performs for a ready item that must not be dispatched.
954
+ *
955
+ * Idempotent by state rather than by memory: an item already out of the queue
956
+ * and already marked needs nothing, so asking twice yields no second mutation.
957
+ * @param {{
958
+ * labels?: unknown
959
+ * body?: unknown
960
+ * comments?: unknown
961
+ * trustedHumanActorIds?: unknown
962
+ * humanNeededLabel?: unknown
963
+ * humanOnly?: unknown
964
+ * readyLabel?: unknown
965
+ * alreadyNotified?: unknown
966
+ * }} input - Candidate surfaces plus the configured lane and marker labels
967
+ * @returns {{ gated: boolean, reason: string, actions: { removeReadyRole: boolean, addHumanNeededLabel: boolean, comment: boolean } }} Repair plan
968
+ */
969
+ export function planHumanGateReconciliation(input = {}) {
970
+ const idle = Object.freeze({
971
+ removeReadyRole: false,
972
+ addHumanNeededLabel: false,
973
+ comment: false,
974
+ });
975
+ if (!isHumanGated(input)) {
976
+ return { gated: false, reason: "not-gated", actions: idle };
977
+ }
978
+
979
+ const labels = normalizeLabels(input.labels);
980
+ const needed = String(input.humanNeededLabel ?? DEFAULT_HUMAN_NEEDED_LABEL)
981
+ .trim()
982
+ .toLowerCase();
983
+ const ready = String(input.readyLabel ?? "")
984
+ .trim()
985
+ .toLowerCase();
986
+ const inReadyLane = ready.length > 0 && labels.includes(ready);
987
+ const marked = needed.length > 0 && labels.includes(needed);
988
+ const actions = {
989
+ removeReadyRole: inReadyLane,
990
+ addHumanNeededLabel: needed.length > 0 && !marked,
991
+ comment:
992
+ input.alreadyNotified !== true &&
993
+ (inReadyLane || (needed.length > 0 && !marked)),
994
+ };
995
+ const changed =
996
+ actions.removeReadyRole || actions.addHumanNeededLabel || actions.comment;
997
+
998
+ return {
999
+ gated: true,
1000
+ reason: changed ? "reconcile" : "already-reconciled",
1001
+ actions,
1002
+ };
1003
+ }
1004
+
1005
+ /**
1006
+ * Marker on the note the release path leaves, so a later cycle recognises its
1007
+ * own work instead of commenting again.
1008
+ *
1009
+ * A superstring of neither declaration marker, for the reason
1010
+ * {@link HUMAN_GATE_RELEASE_MARKER} gives: a note ABOUT a release must not read
1011
+ * as a release, or the note announcing one item's discharge would discharge
1012
+ * every item it names.
1013
+ */
1014
+ export const HUMAN_GATE_RELEASE_NOTE_MARKER =
1015
+ "<!-- [lisa-human-gate-released] -->";
1016
+
1017
+ /**
1018
+ * The one sentence every hold note gives an operator to END the hold.
1019
+ *
1020
+ * One constant, two notes, because the instruction IS the release path as far
1021
+ * as the person reading it is concerned. Two copies of it drift, and a drifted
1022
+ * instruction sends someone to a mechanism that no longer exists — which is
1023
+ * worse than the prose it replaced, since that at least described something
1024
+ * real. It names a comment because the alternative it replaces — "remove the
1025
+ * hold note from the description" — asks for a whole-body rewrite the tooling
1026
+ * has no safe way to perform.
1027
+ */
1028
+ const RESUME_INSTRUCTION = [
1029
+ "- To resume it: leave a comment on this item that starts with ",
1030
+ HUMAN_GATE_RELEASE_MARKER,
1031
+ " and repeats the reason the hold in the description names. The next sweep ",
1032
+ "puts it back in the queue on its own. Nothing else has to change — do not ",
1033
+ "edit the description, and do not move it by hand.",
1034
+ ].join("");
1035
+
1036
+ /**
1037
+ * Plan the state repair for an item whose hold has been discharged.
1038
+ *
1039
+ * The exact inverse of {@link planHumanGateReconciliation}, and deliberately
1040
+ * the same shape: that one takes the ready role away and adds the marker label,
1041
+ * this one takes the marker label away and puts the ready role back. A state
1042
+ * change with no inverse is the defect class this pair exists to close
1043
+ * (`state-changes-without-inverses`), and an inverse that is merely *possible*
1044
+ * is not one — it has to sit on a path something actually runs, which is why
1045
+ * this is a planner the intake sweeps call rather than an instruction to an
1046
+ * operator.
1047
+ *
1048
+ * Two refusals are load-bearing:
1049
+ *
1050
+ * - **A still-held item plans nothing.** Every outstanding reason holds the
1051
+ * whole item, so an item whose second hold has not been answered is not
1052
+ * half-released.
1053
+ * - **An item that was never held plans nothing.** Without that, this would be
1054
+ * a path that adds the build-ready role to arbitrary items — a promotion
1055
+ * mechanism wearing a release mechanism's name.
1056
+ *
1057
+ * The ready role is restored only when the item carries none of the configured
1058
+ * lifecycle labels, mirroring {@link planLabelNormalization}. An item that was
1059
+ * held and has since reached a terminal lane must not be dragged back to the
1060
+ * queue by its own release.
1061
+ *
1062
+ * Idempotent by state rather than by memory: an item already unmarked and
1063
+ * already back in the queue needs nothing, so asking twice yields no second
1064
+ * mutation.
1065
+ * @param {{
1066
+ * labels?: unknown
1067
+ * body?: unknown
1068
+ * comments?: unknown
1069
+ * trustedHumanActorIds?: unknown
1070
+ * humanNeededLabel?: unknown
1071
+ * humanOnly?: unknown
1072
+ * readyLabel?: unknown
1073
+ * lifecycleLabels?: unknown
1074
+ * alreadyNotified?: unknown
1075
+ * }} input - Candidate surfaces plus the configured lane vocabulary
1076
+ * @returns {{ released: boolean, reason: string, discharged: string[], actions: { removeHumanNeededLabel: boolean, addReadyLabel: string | null, comment: boolean } }} Release plan
1077
+ */
1078
+ export function planHumanGateRelease(input = {}) {
1079
+ const idle = Object.freeze({
1080
+ removeHumanNeededLabel: false,
1081
+ addReadyLabel: null,
1082
+ comment: false,
1083
+ });
1084
+ const verdict = humanGateVerdict(input);
1085
+ if (verdict.held) {
1086
+ return {
1087
+ released: false,
1088
+ reason: "hold-outstanding",
1089
+ discharged: [],
1090
+ actions: idle,
1091
+ };
1092
+ }
1093
+ if (verdict.declared === 0 && !verdict.labelPresent) {
1094
+ return {
1095
+ released: false,
1096
+ reason: "no-hold",
1097
+ discharged: [],
1098
+ actions: idle,
1099
+ };
1100
+ }
1101
+
1102
+ const needed = String(input.humanNeededLabel ?? DEFAULT_HUMAN_NEEDED_LABEL)
1103
+ .trim()
1104
+ .toLowerCase();
1105
+ // The marker label is excluded from the lane test on both sides. It is one of
1106
+ // the configured lifecycle labels AND it is the label this plan removes, so
1107
+ // counting it would let the hold's own marker prove the item is already in a
1108
+ // lane and veto the restoration — the release would clear the flag and leave
1109
+ // the item in no queue at all, which is the original defect with one fewer
1110
+ // symptom.
1111
+ const labels = normalizeLabels(input.labels).filter(name => name !== needed);
1112
+ const lifecycle = normalizeLabels(input.lifecycleLabels).filter(
1113
+ name => name !== needed
1114
+ );
1115
+ const ready = trimmedString(input.readyLabel);
1116
+ const inLifecycle = lifecycle.some(name => labels.includes(name));
1117
+ const addReadyLabel =
1118
+ ready.length > 0 && !inLifecycle && !labels.includes(ready.toLowerCase())
1119
+ ? ready
1120
+ : null;
1121
+ const actions = {
1122
+ removeHumanNeededLabel: verdict.labelPresent,
1123
+ addReadyLabel,
1124
+ comment:
1125
+ input.alreadyNotified !== true &&
1126
+ (verdict.labelPresent || addReadyLabel !== null),
1127
+ };
1128
+ const changed =
1129
+ actions.removeHumanNeededLabel || addReadyLabel !== null || actions.comment;
1130
+
1131
+ return {
1132
+ released: true,
1133
+ reason: changed ? "release" : "already-released",
1134
+ discharged: verdict.released,
1135
+ actions,
1136
+ };
1137
+ }
1138
+
1139
+ /**
1140
+ * Render the discharge record a person or a skill leaves to END a hold.
1141
+ *
1142
+ * Generated rather than retyped, because the release names the hold it ends by
1143
+ * its reason and a mistyped reason discharges nothing while looking like it
1144
+ * did. The reason is echoed verbatim from the hold, so the pairing is visible
1145
+ * to a reader as well as to the matcher.
1146
+ * @param {{ reason?: unknown, decidedBy?: unknown, decision?: unknown }} discharge - What was decided, and by whom
1147
+ * @returns {string} Comment body carrying the release marker
1148
+ */
1149
+ export function formatHumanGateRelease(discharge = {}) {
1150
+ const reason = trimmedString(discharge.reason);
1151
+ const declaration =
1152
+ reason.length > 0
1153
+ ? `${HUMAN_GATE_RELEASE_MARKER} ${REASON_KEY}${reason}`
1154
+ : HUMAN_GATE_RELEASE_MARKER;
1155
+ const lines = [declaration, "", "**The hold on this item is lifted.**", ""];
1156
+ lines.push(
1157
+ `- What was being asked: ${reason.length > 0 ? reason : "(the hold named no reason)"}`
1158
+ );
1159
+ const decision = trimmedString(discharge.decision);
1160
+ if (decision.length > 0) lines.push(`- What was decided: ${decision}`);
1161
+ const decidedBy = trimmedString(discharge.decidedBy);
1162
+ if (decidedBy.length > 0) lines.push(`- Decided by: ${decidedBy}`);
1163
+ lines.push(
1164
+ "- What happens next: this item goes back into the queue that agents build from."
1165
+ );
1166
+
1167
+ return lines.join("\n");
1168
+ }
1169
+
1170
+ /**
1171
+ * Render the notice for an item this sweep released.
1172
+ *
1173
+ * Distinct from {@link formatHumanGateNote} for the same reason
1174
+ * {@link formatNormalizationHoldNote} is: the two report opposite events, and
1175
+ * reusing one to report the other tells an operator the wrong thing happened.
1176
+ * @returns {string} Comment body, carrying the marker that keeps a re-run quiet
1177
+ */
1178
+ export function formatHumanGateReleaseNote() {
1179
+ return [
1180
+ "**Back in the queue: the hold was answered**",
1181
+ "",
1182
+ "- What was found: this item was being held for a person, and the " +
1183
+ "decision it was waiting for has since been recorded on it.",
1184
+ "- What changed: the hold flag has been taken off and the item has been " +
1185
+ "put back into the queue that agents build from.",
1186
+ "- Nothing was rewritten: the description is exactly as it was, hold note " +
1187
+ "and all, so the history of why it was held stays readable.",
1188
+ "",
1189
+ HUMAN_GATE_RELEASE_NOTE_MARKER,
1190
+ ].join("\n");
1191
+ }
1192
+
1193
+ /**
1194
+ * Marker on the note the normalization sweep leaves, so a later cycle
1195
+ * recognises its own work instead of commenting again.
1196
+ *
1197
+ * Deliberately NOT the hold marker and deliberately not a superstring of it:
1198
+ * `HUMAN_GATE_MARKER` closes with `]`, so neither this nor
1199
+ * `HUMAN_GATE_NOTE_MARKER` matches it. A note that read as a hold declaration
1200
+ * would make every reported item look held to the next body-reading sweep,
1201
+ * including items the report merely names.
1202
+ */
1203
+ export const NORMALIZATION_HOLD_NOTE_MARKER =
1204
+ "<!-- [lisa-human-gate-normalization-held] -->";
1205
+
1206
+ /**
1207
+ * Decide whether an item carrying NO configured lifecycle label may be
1208
+ * normalized into a ready lane.
1209
+ *
1210
+ * This is the promotion path, and it was keyed on labels alone. The configured
1211
+ * `human_needed` label is one of the lifecycle labels whose *absence* the sweep
1212
+ * enumerates on, so an item held only by the body marker was a member of the
1213
+ * swept population by definition and got the build-ready label applied to it.
1214
+ * The `[lisa-human-gate]` exclusion existed, in a different and read-only sweep
1215
+ * further down the same contract: the one sweep that writes was the one that
1216
+ * could not see the marker.
1217
+ *
1218
+ * Order is load-bearing for the same reason it is in `classifyPreWorkCandidate`:
1219
+ * the hold is checked before lane membership and before any classification, so
1220
+ * nothing downstream — however confident — can promote an item a person parked.
1221
+ *
1222
+ * On a match this plans NO write of its own. `planHumanGateReconciliation`
1223
+ * turns a match into durable state, so a false positive there latches and every
1224
+ * later cycle agrees with the first. The gate test is a plain substring match
1225
+ * whose imprecision is tracked separately, so this path refuses and reports
1226
+ * read-only instead — the same treatment the ungated-filing sweep already gives
1227
+ * a hold it finds.
1228
+ * @param {{
1229
+ * labels?: unknown
1230
+ * body?: unknown
1231
+ * comments?: unknown
1232
+ * trustedHumanActorIds?: unknown
1233
+ * humanNeededLabel?: unknown
1234
+ * humanOnly?: unknown
1235
+ * lifecycleLabels?: unknown
1236
+ * readyLabel?: unknown
1237
+ * }} input - Candidate surfaces plus the configured lifecycle vocabulary
1238
+ * @returns {{ normalize: boolean, reason: string, humanGated: boolean, actions: { addReadyLabel: string | null, reportHold: boolean } }} Normalization plan
1239
+ */
1240
+ export function planLabelNormalization(input = {}) {
1241
+ const idle = Object.freeze({ addReadyLabel: null, reportHold: false });
1242
+ if (isHumanGated(input)) {
1243
+ return {
1244
+ normalize: false,
1245
+ reason: "human-gate",
1246
+ humanGated: true,
1247
+ actions: Object.freeze({ addReadyLabel: null, reportHold: true }),
1248
+ };
1249
+ }
1250
+
1251
+ const labels = normalizeLabels(input.labels);
1252
+ if (normalizeLabels(input.lifecycleLabels).some(l => labels.includes(l))) {
1253
+ return {
1254
+ normalize: false,
1255
+ reason: "already-in-lifecycle",
1256
+ humanGated: false,
1257
+ actions: idle,
1258
+ };
1259
+ }
1260
+
1261
+ const ready = trimmedString(input.readyLabel);
1262
+ if (ready.length === 0) {
1263
+ return {
1264
+ normalize: false,
1265
+ reason: "no-ready-label",
1266
+ humanGated: false,
1267
+ actions: idle,
1268
+ };
1269
+ }
1270
+
1271
+ return {
1272
+ normalize: true,
1273
+ reason: "normalize",
1274
+ humanGated: false,
1275
+ actions: Object.freeze({ addReadyLabel: ready, reportHold: false }),
1276
+ };
1277
+ }
1278
+
1279
+ /**
1280
+ * Render the notice for an item the normalization sweep left alone.
1281
+ *
1282
+ * Distinct from `formatHumanGateNote` because the two say opposite things
1283
+ * about what happened: that one reports a lane that WAS changed, this one
1284
+ * reports a promotion that was declined and nothing else. Reusing it would tell
1285
+ * an operator their item had been moved when it had not.
1286
+ * @returns {string} Comment body, carrying the marker that keeps a re-run quiet
1287
+ */
1288
+ export function formatNormalizationHoldNote() {
1289
+ return [
1290
+ "**Left alone: a person is holding this**",
1291
+ "",
1292
+ "- What was found: the description says a person is holding this one, so " +
1293
+ "it was not put into the queue that agents work from.",
1294
+ "- What changed: nothing at all. It was left exactly as it is, and " +
1295
+ "nothing will pick it up on its own.",
1296
+ RESUME_INSTRUCTION,
1297
+ "",
1298
+ NORMALIZATION_HOLD_NOTE_MARKER,
1299
+ ].join("\n");
1300
+ }
1301
+
1302
+ /**
1303
+ * Render the hold notice for a reader who does not know this subsystem.
1304
+ *
1305
+ * Written for a non-technical operator on purpose — that is who stands at this
1306
+ * gate. It names what was found, what changed, and how to undo it, and uses no
1307
+ * skill name, label syntax, or phase number, none of which a reader can act on.
1308
+ * @returns {string} Comment body, carrying the marker that keeps a re-run quiet
1309
+ */
1310
+ export function formatHumanGateNote() {
1311
+ return [
1312
+ "**On hold for a person**",
1313
+ "",
1314
+ "- What was found: this item is marked as held for a person, but it was " +
1315
+ "also sitting in the queue that agents build from — so it would have " +
1316
+ "been picked up and built anyway.",
1317
+ "- What changed: it has been taken out of that queue and flagged as " +
1318
+ "needing a person, so nothing will build it automatically.",
1319
+ RESUME_INSTRUCTION,
1320
+ "",
1321
+ HUMAN_GATE_NOTE_MARKER,
1322
+ ].join("\n");
1323
+ }
1324
+
1325
+ /**
1326
+ * Render the cycle-summary line naming what was held.
1327
+ *
1328
+ * A lane mutation nobody can see afterwards is the same class of problem as the
1329
+ * one this fixes, so the run says what it moved — and it keeps "nothing was
1330
+ * eligible" distinguishable from "something eligible was held".
1331
+ * @param {readonly unknown[]} held - Item references held this cycle
1332
+ * @returns {string} One summary line
1333
+ */
1334
+ /**
1335
+ * Render the cycle-summary line naming what the precision rule DEMOTED.
1336
+ *
1337
+ * The counterpart of {@link summarizeHumanGateHolds}, and it exists for the
1338
+ * same reason: a mutation nobody can see afterwards is the problem this whole
1339
+ * area keeps having. A rule that quietly declines to honour half the marker
1340
+ * occurrences it sees reads exactly like a rule that saw none, so the count is
1341
+ * printed even when it is zero — measured across this repository's matching
1342
+ * bodies, 33 of 62 occurrences are mentions rather than declarations.
1343
+ * @param {unknown} demoted - How many occurrences were mentions, not declarations
1344
+ * @returns {string} One summary line
1345
+ */
1346
+ export function summarizeHumanGateMentions(demoted = 0) {
1347
+ const count = Number.isFinite(Number(demoted))
1348
+ ? Math.trunc(Number(demoted))
1349
+ : 0;
1350
+ const shown = count > 0 ? String(count) : "none";
1351
+ return `Marker mentions demoted (not declarations): ${shown}.`;
1352
+ }
1353
+
1354
+ export function summarizeHumanGateHolds(held = []) {
1355
+ const names = (Array.isArray(held) ? held : [])
1356
+ .map(item => trimmedString(item))
1357
+ .filter(name => name.length > 0);
1358
+ if (names.length === 0) return "Held for a person: none.";
1359
+ return `Held for a person (${String(names.length)}): ${names.join(", ")}.`;
1360
+ }
1361
+
1362
+ /**
1363
+ * Render the cycle-summary line naming what was RELEASED.
1364
+ *
1365
+ * The counterpart of {@link summarizeHumanGateHolds}, printed even when it is
1366
+ * zero. Without it a release path that has stopped working is indistinguishable
1367
+ * from a cycle where nothing needed releasing — which is exactly how the
1368
+ * missing inverse went unnoticed for as long as it did, and a fix that cannot
1369
+ * be observed to fire is a fix nobody can tell has regressed.
1370
+ * @param {readonly unknown[]} released - Item references released this cycle
1371
+ * @returns {string} One summary line
1372
+ */
1373
+ export function summarizeHumanGateReleases(released = []) {
1374
+ const names = (Array.isArray(released) ? released : [])
1375
+ .map(item => trimmedString(item))
1376
+ .filter(name => name.length > 0);
1377
+ if (names.length === 0) return "Released back to the queue: none.";
1378
+ return `Released back to the queue (${String(names.length)}): ${names.join(", ")}.`;
1379
+ }