@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
@@ -3,14 +3,15 @@ import path from 'node:path';
3
3
 
4
4
  import { canonicalizeTodoArtifact, exactRecord, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
5
5
  import { gitSync } from './git-process.mjs';
6
- import { readAuthoringJsonFile, repairAuthoringArtifact } from './todo-authoring-input.mjs';
6
+ import { completeCreateInput, readAuthoringJsonFile, resolveTodoActor } from './todo-authoring-input.mjs';
7
7
  import { validatePlanCreateInput } from './project-cli.mjs';
8
8
  import {
9
- compilePhaseMigration, planSeed, readPlanBackchainBinding, rebindCarriedWork,
9
+ compileBackchainRevision, planSeed, readPlanBackchainBinding, rebindCarriedWork,
10
10
  } from './plan-backchain.mjs';
11
11
  import {
12
12
  applyPhaseTodoRevision, buildTodoPlan, createTodoStoreWriter, readTodoStore, TodoStoreError,
13
13
  } from './todo-store.mjs';
14
+ import { appendTodoNote } from './todo-note-store.mjs';
14
15
  import { phaseTodoRevisionPlanVersion, validatePhaseTodoRevision } from './todo-revision.mjs';
15
16
 
16
17
  export { validateBindingCarry } from './plan-binding-carry.mjs';
@@ -21,11 +22,159 @@ function fail(reason, pointer, detail = {}) {
21
22
  throw new TodoStoreError('INPUT_INVALID', reason, undefined, { pointer, ...detail });
22
23
  }
23
24
 
24
- export function compilePlanRevision({ member, input }) {
25
- if (!exactRecord(input, ['schema', 'desired', 'continuity']) || input.schema !== INPUT_SCHEMA) {
25
+ /**
26
+ * 軽量改訂のphase移行。作成者が書いた手順の改訂は完了済み・進行中でも許すので、
27
+ * taskの文面や辺の変更ではPhaseを巻き込まない。resetするのは次の2つだけ:
28
+ * 1. Phase定義(title・gate_policy・predecessor_phase_ids・required_evidence_slots)が変わった。
29
+ * 2. 新手順の下で再審査が要る task を迎えた——新規task、他Phaseから移ったtask、resetするtask——
30
+ * で、その行き先の状態がdone/retiredでない。
31
+ * 失うだけ、または完了済みだけを迎えるPhaseは受理済みのまま持ち越す。
32
+ * backchainのcompilePhaseMigrationとは別の規則で、あちらは変えない。
33
+ */
34
+ export function compileLightPhaseMigration(previousPlan, desiredSeed, taskMigration, taskStates) {
35
+ const policyById = new Map(taskMigration.map((row) => [row.from_task_id, row.state_policy]));
36
+ const previousById = new Map(previousPlan.tasks.map((task) => [task.task_id, task]));
37
+ const definition = ({ title, gate_policy: gatePolicy, predecessor_phase_ids: predecessors,
38
+ required_evidence_slots: slots }) => canonicalizeTodoArtifact({
39
+ title, gate_policy: gatePolicy, predecessor_phase_ids: predecessors, required_evidence_slots: slots });
40
+ const gaining = new Set();
41
+ for (const task of desiredSeed.tasks) {
42
+ const previous = previousById.get(task.task_id);
43
+ const reset = policyById.get(task.task_id) === 'reset_pending';
44
+ const arrives = previous === undefined || reset || previous.phase_id !== task.phase_id;
45
+ const state = previous === undefined || reset ? 'pending' : taskStates.get(task.task_id);
46
+ if (arrives && !['done', 'retired'].includes(state)) gaining.add(task.phase_id);
47
+ }
48
+ const nextPhases = new Map(desiredSeed.phases.map((phase) => [phase.phase_id, phase]));
49
+ const oldPhaseIds = new Set(previousPlan.phases.map(({ phase_id: id }) => id));
50
+ return [
51
+ ...previousPlan.phases.map((phase) => {
52
+ const next = nextPhases.get(phase.phase_id);
53
+ if (next === undefined) {
54
+ return { from_phase_id: phase.phase_id, to_phase_id: 'removed', state_policy: 'removed' };
55
+ }
56
+ const carry = !gaining.has(phase.phase_id) && definition(phase) === definition(next);
57
+ return { from_phase_id: phase.phase_id, to_phase_id: phase.phase_id,
58
+ state_policy: carry ? 'carry' : 'reset' };
59
+ }),
60
+ ...desiredSeed.phases.filter(({ phase_id: id }) => !oldPhaseIds.has(id))
61
+ .map(({ phase_id: id }) => ({ from_phase_id: null, to_phase_id: id, state_policy: 'reset' })),
62
+ ];
63
+ }
64
+
65
+ const nullable = (value) => (value === undefined ? null : value);
66
+
67
+ /** 履歴note用に、taskの作成者が書いた面を欄ごとに正準化して返す。 */
68
+ function authoredSurface(plan, taskId) {
69
+ const task = plan.tasks.find(({ task_id: id }) => id === taskId);
70
+ const local = (ref) => ref.plan_key === plan.plan_key && ref.task_id === taskId;
71
+ const rows = (list) => canonicalizeTodoArtifact(list.map((row) => canonicalizeTodoArtifact(row)).sort());
72
+ return {
73
+ title: nullable(task.title), lane: task.lane, design_memo: nullable(task.design_memo),
74
+ done_condition: nullable(task.done_condition), narrative_ref: nullable(task.narrative_ref),
75
+ parent_task_id: nullable(task.parent_task_id), phase_id: nullable(task.phase_id),
76
+ incoming_hard_dependencies: rows(plan.hard_dependencies.filter(({ to }) => local(to))),
77
+ outgoing_hard_dependencies: rows(plan.hard_dependencies.filter(({ from }) => local(from))),
78
+ join_memberships: rows(plan.joins.filter(({ before, after }) => local(before) || after.some(local))),
79
+ phase_accept_dependencies: rows((plan.phase_accept_dependencies ?? []).filter(({ to }) => local(to))),
80
+ };
81
+ }
82
+
83
+ /**
84
+ * 改訂の履歴note。変わったcarry taskごとにtask note1件(変わった欄の全列挙つき)と、
85
+ * 取り除いたtaskごとにplan note1件。本文は `plan revise <from>→<to> <task_id>: <reason>`。
86
+ */
87
+ export function planRevisionHistoryNotes({ previousPlan, successorPlan, continuity }) {
88
+ const prefix = (taskId) => `plan revise ${previousPlan.plan_version}→${successorPlan.plan_version} ${taskId}:`;
89
+ const notes = [];
90
+ const ordered = [...continuity].sort((left, right) => (
91
+ left.task_id < right.task_id ? -1 : left.task_id > right.task_id ? 1 : 0));
92
+ for (const { task_id: taskId, policy, reason } of ordered) {
93
+ if (policy === 'retire') {
94
+ notes.push({ scope: 'plan', task_id: taskId, body: `${prefix(taskId)} ${reason}` });
95
+ } else if (policy === 'carry') {
96
+ const before = authoredSurface(previousPlan, taskId);
97
+ const after = authoredSurface(successorPlan, taskId);
98
+ const changed = Object.keys(before).filter((field) => before[field] !== after[field]);
99
+ if (changed.length > 0) {
100
+ notes.push({ scope: 'task', task_id: taskId,
101
+ body: `${prefix(taskId)} ${reason}\nchanged: ${changed.join(', ')}` });
102
+ }
103
+ }
104
+ }
105
+ return notes;
106
+ }
107
+
108
+ const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
109
+
110
+ /** 公開後にnoteを順に追記する。失敗したら、まだ書けていないnoteと正確な再実行commandを返す。 */
111
+ async function appendRevisionHistoryNotes({ repoRoot, revision, notes, actor }) {
112
+ const planKey = revision.plan_key;
113
+ const planVersion = revision.desired_plan.plan_version;
114
+ const pending = [...notes];
115
+ try {
116
+ while (pending.length > 0) {
117
+ const [note] = pending;
118
+ await appendTodoNote({
119
+ repoRoot, projectId: revision.project_id, planKey, planVersion,
120
+ taskId: note.scope === 'task' ? note.task_id : null,
121
+ actor, recordedAt: new Date().toISOString(), body: note.body,
122
+ supersedes: null, eligibleSupersedes: [],
123
+ });
124
+ pending.shift();
125
+ }
126
+ } catch (error) {
127
+ const wrapped = error instanceof TodoStoreError ? error
128
+ : new TodoStoreError('PLAN_HISTORY_NOTE_PENDING', 'history_note_append_failed', undefined,
129
+ { cause: String(error?.message ?? error) });
130
+ wrapped.detail = {
131
+ ...wrapped.detail, revision_applied: true, revision_digest: revision.revision_digest,
132
+ plan_version: planVersion,
133
+ pending_history_notes: pending.map(({ task_id: taskId, body }) => ({ task_id: taskId, body })),
134
+ pending_history_note_commands: pending.map(({ scope, task_id: taskId, body }) => (
135
+ `lattice todo note --plan ${planKey}${scope === 'task' ? ` --task ${taskId}` : ''} --message ${shellQuote(body)}`)),
136
+ };
137
+ throw wrapped;
138
+ }
139
+ }
140
+
141
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
142
+
143
+ /**
144
+ * 継続方針の算出(u03p N5)。先行planの全taskについて、desiredに在れば作成者の carry/reset
145
+ * (無ければcarry)、無ければretire。desiredの在不在が優先され、読めない入力だけを拒否する。
146
+ */
147
+ function computeContinuity(member, input, desiredIds) {
148
+ const entries = input.continuity ?? [];
149
+ if (!Array.isArray(entries)) fail('plan_revise_continuity_invalid', '/continuity');
150
+ const oldIds = new Set(member.plan.tasks.map(({ task_id }) => task_id));
151
+ const decisions = new Map();
152
+ for (const [index, entry] of entries.entries()) {
153
+ if (!isRecord(entry) || !Object.keys(entry).every((key) => ['task_id', 'policy', 'reason'].includes(key))
154
+ || !isTodoIdentifier(entry.task_id) || !['carry', 'reset', 'retire'].includes(entry.policy)
155
+ || (entry.reason !== undefined && (typeof entry.reason !== 'string' || entry.reason.trim().length === 0))
156
+ || !oldIds.has(entry.task_id) || decisions.has(entry.task_id)) {
157
+ fail('plan_revise_continuity_invalid', `/continuity/${index}`);
158
+ }
159
+ decisions.set(entry.task_id, entry);
160
+ }
161
+ return member.plan.tasks.map(({ task_id: taskId }) => {
162
+ const entry = decisions.get(taskId);
163
+ const policy = !desiredIds.has(taskId) ? 'retire'
164
+ : entry === undefined || entry.policy === 'retire' ? 'carry' : entry.policy;
165
+ return { task_id: taskId, policy,
166
+ reason: entry?.policy === policy && entry.reason !== undefined ? entry.reason : `computed ${policy}` };
167
+ });
168
+ }
169
+
170
+ /** 入力の検査と補完。desired(補完済み)と算出した継続方針を返す。 */
171
+ export function resolvePlanRevision({ member, input, env = process.env, now = new Date() }) {
172
+ if (!exactRecord(input, ['schema', 'desired', 'continuity'])
173
+ && !exactRecord(input, ['schema', 'desired'])) {
26
174
  fail('plan_revise_schema_invalid', '/', { expected: INPUT_SCHEMA });
27
175
  }
28
- const desired = repairAuthoringArtifact(input.desired);
176
+ if (input.schema !== INPUT_SCHEMA) fail('plan_revise_schema_invalid', '/', { expected: INPUT_SCHEMA });
177
+ const desired = completeCreateInput(input.desired, { env, now });
29
178
  try { validatePlanCreateInput(desired); }
30
179
  catch (error) {
31
180
  if (typeof error?.detail?.pointer === 'string') {
@@ -33,6 +182,13 @@ export function compilePlanRevision({ member, input }) {
33
182
  }
34
183
  throw error;
35
184
  }
185
+ // 軽量改訂は設計メモを持つ現行plan(v7/v8)の後継を作る。v1〜v3入力は新規作成だけに使える。
186
+ if (!['lattice.plan_create_input.v4', 'lattice.plan_create_input.v5'].includes(desired.schema)) {
187
+ fail('plan_revise_desired_schema_unsupported', '/desired/schema', {
188
+ accepted: ['lattice.plan_create_input.v4', 'lattice.plan_create_input.v5'],
189
+ actual: desired.schema, next_action: 'lattice plan create --schema-version 5 --json',
190
+ });
191
+ }
36
192
  if (member === undefined) fail('plan_not_active', '/desired/plan_key');
37
193
  if (member.plan.schema === 'lattice.todo_plan.v6'
38
194
  || member.journal.events[0].schema === 'lattice.todo_event.v2'
@@ -41,45 +197,35 @@ export function compilePlanRevision({ member, input }) {
41
197
  next_action: `lattice todo revise-phase --plan ${desired.plan_key} --input <phase-revision.json>`,
42
198
  });
43
199
  }
44
- if (member.plan.schema !== 'lattice.todo_plan.v7') {
200
+ if (!['lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(member.plan.schema)) {
45
201
  fail('predecessor_plan_schema_unsupported', '/desired/plan_key');
46
202
  }
47
203
  if (desired.project_id !== member.plan.project_id || desired.plan_key !== member.plan.plan_key) {
48
204
  fail('plan_revise_identity_mismatch', '/desired/plan_key');
49
205
  }
50
- if (!Array.isArray(input.continuity) || input.continuity.length !== member.plan.tasks.length) {
51
- fail('plan_revise_continuity_incomplete', '/continuity', {
52
- expected: { task_ids: member.plan.tasks.map(({ task_id }) => task_id) },
53
- });
54
- }
55
- const oldIds = new Set(member.plan.tasks.map(({ task_id }) => task_id));
56
- const decisions = new Map();
57
- for (const [index, entry] of input.continuity.entries()) {
58
- if (!exactRecord(entry, ['task_id', 'policy', 'reason']) || !isTodoIdentifier(entry.task_id)
59
- || !['carry', 'reset', 'retire'].includes(entry.policy)
60
- || typeof entry.reason !== 'string' || entry.reason.trim().length === 0
61
- || !oldIds.has(entry.task_id) || decisions.has(entry.task_id)) {
62
- fail('plan_revise_continuity_invalid', `/continuity/${index}`);
63
- }
64
- decisions.set(entry.task_id, entry.policy);
65
- }
66
- const desiredIds = new Set(desired.tasks.map(({ task_id }) => task_id));
67
- const taskMigration = member.plan.tasks.map(({ task_id: id }) => {
68
- const policy = decisions.get(id);
69
- if ((policy === 'retire') === desiredIds.has(id)) {
70
- fail('plan_revise_removed_task_mismatch', '/continuity', { task_id: id });
71
- }
72
- return { from_task_id: id, to_task_id: policy === 'retire' ? 'removed' : id,
73
- state_policy: policy === 'retire' ? 'removed'
74
- : policy === 'carry' ? 'carry_reconciled_metadata' : 'reset_pending' };
75
- });
206
+ const continuity = computeContinuity(member, input,
207
+ new Set(desired.tasks.map(({ task_id }) => task_id)));
208
+ return { desired, continuity };
209
+ }
210
+
211
+ export function compilePlanRevision({ member, input, env, now }) {
212
+ const { desired, continuity } = resolvePlanRevision({ member, input, env, now });
213
+ return compileLightRevision({ member, desired, continuity });
214
+ }
215
+
216
+ function compileLightRevision({ member, desired, continuity }) {
217
+ const taskMigration = continuity.map(({ task_id: id, policy }) => ({
218
+ from_task_id: id, to_task_id: policy === 'retire' ? 'removed' : id,
219
+ state_policy: policy === 'retire' ? 'removed'
220
+ : policy === 'carry' ? 'carry_reconciled_metadata' : 'reset_pending' }));
76
221
  const predecessor = {
77
222
  plan_digest: member.plan.plan_digest,
78
223
  journal_head_digest: member.journal.events.at(-1).event_digest,
79
224
  plan_version: member.plan.plan_version,
80
225
  };
81
- const seed = planSeed(desired, predecessor.plan_digest);
82
- const phaseMigration = compilePhaseMigration(member.plan, seed, taskMigration);
226
+ const seed = planSeed(desired, predecessor.plan_digest, member.plan);
227
+ const phaseMigration = compileLightPhaseMigration(member.plan, seed, taskMigration,
228
+ new Map(member.tasks.map(({ task_id: id, status }) => [id, status])));
83
229
  const version = phaseTodoRevisionPlanVersion({
84
230
  projectId: desired.project_id, planKey: desired.plan_key, predecessor,
85
231
  desiredPlan: seed, taskMigration, phaseMigration,
@@ -94,49 +240,87 @@ export function compilePlanRevision({ member, input }) {
94
240
  return revision;
95
241
  }
96
242
 
243
+ /**
244
+ * backchain束縛plan(u03p N3): 束縛済みの機能連鎖を後継の元にする。tasksはdesiredの各taskに1件
245
+ * (残るtaskは連鎖の項目を保ち、新しいtaskは空の項目)、continuityは算出値。目標と機能は変えない。
246
+ */
247
+ function successorBackchain(chain, desired, continuity) {
248
+ const entries = new Map(chain.tasks.map((entry) => [entry.task_id, entry]));
249
+ const successor = { ...chain, continuity,
250
+ tasks: desired.tasks.map(({ task_id: taskId }) => entries.get(taskId)
251
+ ?? { task_id: taskId, requires_feature_ids: [], provides_feature_ids: [] }),
252
+ chain_digest: '' };
253
+ successor.chain_digest = todoSelfDigest(successor, 'chain_digest');
254
+ return successor;
255
+ }
256
+
97
257
  export async function planReviseSchema() {
98
258
  return JSON.parse(await readFile(new URL('../docs/schemas/lattice.plan_revise_input.v1.schema.json', import.meta.url)));
99
259
  }
100
260
 
101
- export async function runPlanRevise({ cwd, inputRef, stdout, dryRun = false, env = process.env }) {
102
- let repoRoot;
103
- try {
104
- repoRoot = path.resolve(gitSync(['rev-parse', '--show-toplevel'], {
105
- cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
106
- }).replace(/\r?\n$/u, ''));
107
- } catch { throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved'); }
108
- const input = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'INPUT_INVALID' });
109
- const store = await readTodoStore({ repoRoot });
110
- const member = store.members.find(({ plan }) => plan.plan_key === input?.desired?.plan_key);
111
- const revision = compilePlanRevision({ member, input });
112
- if (await readPlanBackchainBinding({ repoRoot, plan: member.plan }) !== null) {
113
- fail('plan_revise_requires_backchain', '/desired/plan_key', {
114
- next_action: 'lattice plan backchain --input <file> --json',
261
+ /**
262
+ * 軽量改訂でそのまま表せるmemberか(a14)。resolvePlanRevisionと作成入力の検査が断る形
263
+ * (v7/v8以外・源泉束縛・旧event・compile_binding付きtask)ならfalse。書く前の判定にだけ使う。
264
+ */
265
+ export function lightRevisionExpresses(member) {
266
+ return ['lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(member.plan.schema)
267
+ && member.journal.events[0]?.schema !== 'lattice.todo_event.v2'
268
+ && member.plan.tasks.every((task) => task.narrative_anchor === null && task.compile_binding === null);
269
+ }
270
+
271
+ /**
272
+ * 現行plan(v7/v8)をそのまま作成入力にする(a14)。辺の追加・削除など、planの一部だけを変える
273
+ * 軽量改訂の「いまの姿」を作る。v8はcreate v5、v7はcreate v4。continuityは付けない(全taskがcarry)。
274
+ * 源泉束縛planと旧schemaは `plan revise` と同じ理由で拒否する。
275
+ */
276
+ export function desiredFromPlan(plan, { env = process.env, now = new Date() } = {}) {
277
+ if (plan.schema === 'lattice.todo_plan.v6' || plan.tasks.some((task) => task.narrative_anchor !== null)) {
278
+ fail('plan_revise_requires_source_revision', '/desired/tasks', {
279
+ next_action: `lattice todo revise-phase --plan ${plan.plan_key} --input <phase-revision.json>`,
115
280
  });
116
281
  }
117
- const unchanged = input.continuity.every(({ policy }) => policy === 'carry')
118
- && canonicalizeTodoArtifact(planSeed(input.desired, null))
282
+ if (!['lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(plan.schema)) {
283
+ fail('predecessor_plan_schema_unsupported', '/desired/plan_key');
284
+ }
285
+ const edge = ({ from, to }) => ({
286
+ from: { project_id: from.project_id, plan_key: from.plan_key, task_id: from.task_id },
287
+ to: { project_id: to.project_id, plan_key: to.plan_key, task_id: to.task_id } });
288
+ return {
289
+ schema: plan.schema === 'lattice.todo_plan.v8'
290
+ ? 'lattice.plan_create_input.v5' : 'lattice.plan_create_input.v4',
291
+ project_id: plan.project_id, plan_key: plan.plan_key, plan_version: plan.plan_version,
292
+ actor: resolveTodoActor(env), recorded_at: now.toISOString(),
293
+ tasks: plan.tasks, phases: plan.phases,
294
+ hard_dependencies: plan.hard_dependencies.map(edge), joins: plan.joins,
295
+ phase_accept_dependencies: plan.phase_accept_dependencies,
296
+ };
297
+ }
298
+
299
+ /**
300
+ * 軽量改訂の適用。入力(`plan_revise_input.v1`)を補完・検査し、算出した継続方針で改訂を作り、
301
+ * 公開→履歴note→作業中taskの結び直しまで行って、結果artifactを返す(印字はしない)。
302
+ * notes: 履歴noteへ足す plan scope の追加note([{task_id, body}])。公開後に改訂noteと同じ経路で追記する。
303
+ */
304
+ export async function applyPlanRevision({
305
+ repoRoot, input, env = process.env, dryRun = false, notes: extraNotes = [],
306
+ }) {
307
+ const store = await readTodoStore({ repoRoot });
308
+ const member = store.members.find(({ plan }) => plan.plan_key === input?.desired?.plan_key);
309
+ const { desired, continuity } = resolvePlanRevision({ member, input, env, now: new Date() });
310
+ // 集合の並びは正準化済みなので、同じ内容の別の並びは「変更なし」になる。
311
+ const unchanged = continuity.every(({ policy }) => policy === 'carry')
312
+ && canonicalizeTodoArtifact(planSeed(desired, null, member.plan))
119
313
  === canonicalizeTodoArtifact(planSeed(member.plan, null));
120
- 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
- }
314
+ const binding = await readPlanBackchainBinding({ repoRoot, plan: member.plan });
315
+ let revision;
316
+ let featureChainFindings = null;
317
+ if (binding !== null && !unchanged) {
318
+ ({ revision, findings: featureChainFindings } = await compileBackchainRevision({
319
+ repoRoot, member, authoring: desired,
320
+ chain: successorBackchain(binding.chain, desired, continuity) }));
321
+ } else {
322
+ revision = compileLightRevision({ member, desired, continuity });
323
+ if (!unchanged && !validatePhaseTodoRevision(revision)) fail('plan_revise_artifact_invalid', '/');
140
324
  }
141
325
  let applied = null;
142
326
  let reboundTaskIds = [];
@@ -144,8 +328,12 @@ export async function runPlanRevise({ cwd, inputRef, stdout, dryRun = false, env
144
328
  if (!unchanged) {
145
329
  applied = await applyPhaseTodoRevision({ repoRoot,
146
330
  writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revision,
147
- actor: input.desired.actor, recordedAt: input.desired.recorded_at,
331
+ actor: desired.actor, recordedAt: desired.recorded_at,
148
332
  });
333
+ await appendRevisionHistoryNotes({ repoRoot, revision, actor: desired.actor,
334
+ notes: [...planRevisionHistoryNotes({ previousPlan: member.plan,
335
+ successorPlan: revision.desired_plan, continuity }),
336
+ ...extraNotes.map(({ task_id: taskId, body: text }) => ({ scope: 'plan', task_id: taskId, body: text }))] });
149
337
  }
150
338
  try {
151
339
  reboundTaskIds = await rebindCarriedWork({ repoRoot, planKey: revision.plan_key, env,
@@ -167,9 +355,23 @@ export async function runPlanRevise({ cwd, inputRef, stdout, dryRun = false, env
167
355
  project_id: revision.project_id, plan_key: revision.plan_key,
168
356
  plan_version: unchanged ? member.plan.plan_version : revision.desired_plan.plan_version,
169
357
  dry_run: dryRun, revision: unchanged ? null : revision, applied,
170
- continuity: input.continuity, rebound_task_ids: reboundTaskIds, result_digest: '',
358
+ continuity, rebound_task_ids: reboundTaskIds,
359
+ ...(featureChainFindings === null ? {} : { feature_chain_findings: featureChainFindings }),
360
+ result_digest: '',
171
361
  };
172
362
  result.result_digest = todoSelfDigest(result, 'result_digest');
363
+ return result;
364
+ }
365
+
366
+ export async function runPlanRevise({ cwd, inputRef, stdout, dryRun = false, env = process.env }) {
367
+ let repoRoot;
368
+ try {
369
+ repoRoot = path.resolve(gitSync(['rev-parse', '--show-toplevel'], {
370
+ cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
371
+ }).replace(/\r?\n$/u, ''));
372
+ } catch { throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved'); }
373
+ const input = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'INPUT_INVALID' });
374
+ const result = await applyPlanRevision({ repoRoot, input, env, dryRun });
173
375
  stdout.write(`${JSON.stringify(result)}\n`);
174
376
  return 0;
175
377
  }