@quolu/lattice 0.47.0 → 0.49.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.
@@ -4,7 +4,7 @@ import { stat } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
 
6
6
  import { readTodoStoreStable } from '../src/todo-store.mjs';
7
- import { projectTodoStatus } from '../src/todo-status.mjs';
7
+ import { TODO_STATUS_DISPATCH_ONLY, projectTodoStatus } from '../src/todo-status.mjs';
8
8
  import { ganttLiveHeadDigest, renderTodoGanttForProject } from '../src/todo-cli.mjs';
9
9
  import {
10
10
  forgetTodoDashboardDaemonRecord,
@@ -61,7 +61,7 @@ async function synchronize() {
61
61
  projectHasActiveRun: async (entry) => {
62
62
  try {
63
63
  const store = await readCachedStore(entry.repo_root);
64
- const active = projectTodoStatus(store).active_set.length > 0
64
+ const active = projectTodoStatus(store, TODO_STATUS_DISPATCH_ONLY).active_set.length > 0
65
65
  || store.members.some(todoDashboardMemberNeedsVisibility);
66
66
  reportedStoreReadFailures.delete(entry.project_id);
67
67
  return active;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.47.0",
3
+ "version": "0.49.0",
4
4
  "description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
5
5
  "author": {
6
6
  "name": "Quo / クオ at kitepon.dev",
package/src/cli-help.mjs CHANGED
@@ -75,7 +75,8 @@ Read commands:
75
75
 
76
76
  Write commands:
77
77
  dashboard adopt --json # 衝突したproject_idの配信元rootを現在repoへ明示的に移す
78
- note --plan <key> --task <id> (--message <text>|--input <file>)
78
+ dashboard remove <project_id> --json # 登録簿から1件外す(対象repoの外からも叩ける)
79
+ note --plan <key> [--task <id>] (--message <text>|--input <file>)
79
80
  # ToDoへ作業継続に必要な方針・調査結果・注意をappend-onlyで追記する
80
81
  migrate --input <extraction.json> [--serialization-reviewed]
81
82
  migrate --input <extraction.json> --dry-run --json [--serialization-reviewed]
@@ -190,7 +191,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
190
191
  'event verify': 'event verify --run .lattice/runs/<id>',
191
192
  'todo status': 'todo status [--json]',
192
193
  'todo show': 'todo show --plan <key> --task <id> --json',
193
- 'todo note': 'todo note --plan <key> --task <id> (--message <text>|--input <file>) | list --plan <key> [--task <id>] --json',
194
+ 'todo note': 'todo note --plan <key> [--task <id>] (--message <text>|--input <file>) | list --plan <key> [--task <id>] --json',
194
195
  'todo note list': 'todo note list --plan <key> [--task <id>] --json',
195
196
  'todo bindings': 'todo bindings [--plan <key>] [--json]',
196
197
  'todo independence': 'todo independence [--plan <key>] [--json] | compile --plan <key> --input <file> | witness migrate --plan <key>',
@@ -200,8 +201,10 @@ const SUBCOMMAND_USAGE = Object.freeze({
200
201
  'todo snapshot': 'todo snapshot --rebuild --plan <key>',
201
202
  'todo gantt': 'todo gantt serve --port <port> [--scope live|all] # 動的表示のみ。静的HTML生成は廃止',
202
203
  'todo gantt serve': 'todo gantt serve --port <0..65535> [--scope live|all] # loopback動的viewer',
203
- 'todo dashboard': 'todo dashboard adopt --json # 配信元rootの衝突を明示的に解消',
204
+ 'todo dashboard': 'todo dashboard adopt --json | remove <project_id> --json'
205
+ + ' # 配信元rootの衝突を明示的に解消/登録簿から1件外す',
204
206
  'todo dashboard adopt': 'todo dashboard adopt --json # 現在repoをproject_idの配信元として明示採用',
207
+ 'todo dashboard remove': 'todo dashboard remove <project_id> --json # 登録簿から1件外す(対象repo不在でも可)',
205
208
  'todo phase': 'todo phase <status|review|accept|reject|reopen|close-unaudited> --plan <key> [options]'
206
209
  + ' | baseline --reason <text> [--except <plan_key>]...',
207
210
  'todo phase status': 'todo phase status --plan <key>',
@@ -16,7 +16,9 @@ import {
16
16
  todoSelfDigest,
17
17
  } from './todo-contracts.mjs';
18
18
  import { projectTodoStatus } from './todo-status.mjs';
19
+ import { readTodoPlanNotesForStatus } from './todo-note-store.mjs';
19
20
  import { projectIndependenceFrontier } from './todo-independence.mjs';
21
+ import { readTodoParallelCandidatesForStatus } from './todo-parallel-candidates.mjs';
20
22
  import { isTodoIndependenceLegacyMarker } from './todo-independence-contracts.mjs';
21
23
  import { selectIndependenceGuidance } from './todo-independence-guidance.mjs';
22
24
  import { ensureTodoDashboardActivity } from './todo-dashboard-registry.mjs';
@@ -179,6 +181,7 @@ async function summarizeIndependence({ repoRoot, store, todo }) {
179
181
  .some(({ unknowns }) => unknowns.some(({ kind }) => kind === 'record_stale')),
180
182
  conflictWithActive: projected.frontier.conflicts_with_active[0]?.severability ?? null,
181
183
  conflictBetweenReady: projected.frontier.serialize_pairs[0]?.severability ?? null,
184
+ coordinationMode: member.coordination?.mode ?? null,
182
185
  }),
183
186
  unreadable_reason: null,
184
187
  parallel_groups: projected.frontier.parallel_groups.map(({ task_ids: ids }) => [...ids]),
@@ -265,7 +268,10 @@ async function resolveProjectState({ cwd, cliVersion }) {
265
268
  }
266
269
  try {
267
270
  const store = await readTodoStore({ repoRoot });
268
- const todo = projectTodoStatus(store);
271
+ const todo = projectTodoStatus(store, {
272
+ planNotes: await readTodoPlanNotesForStatus({ repoRoot, store }),
273
+ parallelCandidates: await readTodoParallelCandidatesForStatus({ repoRoot, store, gitHead }),
274
+ });
269
275
  const activeRuns = todo.active_set.map((entry) => ({
270
276
  plan_key: entry.plan_key, task_id: entry.task_id, label: entry.label,
271
277
  }));
package/src/todo-cli.mjs CHANGED
@@ -8,6 +8,7 @@ import { fileURLToPath } from 'node:url';
8
8
  import { parseTree } from 'jsonc-parser';
9
9
 
10
10
  import {
11
+ TODO_COORDINATION_MODES,
11
12
  TODO_DESIGN_MEMO_PROMPT,
12
13
  canonicalizeTodoArtifact,
13
14
  digestTodoArtifact,
@@ -24,6 +25,7 @@ import { projectTodoChainV1 } from './todo-chain.mjs';
24
25
  import {
25
26
  adoptTodoDashboardActivity,
26
27
  ensureTodoDashboardActivity,
28
+ removeTodoDashboardProject,
27
29
  } from './todo-dashboard-registry.mjs';
28
30
  import { resolveProjectIdentity } from './project-identity.mjs';
29
31
  import { layoutTodoGantt } from './todo-gantt-layout.mjs';
@@ -72,6 +74,7 @@ import {
72
74
  import {
73
75
  computeReadyFrontier,
74
76
  projectTodoBindings,
77
+ TODO_STATUS_DISPATCH_ONLY,
75
78
  projectTodoStatus,
76
79
  } from './todo-status.mjs';
77
80
  import {
@@ -118,7 +121,9 @@ import {
118
121
  readTodoNoteContext,
119
122
  readTodoNoteContextsForPlan,
120
123
  readTodoNoteEvents,
124
+ readTodoPlanNotesForStatus,
121
125
  } from './todo-note-store.mjs';
126
+ import { readTodoParallelCandidatesForStatus } from './todo-parallel-candidates.mjs';
122
127
 
123
128
  const CLI_ERROR_SCHEMA = 'lattice.cli_error.v2';
124
129
  const DEFAULT_GANTT_SCOPE = 'live';
@@ -594,6 +599,9 @@ function designMemoProjection(task) {
594
599
  */
595
600
  async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
596
601
  const artifact = await readTodoIndependenceArtifact({ repoRoot, store, planKey });
602
+ // 調整方式の宣言(ob03)。未宣言はnullで、「まだ選んでいない」を意味する。
603
+ const coordinationMode = store.members
604
+ .find(({ descriptor }) => descriptor.plan_key === planKey)?.coordination?.mode ?? null;
597
605
  if (artifact === null) {
598
606
  // 記録が無ければ鮮度を語る相手がいない。HEADを要求すると、commitがまだ無いrepoで
599
607
  // 「判定できない」でなく「startできない」になってしまう。
@@ -605,7 +613,7 @@ async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
605
613
  .filter((task) => task.plan_key === planKey).map(({ task_id: id }) => id),
606
614
  self_unknowns: [{ kind: 'witness_missing', ref: 'no_independence_record' }],
607
615
  guidance: selectIndependenceGuidance({
608
- coverage: 'missing', taskDeclared: false, taskStale: false,
616
+ coverage: 'missing', taskDeclared: false, taskStale: false, coordinationMode,
609
617
  }),
610
618
  };
611
619
  }
@@ -654,6 +662,7 @@ async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
654
662
  conflictWithActive: conflictsWithActive[0]?.severability ?? null,
655
663
  conflictBetweenReady: readyConflict?.severability ?? null,
656
664
  verdictsAbsent: selfUnknowns.some(({ kind }) => kind === 'plan_verdicts_absent'),
665
+ coordinationMode,
657
666
  }),
658
667
  };
659
668
  }
@@ -685,7 +694,8 @@ async function startTask({
685
694
  repoRoot, env, planKey, taskId, overrideReason, parallelFrontier, serialConfirmed = false,
686
695
  }) {
687
696
  const store = await readTodoStore({ repoRoot });
688
- const projection = projectTodoStatus(store);
697
+ // startはready判定にしかprojectionを使わず、resultを出力しない。
698
+ const projection = projectTodoStatus(store, TODO_STATUS_DISPATCH_ONLY);
689
699
  const readyTask = projection.next_ready.find((task) => (
690
700
  task.plan_key === planKey && task.task_id.toLowerCase() === taskId.toLowerCase()
691
701
  ));
@@ -827,6 +837,33 @@ async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload })
827
837
  return result;
828
838
  }
829
839
 
840
+ /**
841
+ * 調整方式を宣言する(ob03・オーナー裁定C①)。
842
+ *
843
+ * witnessが全planの暗黙義務だった時、「誰がやるか」が誰にも属さず、正確な案内が素通りされた。
844
+ * 起票後にこのコマンドで明示選択させ、eventのactorへ帰属を残す。宣言はdispatchを変えない
845
+ * ——未宣言でもready frontierは通常どおり出る(ADR 0160・ob04のProtected behavior)。
846
+ */
847
+ async function independenceMode({ repoRoot, env, planKey, mode, reason }) {
848
+ const { event } = await appendTodoEvent({
849
+ repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey,
850
+ event: { kind: 'coordination_mode', actor: mutationActor(env), payload: { mode, reason } },
851
+ });
852
+ const result = {
853
+ schema: 'lattice.todo_coordination_mode_result.v1', project_id: event.project_id,
854
+ plan_key: event.plan_key, plan_version: event.plan_version,
855
+ mode: event.payload.mode, reason: event.payload.reason,
856
+ declared_by: event.actor, declared_at: event.recorded_at,
857
+ // 宣言はplan-scoped chainのheadを進める。lifecycle journalのheadは動かない——
858
+ // 「作業が進んだ」の意味をここへ混ぜないため、journal_head_digestは返さない。
859
+ sequence: event.sequence, event_digest: event.event_digest,
860
+ plan_scoped_head_digest: event.event_digest,
861
+ result_digest: '',
862
+ };
863
+ result.result_digest = todoSelfDigest(result, 'result_digest');
864
+ return result;
865
+ }
866
+
830
867
  async function phaseStatus({ repoRoot, planKey }) {
831
868
  const store = await readTodoStore({ repoRoot });
832
869
  const [member] = selectMembers(store, planKey);
@@ -973,7 +1010,8 @@ async function migrate({ repoRoot, inputRef, serializationReviewed = false }) {
973
1010
 
974
1011
  const imported = await appendTodoExtraction({ repoRoot, extraction });
975
1012
  const result = {
976
- schema: 'lattice.todo_migrate_result.v2',
1013
+ // ob03: 調整方式の案内をv3で足す。ADR 0054のとおり既存versionへのin-place追加はしない。
1014
+ schema: 'lattice.todo_migrate_result.v3',
977
1015
  project_id: imported.plan.project_id,
978
1016
  plan_key: imported.plan.plan_key,
979
1017
  plan_version: imported.plan.plan_version,
@@ -1002,6 +1040,13 @@ async function migrate({ repoRoot, inputRef, serializationReviewed = false }) {
1002
1040
  required_state_policy: 'acquire_phase',
1003
1041
  next_action: `lattice todo revise-phase --plan ${imported.plan.plan_key} --input <phase-revision.json>`,
1004
1042
  } : null,
1043
+ // ob03: 起票直後のplanは必ず調整方式が未宣言である。ここで案内しないと、選ぶ機会が
1044
+ // 「誰も呼ぶ動機の無いdrilldown」にしか無くなる——前campaignの監査待ちと同じ形になる。
1045
+ coordination_guidance: {
1046
+ mode: null,
1047
+ modes: [...TODO_COORDINATION_MODES],
1048
+ next_action: `lattice todo independence mode --plan ${imported.plan.plan_key} --set <witness|conversation> --reason <text>`,
1049
+ },
1005
1050
  result_digest: '',
1006
1051
  };
1007
1052
  result.result_digest = todoSelfDigest(result, 'result_digest');
@@ -1278,7 +1323,13 @@ async function revisePhase({ repoRoot, env, planKey, inputRef }) {
1278
1323
  }
1279
1324
 
1280
1325
  async function status({ repoRoot }) {
1281
- return projectTodoStatus(await readTodoStore({ repoRoot }));
1326
+ const store = await readTodoStore({ repoRoot });
1327
+ return projectTodoStatus(store, {
1328
+ planNotes: await readTodoPlanNotesForStatus({ repoRoot, store }),
1329
+ parallelCandidates: await readTodoParallelCandidatesForStatus({
1330
+ repoRoot, store, gitHead: currentHeadSha, changedPathsSince,
1331
+ }),
1332
+ });
1282
1333
  }
1283
1334
 
1284
1335
  async function adoptDashboardRoot({ repoRoot, env }) {
@@ -1324,32 +1375,44 @@ async function todoDetail({ repoRoot, planKey, taskId }) {
1324
1375
  return result;
1325
1376
  }
1326
1377
 
1378
+ /**
1379
+ * `taskId === null`はplan単位note。task noteと違い宛先taskが無いので、
1380
+ * 訂正できる相手はplan noteだけ、返すcontextも特定taskのものにできない。
1381
+ */
1327
1382
  async function appendNote({ repoRoot, env, planKey, taskId, message, inputRef, supersedes }) {
1328
1383
  const store = await readTodoStore({ repoRoot });
1329
1384
  const [member] = selectMembers(store, planKey);
1330
- const task = selectNoteTask(member, taskId);
1385
+ const task = taskId === null ? null : selectNoteTask(member, taskId);
1331
1386
  const body = inputRef === null ? message : await readNoteTextInput(repoRoot, inputRef);
1332
- const projectedBeforeAppend = await readTodoNoteContext({
1333
- repoRoot, store, planKey, taskId: task.task_id,
1334
- });
1387
+ // 訂正はscopeを跨げない。plan noteはplan chainの中だけ、task noteは自分のtaskの中だけを
1388
+ // 訂正できる。contextはplan noteも載せるので、task側はscopeで絞らないと跨げてしまう。
1389
+ const eligibleSupersedes = task === null
1390
+ ? (await readTodoNoteEvents({ repoRoot, planKey, scope: 'plan' })).events
1391
+ .map(({ event_digest: digest }) => digest)
1392
+ : (await readTodoNoteContext({ repoRoot, store, planKey, taskId: task.task_id }))
1393
+ .history.filter(({ scope }) => scope === 'task').map(({ event_digest: digest }) => digest);
1335
1394
  const event = await appendTodoNote({
1336
1395
  repoRoot,
1337
1396
  projectId: store.project_id,
1338
1397
  planKey,
1339
1398
  planVersion: member.plan.plan_version,
1340
- taskId: task.task_id,
1399
+ taskId: task?.task_id ?? null,
1341
1400
  actor: mutationActor(env),
1342
1401
  recordedAt: new Date().toISOString(),
1343
1402
  body,
1344
1403
  supersedes,
1345
- eligibleSupersedes: projectedBeforeAppend.history.map(({ event_digest: digest }) => digest),
1404
+ eligibleSupersedes,
1346
1405
  });
1347
- const { context } = await readTodoNoteContext({ repoRoot, store, planKey, taskId: task.task_id });
1406
+ // plan noteはどのtaskのcontextにも載るので、1つを選んで返すと嘘になる。全部読むなら
1407
+ // `note list --plan <k>`。書けたことの証拠はeventそのものが持つ。
1408
+ const context = task === null
1409
+ ? null : (await readTodoNoteContext({ repoRoot, store, planKey, taskId: task.task_id })).context;
1348
1410
  const result = {
1349
- schema: 'lattice.todo_note_append_result.v1',
1411
+ schema: 'lattice.todo_note_append_result.v2',
1350
1412
  project_id: store.project_id,
1351
1413
  plan_key: planKey,
1352
- task_id: task.task_id,
1414
+ scope: task === null ? 'plan' : 'task',
1415
+ task_id: task?.task_id ?? null,
1353
1416
  event,
1354
1417
  note_context: context,
1355
1418
  result_digest: '',
@@ -1362,7 +1425,10 @@ async function listNotes({ repoRoot, planKey, taskId }) {
1362
1425
  const store = await readTodoStore({ repoRoot });
1363
1426
  const [member] = selectMembers(store, planKey);
1364
1427
  const chain = await readTodoNoteEvents({ repoRoot, planKey });
1365
- let notes = chain.events;
1428
+ const planChain = await readTodoNoteEvents({ repoRoot, planKey, scope: 'plan' });
1429
+ // plan全体の一覧は両chainを返す。`full_history_command`がこの形を指す以上、片方でも
1430
+ // 落とせば「full」と名乗りながら全部を取りに行けない。並びはcontextと同じくplanが先。
1431
+ let notes = [...planChain.events, ...chain.events];
1366
1432
  let archived = [];
1367
1433
  let resolvedTaskId = null;
1368
1434
  if (taskId !== null) {
@@ -1371,17 +1437,20 @@ async function listNotes({ repoRoot, planKey, taskId }) {
1371
1437
  const projected = await readTodoNoteContext({
1372
1438
  repoRoot, store, planKey, taskId: task.task_id,
1373
1439
  });
1374
- notes = projected.history;
1440
+ // `--task`は「そのtaskのnote」を問う形。plan noteはtaskのものではないので混ぜない
1441
+ // ——欲しければ`--task`を外す。
1442
+ notes = projected.history.filter(({ scope }) => scope === 'task');
1375
1443
  archived = projected.archived;
1376
1444
  }
1377
1445
  const result = {
1378
- schema: 'lattice.todo_note_list_result.v1',
1446
+ schema: 'lattice.todo_note_list_result.v2',
1379
1447
  project_id: store.project_id,
1380
1448
  plan_key: planKey,
1381
1449
  requested_task_id: resolvedTaskId,
1382
1450
  notes,
1383
1451
  archived,
1384
1452
  note_head_digest: chain.head_digest,
1453
+ plan_note_head_digest: planChain.head_digest,
1385
1454
  result_digest: '',
1386
1455
  };
1387
1456
  result.result_digest = todoSelfDigest(result, 'result_digest');
@@ -1567,7 +1636,7 @@ async function independence({ repoRoot, requestedPlanKey }) {
1567
1636
  ? undefined : store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
1568
1637
  const artifact = member === undefined
1569
1638
  ? null : await readTodoIndependenceArtifact({ repoRoot, store, planKey });
1570
- const active = projectTodoStatus(store).active_set
1639
+ const active = projectTodoStatus(store, TODO_STATUS_DISPATCH_ONLY).active_set
1571
1640
  .filter((task) => task.plan_key === planKey);
1572
1641
  // HEADが進んでいる時だけdiffを取る。一致していれば宣言境界を見るまでもない。
1573
1642
  const changedPaths = artifact !== null && artifact.base_sha !== null
@@ -1607,6 +1676,9 @@ async function independence({ repoRoot, requestedPlanKey }) {
1607
1676
  .some(({ unknowns }) => unknowns.some(({ kind }) => kind === 'record_stale')),
1608
1677
  conflictWithActive: projected.frontier.conflicts_with_active[0]?.severability ?? null,
1609
1678
  conflictBetweenReady: projected.frontier.serialize_pairs[0]?.severability ?? null,
1679
+ // 案内の正本は1つ(ADR 0130 Decision 1)。着手する人と読みに来た人が同じ状況について
1680
+ // 違う文言を受け取らないよう、調整方式もここへ渡す。
1681
+ coordinationMode: member?.coordination?.mode ?? null,
1610
1682
  verdictsAbsent: projected.frontier.unknown
1611
1683
  .some(({ unknowns }) => unknowns.some(({ kind }) => kind === 'plan_verdicts_absent')),
1612
1684
  }),
@@ -2141,7 +2213,7 @@ async function notesForGantt({ repoRoot, store }) {
2141
2213
 
2142
2214
  async function independenceForGantt({ repoRoot, store }) {
2143
2215
  const frontier = computeReadyFrontier(store);
2144
- const status = projectTodoStatus(store);
2216
+ const status = projectTodoStatus(store, TODO_STATUS_DISPATCH_ONLY);
2145
2217
  let currentBaseSha = null;
2146
2218
  const projections = [];
2147
2219
  for (const member of store.members) {
@@ -2497,6 +2569,30 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env
2497
2569
  }
2498
2570
  }
2499
2571
 
2572
+ // 登録を外したいprojectのrepoは、もう存在しないことが普通である(それが外す理由になる)。
2573
+ // 通常dispatchより前に処理し、repoRoot解決・store読取・dashboard daemon起動を経由させない。
2574
+ if (argv.length === 4 && argv[0] === 'dashboard' && argv[1] === 'remove'
2575
+ && isTodoIdentifier(argv[2]) && argv[3] === '--json') {
2576
+ try {
2577
+ await removeTodoDashboardProject({ projectId: argv[2], env });
2578
+ const result = {
2579
+ schema: 'lattice.todo_dashboard_remove_result.v1',
2580
+ project_id: argv[2],
2581
+ removed: true,
2582
+ result_digest: '',
2583
+ };
2584
+ result.result_digest = todoSelfDigest(result, 'result_digest');
2585
+ stdout.write(`${JSON.stringify(result)}\n`);
2586
+ return 0;
2587
+ } catch (error) {
2588
+ if (typeof error?.code === 'string' && error.detail !== null
2589
+ && typeof error.detail === 'object') return typedFailure(stderr, error);
2590
+ return typedFailure(stderr, {
2591
+ code: 'INTERNAL_FAILURE', message: error?.constructor?.name ?? 'Error',
2592
+ });
2593
+ }
2594
+ }
2595
+
2500
2596
  let action = null;
2501
2597
  if ((argv.length === 1 && argv[0] === 'status')
2502
2598
  || (argv.length === 2 && argv[0] === 'status' && argv[1] === '--json')) {
@@ -2528,6 +2624,20 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env
2528
2624
  inputRef: argv[5] === '--input' ? argv[6] : null,
2529
2625
  supersedes: argv[8] ?? null,
2530
2626
  });
2627
+ } else if ((argv.length === 5 || argv.length === 7) && argv[0] === 'note'
2628
+ && argv[1] === '--plan' && isTodoIdentifier(argv[2])
2629
+ && ['--message', '--input'].includes(argv[3])
2630
+ && ((argv[3] === '--message' && argv[4].length > 0)
2631
+ || (argv[3] === '--input' && isTodoRef(argv[4])))
2632
+ && (argv.length === 5 || (argv[5] === '--supersedes' && isTodoDigest(argv[6])))) {
2633
+ // `--task`省略でplan単位note。工程レベルの義務(順序制約・一度きりの観測が在ること)は
2634
+ // 特定のtaskに属さない。
2635
+ action = (repoRoot) => appendNote({
2636
+ repoRoot, env, planKey: argv[2], taskId: null,
2637
+ message: argv[3] === '--message' ? argv[4] : null,
2638
+ inputRef: argv[3] === '--input' ? argv[4] : null,
2639
+ supersedes: argv[6] ?? null,
2640
+ });
2531
2641
  } else if (argv.length === 5 && argv[0] === 'note' && argv[1] === 'list'
2532
2642
  && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--json') {
2533
2643
  action = (repoRoot) => listNotes({ repoRoot, planKey: argv[3], taskId: null });
@@ -2538,6 +2648,12 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env
2538
2648
  } else if (argv.length === 5 && argv[0] === 'independence' && argv[1] === 'witness'
2539
2649
  && argv[2] === 'migrate' && argv[3] === '--plan' && isTodoIdentifier(argv[4])) {
2540
2650
  action = (repoRoot) => independenceWitnessMigrate({ repoRoot, planKey: argv[4] });
2651
+ } else if (argv.length === 8 && argv[0] === 'independence' && argv[1] === 'mode'
2652
+ && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--set'
2653
+ && TODO_COORDINATION_MODES.includes(argv[5]) && argv[6] === '--reason' && argv[7].length > 0) {
2654
+ action = (repoRoot) => independenceMode({
2655
+ repoRoot, env, planKey: argv[3], mode: argv[5], reason: argv[7],
2656
+ });
2541
2657
  } else if (argv.length === 6 && argv[0] === 'independence' && argv[1] === 'compile'
2542
2658
  && argv[2] === '--plan' && isTodoIdentifier(argv[3]) && argv[4] === '--input') {
2543
2659
  action = (repoRoot) => independenceCompile({
@@ -8,9 +8,35 @@ export const TODO_EVENT_KINDS = Object.freeze([
8
8
  // phase_review/accept/reject/reopenと同じv3 tail event shape(phase_id持ち)に収め、
9
9
  // 新しいevent schema版は作らない。
10
10
  'phase_close_unaudited',
11
+ // ob03: 調整方式(witness検証で並列するか、会話調整で行くか)の宣言。planに帰属する事実で
12
+ // taskにもPhaseにも属さないため、task_idもphase_idも持たない最初のkindになる。actorが
13
+ // 「誰が選んだか」の帰属を持つ——witnessが全planの暗黙義務だった時に帰属が無く、正確な
14
+ // 案内が素通りされたことへの是正である(オーナー裁定C①)。
15
+ 'coordination_mode',
11
16
  ]);
17
+
18
+ /** planへ帰属し、taskにもPhaseにも属さないevent kind。 */
19
+ export const TODO_PLAN_SCOPED_EVENT_KINDS = Object.freeze(['coordination_mode']);
20
+
21
+ /** 調整方式。witness=独立性を宣言し検証して並列する/conversation=会話で調整する。 */
22
+ export const TODO_COORDINATION_MODES = Object.freeze(['witness', 'conversation']);
12
23
  export const TODO_NOTE_EVENT_SCHEMA = 'lattice.todo_note_event.v1';
13
- export const TODO_NOTE_CONTEXT_SCHEMA = 'lattice.todo_note_context.v1';
24
+ /**
25
+ * plan単位のnote event。工程レベルの義務(順序制約・一度きりの観測が在ること)は特定のtaskに
26
+ * 属さないので、v1の`task_id`必須では書けない。v1は書き換えない——既存chainはhash連鎖で
27
+ * 固定済みであり、taskノートの挙動も digest も動かさない。
28
+ *
29
+ * v2は**別のchain file**(`plan-active.jsonl`)へ積む。同じchainへ混ぜると、旧CLIは
30
+ * 1 eventずつのbyte検証で chain全体を壊れと読み、noteの読みを前提条件とする`todo start`が
31
+ * 落ちる。しかもstoreへ書いたものは戻せない。分離すれば旧CLIはfileの存在に気づかず、
32
+ * task noteの読み書きは1バイトも変わらない。
33
+ */
34
+ export const TODO_NOTE_EVENT_V2_SCHEMA = 'lattice.todo_note_event.v2';
35
+ /**
36
+ * v2でnoteの`scope`とplan noteを載せる。v1のままでは`task_id`が identifier 必須・
37
+ * `full_history_command`が`--task <id>`込みの文字列と完全一致で、どちらもplan noteを表せない。
38
+ */
39
+ export const TODO_NOTE_CONTEXT_SCHEMA = 'lattice.todo_note_context.v2';
14
40
  export const TODO_LIMITS = Object.freeze({
15
41
  tasksPerPlan: 512,
16
42
  edgesPerPlan: 2_048,
@@ -20,6 +46,9 @@ export const TODO_LIMITS = Object.freeze({
20
46
  narrativeSectionBytes: 262_144,
21
47
  noteBodyBytes: 16_384,
22
48
  noteContextBytes: 65_536,
49
+ // statusのplan_notes entryが載せる最新noteの件数。本文を載せない代わりに
50
+ // 「誰がいつ置いたか」だけを新しい順で数件出す(中身はnote listが持つ)。
51
+ statusPlanNoteLatest: 3,
23
52
  });
24
53
 
25
54
  const DIGEST = /^[0-9a-f]{64}$/;
@@ -100,15 +129,27 @@ const noteBody = (value) => typeof value === 'string' && value.length > 0
100
129
  && Buffer.byteLength(value, 'utf8') <= TODO_LIMITS.noteBodyBytes
101
130
  && !NOTE_FORBIDDEN_CONTROL.test(value);
102
131
 
103
- /** lifecycle journalとは独立したtask note event v1を検証する。 */
132
+ /**
133
+ * lifecycle journalとは独立したnote eventを検証する。v1(task note)とv2(plan note)は
134
+ * 別chainへ積まれるが、検証器は両方を受ける——どちらのchainを読んでいるかはpathが決め、
135
+ * chainへ他scopeが混ざっていないことは`readTodoNoteEvents`が読み出し時に落とす。
136
+ * v1は`scope`を持たない——定義上taskであり、投影の側で明示`scope`へ正規化する。
137
+ */
104
138
  export function validateTodoNoteEvent(value) {
105
139
  try {
106
- return exactRecord(value, [
140
+ const keys = [
107
141
  'schema', 'project_id', 'plan_key', 'task_id', 'plan_version', 'sequence',
108
142
  'previous_digest', 'actor', 'recorded_at', 'body', 'supersedes', 'event_digest',
109
- ]) && value.schema === TODO_NOTE_EVENT_SCHEMA
143
+ ];
144
+ const planScoped = value?.schema === TODO_NOTE_EVENT_V2_SCHEMA;
145
+ return exactRecord(value, planScoped ? [...keys, 'scope'] : keys)
146
+ && (planScoped
147
+ // v2は今のところplan scopeだけを表す。phase scopeは配達面(audit_pending entry)を
148
+ // 持つtaskと同じ波で足す——書けるが届かない面を作らないため。
149
+ ? value.scope === 'plan' && value.task_id === null
150
+ : value.schema === TODO_NOTE_EVENT_SCHEMA && isTodoIdentifier(value.task_id))
110
151
  && isTodoIdentifier(value.project_id) && isTodoIdentifier(value.plan_key)
111
- && isTodoIdentifier(value.task_id) && isTodoIdentifier(value.plan_version)
152
+ && isTodoIdentifier(value.plan_version)
112
153
  && Number.isSafeInteger(value.sequence) && value.sequence >= 1
113
154
  && (value.sequence === 1 ? value.previous_digest === null : isTodoDigest(value.previous_digest))
114
155
  && actor(value.actor) && isStrictTodoTimestamp(value.recorded_at) && noteBody(value.body)
@@ -120,12 +161,20 @@ export function validateTodoNoteEvent(value) {
120
161
  }
121
162
  }
122
163
 
164
+ /**
165
+ * `scope`は投影が必ず埋める。読み手はここでv1/v2の区別を持たないので、`origin_task_id`が
166
+ * nullであることから「plan単位だ」を推論させない——型で表現していない区別は、exact検証を
167
+ * 通り抜けて受け手の解釈に落ちる。
168
+ */
123
169
  function noteContextEntry(value) {
124
170
  return exactRecord(value, [
125
- 'event_digest', 'origin_plan_version', 'origin_task_id', 'actor', 'recorded_at',
171
+ 'event_digest', 'origin_plan_version', 'scope', 'origin_task_id', 'actor', 'recorded_at',
126
172
  'body', 'supersedes', 'superseded_by', 'correction_state',
127
173
  ]) && isTodoDigest(value.event_digest) && isTodoIdentifier(value.origin_plan_version)
128
- && isTodoIdentifier(value.origin_task_id) && actor(value.actor)
174
+ && ['plan', 'task'].includes(value.scope)
175
+ && (value.scope === 'plan'
176
+ ? value.origin_task_id === null : isTodoIdentifier(value.origin_task_id))
177
+ && actor(value.actor)
129
178
  && isStrictTodoTimestamp(value.recorded_at) && noteBody(value.body)
130
179
  && (value.supersedes === null || isTodoDigest(value.supersedes))
131
180
  && (value.superseded_by === null || isTodoDigest(value.superseded_by))
@@ -139,17 +188,29 @@ export function validateTodoNoteContext(value) {
139
188
  try {
140
189
  if (!exactRecord(value, [
141
190
  'schema', 'project_id', 'plan_key', 'task_id', 'notes', 'note_head_digest',
142
- 'overflow_count', 'full_history_command', 'context_digest',
191
+ 'plan_note_head_digest', 'overflow_count', 'full_history_command', 'context_digest',
143
192
  ]) || value.schema !== TODO_NOTE_CONTEXT_SCHEMA
144
193
  || !isTodoIdentifier(value.project_id) || !isTodoIdentifier(value.plan_key)
145
194
  || !isTodoIdentifier(value.task_id) || !Array.isArray(value.notes)
146
195
  || value.notes.length > TODO_LIMITS.tasksPerPlan || !value.notes.every(noteContextEntry)
147
196
  || !(value.note_head_digest === null || isTodoDigest(value.note_head_digest))
197
+ || !(value.plan_note_head_digest === null || isTodoDigest(value.plan_note_head_digest))
148
198
  || !isNonNegativeSafeInteger(value.overflow_count)
149
- || value.full_history_command !== `lattice todo note list --plan ${value.plan_key} --task ${value.task_id} --json`
199
+ // contextはplan noteも載せるので、案内するのはplan全体を返す形でなければならない。
200
+ // `--task <id>`形はplan noteを落とすため、fullと名乗りながら全部を取りに行けなくなる。
201
+ || value.full_history_command !== `lattice todo note list --plan ${value.plan_key} --json`
150
202
  || !isTodoDigest(value.context_digest)
151
203
  || value.context_digest !== todoSelfDigest(value, 'context_digest')) return false;
152
- if ((value.notes.length === 0) !== (value.note_head_digest === null)) return false;
204
+ // headはchainごとなので、同値もscopeで切る。task noteが空でplan noteが在る時に
205
+ // 「notesが非空なのにheadがnull」を壊れと読まないため。overflowで本文が落ちても
206
+ // headはchainの実在を述べ続ける——同値はnotesではなくoverflow込みの母集合で見る。
207
+ const scoped = (scope) => value.notes.some((note) => note.scope === scope);
208
+ if (value.overflow_count === 0) {
209
+ if (scoped('task') !== (value.note_head_digest !== null)) return false;
210
+ if (scoped('plan') !== (value.plan_note_head_digest !== null)) return false;
211
+ } else if (value.note_head_digest === null && value.plan_note_head_digest === null) {
212
+ return false;
213
+ }
153
214
  return value.notes.reduce((bytes, note) => bytes + Buffer.byteLength(note.body, 'utf8'), 0)
154
215
  <= TODO_LIMITS.noteContextBytes;
155
216
  } catch {
@@ -440,6 +501,11 @@ function validPayload(event) {
440
501
  && (payload.started_at === 'unknown_requires_evidence' || isStrictTodoTimestamp(payload.started_at))
441
502
  && validateTodoImportSource(payload.evidence);
442
503
  }
504
+ if (event.kind === 'coordination_mode') {
505
+ return exactRecord(payload, ['mode', 'reason'])
506
+ && TODO_COORDINATION_MODES.includes(payload.mode)
507
+ && nullableText(payload.reason) && payload.reason !== null;
508
+ }
443
509
  if (event.kind === 'start') return exactRecord(payload, ['override_reason']) && nullableText(payload.override_reason);
444
510
  if (event.kind === 'block') return exactRecord(payload, ['reason']) && nullableText(payload.reason) && payload.reason !== null;
445
511
  if (event.kind === 'unblock') return exactRecord(payload, []);
@@ -561,17 +627,21 @@ export function validateTodoEvent(value) {
561
627
  && validPhaseStateMigration(value.phase_state_migration);
562
628
  const phaseKind = ['phase_review', 'phase_accept', 'phase_reject', 'phase_reopen', 'phase_close_unaudited']
563
629
  .includes(value?.kind);
630
+ // planへ帰属するkindは、plan_genesisと同じくtask_idを持たない(v3/v4ではphase_idも持たない)。
631
+ // plan_genesisと違うのはjournalの途中に何度でも積めることで、最後の1件が現在の宣言になる。
632
+ const planScopedKind = TODO_PLAN_SCOPED_EVENT_KINDS.includes(value?.kind);
633
+ const planLevel = value?.kind === 'plan_genesis' || planScopedKind;
564
634
  return (v1 || v2 || v3 || v4) && isTodoIdentifier(value.project_id)
565
635
  && isTodoIdentifier(value.plan_key) && isTodoIdentifier(value.plan_version)
566
636
  && isNonNegativeSafeInteger(value.sequence) && nullableDigest(value.previous_digest)
567
637
  && TODO_EVENT_KINDS.includes(value.kind)
568
638
  && (v3 || v4
569
- ? ((value.kind === 'plan_genesis' && value.task_id === null && value.phase_id === null)
639
+ ? ((planLevel && value.task_id === null && value.phase_id === null)
570
640
  || (phaseKind && value.task_id === null && isTodoIdentifier(value.phase_id))
571
- || (!phaseKind && value.kind !== 'plan_genesis' && isTodoIdentifier(value.task_id)
641
+ || (!phaseKind && !planLevel && isTodoIdentifier(value.task_id)
572
642
  && value.phase_id === null))
573
- : !phaseKind && ((value.kind === 'plan_genesis' && value.task_id === null)
574
- || (value.kind !== 'plan_genesis' && isTodoIdentifier(value.task_id))))
643
+ : !phaseKind && ((planLevel && value.task_id === null)
644
+ || (!planLevel && isTodoIdentifier(value.task_id))))
575
645
  && actor(value.actor) && isStrictTodoTimestamp(value.recorded_at) && provenance(value.provenance)
576
646
  && validPayload(value) && isTodoDigest(value.event_digest)
577
647
  && value.event_digest === todoSelfDigest(value, 'event_digest');