@quolu/lattice 0.81.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 (71) hide show
  1. package/bin/lattice-bridge-supervisor.mjs +18 -3
  2. package/bin/lattice-dashboard.mjs +3 -18
  3. package/bin/lattice-mcp.mjs +6 -3
  4. package/bin/lattice.mjs +29 -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 +35 -0
  7. package/package.json +4 -2
  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-cli.mjs +16 -4
  33. package/src/bridge-detached-supervisor.mjs +204 -0
  34. package/src/bridge-hub-server.mjs +46 -9
  35. package/src/bridge-startup-folder.mjs +7 -4
  36. package/src/cli-help.mjs +5 -2
  37. package/src/dashboard-lifecycle-journal.mjs +42 -20
  38. package/src/plan-backchain.mjs +31 -12
  39. package/src/plan-binding-carry.mjs +60 -0
  40. package/src/plan-revise.mjs +276 -0
  41. package/src/project-cli.mjs +50 -22
  42. package/src/project-identity.mjs +14 -0
  43. package/src/runtime-cli.mjs +31 -18
  44. package/src/runtime-control-store.mjs +22 -1
  45. package/src/runtime-decision-verifier.mjs +27 -8
  46. package/src/runtime-engine.mjs +34 -5
  47. package/src/runtime-hold-recompile.mjs +19 -15
  48. package/src/runtime-kept-worktree.mjs +136 -0
  49. package/src/runtime-lifecycle-lock.mjs +118 -30
  50. package/src/runtime-managed-supervisor.mjs +10 -10
  51. package/src/runtime-os-observation.mjs +39 -1
  52. package/src/runtime-pull-intake.mjs +87 -43
  53. package/src/store-lock.mjs +146 -59
  54. package/src/todo-authoring-input.mjs +57 -2
  55. package/src/todo-cli.mjs +173 -45
  56. package/src/todo-contracts.mjs +22 -6
  57. package/src/todo-dashboard-registry.mjs +31 -4
  58. package/src/todo-gantt-display.mjs +260 -0
  59. package/src/todo-gantt-html-independence.mjs +8 -1
  60. package/src/todo-gantt-html-shared.mjs +2 -1
  61. package/src/todo-gantt-html.mjs +4 -2
  62. package/src/todo-gantt-layout.mjs +7 -36
  63. package/src/todo-gantt-live.mjs +6 -3
  64. package/src/todo-note-store.mjs +13 -5
  65. package/src/todo-readiness.mjs +29 -8
  66. package/src/todo-revision.mjs +9 -8
  67. package/src/todo-split.mjs +6 -3
  68. package/src/todo-status.mjs +53 -9
  69. package/src/todo-store-cache.mjs +1 -1
  70. package/src/todo-store-view.mjs +21 -2
  71. package/src/todo-store.mjs +642 -172
@@ -0,0 +1,276 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ import { canonicalizeTodoArtifact, exactRecord, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
5
+ import { gitSync } from './git-process.mjs';
6
+ import { readAuthoringJsonFile, repairAuthoringArtifact } from './todo-authoring-input.mjs';
7
+ import { validatePlanCreateInput } from './project-cli.mjs';
8
+ import { planSeed, readPlanBackchainBinding, rebindCarriedWork } from './plan-backchain.mjs';
9
+ import {
10
+ applyPhaseTodoRevision, buildTodoPlan, createTodoStoreWriter, readTodoStore, TodoStoreError,
11
+ } from './todo-store.mjs';
12
+ import { appendTodoNote } from './todo-note-store.mjs';
13
+ import { phaseTodoRevisionPlanVersion, validatePhaseTodoRevision } from './todo-revision.mjs';
14
+
15
+ export { validateBindingCarry } from './plan-binding-carry.mjs';
16
+
17
+ const INPUT_SCHEMA = 'lattice.plan_revise_input.v1';
18
+
19
+ function fail(reason, pointer, detail = {}) {
20
+ throw new TodoStoreError('INPUT_INVALID', reason, undefined, { pointer, ...detail });
21
+ }
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
+
139
+ export function compilePlanRevision({ member, input }) {
140
+ if (!exactRecord(input, ['schema', 'desired', 'continuity']) || input.schema !== INPUT_SCHEMA) {
141
+ fail('plan_revise_schema_invalid', '/', { expected: INPUT_SCHEMA });
142
+ }
143
+ const desired = repairAuthoringArtifact(input.desired);
144
+ try { validatePlanCreateInput(desired); }
145
+ catch (error) {
146
+ if (typeof error?.detail?.pointer === 'string') {
147
+ error.detail.pointer = `/desired${error.detail.pointer === '/' ? '' : error.detail.pointer}`;
148
+ }
149
+ throw error;
150
+ }
151
+ if (member === undefined) fail('plan_not_active', '/desired/plan_key');
152
+ if (member.plan.schema === 'lattice.todo_plan.v6'
153
+ || member.journal.events[0].schema === 'lattice.todo_event.v2'
154
+ || [...member.plan.tasks, ...desired.tasks].some((task) => task.narrative_anchor !== null)) {
155
+ fail('plan_revise_requires_source_revision', '/desired/tasks', {
156
+ next_action: `lattice todo revise-phase --plan ${desired.plan_key} --input <phase-revision.json>`,
157
+ });
158
+ }
159
+ if (!['lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(member.plan.schema)) {
160
+ fail('predecessor_plan_schema_unsupported', '/desired/plan_key');
161
+ }
162
+ if (desired.project_id !== member.plan.project_id || desired.plan_key !== member.plan.plan_key) {
163
+ fail('plan_revise_identity_mismatch', '/desired/plan_key');
164
+ }
165
+ if (!Array.isArray(input.continuity) || input.continuity.length !== member.plan.tasks.length) {
166
+ fail('plan_revise_continuity_incomplete', '/continuity', {
167
+ expected: { task_ids: member.plan.tasks.map(({ task_id }) => task_id) },
168
+ });
169
+ }
170
+ const oldIds = new Set(member.plan.tasks.map(({ task_id }) => task_id));
171
+ const decisions = new Map();
172
+ for (const [index, entry] of input.continuity.entries()) {
173
+ if (!exactRecord(entry, ['task_id', 'policy', 'reason']) || !isTodoIdentifier(entry.task_id)
174
+ || !['carry', 'reset', 'retire'].includes(entry.policy)
175
+ || typeof entry.reason !== 'string' || entry.reason.trim().length === 0
176
+ || !oldIds.has(entry.task_id) || decisions.has(entry.task_id)) {
177
+ fail('plan_revise_continuity_invalid', `/continuity/${index}`);
178
+ }
179
+ decisions.set(entry.task_id, entry.policy);
180
+ }
181
+ const desiredIds = new Set(desired.tasks.map(({ task_id }) => task_id));
182
+ const taskMigration = member.plan.tasks.map(({ task_id: id }) => {
183
+ const policy = decisions.get(id);
184
+ if ((policy === 'retire') === desiredIds.has(id)) {
185
+ fail('plan_revise_removed_task_mismatch', '/continuity', { task_id: id });
186
+ }
187
+ return { from_task_id: id, to_task_id: policy === 'retire' ? 'removed' : id,
188
+ state_policy: policy === 'retire' ? 'removed'
189
+ : policy === 'carry' ? 'carry_reconciled_metadata' : 'reset_pending' };
190
+ });
191
+ const predecessor = {
192
+ plan_digest: member.plan.plan_digest,
193
+ journal_head_digest: member.journal.events.at(-1).event_digest,
194
+ plan_version: member.plan.plan_version,
195
+ };
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])));
199
+ const version = phaseTodoRevisionPlanVersion({
200
+ projectId: desired.project_id, planKey: desired.plan_key, predecessor,
201
+ desiredPlan: seed, taskMigration, phaseMigration,
202
+ });
203
+ const revision = {
204
+ schema: 'lattice.phase_todo_revision.v5', project_id: desired.project_id,
205
+ plan_key: desired.plan_key, predecessor,
206
+ desired_plan: buildTodoPlan({ ...seed, plan_version: version }),
207
+ task_migration: taskMigration, phase_migration: phaseMigration, revision_digest: '',
208
+ };
209
+ revision.revision_digest = todoSelfDigest(revision, 'revision_digest');
210
+ return revision;
211
+ }
212
+
213
+ export async function planReviseSchema() {
214
+ return JSON.parse(await readFile(new URL('../docs/schemas/lattice.plan_revise_input.v1.schema.json', import.meta.url)));
215
+ }
216
+
217
+ export async function runPlanRevise({ cwd, inputRef, stdout, dryRun = false, env = process.env }) {
218
+ let repoRoot;
219
+ try {
220
+ repoRoot = path.resolve(gitSync(['rev-parse', '--show-toplevel'], {
221
+ cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
222
+ }).replace(/\r?\n$/u, ''));
223
+ } catch { throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved'); }
224
+ const input = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'INPUT_INVALID' });
225
+ const store = await readTodoStore({ repoRoot });
226
+ const member = store.members.find(({ plan }) => plan.plan_key === input?.desired?.plan_key);
227
+ const revision = compilePlanRevision({ member, input });
228
+ if (await readPlanBackchainBinding({ repoRoot, plan: member.plan }) !== null) {
229
+ fail('plan_revise_requires_backchain', '/desired/plan_key', {
230
+ next_action: 'lattice plan backchain --input <file> --json',
231
+ });
232
+ }
233
+ // v5入力は集合の並びを正準化するので、同じ内容の別の並びは「変更なし」になる。
234
+ const desired = repairAuthoringArtifact(input.desired);
235
+ const unchanged = input.continuity.every(({ policy }) => policy === 'carry')
236
+ && canonicalizeTodoArtifact(planSeed(desired, null, member.plan))
237
+ === canonicalizeTodoArtifact(planSeed(member.plan, null));
238
+ if (!unchanged && !validatePhaseTodoRevision(revision)) fail('plan_revise_artifact_invalid', '/');
239
+ let applied = null;
240
+ let reboundTaskIds = [];
241
+ if (!dryRun) {
242
+ if (!unchanged) {
243
+ applied = await applyPhaseTodoRevision({ repoRoot,
244
+ writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revision,
245
+ actor: desired.actor, recordedAt: desired.recorded_at,
246
+ });
247
+ await appendRevisionHistoryNotes({ repoRoot, revision, actor: desired.actor,
248
+ notes: planRevisionHistoryNotes({ previousPlan: member.plan,
249
+ successorPlan: revision.desired_plan, continuity: input.continuity }) });
250
+ }
251
+ try {
252
+ reboundTaskIds = await rebindCarriedWork({ repoRoot, planKey: revision.plan_key, env,
253
+ reason: '工程改訂後のplan versionへ作業中ToDoを結び直す',
254
+ failureCode: 'PLAN_REBIND_PENDING' });
255
+ } catch (error) {
256
+ // 公開後に起きたStoreの失敗は、改訂が確定済みであることを必ず報告する(2026-11-07
257
+ // 初回使用: rebind読込の素のbinding_staleが公開済み事実を隠した)
258
+ if (error instanceof TodoStoreError) {
259
+ error.detail = { ...error.detail, revision_applied: !unchanged,
260
+ revision_digest: unchanged ? null : revision.revision_digest,
261
+ plan_version: unchanged ? member.plan.plan_version : revision.desired_plan.plan_version };
262
+ }
263
+ throw error;
264
+ }
265
+ }
266
+ const result = {
267
+ schema: unchanged ? 'lattice.plan_revise_unchanged.v1' : 'lattice.plan_revise_result.v1',
268
+ project_id: revision.project_id, plan_key: revision.plan_key,
269
+ plan_version: unchanged ? member.plan.plan_version : revision.desired_plan.plan_version,
270
+ dry_run: dryRun, revision: unchanged ? null : revision, applied,
271
+ continuity: input.continuity, rebound_task_ids: reboundTaskIds, result_digest: '',
272
+ };
273
+ result.result_digest = todoSelfDigest(result, 'result_digest');
274
+ stdout.write(`${JSON.stringify(result)}\n`);
275
+ return 0;
276
+ }
@@ -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,
@@ -601,14 +612,12 @@ function describeCreateInputViolation(value) {
601
612
  return null;
602
613
  }
603
614
 
604
- export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null, featureChain = null }) {
605
- const repoRoot = resolveRepoRoot(cwd);
606
- if (repoRoot === null) throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved');
607
- const input = inputValue ?? await readCanonicalInput(repoRoot, inputRef);
608
- if (input?.schema !== MEMO_PHASE_CREATE_INPUT_SCHEMA) {
615
+ export function validatePlanCreateInput(input) {
616
+ if (![MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA].includes(input?.schema)) {
609
617
  throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_retired', undefined, {
610
618
  violation_kind: 'const_mismatch', pointer: '/schema',
611
619
  expected: MEMO_PHASE_CREATE_INPUT_SCHEMA,
620
+ accepted: [MEMO_PHASE_CREATE_INPUT_SCHEMA, DONE_CONDITION_CREATE_INPUT_SCHEMA],
612
621
  actual: typeof input?.schema === 'string' ? input.schema : { type: typeof input?.schema },
613
622
  next_action: CURRENT_CREATE_SCHEMA_COMMAND,
614
623
  });
@@ -629,6 +638,19 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
629
638
  prompt: TODO_DESIGN_MEMO_PROMPT, next_action: CURRENT_CREATE_SCHEMA_COMMAND,
630
639
  });
631
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
+ }
632
654
  const violation = describeCreateInputViolation(input);
633
655
  if (violation !== null) {
634
656
  throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_invalid', undefined, {
@@ -636,6 +658,13 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
636
658
  next_action: 'correct_the_reported_pointer_then_rerun_plan_create',
637
659
  });
638
660
  }
661
+ }
662
+
663
+ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null, featureChain = null }) {
664
+ const repoRoot = resolveRepoRoot(cwd);
665
+ if (repoRoot === null) throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved');
666
+ const input = inputValue ?? await readCanonicalInput(repoRoot, inputRef);
667
+ validatePlanCreateInput(input);
639
668
  // dispatch_shapeは結果へ載せる観測であり、直列度では初期化を拒まない(ADR 0180)。
640
669
  const dispatchShape = computeTodoDispatchShapeForPlan({
641
670
  projectId: input.project_id,
@@ -647,16 +676,15 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
647
676
  const options = {
648
677
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
649
678
  plan: buildTodoPlan({
650
- schema: input.schema === MEMO_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v7'
651
- : input.schema === DECOUPLED_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v5'
652
- : input.schema === PHASE_CREATE_INPUT_SCHEMA
653
- ? 'lattice.todo_plan.v4' : 'lattice.todo_plan.v3', project_id: input.project_id,
679
+ schema: planSchemaForCreateInput(input.schema), project_id: input.project_id,
654
680
  plan_key: input.plan_key, plan_version: input.plan_version,
655
681
  predecessor_plan_digest: null, tasks: input.tasks,
656
682
  hard_dependencies: input.hard_dependencies, joins: input.joins,
657
683
  ...([PHASE_CREATE_INPUT_SCHEMA, DECOUPLED_PHASE_CREATE_INPUT_SCHEMA,
658
- MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(input.schema) ? { phases: input.phases } : {}),
659
- ...([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)
660
688
  ? { phase_accept_dependencies: input.phase_accept_dependencies } : {}),
661
689
  }),
662
690
  genesis: { actor: input.actor, recorded_at: input.recorded_at, provenance: null },
@@ -703,8 +731,8 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
703
731
  * 既に機械可読に持っている。壊さずに追加のkeyを足す理由が無いので足さない。
704
732
  */
705
733
  export async function runPlanCreateSchema({ stdout, version = 4 }) {
706
- if (![1, 2, 3, 4].includes(version)) throw new TypeError('unsupported plan create schema version');
707
- 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
708
736
  : version === 3 ? DECOUPLED_PHASE_CREATE_INPUT_SCHEMA
709
737
  : version === 2 ? PHASE_CREATE_INPUT_SCHEMA : CREATE_INPUT_SCHEMA;
710
738
  const schemaUrl = new URL(`../docs/schemas/lattice.plan_create_input.v${version}.schema.json`, import.meta.url);
@@ -741,8 +769,7 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
741
769
  });
742
770
  }
743
771
  const { plan, tasks, phases } = member;
744
- const phaseInput = ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7']
745
- .includes(plan.schema);
772
+ const phaseInput = isPhaseTodoPlanSchema(plan.schema);
746
773
  const stateByTaskId = new Map(tasks.map((state) => [state.task_id, state]));
747
774
  // snapshot artifactの形式(v1にはphasesキーが無い)には縛られない導出ビューを読む
748
775
  // (readTodoStoreが常に member.phases として埋める。ADR 0147)。
@@ -768,6 +795,7 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
768
795
  lane: task.lane,
769
796
  phase_id: phaseInput ? task.phase_id : null,
770
797
  state: stateByTaskId.get(task.task_id).status,
798
+ done_condition: task.done_condition ?? null,
771
799
  depends_on_count: dependsOnCount.get(task.task_id) ?? 0,
772
800
  }));
773
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
+ }
@@ -25,6 +25,7 @@ import {
25
25
  buildIoEscalation, createRunSentinel, probeIoWarning, syncSentinelWatches,
26
26
  } from './runtime-io-sentinel.mjs';
27
27
  import { ensureScriptedWorktree, removeScriptedWorktrees } from './runtime-scripted-worktree.mjs';
28
+ import { recoverKeptWorktrees } from './runtime-kept-worktree.mjs';
28
29
  import {
29
30
  buildRuntimeSeamResolution, readRuntimeFindingRecord, resolveRuntimeSeam,
30
31
  validateRuntimeSeamRequest, verifySeamSplitSuccessor,
@@ -52,6 +53,7 @@ import {
52
53
  adjudicatePendingReceipts,
53
54
  buildNextRunEvent,
54
55
  buildExecutorPackets,
56
+ closeRunAbandoningRemaining,
55
57
  closeRunIfComplete,
56
58
  dispatchReadyFrontier,
57
59
  initializeRunEvents,
@@ -877,6 +879,7 @@ async function readScriptedControllerReceipt({
877
879
  async function reapRunWorkerProcesses({ events }) {
878
880
  const reaped = [];
879
881
  const skipped = [];
882
+ const unavailable = [];
880
883
  const seen = new Set();
881
884
  for (const event of events) {
882
885
  if (event.kind !== 'executor_dispatched') continue;
@@ -886,14 +889,18 @@ async function reapRunWorkerProcesses({ events }) {
886
889
  if (!Number.isSafeInteger(pid) || typeof recorded !== 'string' || seen.has(pid)) continue;
887
890
  seen.add(pid);
888
891
  const observed = await observeManagedProcessStartIdentity(pid).catch(() => null);
889
- if (observed === null) continue; // 既に居ない
892
+ if (observed === null) {
893
+ // 居ないか、居るのに再認証できない。後者には送らず記録する(u03 C25)。
894
+ try { process.kill(pid, 0); unavailable.push(pid); } catch { /* 既に居ない */ }
895
+ continue;
896
+ }
890
897
  if (observed.identity_digest !== recorded) {
891
898
  skipped.push({ pid, reason: 'start identity不一致(pid再利用)' });
892
899
  continue;
893
900
  }
894
901
  try { process.kill(pid, 'SIGKILL'); reaped.push(pid); } catch { /* 競合で既に消えた */ }
895
902
  }
896
- return { reaped, skipped };
903
+ return { reaped, skipped, unavailable };
897
904
  }
898
905
 
899
906
  async function driveScriptedManagedEpoch({
@@ -1817,20 +1824,15 @@ async function runClose({ runDir, repoRoot, stdout, requestId = null }) {
1817
1824
  if (alreadyClosed && existingClose?.payload?.outcome === 'abandoned') {
1818
1825
  throw new CliContractError('RUN_ABANDONED', 'abandoned runは正常closeへ変更できない');
1819
1826
  }
1827
+ let abandonedTodoIds = [];
1820
1828
  if (!alreadyClosed) {
1821
- const closed = closeRunIfComplete({
1829
+ const closed = closeRunAbandoningRemaining({
1822
1830
  runId: meta.run_id,
1823
1831
  plan: compileArtifact.plan,
1824
1832
  events,
1825
1833
  recordedAt: canonicalNow(),
1826
1834
  });
1827
- if (!closed.closed) {
1828
- throw new CliContractError(
1829
- 'RUN_NOT_COMPLETE',
1830
- '全TODOのreceipt accepted前はrunを正常closeできない',
1831
- { guidance: 'run statusで未完了TODOを確認するか、run abandonを明示実行する' },
1832
- );
1833
- }
1835
+ abandonedTodoIds = closed.abandoned_todo_ids;
1834
1836
  if (managed !== null) {
1835
1837
  await runManagedControl({ runDir, runRef: path.relative(repoRoot, runDir),
1836
1838
  operation: 'close', artifactDigest: null, stdout, shutdownReason: 'normal-close',
@@ -1846,6 +1848,7 @@ async function runClose({ runDir, repoRoot, stdout, requestId = null }) {
1846
1848
  outcome: 'closed',
1847
1849
  run_id: meta.run_id,
1848
1850
  already_closed: alreadyClosed,
1851
+ ...(abandonedTodoIds.length > 0 ? { abandoned_todo_ids: abandonedTodoIds } : {}),
1849
1852
  event_count: next.length,
1850
1853
  events_digest: digestArtifact(next.map(({ event_digest: digest }) => digest)),
1851
1854
  landing: await buildRunLandingReport({
@@ -3650,9 +3653,8 @@ export async function runManagedSupervisorDaemon({
3650
3653
  }
3651
3654
  let proposed;
3652
3655
  if (controlRequest.operation === 'close') {
3653
- proposed = closeRunIfComplete({ runId: request.request_id, plan: active.bundle.plan,
3656
+ proposed = closeRunAbandoningRemaining({ runId: request.request_id, plan: active.bundle.plan,
3654
3657
  events, recordedAt: canonicalNow() });
3655
- if (!proposed.closed) throw new ManagedRuntimeError('RUN_NOT_COMPLETE', '全TODO完了前はcloseできない');
3656
3658
  }
3657
3659
  const shutdown = await managedSupervisor.shutdownManaged({ mode: controlRequest.operation,
3658
3660
  reason: shutdownReason, barrierId: `shutdown-${randomUUID()}`,
@@ -3667,19 +3669,30 @@ export async function runManagedSupervisorDaemon({
3667
3669
  }
3668
3670
  await replaceEventsAtomically(runDir, events);
3669
3671
  // **abandonは成果を捨てる決定である。** worker processの終了はcleanupではなく
3670
- // その決定の一部なので、誰を止めたかを記録へ残す。closeでは何もしない——
3671
- // 完走したrunのworkerは既にterminalであり、生きていればそれは欠陥である
3672
- // (`closeRunIfComplete`が全TODO accepted を要求するので、そもそもcloseへ来ない)。
3673
- if (controlRequest.operation === 'abandon') {
3674
- const reaped = await reapRunWorkerProcesses({ events }).catch(() => null);
3675
- if (reaped !== null && (reaped.reaped.length > 0 || reaped.skipped.length > 0)) {
3672
+ // その決定の一部なので、誰を止めたかを記録へ残す。完走したcloseでは何もしない。
3673
+ // u03 C18: 未完了TODOを放棄して閉じるcloseはworkerも止める。作業木はrunの成果なので残す。
3674
+ // SIGKILLは停止中(SIGSTOP)のworkerにも届く。
3675
+ const stopsWorkers = controlRequest.operation === 'abandon'
3676
+ || proposed?.abandoned_todo_ids.length > 0;
3677
+ if (stopsWorkers) {
3678
+ const reaped = await reapRunWorkerProcesses({ events }).catch(() => null)
3679
+ ?? { reaped: [], skipped: [], unavailable: [] };
3680
+ // R2k: a killed worker's tree loses a stale index.lock and names unobserved writes.
3681
+ const keptWorktrees = await recoverKeptWorktrees({ events });
3682
+ if (reaped.reaped.length > 0 || reaped.skipped.length > 0
3683
+ || reaped.unavailable.length > 0 || keptWorktrees.length > 0) {
3676
3684
  await appendControl({ run_id: request.request_id, kind: 'worker_processes_terminated',
3677
3685
  session_nonce_digest: digestArtifact(sessionNonce), payload: {
3678
3686
  reason: shutdownReason,
3679
3687
  terminated_pids: [...reaped.reaped].sort((left, right) => left - right),
3680
3688
  skipped_count: reaped.skipped.length,
3689
+ ...(reaped.unavailable.length > 0
3690
+ ? { signal_unavailable_pids: [...reaped.unavailable].sort((left, right) => left - right) } : {}),
3691
+ ...(keptWorktrees.length > 0 ? { kept_worktrees: keptWorktrees } : {}),
3681
3692
  } });
3682
3693
  }
3694
+ }
3695
+ if (controlRequest.operation === 'abandon') {
3683
3696
  // 木も畳む。closeでは畳まない——木そのものがrunの成果であり、着地させる前に
3684
3697
  // 消したら受理した内容が残らない。
3685
3698
  await removeScriptedWorktrees({ repoRoot, runDir }).catch(() => null);
@@ -187,7 +187,28 @@ export function validateRuntimeControlEventPayload(kind, value) {
187
187
  // 停止したworkerの行き先は「再開」か「破棄」の二択であり、破棄を選んだなら
188
188
  // 誰を止めたかが残っていなければ、後から何が捨てられたか説明できない。
189
189
  if (kind === 'worker_processes_terminated') {
190
- return exact(value, ['reason', 'terminated_pids', 'skipped_count'])
190
+ // signal_unavailable_pids (u03 C25): alive but not re-authenticated, so not signalled.
191
+ const pidList = (pids) => Array.isArray(pids) && pids.length > 0 && pids.length <= 4096
192
+ && pids.every((pid, index) => Number.isSafeInteger(pid) && pid > 0
193
+ && (index === 0 || pids[index - 1] < pid));
194
+ // kept_worktrees (R2k): per tree, index.lock recovery and paths written after the last checkpoint.
195
+ const textList = (items) => Array.isArray(items) && items.length <= 4096
196
+ && items.every((item) => typeof item === 'string' && item.length > 0);
197
+ const keptWorktree = (entry) => plain(entry)
198
+ && (exact(entry, ['todo_ids', 'worktree_path', 'index_lock', 'unobserved_paths'])
199
+ ? textList(entry.unobserved_paths)
200
+ : exact(entry, ['todo_ids', 'worktree_path', 'index_lock', 'observation_error'])
201
+ && typeof entry.observation_error === 'string')
202
+ && Array.isArray(entry.todo_ids) && entry.todo_ids.length > 0 && entry.todo_ids.every(identifier)
203
+ && typeof entry.worktree_path === 'string' && path.isAbsolute(entry.worktree_path)
204
+ && ['absent', 'removed', 'replaced', 'conflict_kept', 'owner_live', 'owner_unproven', 'unknown']
205
+ .includes(entry.index_lock);
206
+ const optional = Object.keys(value ?? {}).filter((key) => !['reason', 'terminated_pids',
207
+ 'skipped_count'].includes(key));
208
+ return exact(value, ['reason', 'terminated_pids', 'skipped_count', ...optional])
209
+ && optional.every((key) => (key === 'signal_unavailable_pids' && pidList(value[key]))
210
+ || (key === 'kept_worktrees' && Array.isArray(value[key]) && value[key].length > 0
211
+ && value[key].length <= 4096 && value[key].every(keptWorktree)))
191
212
  && typeof value.reason === 'string' && value.reason.length > 0
192
213
  && Array.isArray(value.terminated_pids) && value.terminated_pids.length <= 4096
193
214
  && value.terminated_pids.every((pid) => Number.isSafeInteger(pid) && pid > 0)