@event4u/agent-config 14.22.0 → 14.23.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 (111) hide show
  1. package/.augment-plugin/marketplace.json +3 -3
  2. package/.augment-plugin/plugin.json +1 -1
  3. package/.claude-plugin/marketplace.json +1 -1
  4. package/CHANGELOG.md +159 -380
  5. package/README.md +1 -1
  6. package/dist/agent-src/commands/pr/merge.md +47 -38
  7. package/dist/agent-src/commands/roadmap/next.md +8 -0
  8. package/dist/agent-src/contexts/execution/autonomy-mechanics.md +12 -0
  9. package/dist/agent-src/rules/notes-first-reasoning.md +36 -25
  10. package/dist/agent-src/scripts/archive_completed_roadmaps.ts +106 -4
  11. package/dist/agent-src/skills/code-intelligence/SKILL.md +57 -1
  12. package/dist/agent-src/skills/git-workflow/references/push-closes-its-loop.md +9 -0
  13. package/dist/agent-src/skills/tailwind-engineer/SKILL.md +52 -2
  14. package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
  15. package/dist/cli/registry.js +1 -1
  16. package/dist/cli-delegate/archive_completed_roadmaps.js +52 -4
  17. package/dist/cli-delegate/{chunk-TGIPZBCW.js → chunk-2KKXJW25.js} +22 -8
  18. package/dist/cli-delegate/{chunk-4FS4WRXP.js → chunk-IAI3XL43.js} +15 -3
  19. package/dist/cli-delegate/{chunk-BIXEDQPZ.js → chunk-KCNTUSPI.js} +1 -1
  20. package/dist/cli-delegate/cmd_export.js +2 -2
  21. package/dist/cli-delegate/cmd_handoff.js +20 -12
  22. package/dist/cli-delegate/cmd_prune.js +2 -2
  23. package/dist/cli-delegate/cmd_session_recycle.js +3 -13
  24. package/dist/cli-delegate/cmd_settings_migrate.js +2 -2
  25. package/dist/cli-delegate/cmd_settings_set.js +1 -1
  26. package/dist/cli-delegate/cmd_sync.js +2 -2
  27. package/dist/cli-delegate/cmd_uninstall.js +2 -2
  28. package/dist/cli-delegate/cmd_validate.js +2 -2
  29. package/dist/discovery/deprecation-report.md +1 -1
  30. package/dist/discovery/discovery-manifest.json +8 -8
  31. package/dist/discovery/discovery-manifest.json.sha256 +1 -1
  32. package/dist/discovery/discovery-manifest.summary.md +1 -1
  33. package/dist/discovery/dormancy-report.md +1 -1
  34. package/dist/discovery/orphan-report.md +1 -1
  35. package/dist/discovery/packs.json +2 -2
  36. package/dist/discovery/trust-report.md +1 -1
  37. package/dist/discovery/workspaces.json +2 -2
  38. package/dist/hooks/dispatch.js +880 -289
  39. package/dist/install/install.mjs +15 -3
  40. package/dist/mcp/registry-manifest.json +2 -2
  41. package/dist/mcp/server.json +2 -2
  42. package/dist/mcp/server.mjs +5458 -2453
  43. package/dist/scripts/_lib/lean_projection_mode.js +108 -0
  44. package/dist/scripts/_lib/router_match.js +243 -0
  45. package/dist/scripts/_lib/rule_injection.js +216 -0
  46. package/dist/scripts/condense.js +20 -20
  47. package/dist/scripts/project_thin_rules.js +139 -19
  48. package/dist/server/schemas/settings.js +16 -3
  49. package/docs/MIGRATION.md +56 -0
  50. package/docs/contracts/settings-classes.md +39 -7
  51. package/docs/guidelines/agent-infra/notes-horizon-mechanics.md +90 -0
  52. package/llms.txt +1 -1
  53. package/package.json +1 -1
  54. package/src/agent-src/scripts/archive_completed_roadmaps.ts +106 -4
  55. package/src/config/agent-settings.template.yml +47 -1
  56. package/src/config/continuity-surface.json +7 -0
  57. package/src/config/evaluator-budgets.json +4 -4
  58. package/src/config/gate-violation-baselines.json +2 -2
  59. package/src/config/hook-token-budget.json +7 -6
  60. package/src/config/packed-binary-manifest.json +1 -1
  61. package/src/config/routing-coverage-seed.json +9 -2
  62. package/src/scripts/_cli/cmd_session_recycle.ts +2 -25
  63. package/src/scripts/_cli/handoff_sessions.ts +14 -44
  64. package/src/scripts/_lib/continuity_slot.ts +295 -0
  65. package/src/scripts/_lib/continuity_writer.ts +253 -0
  66. package/src/scripts/_lib/hook_settings.ts +85 -0
  67. package/src/scripts/_lib/lean_projection_mode.ts +127 -0
  68. package/src/scripts/_lib/packed_binary_predicate.ts +37 -0
  69. package/src/scripts/_lib/recycle_envelope_paths.ts +109 -21
  70. package/src/scripts/_lib/regression_neighbourhood.ts +159 -22
  71. package/src/scripts/_lib/session_eol.ts +44 -0
  72. package/src/scripts/_lib/session_index_trust.ts +346 -0
  73. package/src/scripts/_lib/standing_bound_ratchet.ts +154 -0
  74. package/src/scripts/_lib/vendored_grammar_upstream.ts +280 -0
  75. package/src/scripts/audit_mcp_tools.ts +69 -25
  76. package/src/scripts/build_mcp_catalog.ts +24 -1
  77. package/src/scripts/check_host_tree_parity.ts +291 -0
  78. package/src/scripts/check_preamble_payload_budget.ts +136 -7
  79. package/src/scripts/check_rule_projection_integrity.ts +102 -2
  80. package/src/scripts/ci_settle.ts +205 -5
  81. package/src/scripts/code_graph/build.ts +79 -0
  82. package/src/scripts/code_graph/cli.ts +258 -7
  83. package/src/scripts/code_graph/detect.ts +38 -0
  84. package/src/scripts/code_graph/query.ts +25 -2
  85. package/src/scripts/code_graph/sqlite_store.ts +16 -1
  86. package/src/scripts/code_graph/types.ts +52 -3
  87. package/src/scripts/code_graph/validate.ts +3 -1
  88. package/src/scripts/code_graph/verbs.ts +590 -0
  89. package/src/scripts/condense.ts +20 -20
  90. package/src/scripts/handoff_context_hook.ts +39 -1
  91. package/src/scripts/hook_manifest.json +1 -1
  92. package/src/scripts/hook_manifest.yaml +24 -1
  93. package/src/scripts/hooks/block_speaking_inbox_dir.ts +182 -16
  94. package/src/scripts/hooks/code_graph_context_hook.ts +7 -18
  95. package/src/scripts/hooks/push_settle_hook.ts +3 -2
  96. package/src/scripts/hooks/rule_inject_hook.ts +107 -20
  97. package/src/scripts/hooks/session_eol_hook.ts +120 -2
  98. package/src/scripts/hot_context_hook.ts +62 -7
  99. package/src/scripts/lint_roadmap_blockers.ts +164 -1
  100. package/src/scripts/mcp_server/consumer_tool_catalog.json +152 -2
  101. package/src/scripts/mcp_server/graph_tools.ts +294 -0
  102. package/src/scripts/mcp_server/path_util.ts +31 -0
  103. package/src/scripts/mcp_server/tool_catalog_source.ts +7 -1
  104. package/src/scripts/mcp_server/tools.ts +3 -13
  105. package/src/scripts/model_rule_injection.ts +61 -4
  106. package/src/scripts/project_thin_rules.ts +149 -16
  107. package/src/scripts/report_standing_payload_by_host.ts +650 -0
  108. package/src/scripts/schemas/agent-settings.schema.json +7 -1
  109. package/src/scripts/session_memory_index.ts +81 -8
  110. package/src/server/schemas/settings.ts +23 -4
  111. package/src/vendor/grammars/README.md +27 -2
@@ -0,0 +1,295 @@
1
+ /**
2
+ * The continuity-record slot — capacity policy and state machine.
3
+ *
4
+ * `road-to-continuity-writer-activation` step 1.1. Until this module existed
5
+ * the slot had a producer (`session:recycle`), a consumer
6
+ * (`handoff_context_hook`) and no documented conflict ownership: the write was
7
+ * an unguarded `atomic_write_json`, so a second publish replaced whatever sat
8
+ * there and nobody had decided whether that was correct. With a MANUAL producer
9
+ * the question was theoretical — a human ran the verb once. Automatic
10
+ * production makes it routine, which is why the policy is settled here BEFORE
11
+ * any automatic writer exists.
12
+ *
13
+ * The full contract, including why the two rejected alternatives are rejected
14
+ * on tree evidence rather than on preference, is
15
+ * `docs/contracts/continuity-record-slot.md`. This module is that document in
16
+ * code; neither is the source of truth for the other's reasoning, and both are
17
+ * checked by `tests/scripts/_lib_continuity_slot.test.ts`.
18
+ *
19
+ * The policy in one line:
20
+ *
21
+ * SUPERSEDE OWN · REFUSE FOREIGN · QUARANTINE UNUSABLE · NEVER GO BACKWARDS.
22
+ *
23
+ * Why not create-if-absent.
24
+ *
25
+ * Create-if-absent is the policy the roadmap's own Risk 2 describes as a silent
26
+ * data loss: "the successor resumes from something plausible and older". It is
27
+ * rejected. Within one session the resident and the incoming record share a
28
+ * key, a workspace and a predecessor — the incoming one is the same lineage at
29
+ * a later moment, so keeping the older is a pure loss with no compensating
30
+ * safety.
31
+ *
32
+ * Why not a bounded multi-record queue.
33
+ *
34
+ * Because the reader forbids the resolution such a queue would need. Picking
35
+ * one of several records requires recency, and `recycle_envelope_paths.ts`
36
+ * carries a recorded decision against exactly that ("No `latest` index, by
37
+ * decision" — a pointer to the newest "would restore the shared write target
38
+ * one layer up"). `resolveContinuityRecord` implements it: several candidates
39
+ * and no session id START CLEAN rather than pick. A queue would either
40
+ * contradict that lock or be unreadable.
41
+ *
42
+ * Where `consuming` lives.
43
+ *
44
+ * Nowhere on disk, and that is the answer rather than a gap. Consumption is a
45
+ * single `fs.renameSync` from the authoritative name to the consumed name
46
+ * (`handoff_context_hook.ts:199`), and publication is a single `fs.renameSync`
47
+ * from a pid-suffixed temp name to the authoritative name
48
+ * (`state_io.ts:_publish_text_locked`). A rename within one directory is
49
+ * atomic on every filesystem this package supports, so an interruption lands
50
+ * strictly before or strictly after it: the authoritative name holds either the
51
+ * previous complete record or the new complete record, never a partial one.
52
+ * `consuming` is therefore a transition, not a state, and no reader has to
53
+ * tolerate a half-written record.
54
+ */
55
+ import * as fs from 'node:fs';
56
+ import * as path from 'node:path';
57
+
58
+ import {
59
+ recycle_consumed_rel,
60
+ recycle_envelope_rel,
61
+ recycle_quarantine_rel,
62
+ RECYCLE_ENVELOPE_MAX_BYTES,
63
+ RECYCLE_MAX_AGE_HOURS,
64
+ } from './recycle_envelope_paths.js';
65
+ import { validateRecycleEnvelope } from './subagent_capsule.js';
66
+ import { update_json_under_lock } from '../hooks/state_io.js';
67
+
68
+ /**
69
+ * The slot's states.
70
+ *
71
+ * Five are observable on disk. `consuming` is declared because the roadmap step
72
+ * names it and a reader looking for it deserves to find the reason it is not a
73
+ * disk state rather than to conclude it was forgotten — see the module header.
74
+ */
75
+ export const SLOT_STATES = [
76
+ 'absent',
77
+ 'published',
78
+ 'consuming',
79
+ 'consumed',
80
+ 'quarantined',
81
+ 'conflicting',
82
+ ] as const;
83
+ export type SlotState = (typeof SLOT_STATES)[number];
84
+
85
+ /** What a publish attempt did, and why. The reason is always present. */
86
+ export interface PublishOutcome {
87
+ /** `published` on a write; otherwise the state that refused it. */
88
+ state: SlotState;
89
+ /** Did the authoritative record change as a result of this call? */
90
+ wrote: boolean;
91
+ /** One line, always present — emitted by callers, never dropped. */
92
+ reason: string;
93
+ /** Absolute path of the record moved aside, when one was. */
94
+ quarantined?: string;
95
+ }
96
+
97
+ /** What {@link inspectSlot} found, without changing anything. */
98
+ export interface SlotInspection {
99
+ state: SlotState;
100
+ reason: string;
101
+ /** The authoritative path this session's records live at. */
102
+ target: string;
103
+ /** Parsed resident record, when one is present AND parseable. */
104
+ resident?: Record<string, unknown>;
105
+ }
106
+
107
+ /** Hours a record stays usable — the reader's own bound, not a second one. */
108
+ const MAX_AGE_MS = RECYCLE_MAX_AGE_HOURS * 3600 * 1000;
109
+
110
+ function _parse(file: string): Record<string, unknown> | null {
111
+ try {
112
+ const decoded: unknown = JSON.parse(fs.readFileSync(file, 'utf-8'));
113
+ if (typeof decoded === 'object' && decoded !== null && !Array.isArray(decoded)) {
114
+ return decoded as Record<string, unknown>;
115
+ }
116
+ return null;
117
+ } catch {
118
+ return null;
119
+ }
120
+ }
121
+
122
+ /** Milliseconds since a record's `written_at`, or `null` when it has none. */
123
+ function _ageMs(record: Record<string, unknown>, now: Date): number | null {
124
+ const raw = record['written_at'];
125
+ if (typeof raw !== 'string') return null;
126
+ const at = Date.parse(raw);
127
+ if (Number.isNaN(at)) return null;
128
+ return now.getTime() - at;
129
+ }
130
+
131
+ /**
132
+ * Read the slot for `session_id` without touching it.
133
+ *
134
+ * `conflicting` here is a statement about the RESIDENT relative to the caller's
135
+ * identity, which is why the session id is required rather than optional: a
136
+ * record is foreign only with respect to somebody.
137
+ */
138
+ export function inspectSlot(
139
+ workspace_root: string,
140
+ session_id: string | null | undefined,
141
+ now: Date = new Date(),
142
+ ): SlotInspection {
143
+ const target = path.join(workspace_root, recycle_envelope_rel(session_id));
144
+ if (!fs.existsSync(target)) {
145
+ const consumed = path.join(workspace_root, recycle_consumed_rel(session_id));
146
+ if (fs.existsSync(consumed)) {
147
+ return { state: 'consumed', reason: 'the record for this session was consumed', target };
148
+ }
149
+ const quarantined = path.join(workspace_root, recycle_quarantine_rel(session_id));
150
+ if (fs.existsSync(quarantined)) {
151
+ return {
152
+ state: 'quarantined',
153
+ reason: 'the slot is free; an unusable record sits in quarantine',
154
+ target,
155
+ };
156
+ }
157
+ return { state: 'absent', reason: 'no record in this slot', target };
158
+ }
159
+ const resident = _parse(target);
160
+ if (resident === null) {
161
+ return { state: 'quarantined', reason: 'the resident record does not parse as an object', target };
162
+ }
163
+ const violations = validateRecycleEnvelope(resident);
164
+ if (violations.length > 0) {
165
+ return {
166
+ state: 'quarantined',
167
+ reason: `the resident record fails validation (${violations.length} violation(s))`,
168
+ target,
169
+ resident,
170
+ };
171
+ }
172
+ const age = _ageMs(resident, now);
173
+ if (age === null || age > MAX_AGE_MS) {
174
+ return {
175
+ state: 'quarantined',
176
+ reason:
177
+ age === null
178
+ ? 'the resident record carries no parseable written_at'
179
+ : `the resident record is older than ${RECYCLE_MAX_AGE_HOURS} h`,
180
+ target,
181
+ resident,
182
+ };
183
+ }
184
+ const owner = String(resident['session_id'] ?? '').trim();
185
+ const mine = String(session_id ?? '').trim();
186
+ if (owner !== '' && mine !== '' && owner !== mine) {
187
+ return {
188
+ state: 'conflicting',
189
+ reason: `the slot holds an unconsumed record belonging to session ${owner}`,
190
+ target,
191
+ resident,
192
+ };
193
+ }
194
+ return { state: 'published', reason: 'this session has an unconsumed record', target, resident };
195
+ }
196
+
197
+ /**
198
+ * Publish `record` into this session's slot under the capacity policy.
199
+ *
200
+ * Never throws for a policy reason: a refusal is a return value, because this
201
+ * runs on the Stop path where an exception is a worse outcome than a missed
202
+ * record. A genuine I/O failure is reported as `wrote: false` with the reason,
203
+ * for the same reason.
204
+ *
205
+ * The write itself goes through {@link update_json_under_lock} rather than
206
+ * `atomic_write_json`, and the difference is the whole point: the locked form
207
+ * gives a read-modify-write, so the resident is inspected and the decision
208
+ * taken INSIDE the exclusion that stops a peer from publishing between the
209
+ * inspection and the write. `atomic_write_json` — the path
210
+ * `session:recycle` still uses — has no such window and cannot express a
211
+ * refusal.
212
+ */
213
+ export function publishContinuityRecord(
214
+ workspace_root: string,
215
+ session_id: string | null | undefined,
216
+ record: Record<string, unknown>,
217
+ now: Date = new Date(),
218
+ ): PublishOutcome {
219
+ const violations = validateRecycleEnvelope(record);
220
+ if (violations.length > 0) {
221
+ return {
222
+ state: 'absent',
223
+ wrote: false,
224
+ reason: `refused — the record to publish fails validation: ${violations[0] as string}`,
225
+ };
226
+ }
227
+ const bytes = Buffer.byteLength(JSON.stringify(record, null, 2), 'utf-8');
228
+ if (bytes > RECYCLE_ENVELOPE_MAX_BYTES) {
229
+ return {
230
+ state: 'absent',
231
+ wrote: false,
232
+ reason: `refused — ${bytes} bytes exceeds the ${RECYCLE_ENVELOPE_MAX_BYTES} byte slot cap`,
233
+ };
234
+ }
235
+
236
+ const target = path.join(workspace_root, recycle_envelope_rel(session_id));
237
+ const before = inspectSlot(workspace_root, session_id, now);
238
+
239
+ // A foreign, still-usable record is not this session's to move or replace.
240
+ // Refusing costs this session's resume; superseding costs another session's,
241
+ // and that one has no way to find out.
242
+ if (before.state === 'conflicting') {
243
+ return { state: 'conflicting', wrote: false, reason: `refused — ${before.reason}` };
244
+ }
245
+
246
+ // Monotonicity. A delayed or retried publisher must not roll the slot back
247
+ // to an earlier moment of the same session.
248
+ if (before.state === 'published' && before.resident !== undefined) {
249
+ const residentAt = Date.parse(String(before.resident['written_at'] ?? ''));
250
+ const incomingAt = Date.parse(String(record['written_at'] ?? ''));
251
+ if (!Number.isNaN(residentAt) && !Number.isNaN(incomingAt) && incomingAt < residentAt) {
252
+ return {
253
+ state: 'published',
254
+ wrote: false,
255
+ reason: 'refused — the resident record is newer than the one offered',
256
+ };
257
+ }
258
+ }
259
+
260
+ let quarantined: string | undefined;
261
+ if (before.state === 'quarantined' && fs.existsSync(target)) {
262
+ // Move aside, never delete. See `recycle_quarantine_rel`.
263
+ const dest = path.join(workspace_root, recycle_quarantine_rel(session_id));
264
+ try {
265
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
266
+ fs.renameSync(target, dest);
267
+ quarantined = dest;
268
+ } catch (exc) {
269
+ return {
270
+ state: 'quarantined',
271
+ wrote: false,
272
+ reason: `refused — could not quarantine the unusable resident: ${String(exc)}`,
273
+ };
274
+ }
275
+ }
276
+
277
+ const result = update_json_under_lock<Record<string, unknown>>(target, () => record);
278
+ if (result !== 'written') {
279
+ return {
280
+ state: before.state,
281
+ wrote: false,
282
+ reason: `refused — the slot write did not complete (${result})`,
283
+ ...(quarantined !== undefined ? { quarantined } : {}),
284
+ };
285
+ }
286
+ return {
287
+ state: 'published',
288
+ wrote: true,
289
+ reason:
290
+ before.state === 'published'
291
+ ? 'superseded this session’s earlier record'
292
+ : `published into a ${before.state} slot`,
293
+ ...(quarantined !== undefined ? { quarantined } : {}),
294
+ };
295
+ }
@@ -0,0 +1,253 @@
1
+ /**
2
+ * The deterministic continuity-record writer.
3
+ *
4
+ * `road-to-continuity-writer-activation` step 1.2. Until this module existed
5
+ * `agent-config session:recycle` was the ONLY writer of the continuity record
6
+ * in the tree, which is why `verb:session:recycle` counts on the
7
+ * `public_continuity_commands` axis and why an advisory has to tell a human to
8
+ * run it before `/clear`: continuity did not happen unless somebody
9
+ * remembered.
10
+ *
11
+ * Every field here is computed from on-disk state and nothing is asked of a
12
+ * model. That is not a cost optimisation, it is what makes the record a
13
+ * `continuity_record` rather than a `main_session` one: the judgement fields
14
+ * (`decisions`, `failed_approaches`, `successful_approaches`, …) are FORBIDDEN
15
+ * on the variant precisely so a deterministic writer cannot fill one with a
16
+ * guess and a reader cannot be left unable to tell a derived record from a
17
+ * judged one.
18
+ *
19
+ * Two gates, and both are needed:
20
+ *
21
+ * 1. `continuity.auto_record` must be `on`. It ships `off`, so with the
22
+ * shipped default this module is never reached and the tree behaves
23
+ * exactly as it does today.
24
+ * 2. The session must be SUBSTANTIVE by the committed floor
25
+ * (`is_substantive`) and must have a resolvable task. Both come from the
26
+ * concern's own counters and claim state, never from file presence.
27
+ *
28
+ * The task gate is the sharper of the two, and its bound is stated rather than
29
+ * hidden: a record needs at least one `acceptance_criteria` entry, and the only
30
+ * deterministic source of one in this tree is the roadmap a session has
31
+ * claimed. A session with no claim therefore leaves no record — and the
32
+ * alternative, writing a placeholder acceptance criterion, would assert a
33
+ * definition of "done" nobody set, which is the exact failure the variant's
34
+ * forbidden-key set exists to prevent.
35
+ */
36
+ import * as fs from 'node:fs';
37
+
38
+ import { load_agent_settings } from './agent_settings.js';
39
+ import { resolvePredecessor } from './recycle_envelope_paths.js';
40
+ import { CHECKBOX_LINE, phaseLines } from './roadmap_checkboxes.js';
41
+ import { readHead, roadmapPath } from './run_checkpoint.js';
42
+ import { is_substantive, type StoredEolCounters } from './session_eol.js';
43
+ import { CAPSULE_SCHEMA_VERSION, MAX_ENTRIES, MAX_LINE_CHARS } from './subagent_capsule.js';
44
+
45
+ /** Settings key that arms this writer. Ships `off`. */
46
+ export const AUTO_RECORD_KEY = 'continuity.auto_record';
47
+
48
+ /**
49
+ * Read `continuity.auto_record` from the merged settings cascade.
50
+ *
51
+ * The cascade merges the shipped template, so a workspace with no settings file
52
+ * resolves `off` through the template rather than through the trailing
53
+ * `return false` — which is why that line is defence against an unreadable
54
+ * cascade and not the path a default install takes. Both directions are pinned
55
+ * by fixtures, because "absent" and "off" arriving by different routes is
56
+ * exactly the kind of thing a reader assumes and a test has to establish.
57
+ */
58
+ export function auto_record_enabled(root: string): boolean {
59
+ try {
60
+ const settings = load_agent_settings({ cwd: root });
61
+ const section = settings['continuity'];
62
+ if (section && typeof section === 'object' && !Array.isArray(section)) {
63
+ const v = (section as Record<string, unknown>)['auto_record'];
64
+ // YAML 1.1 parses a bare `on` as boolean true — accept both.
65
+ return v === 'on' || v === true;
66
+ }
67
+ } catch {
68
+ // fail-closed: unreadable settings leave the writer disarmed
69
+ }
70
+ return false;
71
+ }
72
+
73
+ /** Settings key that governs run-checkpoint production. Ships `on`. */
74
+ export const RUN_CHECKPOINTS_KEY = 'continuity.run_checkpoints';
75
+
76
+ /**
77
+ * Read `continuity.run_checkpoints` from the merged settings cascade.
78
+ *
79
+ * Fails OPEN, unlike its sibling above, and the asymmetry is the point: this
80
+ * switch governs behaviour the tree already had, so an unreadable cascade must
81
+ * leave it running. Its sibling arms something new, so an unreadable cascade
82
+ * must leave that disarmed. A single helper with one polarity would have been
83
+ * wrong for one of the two.
84
+ */
85
+ export function run_checkpoints_enabled(root: string): boolean {
86
+ try {
87
+ const settings = load_agent_settings({ cwd: root });
88
+ const section = settings['continuity'];
89
+ if (section && typeof section === 'object' && !Array.isArray(section)) {
90
+ const v = (section as Record<string, unknown>)['run_checkpoints'];
91
+ if (v === 'off' || v === false) return false;
92
+ }
93
+ } catch {
94
+ // fail-open: an unreadable cascade never silently removes a recovery aid
95
+ }
96
+ return true;
97
+ }
98
+
99
+ /** Why no record was built, when none was. Always a stated reason. */
100
+ export interface WriterDecision {
101
+ record: Record<string, unknown> | null;
102
+ reason: string;
103
+ }
104
+
105
+ /** How many `remaining` / `acceptance_criteria` lines a record carries. */
106
+ const LIST_CAP = 12;
107
+
108
+ function _clip(line: string): string {
109
+ const one = line.replace(/\s+/g, ' ').trim();
110
+ return one.length <= MAX_LINE_CHARS ? one : `${one.slice(0, MAX_LINE_CHARS - 1)}…`;
111
+ }
112
+
113
+ /**
114
+ * Open, closed and parked step counts plus the open step bodies.
115
+ *
116
+ * Deliberately reuses `phaseLines` + `CHECKBOX_LINE` rather than a fourth
117
+ * regex: a writer that disagreed with the dashboard about whether a roadmap is
118
+ * finished would put that disagreement into the record a successor resumes
119
+ * from.
120
+ */
121
+ export function roadmapShape(text: string): { done: number; total: number; open: string[] } {
122
+ let done = 0;
123
+ let total = 0;
124
+ const open: string[] = [];
125
+ for (const raw of phaseLines(text)) {
126
+ const m = CHECKBOX_LINE.exec(raw);
127
+ if (m === null) continue;
128
+ total += 1;
129
+ const mark = m[1];
130
+ if (mark === 'x' || mark === 'X') {
131
+ done += 1;
132
+ continue;
133
+ }
134
+ if (mark === '~' || mark === '-') continue;
135
+ if (open.length < LIST_CAP) {
136
+ open.push(_clip((m[2] ?? '').replace(/\*\*/g, '')));
137
+ }
138
+ }
139
+ return { done, total, open };
140
+ }
141
+
142
+ /**
143
+ * Checkbox bodies under an `## Acceptance Criteria` heading.
144
+ *
145
+ * `phaseLines` deliberately excludes this section — an autonomous run must not
146
+ * mistake an acceptance criterion for its next step — so it is read separately
147
+ * here, which is the one place the two readings legitimately differ.
148
+ */
149
+ export function acceptanceCriteria(text: string): string[] {
150
+ const lines = text.split('\n');
151
+ const out: string[] = [];
152
+ let inside = false;
153
+ for (const raw of lines) {
154
+ const heading = /^(#{2,3})[ \t]+(.*?)[ \t]*$/.exec(raw);
155
+ if (heading !== null) {
156
+ inside = /^Acceptance[ \t]+Criteria\b/i.test(heading[2] ?? '');
157
+ continue;
158
+ }
159
+ if (!inside) continue;
160
+ const m = CHECKBOX_LINE.exec(raw);
161
+ if (m === null) continue;
162
+ if (out.length < LIST_CAP) {
163
+ out.push(_clip((m[2] ?? '').replace(/\*\*/g, '')));
164
+ }
165
+ }
166
+ return out;
167
+ }
168
+
169
+ export interface BuildInput {
170
+ /** Workspace root — the record's `workspace`, and the root every read is relative to. */
171
+ root: string;
172
+ /** Raw session id, as the record paths and the claim state key on it. */
173
+ sessionId: string;
174
+ /** The roadmap slug this session claimed, or `null` when it claimed none. */
175
+ slug: string | null;
176
+ /** The concern's own counters for this session. */
177
+ counters: StoredEolCounters | null;
178
+ /** Injected for determinism in tests. */
179
+ now?: Date;
180
+ }
181
+
182
+ /**
183
+ * Build the record, or say why there is none.
184
+ *
185
+ * Never throws and never shells out: this runs on the Stop path, where a
186
+ * subprocess is a latency cost paid on every turn's end and an exception is
187
+ * worse than a missing record. `head` is read from `.git` directly (worktree
188
+ * aware) rather than through `git`, and the richer anchor fields
189
+ * `session:recycle` collects with `git status` are deliberately omitted — the
190
+ * trade is one drift line for a Stop path that spawns nothing, and it is stated
191
+ * in `docs/contracts/continuity-record-slot.md` rather than left for a reader
192
+ * to discover by diffing two producers.
193
+ */
194
+ export function buildContinuityRecord(input: BuildInput): WriterDecision {
195
+ const { root, sessionId, slug, counters } = input;
196
+ const now = input.now ?? new Date();
197
+
198
+ if (!is_substantive(counters)) {
199
+ return {
200
+ record: null,
201
+ reason: 'no record — the session is not substantive by the committed floor',
202
+ };
203
+ }
204
+ if (slug === null || slug.trim() === '') {
205
+ return {
206
+ record: null,
207
+ reason: 'no record — no claimed roadmap, so no deterministic acceptance criterion exists',
208
+ };
209
+ }
210
+
211
+ let text: string;
212
+ try {
213
+ text = fs.readFileSync(roadmapPath(root, slug), 'utf-8');
214
+ } catch {
215
+ return { record: null, reason: `no record — the claimed roadmap ${slug} is not readable` };
216
+ }
217
+
218
+ const shape = roadmapShape(text);
219
+ if (shape.total === 0) {
220
+ return { record: null, reason: `no record — ${slug} carries no phase checkboxes to count` };
221
+ }
222
+
223
+ const declared = acceptanceCriteria(text);
224
+ const criteria =
225
+ declared.length > 0
226
+ ? declared
227
+ : // A roadmap with no declared criteria still has one definitional
228
+ // completion condition, and it is derived from the artefact class
229
+ // rather than judged: every step closed. Anything richer would be
230
+ // a definition of done nobody wrote.
231
+ [`every phase step in agents/roadmaps/${slug}.md is closed`];
232
+
233
+ const record: Record<string, unknown> = {
234
+ capsule_version: CAPSULE_SCHEMA_VERSION,
235
+ variant: 'continuity_record',
236
+ summary: _clip(`${slug}: ${shape.done} of ${shape.total} steps closed`),
237
+ task: _clip(slug),
238
+ workspace: root,
239
+ written_at: now.toISOString(),
240
+ acceptance_criteria: criteria.slice(0, MAX_ENTRIES),
241
+ remaining: shape.open.slice(0, MAX_ENTRIES),
242
+ predecessor: resolvePredecessor(root, sessionId),
243
+ artifact_paths: [`agents/roadmaps/${slug}.md`],
244
+ };
245
+ if (sessionId.trim() !== '') {
246
+ record['session_id'] = sessionId.trim();
247
+ }
248
+ const head = readHead(root);
249
+ if (head !== null) {
250
+ record['head'] = head;
251
+ }
252
+ return { record, reason: `record built for ${slug} (${shape.done}/${shape.total} closed)` };
253
+ }
@@ -110,3 +110,88 @@ export function leanProjectionModeRaw(root: string): string {
110
110
  }
111
111
  return '';
112
112
  }
113
+
114
+ /**
115
+ * Raw `lean_projection.hosts` list out of `.agent-settings.yml`, or `[]`.
116
+ *
117
+ * Same indentation-shaped discipline as `leanProjectionModeRaw` above and for
118
+ * the same reason — a hook must never fail a tool call because a YAML parser
119
+ * could not load — extended to the three list shapes a human writes:
120
+ *
121
+ * lean_projection:
122
+ * hosts: [claude-code] # inline
123
+ * lean_projection:
124
+ * hosts: # block, indented under the key
125
+ * - claude-code
126
+ * lean_projection:
127
+ * hosts: # block, at the key's own indent
128
+ * - claude-code
129
+ *
130
+ * All three are legal YAML and `js-yaml` loads them identically; the third was
131
+ * read as `[]` until 2026-09-08 (R2 finding 2) and is covered by three fixtures
132
+ * in `tests/scripts/lean_projection_hosts.test.ts`.
133
+ *
134
+ * Interpretation is NOT done here. `[]` means "nothing was written", and
135
+ * `_lib/lean_projection_mode.ts::resolveLeanProjectionHosts` decides that this
136
+ * means the default rather than "no host" — keeping that decision in one place
137
+ * is what stops the projector and the delivery concern from disagreeing, which
138
+ * is the whole reason the mode reader is split this way.
139
+ */
140
+ export function leanProjectionHostsRaw(root: string): string[] {
141
+ const file = path.join(root, SETTINGS_FILE);
142
+ let text: string;
143
+ try {
144
+ if (!fs.statSync(file).isFile()) return [];
145
+ text = fs.readFileSync(file, 'utf-8');
146
+ } catch {
147
+ return [];
148
+ }
149
+ const strip = (s: string): string => s.trim().replace(/^["']|["']$/g, '');
150
+ let inSection = false;
151
+ let inBlock = false;
152
+ let blockIndent = -1;
153
+ const out: string[] = [];
154
+ for (const raw of text.split(/\r\n|\r|\n/)) {
155
+ const line = raw.replace(/\s+$/, '');
156
+ if (!line || line.replace(/^\s+/, '').startsWith('#')) continue;
157
+ if (!(line.startsWith(' ') || line.startsWith('\t'))) {
158
+ inSection = /^lean_projection\s*:\s*$/.test(line);
159
+ inBlock = false;
160
+ continue;
161
+ }
162
+ if (!inSection) continue;
163
+ const indent = (/^\s*/.exec(line) as RegExpExecArray)[0].length;
164
+ if (inBlock) {
165
+ const item = /^\s*-\s*(\S.*)$/.exec(line);
166
+ // `>=`, not `>`: YAML lets a block sequence sit at its KEY's own
167
+ // indent, and `js-yaml` — the parser `condense` uses on this same
168
+ // file — loads that shape identically to the deeper-indented one.
169
+ // With `>` the same-indent form parsed as `[]`, which
170
+ // `resolveLeanProjectionHosts` reads as "nothing was written" and
171
+ // answers with the default `[claude-code]` while the projector
172
+ // thins whatever the file actually says. Two readers disagreeing
173
+ // about the delivery-host set is the one failure this split exists
174
+ // to prevent (R2 finding 2). A SHALLOWER item still ends the block:
175
+ // it belongs to a different mapping level, never to `hosts`.
176
+ if (item !== null && indent >= blockIndent) {
177
+ const v = strip(item[1] ?? '');
178
+ if (v !== '') out.push(v);
179
+ continue;
180
+ }
181
+ inBlock = false;
182
+ }
183
+ const inline = /^\s+hosts\s*:\s*\[([^\]]*)\]\s*$/.exec(line);
184
+ if (inline !== null) {
185
+ for (const part of (inline[1] ?? '').split(',')) {
186
+ const v = strip(part);
187
+ if (v !== '') out.push(v);
188
+ }
189
+ continue;
190
+ }
191
+ if (/^\s+hosts\s*:\s*$/.test(line)) {
192
+ inBlock = true;
193
+ blockIndent = indent;
194
+ }
195
+ }
196
+ return out;
197
+ }