@quolu/lattice 0.82.0 → 0.84.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 (77) hide show
  1. package/README.ja.md +7 -6
  2. package/README.md +1 -1
  3. package/bin/lattice-bridge-supervisor.mjs +10 -0
  4. package/bin/lattice-dashboard.mjs +3 -18
  5. package/bin/lattice-mcp.mjs +6 -3
  6. package/bin/lattice.mjs +30 -23
  7. package/docs/schemas/lattice.plan_create_input.v4.schema.json +5 -11
  8. package/docs/schemas/lattice.plan_create_input.v5.schema.json +362 -0
  9. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +38 -11
  10. package/package.json +2 -1
  11. package/sensor/dist/db/index.d.ts +1 -0
  12. package/sensor/dist/db/index.d.ts.map +1 -1
  13. package/sensor/dist/db/index.js +13 -0
  14. package/sensor/dist/db/index.js.map +1 -1
  15. package/sensor/dist/index.d.ts.map +1 -1
  16. package/sensor/dist/index.js +12 -2
  17. package/sensor/dist/index.js.map +1 -1
  18. package/sensor/dist/mcp/answer-freshness.js +1 -1
  19. package/sensor/dist/mcp/answer-freshness.js.map +1 -1
  20. package/sensor/dist/mcp/daemon-paths.d.ts +6 -0
  21. package/sensor/dist/mcp/daemon-paths.d.ts.map +1 -1
  22. package/sensor/dist/mcp/daemon-paths.js +7 -1
  23. package/sensor/dist/mcp/daemon-paths.js.map +1 -1
  24. package/sensor/dist/mcp/engine.d.ts +11 -0
  25. package/sensor/dist/mcp/engine.d.ts.map +1 -1
  26. package/sensor/dist/mcp/engine.js +83 -4
  27. package/sensor/dist/mcp/engine.js.map +1 -1
  28. package/sensor/dist/mcp/index-repair.d.ts +7 -0
  29. package/sensor/dist/mcp/index-repair.d.ts.map +1 -0
  30. package/sensor/dist/mcp/index-repair.js +93 -0
  31. package/sensor/dist/mcp/index-repair.js.map +1 -0
  32. package/sensor/dist/mcp/index.d.ts.map +1 -1
  33. package/sensor/dist/mcp/index.js +12 -7
  34. package/sensor/dist/mcp/index.js.map +1 -1
  35. package/sensor/dist/mcp/tools.d.ts +4 -0
  36. package/sensor/dist/mcp/tools.d.ts.map +1 -1
  37. package/sensor/dist/mcp/tools.js +29 -9
  38. package/sensor/dist/mcp/tools.js.map +1 -1
  39. package/src/bridge-hub-server.mjs +46 -9
  40. package/src/cli-help.mjs +10 -8
  41. package/src/cli-refusal-guidance.mjs +354 -0
  42. package/src/dashboard-delivery.mjs +2 -1
  43. package/src/dashboard-lifecycle-journal.mjs +42 -20
  44. package/src/hooks-cli.mjs +30 -6
  45. package/src/plan-backchain.mjs +95 -41
  46. package/src/plan-revise.mjs +274 -72
  47. package/src/project-cli.mjs +301 -163
  48. package/src/project-identity.mjs +14 -0
  49. package/src/runtime-cli.mjs +38 -29
  50. package/src/runtime-control-store.mjs +22 -1
  51. package/src/runtime-decision-verifier.mjs +27 -8
  52. package/src/runtime-engine.mjs +34 -5
  53. package/src/runtime-hold-recompile.mjs +19 -15
  54. package/src/runtime-kept-worktree.mjs +136 -0
  55. package/src/runtime-lifecycle-lock.mjs +118 -30
  56. package/src/runtime-managed-supervisor.mjs +10 -10
  57. package/src/runtime-pull-intake.mjs +90 -44
  58. package/src/store-lock.mjs +142 -57
  59. package/src/todo-authoring-input.mjs +211 -2
  60. package/src/todo-cli.mjs +554 -200
  61. package/src/todo-contracts.mjs +22 -6
  62. package/src/todo-dashboard-registry.mjs +35 -6
  63. package/src/todo-gantt-display.mjs +259 -0
  64. package/src/todo-gantt-html-independence.mjs +10 -3
  65. package/src/todo-gantt-html-shared.mjs +16 -1
  66. package/src/todo-gantt-html.mjs +74 -53
  67. package/src/todo-gantt-layout.mjs +137 -59
  68. package/src/todo-gantt-live.mjs +6 -3
  69. package/src/todo-independence-guidance.mjs +4 -26
  70. package/src/todo-note-store.mjs +6 -3
  71. package/src/todo-readiness.mjs +83 -20
  72. package/src/todo-revision.mjs +156 -8
  73. package/src/todo-split.mjs +6 -3
  74. package/src/todo-status.mjs +141 -54
  75. package/src/todo-store-cache.mjs +1 -1
  76. package/src/todo-store-view.mjs +20 -2
  77. package/src/todo-store.mjs +562 -444
@@ -26,7 +26,7 @@ import { isIP } from 'node:net';
26
26
  import { randomBytes } from 'node:crypto';
27
27
  import { homedir } from 'node:os';
28
28
  import {
29
- mkdir, open, readFile, rename, rm, writeFile,
29
+ mkdir, open, readdir, readFile, rename, rm, writeFile,
30
30
  } from 'node:fs/promises';
31
31
  import path from 'node:path';
32
32
  import { domainToASCII } from 'node:url';
@@ -373,12 +373,40 @@ export async function readBridgeHubPublicVisibility({ env = process.env } = {})
373
373
  };
374
374
  }
375
375
 
376
+ const QUARANTINE_KEEP = 3;
377
+
378
+ /**
379
+ * u03 D20: an unreadable registry is moved aside (`terminals.json.invalid-<UTC>`, newest 3
380
+ * kept) and read as empty, so the hub keeps serving and terminals register again. A failed
381
+ * move leaves the file; the next read retries.
382
+ */
383
+ async function quarantineRegistry(ref) {
384
+ // The random tail keeps two moves in the same millisecond from overwriting each other.
385
+ const stamp = `${new Date().toISOString().replace(/[:.]/gu, '-')}-${randomBytes(4).toString('hex')}`;
386
+ try { await rename(ref, `${ref}.invalid-${stamp}`); } catch { return; }
387
+ process.emitWarning(`hub registry was invalid and moved aside: ${ref}.invalid-${stamp}`,
388
+ { code: 'LATTICE_BRIDGE_HUB_REGISTRY_QUARANTINED' });
389
+ const prefix = `${path.basename(ref)}.invalid-`;
390
+ const names = (await readdir(path.dirname(ref)).catch(() => []))
391
+ .filter((name) => name.startsWith(prefix)).sort().reverse();
392
+ for (const name of names.slice(QUARANTINE_KEEP)) {
393
+ await rm(path.join(path.dirname(ref), name), { force: true }).catch(() => {});
394
+ }
395
+ }
396
+
376
397
  /** Read the persisted registry. A missing file is an empty registry, not an error. */
377
398
  export async function readBridgeHubRegistry({ env = process.env } = {}) {
378
399
  const refs = hubRuntimePaths(env);
379
- const document = await readJsonDocument(refs.registry, { schema: HUB_REGISTRY_DOCUMENT_SCHEMA, entries: [] });
380
- if (!validRegistryDocument(document)) {
381
- throw new BridgeHubServerError('BRIDGE_HUB_REGISTRY_FILE_INVALID', 'hub registry file is invalid');
400
+ let document;
401
+ try {
402
+ document = await readJsonDocument(refs.registry, { schema: HUB_REGISTRY_DOCUMENT_SCHEMA, entries: [] });
403
+ } catch (error) {
404
+ if (error?.code !== 'BRIDGE_HUB_REGISTRY_FILE_INVALID') throw error;
405
+ document = null;
406
+ }
407
+ if (document === null || !validRegistryDocument(document)) {
408
+ await quarantineRegistry(refs.registry);
409
+ return [];
382
410
  }
383
411
  return document.entries;
384
412
  }
@@ -482,14 +510,22 @@ export async function startBridgeHubServer({
482
510
  return;
483
511
  }
484
512
  const entries = await store.read();
485
- const visibility = await readBridgeHubPublicVisibility({ env });
486
- const hiddenProjects = new Set(visibility.hidden_project_ids);
487
- const hiddenTerminals = new Set(visibility.hidden_terminal_ids);
513
+ let visibility;
514
+ try { visibility = await readBridgeHubPublicVisibility({ env }); } catch (error) {
515
+ if (error?.code !== 'BRIDGE_HUB_VISIBILITY_FILE_INVALID') throw error;
516
+ // u03 D20: the operator's hide list is unreadable. Never publish what it may hide, never
517
+ // stop the hub: list nothing until the file is fixed (hot-read, no restart needed).
518
+ process.emitWarning(`hub public-visibility file is invalid; the listing is empty until it is fixed`,
519
+ { code: 'LATTICE_BRIDGE_HUB_VISIBILITY_INVALID' });
520
+ visibility = null;
521
+ }
522
+ const hiddenProjects = new Set(visibility?.hidden_project_ids ?? []);
523
+ const hiddenTerminals = new Set(visibility?.hidden_terminal_ids ?? []);
488
524
  // The visibility filter applies to the listing only (both HTML and JSON);
489
525
  // `/projects/<hidden>/` keeps proxying — hidden is not private (ADR 0164
490
526
  // Decision 3, deliberately: smoke tests fetch their own page, operators
491
527
  // keep the direct URL).
492
- const projected = projectBridgeHubRegistry({ registry: entries, now: now(), ttlMs })
528
+ const projected = visibility === null ? [] : projectBridgeHubRegistry({ registry: entries, now: now(), ttlMs })
493
529
  .filter((entry) => !hiddenProjects.has(entry.project_id) && !hiddenTerminals.has(entry.terminal_id));
494
530
  // Only the fields humans need for the public index are exposed; internal
495
531
  // routing fields (terminal_id, address, port) stay server-side, matching
@@ -517,7 +553,8 @@ export async function startBridgeHubServer({
517
553
  response.end(`${JSON.stringify(view)}\n`);
518
554
  return;
519
555
  }
520
- const html = renderBridgeHubLanding({ projects: view, lang, displayNames: visibility.display_names });
556
+ const html = renderBridgeHubLanding({ projects: view, lang,
557
+ displayNames: visibility?.display_names ?? EMPTY_VISIBILITY.display_names });
521
558
  response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store',
522
559
  'x-content-type-options': 'nosniff' });
523
560
  response.end(html);
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を返す
31
- create --schema-version <1|2|3|4> --json
30
+ create --schema --json # 既定は最新版(v5)のJSON Schemaを返す
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> --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: no bridge is the seat's choice, not a failure; say nothing on every write.
114
+ if (delivery.state !== 'local_only') stderr?.write(`${JSON.stringify(delivery)}\n`);
114
115
  return delivery;
115
116
  }
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { constants } from 'node:fs';
3
- import { lstat, mkdir, open, readdir, readFile, rename, rm } from 'node:fs/promises';
3
+ import { lstat, mkdir, open, readdir, rename, rm } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
 
6
6
  const SCHEMA = 'lattice.dashboard_lifecycle.v1';
@@ -64,6 +64,40 @@ export async function prepareLifecycleDirectory(root) {
64
64
  }
65
65
  }
66
66
 
67
+ const QUARANTINE_KEEP = 8;
68
+
69
+ /**
70
+ * u03 D-lifecycle: an unreadable record is diagnostic history, never a reason to stop the
71
+ * dashboard. Move it aside as `<name>.invalid` (newest QUARANTINE_KEEP kept) and go on.
72
+ * A failed move only leaves the file in place; the next read tries again.
73
+ */
74
+ async function quarantineLifecycleRecord(ref) {
75
+ try { await rename(ref, `${ref}.invalid`); } catch { return; }
76
+ process.emitWarning(`dashboard lifecycle record was invalid and moved aside: ${ref}.invalid`,
77
+ { code: 'LATTICE_DASHBOARD_LIFECYCLE_QUARANTINED' });
78
+ const parent = path.dirname(ref);
79
+ const kept = [];
80
+ for (const name of await readdir(parent).catch(() => [])) {
81
+ if (!name.endsWith('.json.invalid')) continue;
82
+ const info = await lstat(path.join(parent, name)).catch(() => null);
83
+ if (info?.isFile()) kept.push({ name, mtime: info.mtimeMs });
84
+ }
85
+ kept.sort((a, b) => b.mtime - a.mtime);
86
+ for (const { name } of kept.slice(QUARANTINE_KEEP)) await rm(path.join(parent, name), { force: true }).catch(() => {});
87
+ }
88
+
89
+ async function readLifecycleRecord(ref, valid) {
90
+ const info = await checkOwned(ref, 'file');
91
+ let value = null;
92
+ if (info.size <= LIFECYCLE_MAX_BYTES) {
93
+ const handle = await open(ref, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
94
+ try { value = JSON.parse(await handle.readFile('utf8')); } catch { value = null; } finally { await handle.close(); }
95
+ }
96
+ if (value !== null && valid(value)) return value;
97
+ await quarantineLifecycleRecord(ref);
98
+ return null;
99
+ }
100
+
67
101
  export async function readLifecycleRuns(root) {
68
102
  try { await checkOwned(directory(root), 'directory'); } catch (error) {
69
103
  if (error.code === 'ENOENT') return [];
@@ -72,19 +106,11 @@ export async function readLifecycleRuns(root) {
72
106
  const runs = [];
73
107
  for (const name of (await readdir(directory(root))).sort()) {
74
108
  if (!name.endsWith('.json') || !RUN_ID.test(name.slice(0, -5))) continue;
75
- const ref = path.join(directory(root), name);
76
- const info = await checkOwned(ref, 'file');
77
- if (info.size > LIFECYCLE_MAX_BYTES) throw lifecycleError('DASHBOARD_LIFECYCLE_INVALID');
78
- const handle = await open(ref, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
79
- let value;
80
- try { value = JSON.parse(await handle.readFile('utf8')); }
81
- catch { throw lifecycleError('DASHBOARD_LIFECYCLE_INVALID'); }
82
- finally { await handle.close(); }
83
- if (value?.schema !== SCHEMA || value.run_id !== name.slice(0, -5)
84
- || !['active', 'closed', 'supervisor_lost'].includes(value.state)) {
85
- throw lifecycleError('DASHBOARD_LIFECYCLE_INVALID');
86
- }
87
- runs.push(value);
109
+ const value = await readLifecycleRecord(path.join(directory(root), name), (record) =>
110
+ record?.schema === SCHEMA && record.run_id === name.slice(0, -5)
111
+ && typeof record.started_at === 'string'
112
+ && ['active', 'closed', 'supervisor_lost'].includes(record.state));
113
+ if (value !== null) runs.push(value);
88
114
  }
89
115
  return runs.sort((a, b) => a.started_at.localeCompare(b.started_at));
90
116
  }
@@ -224,12 +250,8 @@ export async function readDashboardLifecycleStatus(root) {
224
250
  terminationTime(a).localeCompare(terminationTime(b)));
225
251
  let ensure = null;
226
252
  try {
227
- const ref = path.join(directory(root), 'ensure.json');
228
- const info = await checkOwned(ref, 'file');
229
- if (info.size > LIFECYCLE_MAX_BYTES) throw lifecycleError('DASHBOARD_LIFECYCLE_INVALID');
230
- try { ensure = JSON.parse(await readFile(ref, 'utf8')); }
231
- catch { throw lifecycleError('DASHBOARD_LIFECYCLE_INVALID'); }
232
- if (ensure.schema !== 'lattice.dashboard_ensure.v1') throw lifecycleError('DASHBOARD_LIFECYCLE_INVALID');
253
+ ensure = await readLifecycleRecord(path.join(directory(root), 'ensure.json'),
254
+ (record) => record?.schema === 'lattice.dashboard_ensure.v1');
233
255
  } catch (error) { if (error.code !== 'ENOENT') throw error; }
234
256
  return { schema: 'lattice.dashboard_lifecycle_status.v1',
235
257
  last_ensure: ensure, active: runs.filter((run) => run.state === 'active'),
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)