@quolu/lattice 0.80.0 → 0.81.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.80.0",
3
+ "version": "0.81.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",
@@ -1,6 +1,5 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { randomBytes, randomInt } from 'node:crypto';
3
- import { homedir } from 'node:os';
4
3
  import { isIP } from 'node:net';
5
4
  import {
6
5
  chmod, lstat, mkdir, open, readFile, rename, rm, writeFile,
@@ -9,6 +8,8 @@ import path from 'node:path';
9
8
  import { domainToASCII } from 'node:url';
10
9
  import { parseTree } from 'jsonc-parser';
11
10
 
11
+ import { resolveSeatIdentity } from './seat-identity.mjs';
12
+
12
13
  export const BRIDGE_CONFIG_SCHEMA = 'lattice.bridge_config.v1';
13
14
  export const BRIDGE_PORT_MIN = 49_152;
14
15
  export const BRIDGE_PORT_MAX = 65_535;
@@ -36,13 +37,11 @@ function exact(value, keys) {
36
37
 
37
38
  function configRoot(env) {
38
39
  const configured = env.LATTICE_CONFIG_DIR;
39
- if (configured !== undefined) {
40
- if (typeof configured !== 'string' || !path.isAbsolute(configured)) {
41
- throw new BridgeConfigError('BRIDGE_CONFIG_DIR_INVALID', 'LATTICE_CONFIG_DIR must be absolute');
42
- }
43
- return configured;
40
+ if (configured !== undefined && (typeof configured !== 'string' || !path.isAbsolute(configured))) {
41
+ throw new BridgeConfigError('BRIDGE_CONFIG_DIR_INVALID', 'LATTICE_CONFIG_DIR must be absolute');
44
42
  }
45
- return path.join(homedir(), '.lattice');
43
+ // 席ごとの置き場は seat-identity が導く(LATTICE_CONFIG_DIR > LATTICE_SEAT_ID > ~/.lattice)。
44
+ return resolveSeatIdentity(env).state_dir;
46
45
  }
47
46
 
48
47
  export function bridgeConfigPaths(env = process.env) {
@@ -7,7 +7,7 @@ import {
7
7
  digestTodoArtifact, todoSelfDigest,
8
8
  } from './todo-contracts.mjs';
9
9
  import {
10
- appendImportedPlan, applyPhaseTodoRevision, buildTodoPlan, createTodoStoreWriter,
10
+ appendAuthoredTodoPlan, applyPhaseTodoRevision, buildTodoPlan, createTodoStoreWriter,
11
11
  readTodoStore, TodoStoreError,
12
12
  } from './todo-store.mjs';
13
13
  import { gitSync } from './git-process.mjs';
@@ -590,11 +590,12 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
590
590
  const plan = buildTodoPlan({
591
591
  ...planSeed(amended, null), plan_version: chain.plan_version,
592
592
  });
593
- const added = await appendImportedPlan({
594
- repoRoot, writer: createTodoStoreWriter({ caller: 'g4-migration' }),
593
+ const addedStore = await appendAuthoredTodoPlan({
594
+ repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
595
595
  plan, genesis: { actor: authoring.actor, recorded_at: authoring.recorded_at,
596
596
  provenance: null }, featureChain: chain,
597
597
  });
598
+ const added = addedStore.members.find(({ plan: candidate }) => candidate.plan_key === plan.plan_key);
598
599
  created = {
599
600
  schema: 'lattice.plan_backchain_add_result.v1',
600
601
  plan_key: added.plan.plan_key, plan_version: added.plan.plan_version,
@@ -27,9 +27,11 @@ import { ensureTodoDashboardActivity } from './todo-dashboard-registry.mjs';
27
27
  import { reportProjectDashboardDelivery } from './dashboard-delivery.mjs';
28
28
  import { resolveProjectIdentity } from './project-identity.mjs';
29
29
  import {
30
+ appendAuthoredTodoPlan,
30
31
  buildTodoPlan,
31
32
  createTodoStoreWriter,
32
33
  initializeAuthoredTodoStore,
34
+ isUninitializedTodoStore,
33
35
  isPhaselessTodoPlanSchema,
34
36
  readTodoIndependenceArtifact,
35
37
  readTodoStore,
@@ -121,7 +123,7 @@ export function validateProjectStatus(value) {
121
123
  && typeof value.next_action.reason === 'string' && value.next_action.reason.length > 0;
122
124
  }
123
125
  return value.project !== null && isTodoIdentifier(value.project.project_id)
124
- && value.can_create_plan === false && exactRecord(value.next_action, ['command', 'reason'])
126
+ && value.can_create_plan === true && exactRecord(value.next_action, ['command', 'reason'])
125
127
  && typeof value.next_action.reason === 'string' && value.next_action.reason.length > 0
126
128
  && (value.state !== 'active_run' || value.active_runs.length > 0)
127
129
  && (value.state !== 'ready' || value.active_runs.length === 0);
@@ -252,7 +254,10 @@ async function resolveProjectState({ cwd, cliVersion, diagnoseStructureArtifacts
252
254
  try { manifestState = await lstat(manifestAbsolute); } catch (error) {
253
255
  if (error?.code !== 'ENOENT') return invalid('manifest_unreadable');
254
256
  }
255
- if (storeState === undefined && manifestState === undefined) {
257
+ let uninitialized;
258
+ try { uninitialized = await isUninitializedTodoStore({ repoRoot }); }
259
+ catch { return invalid('store_unreadable'); }
260
+ if (uninitialized) {
256
261
  return { exitCode: 0, repoRoot, store: null, todo: null, result: statusResult({
257
262
  cli: { available: true, version: cliVersion },
258
263
  project: { root: repoRoot, git_head: gitHead(repoRoot), project_id: null },
@@ -318,7 +323,7 @@ async function resolveProjectState({ cwd, cliVersion, diagnoseStructureArtifacts
318
323
  plan_key: entry.plan_key, plan_version: entry.plan_version,
319
324
  })),
320
325
  active_runs: activeRuns,
321
- can_create_plan: false,
326
+ can_create_plan: true,
322
327
  next_action: next,
323
328
  });
324
329
  return { exitCode: 0, repoRoot, store, todo, result };
@@ -639,10 +644,9 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
639
644
  hardDependencies: input.hard_dependencies,
640
645
  joins: input.joins,
641
646
  });
642
- const store = await initializeAuthoredTodoStore({
647
+ const options = {
643
648
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
644
- projectId: input.project_id, repositories: [{ repo_id: 'self', path: '.' }],
645
- plan: {
649
+ plan: buildTodoPlan({
646
650
  schema: input.schema === MEMO_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v7'
647
651
  : input.schema === DECOUPLED_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v5'
648
652
  : input.schema === PHASE_CREATE_INPUT_SCHEMA
@@ -654,11 +658,19 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
654
658
  MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(input.schema) ? { phases: input.phases } : {}),
655
659
  ...([DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(input.schema)
656
660
  ? { phase_accept_dependencies: input.phase_accept_dependencies } : {}),
657
- },
661
+ }),
658
662
  genesis: { actor: input.actor, recorded_at: input.recorded_at, provenance: null },
659
663
  ...(featureChain === null ? {} : { featureChain }),
664
+ };
665
+ const manifest = await lstat(path.join(repoRoot, MANIFEST_REF)).catch((error) => {
666
+ if (!['ENOENT', 'ENOTDIR'].includes(error?.code)) throw error;
667
+ return null;
660
668
  });
661
- const member = store.members[0];
669
+ const store = manifest === null
670
+ ? await initializeAuthoredTodoStore({ ...options,
671
+ projectId: input.project_id, repositories: [{ repo_id: 'self', path: '.' }] })
672
+ : await appendAuthoredTodoPlan(options);
673
+ const member = store.members.find(({ plan }) => plan.plan_key === input.plan_key);
662
674
  const result = {
663
675
  schema: CREATE_RESULT_SCHEMA, project_id: store.project_id,
664
676
  plan_key: member.plan.plan_key, plan_version: member.plan.plan_version,
@@ -12,6 +12,8 @@ import path from 'node:path';
12
12
 
13
13
  import { canonicalizeArtifact, digestArtifact } from './artifact-contracts.mjs';
14
14
  import { buildExecutorPackets } from './runtime-engine.mjs';
15
+ import { verifyRunEventChain } from './runtime-event-store.mjs';
16
+ import { validateRuntimeControlJournal } from './runtime-control-store.mjs';
15
17
  import {
16
18
  RUNTIME_CONFLICT_KINDS,
17
19
  validateExecutorPacket,
@@ -93,6 +95,42 @@ function selfDigestValid(value, field) {
93
95
  return digestArtifact(body) === value[field];
94
96
  }
95
97
 
98
+ function activationPrefixEvidence(events, expectedDigest, { stream, runId, plan }) {
99
+ plan ??= {};
100
+ const isArray = Array.isArray(events);
101
+ const index = isArray ? events.findIndex((event) => event?.event_digest === expectedDigest) : -1;
102
+ const actual = isArray ? events.at(-1)?.event_digest : null;
103
+ const chainValid = isArray && (stream === 'run'
104
+ ? verifyRunEventChain({ events }).valid && events[0]?.run_id === runId
105
+ : validateRuntimeControlJournal(events, runId));
106
+ const conflicting = chainValid && index >= 0 ? events.slice(index + 1).find((event) => {
107
+ if (stream === 'run') {
108
+ return event.plan_epoch > plan.plan_epoch
109
+ || ['run_closed', 'intake_frozen'].includes(event.kind)
110
+ || (event.kind === 'intake_resumed' && event.plan_epoch === plan.plan_epoch)
111
+ || (event.kind === 'plan_recompiled' && event.plan_epoch >= plan.plan_epoch
112
+ && (event.plan_epoch !== plan.plan_epoch
113
+ || event.payload.new_plan_digest !== plan.plan_digest
114
+ || event.subject.ref !== plan.plan_ref));
115
+ }
116
+ return ['supervisor_stopped', 'supervisor_recovery_barrier', 'write_gate_committed'].includes(event.kind)
117
+ || (['epoch_activated', 'intake_resumed'].includes(event.kind)
118
+ && event.payload.plan_epoch >= plan.plan_epoch);
119
+ }) : null;
120
+ return {
121
+ expected_tail: expectedDigest, actual_tail: HEX_DIGEST.test(actual ?? '') ? actual : null,
122
+ expected_in_chain: index >= 0, chain_valid: chainValid,
123
+ conflicting_event_digest: conflicting?.event_digest ?? null,
124
+ };
125
+ }
126
+
127
+ function activationEvidence(runEvents, controlEvents, runDigest, controlDigest, runId, plan) {
128
+ return {
129
+ run: activationPrefixEvidence(runEvents, runDigest, { stream: 'run', runId, plan }),
130
+ control: activationPrefixEvidence(controlEvents, controlDigest, { stream: 'control', runId, plan }),
131
+ };
132
+ }
133
+
96
134
  export function validateRuntimeFindingRecord(value) {
97
135
  if (!exactRecord(value, ['schema', 'finding_id', 'run_id', 'plan_epoch',
98
136
  'source_checkpoint_digest', 'observed_event_digest', 'finding', 'recorded_by', 'finding_digest'])
@@ -431,13 +469,12 @@ export async function activateEpochOneStore({
431
469
  }
432
470
  const runEvents = await readRegularJson(path.join(runDir, 'events.json'), 'run events');
433
471
  const controlEvents = await readRegularJson(path.join(runDir, 'control-events.json'), 'runtime control events');
434
- const controlHead = controlEvents.at?.(-1);
435
- if (!Array.isArray(runEvents) || runEvents.at(-1)?.event_digest !== activationRunEventDigest
436
- || !Array.isArray(controlEvents)
437
- || controlHead?.event_digest !== activationControlEventDigest
438
- || controlHead?.kind !== 'supervisor_activated'
439
- || !selfDigestValid(controlHead, 'event_digest')) {
440
- fail('INVALID_RUN_STORE', 'activation pointerがdurable event headへbindしない');
472
+ const evidence = activationEvidence(runEvents, controlEvents, activationRunEventDigest,
473
+ activationControlEventDigest, request?.request_id, compileArtifact?.plan);
474
+ if (!Object.values(evidence).every((entry) => entry.chain_valid && entry.expected_in_chain
475
+ && entry.conflicting_event_digest === null)
476
+ || controlEvents.find((event) => event.event_digest === activationControlEventDigest)?.kind !== 'supervisor_activated') {
477
+ fail('INVALID_RUN_STORE', `activation pointerがdurable event prefixへbindしない: ${JSON.stringify(evidence)}`, evidence);
441
478
  }
442
479
  const normalizedMeta = normalizeActivationMeta(legacyMeta, request, compileArtifact);
443
480
  const bundle = buildEpochOneBundle({ request, compileArtifact, legacyMeta: normalizedMeta });
@@ -507,7 +544,7 @@ export async function activateEpochOneStore({
507
544
  };
508
545
  meta.meta_digest = digestArtifact(meta);
509
546
  await replaceDurableJson(runDir, 'run-meta.json', meta);
510
- return { bundle, meta, pointer };
547
+ return { bundle, meta, pointer, activation_evidence: evidence };
511
548
  }
512
549
 
513
550
  /** pointerを正本としてactive bundleだけを読む。directory最大値へfallbackしない。 */
@@ -697,7 +734,7 @@ export async function stageSuccessorEpoch({ runDir, transactionId, bundle, recom
697
734
  }
698
735
 
699
736
  /**
700
- * staged successorをepoch historyへrenameし、durable event headsを確認してpointerを最後にcommitする。
737
+ * staged successorをepoch historyへrenameし、durable activation prefixを確認してpointerを最後にcommitする。
701
738
  * 同digest retryだけを許し、directory最大値や別transactionへfallbackしない。
702
739
  */
703
740
  export async function commitStagedSuccessorEpoch({ runDir, transactionId,
@@ -746,9 +783,12 @@ export async function commitStagedSuccessorEpoch({ runDir, transactionId,
746
783
  const controlEvents = typeof readActivationControlEvents === 'function'
747
784
  ? await readActivationControlEvents()
748
785
  : await readRegularJson(path.join(runDir, 'control-events.json'), 'runtime control events');
749
- if (!Array.isArray(runEvents) || runEvents.at(-1)?.event_digest !== activationRunEventDigest
750
- || !Array.isArray(controlEvents) || controlEvents.at(-1)?.event_digest !== activationControlEventDigest) {
751
- fail('EPOCH_ACTIVATION_INCOMPLETE', 'successor activation event headが未耐久化');
786
+ const evidence = activationEvidence(runEvents, controlEvents, activationRunEventDigest,
787
+ activationControlEventDigest, bundle.run_id, bundle.plan);
788
+ if (!Object.values(evidence).every((entry) => entry.chain_valid && entry.expected_in_chain
789
+ && entry.conflicting_event_digest === null)) {
790
+ fail('EPOCH_ACTIVATION_INCOMPLETE',
791
+ `successor activation event prefixが未耐久化又は矛盾: ${JSON.stringify(evidence)}`, evidence);
752
792
  }
753
793
  const epochsDir = path.join(runDir, 'epochs');
754
794
  const epochDir = path.join(epochsDir, String(bundle.plan_epoch).padStart(8, '0'));
@@ -776,7 +816,7 @@ export async function commitStagedSuccessorEpoch({ runDir, transactionId,
776
816
  };
777
817
  pointer.pointer_digest = digestArtifact(pointer);
778
818
  await replaceDurableJson(runDir, 'committed-epoch.json', pointer);
779
- return { bundle, pointer };
819
+ return { bundle, pointer, activation_evidence: evidence };
780
820
  }
781
821
 
782
822
  export async function commitReleaseEpochBarrier({ runDir, barrier }) {
@@ -0,0 +1,23 @@
1
+ // 席の識別の唯一の置き場。AIは LATTICE_SEAT_ID を言い、機械が seat_id と状態の置き場を導く。
2
+ // 不正な値は拒否せず null に落とす(席が無名になるだけで、何も止めない)。
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ const SEAT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
7
+
8
+ /** @returns {{ seat_id: string|null, state_dir: string }} */
9
+ export function resolveSeatIdentity(env = process.env) {
10
+ const raw = env.LATTICE_SEAT_ID;
11
+ const seat_id = typeof raw === 'string' && SEAT_ID.test(raw) ? raw : null;
12
+ const configured = env.LATTICE_CONFIG_DIR;
13
+ const state_dir = typeof configured === 'string' && path.isAbsolute(configured)
14
+ ? configured
15
+ : seat_id === null ? path.join(homedir(), '.lattice') : path.join(homedir(), '.lattice', 'seats', seat_id);
16
+ return Object.freeze({ seat_id, state_dir });
17
+ }
18
+
19
+ /** status / session-context の top-level へ混ぜる欄。未設定なら空(欄を出さない)。 */
20
+ export function seatIdentityFields(env = process.env) {
21
+ const { seat_id } = resolveSeatIdentity(env);
22
+ return seat_id === null ? {} : { seat_id };
23
+ }
@@ -296,15 +296,16 @@ export function validatePhaseTodoRevision(value) {
296
296
  const revisionV2 = value?.schema === 'lattice.phase_todo_revision.v2';
297
297
  const revisionV3 = value?.schema === 'lattice.phase_todo_revision.v3';
298
298
  const revisionV4 = value?.schema === 'lattice.phase_todo_revision.v4';
299
+ const revisionV5 = value?.schema === 'lattice.phase_todo_revision.v5';
299
300
  const keys = revisionV3 ? PHASE_REVISION_V3_KEYS
300
301
  : revisionV4 ? PHASE_REVISION_V4_KEYS : PHASE_REVISION_KEYS;
301
- if (!exactRecord(value, keys) || (!revisionV1 && !revisionV2 && !revisionV3 && !revisionV4)) return false;
302
+ if (!exactRecord(value, keys) || (!revisionV1 && !revisionV2 && !revisionV3 && !revisionV4 && !revisionV5)) return false;
302
303
  if (!isTodoIdentifier(value.project_id) || !isTodoIdentifier(value.plan_key)) return false;
303
304
  if (!validPredecessor(value.predecessor) || !validateTodoPlan(value.desired_plan)
304
305
  || !(revisionV3
305
306
  ? ['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.desired_plan.schema)
306
307
  : value.desired_plan.schema === (revisionV2 ? 'lattice.todo_plan.v5'
307
- : revisionV4 ? 'lattice.todo_plan.v7' : 'lattice.todo_plan.v4'))
308
+ : (revisionV4 || revisionV5) ? 'lattice.todo_plan.v7' : 'lattice.todo_plan.v4'))
308
309
  || value.desired_plan.project_id !== value.project_id
309
310
  || value.desired_plan.plan_key !== value.plan_key
310
311
  || value.desired_plan.predecessor_plan_digest !== value.predecessor.plan_digest
@@ -832,7 +833,7 @@ export function explainTodoRevision(value) {
832
833
  }
833
834
 
834
835
  /**
835
- * `lattice todo revise-phase`が受理する`lattice.phase_todo_revision.v1/v2/v3`を診断する。
836
+ * `lattice todo revise-phase`が受理する`lattice.phase_todo_revision.v1/v2/v3/v4/v5`を診断する。
836
837
  * 方針は`explainTodoRevision`と同じ——desired_planのgraph整合は単一reasonへ丸め、
837
838
  * v3で増える`runtime_task_migration`・`source_cutover_batch`・8-key reconciliationの
838
839
  * 各digestを個別に名指しする。
@@ -844,7 +845,8 @@ export function explainPhaseTodoRevision(value) {
844
845
  const revisionV2 = value.schema === 'lattice.phase_todo_revision.v2';
845
846
  const revisionV3 = value.schema === 'lattice.phase_todo_revision.v3';
846
847
  const revisionV4 = value.schema === 'lattice.phase_todo_revision.v4';
847
- if (!revisionV1 && !revisionV2 && !revisionV3 && !revisionV4) return reject('schema_mismatch', '/schema');
848
+ const revisionV5 = value.schema === 'lattice.phase_todo_revision.v5';
849
+ if (!revisionV1 && !revisionV2 && !revisionV3 && !revisionV4 && !revisionV5) return reject('schema_mismatch', '/schema');
848
850
  const keyCheck = explainKeys(value, revisionV3 ? PHASE_REVISION_V3_KEYS
849
851
  : revisionV4 ? PHASE_REVISION_V4_KEYS : PHASE_REVISION_KEYS, '');
850
852
  if (!keyCheck.valid) return keyCheck;
@@ -855,7 +857,7 @@ export function explainPhaseTodoRevision(value) {
855
857
  if (!validateTodoPlan(value.desired_plan)) return reject('desired_plan_invalid', '/desired_plan');
856
858
  const expectedPlanSchemas = revisionV3 ? ['lattice.todo_plan.v5', 'lattice.todo_plan.v7']
857
859
  : [revisionV2 ? 'lattice.todo_plan.v5'
858
- : revisionV4 ? 'lattice.todo_plan.v7' : 'lattice.todo_plan.v4'];
860
+ : (revisionV4 || revisionV5) ? 'lattice.todo_plan.v7' : 'lattice.todo_plan.v4'];
859
861
  if (!expectedPlanSchemas.includes(value.desired_plan.schema)) {
860
862
  return reject('desired_plan_schema_mismatch', '/desired_plan/schema');
861
863
  }
@@ -1,4 +1,5 @@
1
1
  /* Pure projections shared by Store and Plan; no I/O or lifecycle mutation. */
2
+ import { canonicalizeTodoArtifact } from './todo-contracts.mjs';
2
3
 
3
4
  export function isPhaseTodoPlanSchema(schema) {
4
5
  return ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(schema);
@@ -45,3 +46,60 @@ export function projectTodoCrossPlanDependencies(members) {
45
46
  return key(left) < key(right) ? -1 : key(left) > key(right) ? 1 : 0;
46
47
  });
47
48
  }
49
+
50
+ function mappedNodeRef(ref, plan, idMap) {
51
+ if (ref.project_id !== plan.project_id || ref.plan_key !== plan.plan_key) return ref;
52
+ return { ...ref, task_id: idMap.get(ref.task_id) ?? ref.task_id };
53
+ }
54
+
55
+ export function localTaskRef(ref, plan, taskId) {
56
+ return ref.project_id === plan.project_id && ref.plan_key === plan.plan_key
57
+ && ref.task_id === taskId;
58
+ }
59
+
60
+ export function removedTaskRef(ref, plan, removedTaskIds) {
61
+ return ref.project_id === plan.project_id && ref.plan_key === plan.plan_key
62
+ && removedTaskIds.has(ref.task_id);
63
+ }
64
+
65
+ export function todoTaskCarrySemantics(plan, taskId, idMap, {
66
+ reconciliationMetadata = false, includeDesignMemo = false, removedTaskIds = new Set(),
67
+ } = {}) {
68
+ const task = plan.tasks.find(({ task_id }) => task_id === taskId);
69
+ if (!task) return null;
70
+ const mapId = (id) => id === null ? null : idMap.get(id) ?? id;
71
+ const normalizedTask = reconciliationMetadata ? {
72
+ task_id: mapId(task.task_id), title: task.title, lane: task.lane,
73
+ compile_binding: task.compile_binding,
74
+ } : {
75
+ task_id: mapId(task.task_id), title: task.title, lane: task.lane,
76
+ ...(includeDesignMemo ? { design_memo: task.design_memo } : {}),
77
+ narrative_ref: task.narrative_ref, narrative_anchor: task.narrative_anchor ?? null,
78
+ compile_binding: task.compile_binding, parent_task_id: mapId(task.parent_task_id ?? null),
79
+ };
80
+ const edges = plan.hard_dependencies
81
+ .filter(({ from, to }) => !removedTaskRef(from, plan, removedTaskIds)
82
+ && !removedTaskRef(to, plan, removedTaskIds)
83
+ && (localTaskRef(from, plan, taskId) || localTaskRef(to, plan, taskId)))
84
+ .map(({ from, to }) => ({ from: mappedNodeRef(from, plan, idMap), to: mappedNodeRef(to, plan, idMap) }))
85
+ .sort((left, right) => canonicalizeTodoArtifact(left) < canonicalizeTodoArtifact(right) ? -1 : 1);
86
+ const joins = plan.joins
87
+ .flatMap((join) => {
88
+ if (removedTaskRef(join.before, plan, removedTaskIds)) return [];
89
+ const after = join.after.filter((ref) => !removedTaskRef(ref, plan, removedTaskIds));
90
+ if (after.length === 0 || (!localTaskRef(join.before, plan, taskId)
91
+ && !after.some((ref) => localTaskRef(ref, plan, taskId)))) return [];
92
+ return [{ ...join,
93
+ after: after.map((ref) => mappedNodeRef(ref, plan, idMap))
94
+ .sort((left, right) => canonicalizeTodoArtifact(left) < canonicalizeTodoArtifact(right) ? -1 : 1),
95
+ before: mappedNodeRef(join.before, plan, idMap),
96
+ }];
97
+ }).sort((left, right) => left.id < right.id ? -1 : 1);
98
+ const phaseAcceptDependencies = isDecoupledPhaseTodoPlanSchema(plan.schema)
99
+ ? plan.phase_accept_dependencies
100
+ .filter(({ to }) => localTaskRef(to, plan, taskId))
101
+ .map(({ from, to }) => ({ from, to: mappedNodeRef(to, plan, idMap) }))
102
+ .sort((left, right) => canonicalizeTodoArtifact(left) < canonicalizeTodoArtifact(right) ? -1 : 1)
103
+ : [];
104
+ return { task: normalizedTask, hard_dependencies: edges, joins, phase_accept_dependencies: phaseAcceptDependencies };
105
+ }
@@ -3,12 +3,16 @@ import {
3
3
  isPhaseTodoPlanSchema,
4
4
  isPhaselessTodoPlanSchema,
5
5
  projectTodoCrossPlanDependencies,
6
+ localTaskRef,
7
+ removedTaskRef,
8
+ todoTaskCarrySemantics as taskSemantics,
6
9
  } from './todo-store-view.mjs';
7
10
  export {
8
11
  isDecoupledPhaseTodoPlanSchema,
9
12
  isPhaseTodoPlanSchema,
10
13
  isPhaselessTodoPlanSchema,
11
14
  projectTodoCrossPlanDependencies,
15
+ todoTaskCarrySemantics,
12
16
  } from './todo-store-view.mjs';
13
17
  import { randomBytes } from 'node:crypto';
14
18
  import { fsyncDirectory } from './fs-dir-sync.mjs';
@@ -85,6 +89,7 @@ const TODO_REVISION_SCHEMAS = Object.freeze([
85
89
  const PHASE_TODO_REVISION_SCHEMAS = Object.freeze([
86
90
  'lattice.phase_todo_revision.v1', 'lattice.phase_todo_revision.v2',
87
91
  'lattice.phase_todo_revision.v3', 'lattice.phase_todo_revision.v4',
92
+ 'lattice.phase_todo_revision.v5',
88
93
  ]);
89
94
 
90
95
  export class TodoStoreError extends Error {
@@ -3263,69 +3268,12 @@ export async function verifyPhaseTodoRevisionSources(options = {}) {
3263
3268
  return true;
3264
3269
  }
3265
3270
 
3266
- function mappedNodeRef(ref, plan, idMap) {
3267
- if (ref.project_id !== plan.project_id || ref.plan_key !== plan.plan_key) return ref;
3268
- return { ...ref, task_id: idMap.get(ref.task_id) ?? ref.task_id };
3269
- }
3270
-
3271
- function localTaskRef(ref, plan, taskId) {
3272
- return ref.project_id === plan.project_id && ref.plan_key === plan.plan_key
3273
- && ref.task_id === taskId;
3274
- }
3275
-
3276
3271
  function removedTaskIdsFor(revision) {
3277
3272
  return new Set(revision.task_migration
3278
3273
  .filter(({ to_task_id, state_policy }) => to_task_id === 'removed' && state_policy === 'removed')
3279
3274
  .map(({ from_task_id }) => from_task_id));
3280
3275
  }
3281
3276
 
3282
- function removedTaskRef(ref, plan, removedTaskIds) {
3283
- return ref.project_id === plan.project_id && ref.plan_key === plan.plan_key
3284
- && removedTaskIds.has(ref.task_id);
3285
- }
3286
-
3287
- function taskSemantics(plan, taskId, idMap, {
3288
- reconciliationMetadata = false, includeDesignMemo = false, removedTaskIds = new Set(),
3289
- } = {}) {
3290
- const task = plan.tasks.find(({ task_id }) => task_id === taskId);
3291
- if (!task) return null;
3292
- const mapId = (id) => id === null ? null : idMap.get(id) ?? id;
3293
- const normalizedTask = reconciliationMetadata ? {
3294
- task_id: mapId(task.task_id), title: task.title, lane: task.lane,
3295
- compile_binding: task.compile_binding,
3296
- } : {
3297
- task_id: mapId(task.task_id), title: task.title, lane: task.lane,
3298
- ...(includeDesignMemo ? { design_memo: task.design_memo } : {}),
3299
- narrative_ref: task.narrative_ref, narrative_anchor: task.narrative_anchor ?? null,
3300
- compile_binding: task.compile_binding, parent_task_id: mapId(task.parent_task_id ?? null),
3301
- };
3302
- const edges = plan.hard_dependencies
3303
- .filter(({ from, to }) => !removedTaskRef(from, plan, removedTaskIds)
3304
- && !removedTaskRef(to, plan, removedTaskIds)
3305
- && (localTaskRef(from, plan, taskId) || localTaskRef(to, plan, taskId)))
3306
- .map(({ from, to }) => ({ from: mappedNodeRef(from, plan, idMap), to: mappedNodeRef(to, plan, idMap) }))
3307
- .sort((left, right) => canonicalizeTodoArtifact(left) < canonicalizeTodoArtifact(right) ? -1 : 1);
3308
- const joins = plan.joins
3309
- .flatMap((join) => {
3310
- if (removedTaskRef(join.before, plan, removedTaskIds)) return [];
3311
- const after = join.after.filter((ref) => !removedTaskRef(ref, plan, removedTaskIds));
3312
- if (after.length === 0 || (!localTaskRef(join.before, plan, taskId)
3313
- && !after.some((ref) => localTaskRef(ref, plan, taskId)))) return [];
3314
- return [{ ...join,
3315
- after: after.map((ref) => mappedNodeRef(ref, plan, idMap))
3316
- .sort((left, right) => canonicalizeTodoArtifact(left) < canonicalizeTodoArtifact(right) ? -1 : 1),
3317
- before: mappedNodeRef(join.before, plan, idMap),
3318
- }];
3319
- }).sort((left, right) => left.id < right.id ? -1 : 1);
3320
- const phaseAcceptDependencies = isDecoupledPhaseTodoPlanSchema(plan.schema)
3321
- ? plan.phase_accept_dependencies
3322
- .filter(({ to }) => localTaskRef(to, plan, taskId))
3323
- .map(({ from, to }) => ({ from, to: mappedNodeRef(to, plan, idMap) }))
3324
- .sort((left, right) => canonicalizeTodoArtifact(left) < canonicalizeTodoArtifact(right) ? -1 : 1)
3325
- : [];
3326
- return { task: normalizedTask, hard_dependencies: edges, joins, phase_accept_dependencies: phaseAcceptDependencies };
3327
- }
3328
-
3329
3277
  function phaseV3CarrySemantics(plan, taskId, taskIdMap, phaseIdMap,
3330
3278
  { reconciliationMetadata = false, includeDesignMemo = false, removedTaskIds = new Set() } = {}) {
3331
3279
  const task = plan.tasks.find(({ task_id: id }) => id === taskId);