@quolu/lattice 0.82.0 → 0.83.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 (66) hide show
  1. package/bin/lattice-bridge-supervisor.mjs +10 -0
  2. package/bin/lattice-dashboard.mjs +3 -18
  3. package/bin/lattice-mcp.mjs +6 -3
  4. package/bin/lattice.mjs +1 -1
  5. package/docs/schemas/lattice.plan_create_input.v5.schema.json +375 -0
  6. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +6 -3
  7. package/package.json +2 -1
  8. package/sensor/dist/db/index.d.ts +1 -0
  9. package/sensor/dist/db/index.d.ts.map +1 -1
  10. package/sensor/dist/db/index.js +13 -0
  11. package/sensor/dist/db/index.js.map +1 -1
  12. package/sensor/dist/index.d.ts.map +1 -1
  13. package/sensor/dist/index.js +12 -2
  14. package/sensor/dist/index.js.map +1 -1
  15. package/sensor/dist/mcp/answer-freshness.js +1 -1
  16. package/sensor/dist/mcp/answer-freshness.js.map +1 -1
  17. package/sensor/dist/mcp/engine.d.ts +11 -0
  18. package/sensor/dist/mcp/engine.d.ts.map +1 -1
  19. package/sensor/dist/mcp/engine.js +83 -4
  20. package/sensor/dist/mcp/engine.js.map +1 -1
  21. package/sensor/dist/mcp/index-repair.d.ts +7 -0
  22. package/sensor/dist/mcp/index-repair.d.ts.map +1 -0
  23. package/sensor/dist/mcp/index-repair.js +93 -0
  24. package/sensor/dist/mcp/index-repair.js.map +1 -0
  25. package/sensor/dist/mcp/index.d.ts.map +1 -1
  26. package/sensor/dist/mcp/index.js +12 -7
  27. package/sensor/dist/mcp/index.js.map +1 -1
  28. package/sensor/dist/mcp/tools.d.ts +4 -0
  29. package/sensor/dist/mcp/tools.d.ts.map +1 -1
  30. package/sensor/dist/mcp/tools.js +29 -9
  31. package/sensor/dist/mcp/tools.js.map +1 -1
  32. package/src/bridge-hub-server.mjs +46 -9
  33. package/src/cli-help.mjs +2 -2
  34. package/src/dashboard-lifecycle-journal.mjs +42 -20
  35. package/src/plan-backchain.mjs +25 -8
  36. package/src/plan-revise.mjs +129 -28
  37. package/src/project-cli.mjs +42 -18
  38. package/src/project-identity.mjs +14 -0
  39. package/src/runtime-cli.mjs +31 -18
  40. package/src/runtime-control-store.mjs +22 -1
  41. package/src/runtime-decision-verifier.mjs +27 -8
  42. package/src/runtime-engine.mjs +34 -5
  43. package/src/runtime-hold-recompile.mjs +19 -15
  44. package/src/runtime-kept-worktree.mjs +136 -0
  45. package/src/runtime-lifecycle-lock.mjs +118 -30
  46. package/src/runtime-managed-supervisor.mjs +10 -10
  47. package/src/runtime-pull-intake.mjs +87 -43
  48. package/src/store-lock.mjs +142 -57
  49. package/src/todo-authoring-input.mjs +56 -2
  50. package/src/todo-cli.mjs +168 -42
  51. package/src/todo-contracts.mjs +22 -6
  52. package/src/todo-dashboard-registry.mjs +31 -4
  53. package/src/todo-gantt-display.mjs +260 -0
  54. package/src/todo-gantt-html-independence.mjs +8 -1
  55. package/src/todo-gantt-html-shared.mjs +2 -1
  56. package/src/todo-gantt-html.mjs +4 -2
  57. package/src/todo-gantt-layout.mjs +7 -36
  58. package/src/todo-gantt-live.mjs +6 -3
  59. package/src/todo-note-store.mjs +6 -3
  60. package/src/todo-readiness.mjs +29 -8
  61. package/src/todo-revision.mjs +9 -8
  62. package/src/todo-split.mjs +6 -3
  63. package/src/todo-status.mjs +53 -9
  64. package/src/todo-store-cache.mjs +1 -1
  65. package/src/todo-store-view.mjs +21 -2
  66. package/src/todo-store.mjs +545 -166
@@ -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
@@ -28,7 +28,7 @@ Commands:
28
28
  create --input <file> [--serialization-reviewed]
29
29
  # 結果へdispatch_shapeを載せる。--serialization-reviewedは互換のため受理するだけで門ではない
30
30
  create --schema --json # 既定は最新版(v4)のJSON Schemaを返す
31
- create --schema-version <1|2|3|4> --json
31
+ create --schema-version <1|2|3|4|5> --json
32
32
  backchain --schema --json # 最終成果から必要な機能を逆算する入力契約
33
33
  revise --input <file> [--dry-run] --json # 工程の全体と明示した状態移行から改訂する
34
34
  revise --schema --json
@@ -233,7 +233,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
233
233
  'setup status': 'setup status [--host <claude|codex|grok|cursor|all>] [--json]',
234
234
  status: 'status --json',
235
235
  'session-context': 'session-context --json',
236
- 'plan create': 'plan create --input <file> [--serialization-reviewed] | --schema --json | --schema-version <1|2|3|4> --json',
236
+ 'plan create': 'plan create --input <file> [--serialization-reviewed] | --schema --json | --schema-version <1|2|3|4|5> --json',
237
237
  'plan show': 'plan show <plan_key> --json',
238
238
  'plan scope-review': 'plan scope-review --plan-input <plan-create-or-extraction.json> --review <scope-review.json> --json | --schema --json',
239
239
  'plan backchain': 'plan backchain --input <file> [--dry-run] --json | --schema --json',
@@ -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'),
@@ -342,11 +342,27 @@ async function verifyExistingFeatureReferences(repoRoot, chain) {
342
342
  }
343
343
  }
344
344
 
345
- export function planSeed(authoring, predecessorPlanDigest) {
345
+ const DONE_CONDITION_PLAN_SCHEMA = 'lattice.todo_plan.v8';
346
+
347
+ /**
348
+ * authoring(create入力またはplan本体)から後継planの種を作る。
349
+ * 作る版: v5入力か先行planがv8ならv8(v8→v7へ戻さない)、それ以外はv7。
350
+ * v8でdone_conditionを書いていないtask(v4入力)は、先行planの同じtaskの値を引き継ぐ
351
+ * (書き換えも消去もしていないので意味を変えない)。新規taskはnull。
352
+ */
353
+ export function planSeed(authoring, predecessorPlanDigest, predecessorPlan = null) {
354
+ const v8 = authoring.schema === 'lattice.plan_create_input.v5'
355
+ || authoring.schema === DONE_CONDITION_PLAN_SCHEMA
356
+ || predecessorPlan?.schema === DONE_CONDITION_PLAN_SCHEMA;
357
+ const inherited = new Map(predecessorPlan?.schema === DONE_CONDITION_PLAN_SCHEMA
358
+ ? predecessorPlan.tasks.map(({ task_id: id, done_condition: value }) => [id, value]) : []);
346
359
  return {
347
- schema: 'lattice.todo_plan.v7', project_id: authoring.project_id,
360
+ schema: v8 ? DONE_CONDITION_PLAN_SCHEMA : 'lattice.todo_plan.v7', project_id: authoring.project_id,
348
361
  plan_key: authoring.plan_key, predecessor_plan_digest: predecessorPlanDigest,
349
- tasks: authoring.tasks, phases: authoring.phases,
362
+ tasks: v8 ? authoring.tasks.map((task) => ({ ...task,
363
+ done_condition: Object.hasOwn(task, 'done_condition')
364
+ ? task.done_condition : inherited.get(task.task_id) ?? null })) : authoring.tasks,
365
+ phases: authoring.phases,
350
366
  hard_dependencies: authoring.hard_dependencies, joins: authoring.joins,
351
367
  phase_accept_dependencies: authoring.phase_accept_dependencies,
352
368
  };
@@ -434,7 +450,7 @@ export function compilePhaseMigration(previousPlan, desiredSeed, taskMigration)
434
450
  }
435
451
 
436
452
  async function compileBackchainRevision({ repoRoot, member, chain, authoring }) {
437
- if (member.plan.schema !== 'lattice.todo_plan.v7') {
453
+ if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA].includes(member.plan.schema)) {
438
454
  fail('predecessor_plan_schema_unsupported', '/plan_key', {
439
455
  actual: member.plan.schema, next_action: 'author_a_new_backchain_plan',
440
456
  });
@@ -447,7 +463,7 @@ async function compileBackchainRevision({ repoRoot, member, chain, authoring })
447
463
  journal_head_digest: member.journal.events.at(-1).event_digest,
448
464
  plan_version: member.plan.plan_version,
449
465
  };
450
- const seed = planSeed(amended, predecessor.plan_digest);
466
+ const seed = planSeed(amended, predecessor.plan_digest, member.plan);
451
467
  const taskMigration = compileTaskMigration(member.plan, previousChain, seed, chain);
452
468
  const phaseMigration = compilePhaseMigration(member.plan, seed, taskMigration);
453
469
  const version = phaseTodoRevisionPlanVersion({
@@ -477,12 +493,13 @@ async function compileBackchainRevision({ repoRoot, member, chain, authoring })
477
493
  }
478
494
 
479
495
  async function activeIntentUnchanged({ repoRoot, member, chain, authoring }) {
480
- if (member.plan.schema !== 'lattice.todo_plan.v7') return false;
496
+ if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA].includes(member.plan.schema)) return false;
481
497
  const binding = await readPlanBackchainBinding({ repoRoot, plan: member.plan });
482
498
  if (binding === null || featureGraphDigest(binding.chain) !== featureGraphDigest(chain)) return false;
483
499
  const amended = attachBackchainMemos(chain, authoring, { previousChain: binding.chain });
484
- return canonicalizeTodoArtifact({
485
- tasks: amended.tasks, phases: amended.phases,
500
+ const seed = planSeed(amended, null, member.plan);
501
+ return seed.schema === member.plan.schema && canonicalizeTodoArtifact({
502
+ tasks: seed.tasks, phases: amended.phases,
486
503
  hard_dependencies: amended.hard_dependencies, joins: amended.joins,
487
504
  phase_accept_dependencies: amended.phase_accept_dependencies,
488
505
  }) === canonicalizeTodoArtifact({
@@ -5,12 +5,11 @@ import { canonicalizeTodoArtifact, exactRecord, isTodoIdentifier, todoSelfDigest
5
5
  import { gitSync } from './git-process.mjs';
6
6
  import { readAuthoringJsonFile, repairAuthoringArtifact } from './todo-authoring-input.mjs';
7
7
  import { validatePlanCreateInput } from './project-cli.mjs';
8
- import {
9
- compilePhaseMigration, planSeed, readPlanBackchainBinding, rebindCarriedWork,
10
- } from './plan-backchain.mjs';
8
+ import { planSeed, readPlanBackchainBinding, rebindCarriedWork } from './plan-backchain.mjs';
11
9
  import {
12
10
  applyPhaseTodoRevision, buildTodoPlan, createTodoStoreWriter, readTodoStore, TodoStoreError,
13
11
  } from './todo-store.mjs';
12
+ import { appendTodoNote } from './todo-note-store.mjs';
14
13
  import { phaseTodoRevisionPlanVersion, validatePhaseTodoRevision } from './todo-revision.mjs';
15
14
 
16
15
  export { validateBindingCarry } from './plan-binding-carry.mjs';
@@ -21,6 +20,122 @@ function fail(reason, pointer, detail = {}) {
21
20
  throw new TodoStoreError('INPUT_INVALID', reason, undefined, { pointer, ...detail });
22
21
  }
23
22
 
23
+ /**
24
+ * 軽量改訂のphase移行。作成者が書いた手順の改訂は完了済み・進行中でも許すので、
25
+ * taskの文面や辺の変更ではPhaseを巻き込まない。resetするのは次の2つだけ:
26
+ * 1. Phase定義(title・gate_policy・predecessor_phase_ids・required_evidence_slots)が変わった。
27
+ * 2. 新手順の下で再審査が要る task を迎えた——新規task、他Phaseから移ったtask、resetするtask——
28
+ * で、その行き先の状態がdone/retiredでない。
29
+ * 失うだけ、または完了済みだけを迎えるPhaseは受理済みのまま持ち越す。
30
+ * backchainのcompilePhaseMigrationとは別の規則で、あちらは変えない。
31
+ */
32
+ export function compileLightPhaseMigration(previousPlan, desiredSeed, taskMigration, taskStates) {
33
+ const policyById = new Map(taskMigration.map((row) => [row.from_task_id, row.state_policy]));
34
+ const previousById = new Map(previousPlan.tasks.map((task) => [task.task_id, task]));
35
+ const definition = ({ title, gate_policy: gatePolicy, predecessor_phase_ids: predecessors,
36
+ required_evidence_slots: slots }) => canonicalizeTodoArtifact({
37
+ title, gate_policy: gatePolicy, predecessor_phase_ids: predecessors, required_evidence_slots: slots });
38
+ const gaining = new Set();
39
+ for (const task of desiredSeed.tasks) {
40
+ const previous = previousById.get(task.task_id);
41
+ const reset = policyById.get(task.task_id) === 'reset_pending';
42
+ const arrives = previous === undefined || reset || previous.phase_id !== task.phase_id;
43
+ const state = previous === undefined || reset ? 'pending' : taskStates.get(task.task_id);
44
+ if (arrives && !['done', 'retired'].includes(state)) gaining.add(task.phase_id);
45
+ }
46
+ const nextPhases = new Map(desiredSeed.phases.map((phase) => [phase.phase_id, phase]));
47
+ const oldPhaseIds = new Set(previousPlan.phases.map(({ phase_id: id }) => id));
48
+ return [
49
+ ...previousPlan.phases.map((phase) => {
50
+ const next = nextPhases.get(phase.phase_id);
51
+ if (next === undefined) {
52
+ return { from_phase_id: phase.phase_id, to_phase_id: 'removed', state_policy: 'removed' };
53
+ }
54
+ const carry = !gaining.has(phase.phase_id) && definition(phase) === definition(next);
55
+ return { from_phase_id: phase.phase_id, to_phase_id: phase.phase_id,
56
+ state_policy: carry ? 'carry' : 'reset' };
57
+ }),
58
+ ...desiredSeed.phases.filter(({ phase_id: id }) => !oldPhaseIds.has(id))
59
+ .map(({ phase_id: id }) => ({ from_phase_id: null, to_phase_id: id, state_policy: 'reset' })),
60
+ ];
61
+ }
62
+
63
+ const nullable = (value) => (value === undefined ? null : value);
64
+
65
+ /** 履歴note用に、taskの作成者が書いた面を欄ごとに正準化して返す。 */
66
+ function authoredSurface(plan, taskId) {
67
+ const task = plan.tasks.find(({ task_id: id }) => id === taskId);
68
+ const local = (ref) => ref.plan_key === plan.plan_key && ref.task_id === taskId;
69
+ const rows = (list) => canonicalizeTodoArtifact(list.map((row) => canonicalizeTodoArtifact(row)).sort());
70
+ return {
71
+ title: nullable(task.title), lane: task.lane, design_memo: nullable(task.design_memo),
72
+ done_condition: nullable(task.done_condition), narrative_ref: nullable(task.narrative_ref),
73
+ parent_task_id: nullable(task.parent_task_id), phase_id: nullable(task.phase_id),
74
+ incoming_hard_dependencies: rows(plan.hard_dependencies.filter(({ to }) => local(to))),
75
+ outgoing_hard_dependencies: rows(plan.hard_dependencies.filter(({ from }) => local(from))),
76
+ join_memberships: rows(plan.joins.filter(({ before, after }) => local(before) || after.some(local))),
77
+ phase_accept_dependencies: rows((plan.phase_accept_dependencies ?? []).filter(({ to }) => local(to))),
78
+ };
79
+ }
80
+
81
+ /**
82
+ * 改訂の履歴note。変わったcarry taskごとにtask note1件(変わった欄の全列挙つき)と、
83
+ * 取り除いたtaskごとにplan note1件。本文は `plan revise <from>→<to> <task_id>: <reason>`。
84
+ */
85
+ export function planRevisionHistoryNotes({ previousPlan, successorPlan, continuity }) {
86
+ const prefix = (taskId) => `plan revise ${previousPlan.plan_version}→${successorPlan.plan_version} ${taskId}:`;
87
+ const notes = [];
88
+ const ordered = [...continuity].sort((left, right) => (
89
+ left.task_id < right.task_id ? -1 : left.task_id > right.task_id ? 1 : 0));
90
+ for (const { task_id: taskId, policy, reason } of ordered) {
91
+ if (policy === 'retire') {
92
+ notes.push({ scope: 'plan', task_id: taskId, body: `${prefix(taskId)} ${reason}` });
93
+ } else if (policy === 'carry') {
94
+ const before = authoredSurface(previousPlan, taskId);
95
+ const after = authoredSurface(successorPlan, taskId);
96
+ const changed = Object.keys(before).filter((field) => before[field] !== after[field]);
97
+ if (changed.length > 0) {
98
+ notes.push({ scope: 'task', task_id: taskId,
99
+ body: `${prefix(taskId)} ${reason}\nchanged: ${changed.join(', ')}` });
100
+ }
101
+ }
102
+ }
103
+ return notes;
104
+ }
105
+
106
+ const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
107
+
108
+ /** 公開後にnoteを順に追記する。失敗したら、まだ書けていないnoteと正確な再実行commandを返す。 */
109
+ async function appendRevisionHistoryNotes({ repoRoot, revision, notes, actor }) {
110
+ const planKey = revision.plan_key;
111
+ const planVersion = revision.desired_plan.plan_version;
112
+ const pending = [...notes];
113
+ try {
114
+ while (pending.length > 0) {
115
+ const [note] = pending;
116
+ await appendTodoNote({
117
+ repoRoot, projectId: revision.project_id, planKey, planVersion,
118
+ taskId: note.scope === 'task' ? note.task_id : null,
119
+ actor, recordedAt: new Date().toISOString(), body: note.body,
120
+ supersedes: null, eligibleSupersedes: [],
121
+ });
122
+ pending.shift();
123
+ }
124
+ } catch (error) {
125
+ const wrapped = error instanceof TodoStoreError ? error
126
+ : new TodoStoreError('PLAN_HISTORY_NOTE_PENDING', 'history_note_append_failed', undefined,
127
+ { cause: String(error?.message ?? error) });
128
+ wrapped.detail = {
129
+ ...wrapped.detail, revision_applied: true, revision_digest: revision.revision_digest,
130
+ plan_version: planVersion,
131
+ pending_history_notes: pending.map(({ task_id: taskId, body }) => ({ task_id: taskId, body })),
132
+ pending_history_note_commands: pending.map(({ scope, task_id: taskId, body }) => (
133
+ `lattice todo note --plan ${planKey}${scope === 'task' ? ` --task ${taskId}` : ''} --message ${shellQuote(body)}`)),
134
+ };
135
+ throw wrapped;
136
+ }
137
+ }
138
+
24
139
  export function compilePlanRevision({ member, input }) {
25
140
  if (!exactRecord(input, ['schema', 'desired', 'continuity']) || input.schema !== INPUT_SCHEMA) {
26
141
  fail('plan_revise_schema_invalid', '/', { expected: INPUT_SCHEMA });
@@ -41,7 +156,7 @@ export function compilePlanRevision({ member, input }) {
41
156
  next_action: `lattice todo revise-phase --plan ${desired.plan_key} --input <phase-revision.json>`,
42
157
  });
43
158
  }
44
- if (member.plan.schema !== 'lattice.todo_plan.v7') {
159
+ if (!['lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(member.plan.schema)) {
45
160
  fail('predecessor_plan_schema_unsupported', '/desired/plan_key');
46
161
  }
47
162
  if (desired.project_id !== member.plan.project_id || desired.plan_key !== member.plan.plan_key) {
@@ -78,8 +193,9 @@ export function compilePlanRevision({ member, input }) {
78
193
  journal_head_digest: member.journal.events.at(-1).event_digest,
79
194
  plan_version: member.plan.plan_version,
80
195
  };
81
- const seed = planSeed(desired, predecessor.plan_digest);
82
- const phaseMigration = compilePhaseMigration(member.plan, seed, taskMigration);
196
+ const seed = planSeed(desired, predecessor.plan_digest, member.plan);
197
+ const phaseMigration = compileLightPhaseMigration(member.plan, seed, taskMigration,
198
+ new Map(member.tasks.map(({ task_id: id, status }) => [id, status])));
83
199
  const version = phaseTodoRevisionPlanVersion({
84
200
  projectId: desired.project_id, planKey: desired.plan_key, predecessor,
85
201
  desiredPlan: seed, taskMigration, phaseMigration,
@@ -114,38 +230,23 @@ export async function runPlanRevise({ cwd, inputRef, stdout, dryRun = false, env
114
230
  next_action: 'lattice plan backchain --input <file> --json',
115
231
  });
116
232
  }
233
+ // v5入力は集合の並びを正準化するので、同じ内容の別の並びは「変更なし」になる。
234
+ const desired = repairAuthoringArtifact(input.desired);
117
235
  const unchanged = input.continuity.every(({ policy }) => policy === 'carry')
118
- && canonicalizeTodoArtifact(planSeed(input.desired, null))
236
+ && canonicalizeTodoArtifact(planSeed(desired, null, member.plan))
119
237
  === canonicalizeTodoArtifact(planSeed(member.plan, null));
120
238
  if (!unchanged && !validatePhaseTodoRevision(revision)) fail('plan_revise_artifact_invalid', '/');
121
- if (!unchanged) {
122
- const { todoTaskCarrySemantics } = await import('./todo-store-view.mjs');
123
- const idMap = new Map(revision.task_migration.map(({ from_task_id, to_task_id }) => [from_task_id, to_task_id]));
124
- const removedTaskIds = new Set(revision.task_migration.filter(({ state_policy }) => state_policy === 'removed')
125
- .map(({ from_task_id }) => from_task_id));
126
- for (const [index, entry] of input.continuity.entries()) {
127
- if (entry.policy !== 'carry') continue;
128
- const before = todoTaskCarrySemantics(member.plan, entry.task_id, idMap,
129
- { reconciliationMetadata: true, includeDesignMemo: false, removedTaskIds });
130
- const after = todoTaskCarrySemantics(revision.desired_plan, entry.task_id, new Map(),
131
- { reconciliationMetadata: true, includeDesignMemo: false });
132
- if (canonicalizeTodoArtifact(before) !== canonicalizeTodoArtifact(after)) {
133
- throw new TodoStoreError('REVISION_INVALID', 'carry_semantics_changed', undefined, {
134
- pointer: `/continuity/${index}`, task_id: entry.task_id,
135
- expected: { policy: 'reset' }, actual: { policy: 'carry' },
136
- next_action: 'set_the_reported_continuity_policy_to_reset_then_rerun_plan_revise_dry_run',
137
- });
138
- }
139
- }
140
- }
141
239
  let applied = null;
142
240
  let reboundTaskIds = [];
143
241
  if (!dryRun) {
144
242
  if (!unchanged) {
145
243
  applied = await applyPhaseTodoRevision({ repoRoot,
146
244
  writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revision,
147
- actor: input.desired.actor, recordedAt: input.desired.recorded_at,
245
+ actor: desired.actor, recordedAt: desired.recorded_at,
148
246
  });
247
+ await appendRevisionHistoryNotes({ repoRoot, revision, actor: desired.actor,
248
+ notes: planRevisionHistoryNotes({ previousPlan: member.plan,
249
+ successorPlan: revision.desired_plan, continuity: input.continuity }) });
149
250
  }
150
251
  try {
151
252
  reboundTaskIds = await rebindCarriedWork({ repoRoot, planKey: revision.plan_key, env,
@@ -32,6 +32,7 @@ import {
32
32
  createTodoStoreWriter,
33
33
  initializeAuthoredTodoStore,
34
34
  isUninitializedTodoStore,
35
+ isPhaseTodoPlanSchema,
35
36
  isPhaselessTodoPlanSchema,
36
37
  readTodoIndependenceArtifact,
37
38
  readTodoStore,
@@ -52,10 +53,20 @@ const CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v1';
52
53
  const PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v2';
53
54
  const DECOUPLED_PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v3';
54
55
  const MEMO_PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v4';
56
+ // v5 = v4 + 作成者が書く終了条件`done_condition`(u12)。planはv8になる。既定入力はv4のまま。
57
+ const DONE_CONDITION_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v5';
55
58
  const CURRENT_CREATE_INPUT_SCHEMA = MEMO_PHASE_CREATE_INPUT_SCHEMA;
56
59
  const CURRENT_CREATE_SCHEMA_COMMAND = 'lattice plan create --schema-version 4 --json';
57
60
  const CREATE_RESULT_SCHEMA = 'lattice.plan_create_result.v1';
58
61
 
62
+ /** create入力schemaが作るplan schema。v4→v7、v5→v8。 */
63
+ function planSchemaForCreateInput(schema) {
64
+ return schema === DONE_CONDITION_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v8'
65
+ : schema === MEMO_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v7'
66
+ : schema === DECOUPLED_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v5'
67
+ : schema === PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v4' : 'lattice.todo_plan.v3';
68
+ }
69
+
59
70
  function resolveRepoRoot(cwd) {
60
71
  try {
61
72
  // gitはWindowsでもforward slashを返すため、OS nativeへ正規化して
@@ -424,7 +435,8 @@ async function readCanonicalInput(repoRoot, inputRef) {
424
435
  */
425
436
  function describePlanShapeViolation(value, { phaseInput }) {
426
437
  const TASK_KEYS = ['task_id', 'title', 'lane', 'design_memo', 'narrative_ref',
427
- 'narrative_anchor', 'compile_binding', 'parent_task_id', 'phase_id'];
438
+ 'narrative_anchor', 'compile_binding', 'parent_task_id', 'phase_id',
439
+ ...(value.schema === DONE_CONDITION_CREATE_INPUT_SCHEMA ? ['done_condition'] : [])];
428
440
  const PHASE_KEYS = ['phase_id', 'title', 'gate_policy', 'predecessor_phase_ids',
429
441
  'required_evidence_slots'];
430
442
 
@@ -512,9 +524,9 @@ function describePlanShapeViolation(value, { phaseInput }) {
512
524
  */
513
525
  function describeCreateInputViolation(value) {
514
526
  const phaseInput = [PHASE_CREATE_INPUT_SCHEMA, DECOUPLED_PHASE_CREATE_INPUT_SCHEMA,
515
- MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(value?.schema);
527
+ MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(value?.schema);
516
528
  const decoupledPhaseInput = [DECOUPLED_PHASE_CREATE_INPUT_SCHEMA,
517
- MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(value?.schema);
529
+ MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(value?.schema);
518
530
  const keys = [
519
531
  'schema', 'project_id', 'plan_key', 'plan_version', 'actor', 'recorded_at',
520
532
  'tasks', 'hard_dependencies', 'joins', 'input_digest',
@@ -530,7 +542,8 @@ function describeCreateInputViolation(value) {
530
542
  expected: { keys: [...keys].sort() }, actual };
531
543
  }
532
544
  const schemas = [CREATE_INPUT_SCHEMA, PHASE_CREATE_INPUT_SCHEMA,
533
- DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA];
545
+ DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA,
546
+ DONE_CONDITION_CREATE_INPUT_SCHEMA];
534
547
  if (!schemas.includes(value.schema)) {
535
548
  return { violation_kind: 'const_mismatch', pointer: '/schema',
536
549
  expected: { one_of: schemas }, actual: value.schema };
@@ -578,9 +591,7 @@ function describeCreateInputViolation(value) {
578
591
  }
579
592
  try {
580
593
  buildTodoPlan({
581
- schema: value.schema === MEMO_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v7'
582
- : decoupledPhaseInput ? 'lattice.todo_plan.v5'
583
- : phaseInput ? 'lattice.todo_plan.v4' : 'lattice.todo_plan.v3', project_id: value.project_id,
594
+ schema: planSchemaForCreateInput(value.schema), project_id: value.project_id,
584
595
  plan_key: value.plan_key, plan_version: value.plan_version,
585
596
  predecessor_plan_digest: null, tasks: value.tasks,
586
597
  hard_dependencies: value.hard_dependencies, joins: value.joins,
@@ -602,10 +613,11 @@ function describeCreateInputViolation(value) {
602
613
  }
603
614
 
604
615
  export function validatePlanCreateInput(input) {
605
- if (input?.schema !== MEMO_PHASE_CREATE_INPUT_SCHEMA) {
616
+ if (![MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(input?.schema)) {
606
617
  throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_retired', undefined, {
607
618
  violation_kind: 'const_mismatch', pointer: '/schema',
608
619
  expected: MEMO_PHASE_CREATE_INPUT_SCHEMA,
620
+ accepted: [MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA],
609
621
  actual: typeof input?.schema === 'string' ? input.schema : { type: typeof input?.schema },
610
622
  next_action: CURRENT_CREATE_SCHEMA_COMMAND,
611
623
  });
@@ -626,6 +638,19 @@ export function validatePlanCreateInput(input) {
626
638
  prompt: TODO_DESIGN_MEMO_PROMPT, next_action: CURRENT_CREATE_SCHEMA_COMMAND,
627
639
  });
628
640
  }
641
+ if (input.schema === DONE_CONDITION_CREATE_INPUT_SCHEMA) {
642
+ // design_memoと同じ本文規則。違いはnull(終了条件なし)を許すことだけ。
643
+ const invalidIndex = input.tasks.findIndex((task) => task?.done_condition !== null
644
+ && !isTodoDesignMemo(task?.done_condition));
645
+ if (invalidIndex >= 0) {
646
+ const explained = explainTodoDesignMemo(input.tasks[invalidIndex]?.done_condition);
647
+ throw new TodoStoreError('INPUT_INVALID', 'plan_create_done_condition_invalid', undefined, {
648
+ violation_kind: explained.reason, pointer: `/tasks/${invalidIndex}/done_condition`,
649
+ expected: { ...explained.expected, nullable: true }, actual: explained.actual,
650
+ next_action: 'correct_the_reported_pointer_then_rerun_plan_create',
651
+ });
652
+ }
653
+ }
629
654
  const violation = describeCreateInputViolation(input);
630
655
  if (violation !== null) {
631
656
  throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_invalid', undefined, {
@@ -651,16 +676,15 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
651
676
  const options = {
652
677
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
653
678
  plan: buildTodoPlan({
654
- schema: input.schema === MEMO_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v7'
655
- : input.schema === DECOUPLED_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v5'
656
- : input.schema === PHASE_CREATE_INPUT_SCHEMA
657
- ? 'lattice.todo_plan.v4' : 'lattice.todo_plan.v3', project_id: input.project_id,
679
+ schema: planSchemaForCreateInput(input.schema), project_id: input.project_id,
658
680
  plan_key: input.plan_key, plan_version: input.plan_version,
659
681
  predecessor_plan_digest: null, tasks: input.tasks,
660
682
  hard_dependencies: input.hard_dependencies, joins: input.joins,
661
683
  ...([PHASE_CREATE_INPUT_SCHEMA, DECOUPLED_PHASE_CREATE_INPUT_SCHEMA,
662
- MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(input.schema) ? { phases: input.phases } : {}),
663
- ...([DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(input.schema)
684
+ MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(input.schema)
685
+ ? { phases: input.phases } : {}),
686
+ ...([DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA,
687
+ DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(input.schema)
664
688
  ? { phase_accept_dependencies: input.phase_accept_dependencies } : {}),
665
689
  }),
666
690
  genesis: { actor: input.actor, recorded_at: input.recorded_at, provenance: null },
@@ -707,8 +731,8 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
707
731
  * 既に機械可読に持っている。壊さずに追加のkeyを足す理由が無いので足さない。
708
732
  */
709
733
  export async function runPlanCreateSchema({ stdout, version = 4 }) {
710
- if (![1, 2, 3, 4].includes(version)) throw new TypeError('unsupported plan create schema version');
711
- const expected = version === 4 ? MEMO_PHASE_CREATE_INPUT_SCHEMA
734
+ if (![1, 2, 3, 4, 5].includes(version)) throw new TypeError('unsupported plan create schema version');
735
+ const expected = version === 5 ? DONE_CONDITION_CREATE_INPUT_SCHEMA : version === 4 ? MEMO_PHASE_CREATE_INPUT_SCHEMA
712
736
  : version === 3 ? DECOUPLED_PHASE_CREATE_INPUT_SCHEMA
713
737
  : version === 2 ? PHASE_CREATE_INPUT_SCHEMA : CREATE_INPUT_SCHEMA;
714
738
  const schemaUrl = new URL(`../docs/schemas/lattice.plan_create_input.v${version}.schema.json`, import.meta.url);
@@ -745,8 +769,7 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
745
769
  });
746
770
  }
747
771
  const { plan, tasks, phases } = member;
748
- const phaseInput = ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7']
749
- .includes(plan.schema);
772
+ const phaseInput = isPhaseTodoPlanSchema(plan.schema);
750
773
  const stateByTaskId = new Map(tasks.map((state) => [state.task_id, state]));
751
774
  // snapshot artifactの形式(v1にはphasesキーが無い)には縛られない導出ビューを読む
752
775
  // (readTodoStoreが常に member.phases として埋める。ADR 0147)。
@@ -772,6 +795,7 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
772
795
  lane: task.lane,
773
796
  phase_id: phaseInput ? task.phase_id : null,
774
797
  state: stateByTaskId.get(task.task_id).status,
798
+ done_condition: task.done_condition ?? null,
775
799
  depends_on_count: dependsOnCount.get(task.task_id) ?? 0,
776
800
  }));
777
801
 
@@ -128,3 +128,17 @@ export async function readProjectExternalPane({ repoRoot, projectId }) {
128
128
  if (document === null || document.external_pane === undefined) return null;
129
129
  return externalPane(document.external_pane);
130
130
  }
131
+
132
+ /**
133
+ * The project id a repository registered in its identity file, or null. A route hint for a
134
+ * serving process that cannot read the Store; the file's own validity is judged elsewhere.
135
+ */
136
+ export async function readRegisteredProjectId({ repoRoot }) {
137
+ try {
138
+ const ref = path.join(await realpath(repoRoot), PROJECT_IDENTITY_REF);
139
+ const stats = await lstat(ref);
140
+ if (!stats.isFile() || stats.isSymbolicLink() || stats.size > MAX_BYTES) return null;
141
+ const id = JSON.parse(await readFile(ref, 'utf8')).project_id;
142
+ return typeof id === 'string' ? id : null;
143
+ } catch { return null; }
144
+ }