@quolu/lattice 0.83.0 → 0.84.1

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.
package/src/cli-help.mjs CHANGED
@@ -27,14 +27,15 @@ const NAMESPACE_HELP = Object.freeze({
27
27
  Commands:
28
28
  create --input <file> [--serialization-reviewed]
29
29
  # 結果へdispatch_shapeを載せる。--serialization-reviewedは互換のため受理するだけで門ではない
30
- create --schema --json # 既定は最新版(v4)のJSON Schemaを返す
30
+ create --schema --json # 既定は最新版(v5)のJSON Schemaを返す
31
31
  create --schema-version <1|2|3|4|5> --json
32
+ create --template --json # 作者が書くkeyだけの最小のv5入力(そのままplan createが受理する)
32
33
  backchain --schema --json # 最終成果から必要な機能を逆算する入力契約
33
34
  revise --input <file> [--dry-run] --json # 工程の全体と明示した状態移行から改訂する
34
35
  revise --schema --json
35
36
  backchain --input <file> [--dry-run] --json
36
37
  # 各工程の必要・提供機能を照合し、初回又は既存storeへのplan登録まで行う
37
- show <plan_key> --json # task・依存・phase・状態をplan本体から1コマンドで投影する
38
+ show <plan_key> --json # task・依存辺・phase・状態をplan本体から1コマンドで投影する
38
39
  compile --request <request.json>
39
40
  compile --schema --json # lattice.run_request.v1 の JSON Schema を出す
40
41
  verify --request <request.json> --plan <plan.json>
@@ -110,8 +111,9 @@ Write commands:
110
111
  block --plan <key> --task <id> --reason <text>
111
112
  unblock --plan <key> --task <id>
112
113
  retire --plan <key> --task <id> --reason <text>
113
- done --plan <key> --task <id> (--evidence <file>|--message <text>)
114
- # taskを閉じる。--evidenceはdescriptor JSONでも証拠本文でもよい。repo内なら絶対path可。
114
+ done --plan <key> --task <id> [--evidence <file>] [--message <text>]
115
+ # taskを閉じる。どちらも省略でき、両方なら本文がfileを名指す(A58)。--evidenceはdescriptor JSONでも証拠本文でもよい。repo内なら絶対path可。
116
+ # 既にdoneなら何も足さずunchanged:trueで成功する(a12)
115
117
  # 監査と構造finalizationは残作業であり、doneの門ではない
116
118
  reopen --plan <key> --task <id> --reason <text> [--override-reason <text>]
117
119
  evidence promote --plan <key> --task <id> --evidence <file>
@@ -119,7 +121,7 @@ Write commands:
119
121
  start --plan <key> --task <id> --rebind --reason <text> # 改訂でcarryされたin-progressへ現版のstart束縛を積み直す(ADR 0191)
120
122
  dependency connect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>
121
123
  dependency disconnect --from-plan <key> --from-task <id> --to-plan <key> --to-task <id> --reason <text>
122
- # 開発中に発見した依存を明示接続する(同一plan内・plan跨ぎとも)。依存の自動推定は行わない
124
+ # 開発中に発見した依存を明示接続する。同一plan内の辺はplan本体を軽い改訂で書き換え(plan_versionが変わる)、plan跨ぎは台帳に積む。依存の自動推定は行わない
123
125
  independence compile --plan <key> --input <file> # witness setとsensorから並列可否を記録する
124
126
  independence witness migrate --plan <key> # revision後の宣言をtask migrationで写す
125
127
  independence witness scaffold --plan <key> --input <draft> # 下書きとfresh観測から宣言を書き出す
@@ -233,7 +235,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
233
235
  'setup status': 'setup status [--host <claude|codex|grok|cursor|all>] [--json]',
234
236
  status: 'status --json',
235
237
  'session-context': 'session-context --json',
236
- 'plan create': 'plan create --input <file> [--serialization-reviewed] | --schema --json | --schema-version <1|2|3|4|5> --json',
238
+ 'plan create': 'plan create --input <file> [--serialization-reviewed] | --schema --json | --schema-version <1|2|3|4|5> --json | --template --json',
237
239
  'plan show': 'plan show <plan_key> --json',
238
240
  'plan scope-review': 'plan scope-review --plan-input <plan-create-or-extraction.json> --review <scope-review.json> --json | --schema --json',
239
241
  'plan backchain': 'plan backchain --input <file> [--dry-run] --json | --schema --json',
@@ -300,7 +302,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
300
302
  'todo block': 'todo block --plan <key> --task <id> --reason <text>',
301
303
  'todo unblock': 'todo unblock --plan <key> --task <id>',
302
304
  'todo retire': 'todo retire --plan <key> --task <id> --reason <text>',
303
- 'todo done': 'todo done --plan <key> --task <id> (--evidence <file>|--message <text>) [--test-result <markdown-file>]',
305
+ 'todo done': 'todo done --plan <key> --task <id> [--evidence <file>] [--message <text>] [--test-result <markdown-file>]',
304
306
  'todo reopen': 'todo reopen --plan <key> --task <id> --reason <text> [--override-reason <text>]',
305
307
  'todo evidence': 'todo evidence promote --plan <key> --task <id> --evidence <file>',
306
308
  'todo evidence promote': 'todo evidence promote --plan <key> --task <id> --evidence <file>',
@@ -0,0 +1,354 @@
1
+ // Every plan/todo CLI refusal says where (pointer), which rule (rule) and how to repair
2
+ // (next_action) in one detail. Pure: reads only the error and the CLI context, no I/O.
3
+ // Refusal sites keep their own keys; this fills the three keys the seat contract requires.
4
+
5
+ const PLACEHOLDER = /^[a-z_]+$/u;
6
+ const EXAMPLE_TIMESTAMP = '2026-11-08T12:00:00.000Z';
7
+
8
+ const q = (value) => (typeof value === 'string' ? `'${value}'` : JSON.stringify(value));
9
+ const names = (values) => `[${values.join(', ')}]`;
10
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
11
+ const strings = (value) => (Array.isArray(value) ? value.filter((entry) => typeof entry === 'string') : []);
12
+ const planOf = (detail, ctx) => ctx.plan ?? detail.plan_key ?? '<plan>';
13
+ const taskOf = (detail, ctx) => ctx.task ?? detail.task_id ?? detail.requested_task_id ?? '<task>';
14
+ const migratedTask = (detail) => detail.from_task_id ?? '<task>';
15
+ const run = (ctx, ...tail) => ['lattice', ctx.family ?? 'todo', ctx.command, ...tail].filter(Boolean).join(' ');
16
+ const schemaCommand = (ctx) => run(ctx, '--schema', '--json');
17
+ const showTask = (detail, ctx) => `lattice todo show --plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)} --json`;
18
+ const startTask = (detail, ctx) => `lattice todo start --plan ${planOf(detail, ctx)} --task ${taskOf(detail, ctx)}`;
19
+ // a12: name the blocking task (seat contract), falling back to the refused task's own detail.
20
+ const blocker = (detail) => (Array.isArray(detail.blocking_tasks) ? detail.blocking_tasks.find(record) : undefined);
21
+ const unfinishedFirst = (detail, ctx) => {
22
+ const first = blocker(detail);
23
+ if (first === undefined) return `Record done on its unfinished predecessors first (see \`${showTask(detail, ctx)}\`)`;
24
+ return `Record done on ${first.plan_key}/${first.task_id} (${first.status}) first (see \`lattice todo show --plan ${first.plan_key} --task ${first.task_id} --json\`)`;
25
+ };
26
+
27
+ /** The flag that carried the unreadable input: the one whose value is the refused path. */
28
+ function inputFlag(detail, ctx) {
29
+ const flags = record(ctx.flags) ? ctx.flags : {};
30
+ const byValue = Object.keys(flags).find((name) => flags[name] === detail.input_ref);
31
+ return `--${byValue ?? ['input', 'evidence', 'test-result', 'message'].find((key) => key in flags) ?? 'input'}`;
32
+ }
33
+
34
+ function movedAfter(detail, ctx, pointer) {
35
+ const where = record(detail.expected) ? detail.expected.greater_than : undefined;
36
+ // The machine sorts distinct ids itself, so an equal neighbour is a duplicate with different content.
37
+ if (where !== undefined && where === detail.actual) {
38
+ return `${q(detail.actual)} appears twice with different content (${pointer}); keep one entry.`;
39
+ }
40
+ return `Move ${q(detail.actual)} after ${q(where)}; ${pointer} must be ascending and unique.`;
41
+ }
42
+
43
+ function keyDifference(detail, ctx, pointer) {
44
+ const expected = strings(detail.expected?.keys);
45
+ if (!Array.isArray(detail.actual?.keys)) {
46
+ return `At ${pointer} provide an object with exactly the keys ${names(expected)}.`;
47
+ }
48
+ const actual = strings(detail.actual.keys);
49
+ const missing = expected.filter((key) => !actual.includes(key));
50
+ const extra = actual.filter((key) => !expected.includes(key));
51
+ const parts = [];
52
+ if (missing.length > 0) parts.push(`add keys ${names(missing)}`);
53
+ if (extra.length > 0) parts.push(`remove keys ${names(extra)}`);
54
+ return `At ${pointer} ${parts.join(' and ') || `use exactly the keys ${names(expected)}`}.`;
55
+ }
56
+
57
+ function acceptedValues(detail) {
58
+ if (Array.isArray(detail.accepted)) return detail.accepted;
59
+ if (record(detail.expected) && Array.isArray(detail.expected.one_of)) return detail.expected.one_of;
60
+ return [detail.expected];
61
+ }
62
+
63
+ const phaseAcceptFirst = (detail, ctx) => {
64
+ const phase = Array.isArray(detail.blocking_phases) ? detail.blocking_phases.find(record) : undefined;
65
+ return `Accept the phase this task depends on first (\`lattice todo phase accept --plan ${phase?.plan_key ?? planOf(detail, ctx)} --phase ${phase?.phase_id ?? '<phase_id>'} --input <file>\`), then rerun.`;
66
+ };
67
+ const inputFile = (what) => ({ pointer: inputFlag, repair: (detail, ctx, pointer) => `${what} Fix the file passed to ${pointer} and rerun \`${run(ctx)}\`.` });
68
+ const revisionDigest = (what) => ({
69
+ pointer: '--input',
70
+ repair: (detail, ctx) => `The ${what} does not match its schema or its digest is stale: see \`${schemaCommand(ctx)}\` and recompute the digest.`,
71
+ });
72
+
73
+ // rule -> { pointer?: string | (detail, ctx) => string, repair: (detail, ctx, pointer) => string }
74
+ const REGISTRY = {
75
+ unsorted: { repair: movedAfter },
76
+ unsorted_or_duplicate_collection: {
77
+ repair: (detail, ctx, pointer) => `${movedAfter(detail, ctx, pointer)} Remove the entry if ${q(detail.actual)} appears twice.`,
78
+ },
79
+ unexpected_or_missing_keys: { repair: keyDifference },
80
+ identifier_invalid: {
81
+ repair: (detail, ctx, pointer) => `Set ${pointer} to a todo identifier (1-128 characters of letters, digits, '.', '_' or '-', starting with a letter or digit); ${q(detail.actual)} is not one.`,
82
+ },
83
+ const_mismatch: {
84
+ repair: (detail, ctx, pointer) => `Set ${pointer} to ${acceptedValues(detail).map(q).join(' or ')}; it is ${q(detail.actual)}.`,
85
+ },
86
+ timestamp_invalid: {
87
+ repair: (detail, ctx, pointer) => `Set ${pointer} to a UTC ISO 8601 timestamp with milliseconds, for example ${EXAMPLE_TIMESTAMP}; it is ${q(detail.actual)}.`,
88
+ },
89
+ input_digest_mismatch: {
90
+ repair: (detail, ctx, pointer) => `Set ${pointer} to ${q(detail.expected)}, the canonical digest of the other fields; recompute it after every edit.`,
91
+ },
92
+ empty: {
93
+ repair: (detail, ctx, pointer) => `Add at least ${detail.expected?.min_items ?? 1} item(s) at ${pointer}.${typeof detail.expected?.note === 'string' ? ` ${detail.expected.note}.` : ''}`,
94
+ },
95
+ type: {
96
+ repair: (detail, ctx, pointer) => `Set ${pointer} to a value of type ${detail.expected?.type ?? 'the expected type'}${detail.expected?.nullable ? ' or null' : ''}; it is ${q(detail.actual?.type ?? detail.actual)}.`,
97
+ },
98
+ blank: { repair: (detail, ctx, pointer) => `Write non-blank text at ${pointer}; it is empty or only whitespace.` },
99
+ too_large: {
100
+ repair: (detail, ctx, pointer) => `Shorten the text at ${pointer} to at most ${detail.expected?.max_utf8_bytes} UTF-8 bytes; it is ${detail.actual?.byte_length} bytes.`,
101
+ },
102
+ forbidden_control: {
103
+ repair: (detail, ctx, pointer) => `Remove the control characters from the text at ${pointer}.`,
104
+ },
105
+ unknown_reference: {
106
+ repair: (detail, ctx, pointer) => `Set ${pointer} to one of ${names(strings(detail.expected?.one_of))}; it is ${q(detail.actual)}.`,
107
+ },
108
+ not_authorable_at_create: {
109
+ repair: (detail, ctx, pointer) => `Set ${pointer} to null; it is assigned after creation, never authored.`,
110
+ },
111
+
112
+ invalid_done_transition: {
113
+ repair: (detail, ctx) => ({
114
+ predecessor_unfinished: `${unfinishedFirst(detail, ctx)}.`,
115
+ acceptance_edge: phaseAcceptFirst(detail, ctx),
116
+ task_state: `It must be in-progress: run \`${startTask(detail, ctx)}\` first.`,
117
+ })[detail.cause] ?? `Check the task state with \`${showTask(detail, ctx)}\`, then rerun.`,
118
+ },
119
+ invalid_start_transition: {
120
+ repair: (detail, ctx) => ({
121
+ predecessor_unfinished: `${unfinishedFirst(detail, ctx)}, or start with --override-reason <text>.`,
122
+ acceptance_edge: phaseAcceptFirst(detail, ctx),
123
+ task_state: `Only a pending task can start; check its status with \`${showTask(detail, ctx)}\`.`,
124
+ phase_state: 'Its phase is not active; check the phase status with `lattice todo status --json`.',
125
+ })[detail.cause] ?? `Check the task state with \`${showTask(detail, ctx)}\`, then rerun.`,
126
+ },
127
+ invalid_block_transition: {
128
+ repair: (detail, ctx) => `Only an in-progress task can be blocked; check its status with \`${showTask(detail, ctx)}\`.`,
129
+ },
130
+ invalid_unblock_transition: {
131
+ repair: (detail, ctx) => `Only a blocked task can be unblocked; check its status with \`${showTask(detail, ctx)}\`.`,
132
+ },
133
+ reopen_has_started_successor: {
134
+ repair: (detail, ctx) => `A successor of ${taskOf(detail, ctx)} has already started: split the work with \`lattice todo split --plan ${planOf(detail, ctx)} --input <file>\`, or pass --override-reason <text> to reopen anyway.`,
135
+ },
136
+ requested_plan_mismatch: {
137
+ pointer: '--plan',
138
+ repair: (detail, ctx) => `The revision's plan_key differs from --plan${ctx.plan ? ` (${q(ctx.plan)})` : ''}: pass --plan with the plan_key written inside the revision input.`,
139
+ },
140
+ plan_not_active: {
141
+ pointer: '--plan',
142
+ repair: (detail, ctx, pointer) => `${q(detail.plan_key ?? ctx.plan ?? '')} is not an active plan: run \`lattice todo status --json\` to list the active plan keys, then set ${pointer} to one of them.`,
143
+ },
144
+ task_not_found: {
145
+ pointer: '--task',
146
+ repair: (detail, ctx) => `No task ${q(detail.requested_task_id ?? ctx.task ?? '')} in plan ${planOf(detail, ctx)}: run \`lattice plan show ${planOf(detail, ctx)} --json\` to list its task ids.`,
147
+ },
148
+ task_id_case_ambiguous: {
149
+ pointer: '--task',
150
+ repair: (detail) => `${q(detail.requested_task_id)} matches several task ids ${names(strings(detail.matching_task_ids))}; pass the exact one to --task.`,
151
+ },
152
+ plan_key_already_exists: {
153
+ pointer: '/plan_key',
154
+ repair: (detail, ctx) => `Plan key ${q(detail.plan_key ?? ctx.plan ?? '')} already exists: choose a new plan_key, or change the existing plan with \`lattice plan revise --input <file> --json\`.`,
155
+ },
156
+ dispatch_shape_dependency_cycle: {
157
+ pointer: '/hard_dependencies',
158
+ repair: () => 'Remove one hard dependency (or join) that closes the cycle, then rerun.',
159
+ },
160
+ dispatch_shape_self_edge: {
161
+ pointer: '/hard_dependencies',
162
+ repair: () => 'Remove the hard dependency whose from and to are the same task, then rerun.',
163
+ },
164
+ dangling_dependency: {
165
+ pointer: '/hard_dependencies',
166
+ repair: () => 'Point every dependency at a task that exists; remove or correct the edge whose task is missing.',
167
+ },
168
+ self_edge: {
169
+ pointer: '/hard_dependencies',
170
+ repair: () => 'Remove the dependency whose from and to are the same task.',
171
+ },
172
+ merged_cycle: {
173
+ pointer: '/hard_dependencies',
174
+ repair: () => 'Remove one dependency (including cross-plan ones) that closes the cycle, then rerun.',
175
+ },
176
+ join_self_edge: {
177
+ pointer: '/joins',
178
+ repair: () => 'Remove the join whose `after` lists its own id, then rerun.',
179
+ },
180
+ unknown_requires_evidence: {
181
+ pointer: '/tasks',
182
+ repair: (detail) => `Give task(s) ${names(strings(detail.task_ids))} a register_* or skip disposition in the extraction (unknown_requires_evidence cannot migrate), then rerun \`lattice todo migrate\`.`,
183
+ },
184
+ no_registered_tasks: {
185
+ pointer: '/tasks',
186
+ repair: () => 'Give at least one task a register_* disposition in the extraction, then rerun `lattice todo migrate`.',
187
+ },
188
+ store_locked: {
189
+ repair: () => 'Another writer holds the store lock: wait for it to exit and rerun the same command.',
190
+ },
191
+ stale_predecessor: {
192
+ repair: (detail, ctx) => `The plan changed after your input was built: re-read it with \`lattice plan show ${planOf(detail, ctx)} --json\`, rebuild the revision from the current plan, and rerun.`,
193
+ },
194
+ manifest_digest_changed: {
195
+ repair: (detail, ctx) => `The store changed since it was read: rerun \`${run(ctx)}\` unchanged.`,
196
+ },
197
+ revision_schema_or_digest_invalid: revisionDigest('revision'),
198
+ phase_revision_schema_or_digest_invalid: revisionDigest('phase revision'),
199
+ revision_set_schema_invalid: {
200
+ pointer: '--input',
201
+ repair: (detail, ctx) => `The revision set does not match its schema: see \`${schemaCommand(ctx)}\`.`,
202
+ },
203
+ schema_invalid: {
204
+ repair: (detail, ctx, pointer) => `The input${pointer === null ? '' : ` at ${pointer}`} does not match its schema: see \`${schemaCommand(ctx)}\`.`,
205
+ },
206
+ todo_extraction_schema_unsupported: {
207
+ pointer: '--input',
208
+ repair: () => 'Rebuild the extraction as lattice.todo_extraction.v4; see `lattice todo migrate --schema --json`.',
209
+ },
210
+
211
+ input_missing: {
212
+ pointer: inputFlag,
213
+ repair: (detail, ctx, pointer) => `${q(detail.input_ref)} does not exist: pass an existing repo file to ${pointer}.`,
214
+ },
215
+ input_ref_invalid: {
216
+ pointer: inputFlag,
217
+ repair: (detail, ctx, pointer) => `Pass a non-empty repo file path to ${pointer}.`,
218
+ },
219
+ unsafe_input_path: {
220
+ pointer: inputFlag,
221
+ repair: (detail, ctx, pointer) => `${q(detail.input_ref)} is not a regular file (symlink or directory): pass a regular repo file to ${pointer}.`,
222
+ },
223
+ input_path_outside_repo: {
224
+ pointer: inputFlag,
225
+ repair: (detail, ctx, pointer) => `Copy ${q(detail.input_ref)} into the repo and pass the repo path to ${pointer}.`,
226
+ },
227
+ input_size_limit_exceeded: inputFile('The input is over 8 MiB.'),
228
+ invalid_utf8: inputFile('The input is not valid UTF-8.'),
229
+ json_parse_failed: inputFile('The input is not valid JSON (no comments or trailing commas).'),
230
+ duplicate_key: inputFile('The input repeats a JSON object key.'),
231
+ note_input_invalid_utf8: inputFile('The input is not valid UTF-8.'),
232
+ note_input_too_large: inputFile('The input is too large.'),
233
+ evidence_input_invalid_utf8: {
234
+ pointer: '--evidence',
235
+ repair: () => 'Save the evidence file as UTF-8 and pass it to --evidence again.',
236
+ },
237
+ authored_evidence_descriptor_invalid: {
238
+ pointer: '--evidence',
239
+ repair: () => 'Pass a non-empty text file to --evidence (or use --message <text>) whose content can be stored as evidence.',
240
+ },
241
+ test_result_must_be_non_empty_markdown: {
242
+ pointer: '--test-result',
243
+ repair: () => 'Pass a non-empty Markdown file to --test-result.',
244
+ },
245
+
246
+ flag_missing: {
247
+ repair: (detail, ctx, pointer) => `Add ${pointer}${detail.expected?.type === 'boolean' ? '' : ' <value>'} to \`${run(ctx)}\`.`,
248
+ },
249
+ flag_takes_no_value: {
250
+ repair: (detail, ctx, pointer) => `${pointer} is a switch: pass it without a value to \`${run(ctx)}\`.`,
251
+ },
252
+ flag_unknown: {
253
+ repair: (detail, ctx, pointer) => `Remove ${pointer}: \`${run(ctx)}\` does not accept it; see \`${run(ctx, '--help')}\`.`,
254
+ },
255
+ path_token_invalid: {
256
+ repair: (detail, ctx, pointer) => `Give ${pointer} a repo file path (non-empty, not starting with '--').`,
257
+ },
258
+
259
+ plan_revise_schema_invalid: {
260
+ pointer: '--input',
261
+ repair: (detail, ctx) => `Use schema ${q(detail.expected)}; see \`${schemaCommand(ctx)}\`.`,
262
+ },
263
+ plan_revise_requires_source_revision: {
264
+ repair: (detail) => `This plan carries source revisions: use ${detail.next_action ?? '`lattice todo revise-phase --plan <plan> --input <file>`'}.`,
265
+ },
266
+ predecessor_plan_schema_unsupported: {
267
+ repair: (detail, ctx) => `Plan ${planOf(detail, ctx)} uses a schema that plan revise cannot extend; revise it with \`lattice todo revise-phase\`.`,
268
+ },
269
+ plan_revise_identity_mismatch: {
270
+ repair: () => 'Set /desired/project_id and /desired/plan_key to the active plan\'s values (see `lattice todo status --json`).',
271
+ },
272
+ plan_revise_continuity_incomplete: {
273
+ repair: (detail) => `Give /continuity exactly one entry for each of the plan's tasks ${names(strings(detail.expected?.task_ids))}.`,
274
+ },
275
+ plan_revise_continuity_invalid: {
276
+ repair: (detail, ctx, pointer) => `Fix the continuity entry at ${pointer}: it must name an existing task and a policy.`,
277
+ },
278
+ plan_revise_removed_task_mismatch: {
279
+ repair: (detail) => `Task ${q(detail.task_id)} is missing from /desired/tasks: either keep it there, or give it policy 'retire' in /continuity.`,
280
+ },
281
+ plan_revise_requires_backchain: {
282
+ repair: () => 'This plan has a backchain binding: revise it with `lattice plan backchain --input <file> --json`.',
283
+ },
284
+ plan_revise_artifact_invalid: {
285
+ repair: (detail, ctx) => `The derived revision is invalid; check /desired against \`${schemaCommand(ctx)}\`.`,
286
+ },
287
+
288
+ carry_semantics_changed: {
289
+ repair: (detail) => `Task ${migratedTask(detail)} changed its phase, dependencies or other carried meaning: restore it to match the predecessor, or migrate it with policy 'reset'.`,
290
+ },
291
+ carry_outgoing_edge_removed: {
292
+ repair: (detail) => `Task ${migratedTask(detail)} lost an outgoing dependency edge: add the edge back to the desired plan, or migrate the task with policy 'reset'.`,
293
+ },
294
+ phase_carry_semantics_changed: {
295
+ repair: (detail) => `Phase ${q(detail.from_phase_id)} changed its definition or members: restore it to match the predecessor, or migrate it with policy 'reset'.`,
296
+ },
297
+ predecessor_task_migration_incomplete: {
298
+ repair: () => 'List every predecessor task exactly once as from_task_id in task_migration, then rerun.',
299
+ },
300
+ predecessor_phase_migration_incomplete: {
301
+ repair: () => 'List every predecessor phase exactly once as from_phase_id in phase_migration, then rerun.',
302
+ },
303
+ design_memo_schema_downgrade: {
304
+ repair: (detail) => `The desired plan schema ${q(detail.desired_schema)} is older than ${q(detail.predecessor_schema)}: build the desired plan with ${q(detail.predecessor_schema)} or newer.`,
305
+ },
306
+ done_condition_schema_downgrade: {
307
+ repair: (detail) => `The desired plan schema ${q(detail.desired_schema)} drops done_condition from ${q(detail.predecessor_schema)}: build the desired plan with ${q(detail.predecessor_schema)}.`,
308
+ },
309
+ acquire_phase_requires_unassigned_predecessor: {
310
+ repair: (detail) => `Task ${migratedTask(detail)} already has a phase, so it cannot acquire one: migrate it with policy 'carry' or 'reset' instead.`,
311
+ },
312
+ acquire_phase_requires_assigned_successor: {
313
+ repair: (detail) => `Give the successor of task ${migratedTask(detail)} a phase_id when its policy is acquire_phase.`,
314
+ },
315
+ };
316
+
317
+ // PLAN_BACKCHAIN_INVALID reasons: one repair per family.
318
+ const BACKCHAIN_FAMILIES = [
319
+ [/^(authoring|binding|existing_feature_reference)_/u, 'Make the referenced file exist as a regular repo file holding valid JSON of the expected schema.'],
320
+ [/^(feature|task|required_feature|orphan|goal)/u, 'Make features, tasks and goal consistent: every required feature has a provider, every task provides what it declares, nothing repeats or cycles.'],
321
+ [/^(continuity|dependency)/u, 'Make /continuity cover every predecessor task exactly once and keep the dependencies tasks still need.'],
322
+ ];
323
+
324
+ function backchainRepair(detail, ctx, pointer) {
325
+ const family = BACKCHAIN_FAMILIES.find(([pattern]) => pattern.test(detail.reason ?? ''));
326
+ return `At ${pointer ?? '/'}: ${family?.[1] ?? 'Correct the value so it matches the backchain schema and recompute chain_digest.'} See \`${schemaCommand(ctx)}\`.`;
327
+ }
328
+
329
+ function registeredPointer(entry, detail, ctx) {
330
+ if (entry?.pointer === undefined) return undefined;
331
+ return typeof entry.pointer === 'function' ? entry.pointer(detail, ctx) : entry.pointer;
332
+ }
333
+
334
+ /**
335
+ * Returns a NEW detail with `pointer`, `rule` and `next_action` always set; every other key is kept.
336
+ * A concrete existing next_action wins; a placeholder token (^[a-z_]+$) is replaced by the registered repair.
337
+ * context = { family: 'todo' | 'plan', command, plan, task, flags } (all optional).
338
+ */
339
+ export function withRefusalGuidance({ code, message, detail }, context = {}) {
340
+ const base = record(detail) ? detail : {};
341
+ const rule = base.rule ?? base.violation_kind ?? base.violation_reason ?? base.reason ?? message;
342
+ const entry = Object.hasOwn(REGISTRY, rule) ? REGISTRY[rule] : undefined;
343
+ const pointer = [base.pointer, base.violation_path, registeredPointer(entry, base, context)]
344
+ .find((value) => typeof value === 'string') ?? null;
345
+
346
+ const existing = typeof base.next_action === 'string' && base.next_action.length > 0 ? base.next_action : null;
347
+ let nextAction = existing !== null && !PLACEHOLDER.test(existing) ? existing : null;
348
+ if (nextAction === null) {
349
+ const repair = entry?.repair(base, context, pointer)
350
+ ?? (code === 'PLAN_BACKCHAIN_INVALID' ? backchainRepair(base, context, pointer) : null);
351
+ nextAction = repair ?? existing ?? run(context, '--help');
352
+ }
353
+ return { ...base, pointer, rule, next_action: nextAction };
354
+ }
@@ -110,6 +110,7 @@ export async function reportProjectDashboardDelivery({ projectId, env, stderr,
110
110
  ? { stage: FAILURE_STAGES.get(subreason), subreason }
111
111
  : { stage: 'unknown', subreason: 'unavailable' };
112
112
  }
113
- stderr?.write(`${JSON.stringify(delivery)}\n`);
113
+ // a15: only a failed delivery is news on a write; no bridge or a delivered page says nothing.
114
+ if (delivery.state === 'failed') stderr?.write(`${JSON.stringify(delivery)}\n`);
114
115
  return delivery;
115
116
  }
package/src/hooks-cli.mjs CHANGED
@@ -446,6 +446,34 @@ function stripIdentity(value, identities, host) {
446
446
  return removed;
447
447
  }
448
448
 
449
+ // Install: Lattice's own entry is replaced where it stands; other products' entries keep their
450
+ // positions (Codex [hooks.state] keys trusted_hash by position). Only a first install appends.
451
+ function replaceIdentity(value, identities, host, entry) {
452
+ let removed = 0;
453
+ let placed = false;
454
+ const name = eventName(host);
455
+ const list = hooksList(value, host);
456
+ const owned = (item) => isCommandHandler(item, host) && commandIs(item.command, identities);
457
+ const take = () => {
458
+ removed += 1;
459
+ if (placed) return [];
460
+ placed = true;
461
+ return [entry];
462
+ };
463
+ if (isFlatHost(host)) {
464
+ value.hooks[name] = list.flatMap((item) => (owned(item) ? take() : [item]));
465
+ if (!placed) value.hooks[name].push(entry);
466
+ return removed;
467
+ }
468
+ value.hooks[name] = list.flatMap((wrapper) => {
469
+ if (!wrapper || !Array.isArray(wrapper.hooks)) return [wrapper];
470
+ const handlers = wrapper.hooks.flatMap((item) => (owned(item) ? take() : [item]));
471
+ return handlers.length > 0 ? [{ ...wrapper, hooks: handlers }] : [];
472
+ });
473
+ if (!placed) value.hooks[name].push({ hooks: [entry] });
474
+ return removed;
475
+ }
476
+
449
477
  function hostHandler(host, command) {
450
478
  if (host === 'claude') return { type: 'command', command, timeout: 5 };
451
479
  if (host === 'cursor') return { command, timeout: 5 };
@@ -683,12 +711,8 @@ async function mutate(host, env, stdout, uninstall, source, platform, testHooks)
683
711
  const identities = [current, ...committedIdentities(receipt)];
684
712
  const next = structuredClone(prestate.value);
685
713
  if (host === 'cursor' && next.version === undefined) next.version = 1;
686
- const removed = stripIdentity(next, identities, host);
687
- if (!uninstall) {
688
- const entry = hostHandler(host, shell(current));
689
- if (isFlatHost(host)) hooksList(next, host).push(entry);
690
- else hooksList(next, host).push({ hooks: [entry] });
691
- }
714
+ const removed = uninstall ? stripIdentity(next, identities, host)
715
+ : replaceIdentity(next, identities, host, hostHandler(host, shell(current)));
692
716
 
693
717
  const currentHandlers = allHandlers(prestate.value, host).filter((item) => (
694
718
  isCommandHandler(item, host) && commandIs(item.command, identities)