@quolu/lattice 0.102.0 → 0.103.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.102.0",
3
+ "version": "0.103.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",
@@ -12,6 +12,7 @@ import {
12
12
  applyPhaseTodoRevision, buildTodoPlan, createTodoStoreWriter, readTodoStore, TodoStoreError,
13
13
  } from './todo-store.mjs';
14
14
  import { appendTodoNote } from './todo-note-store.mjs';
15
+ import { planReviseNoteBody } from './todo-revision-note.mjs';
15
16
  import { phaseTodoRevisionPlanVersion, validatePhaseTodoRevision } from './todo-revision.mjs';
16
17
 
17
18
  export { validateBindingCarry } from './plan-binding-carry.mjs';
@@ -85,20 +86,20 @@ function authoredSurface(plan, taskId) {
85
86
  * 取り除いたtaskごとにplan note1件。本文は `plan revise <from>→<to> <task_id>: <reason>`。
86
87
  */
87
88
  export function planRevisionHistoryNotes({ previousPlan, successorPlan, continuity }) {
88
- const prefix = (taskId) => `plan revise ${previousPlan.plan_version}→${successorPlan.plan_version} ${taskId}:`;
89
+ const body = (taskId, reason) => planReviseNoteBody(previousPlan.plan_version, successorPlan.plan_version, taskId, reason);
89
90
  const notes = [];
90
91
  const ordered = [...continuity].sort((left, right) => (
91
92
  left.task_id < right.task_id ? -1 : left.task_id > right.task_id ? 1 : 0));
92
93
  for (const { task_id: taskId, policy, reason } of ordered) {
93
94
  if (policy === 'retire') {
94
- notes.push({ scope: 'plan', task_id: taskId, body: `${prefix(taskId)} ${reason}` });
95
+ notes.push({ scope: 'plan', task_id: taskId, body: body(taskId, reason) });
95
96
  } else if (policy === 'carry') {
96
97
  const before = authoredSurface(previousPlan, taskId);
97
98
  const after = authoredSurface(successorPlan, taskId);
98
99
  const changed = Object.keys(before).filter((field) => before[field] !== after[field]);
99
100
  if (changed.length > 0) {
100
101
  notes.push({ scope: 'task', task_id: taskId,
101
- body: `${prefix(taskId)} ${reason}\nchanged: ${changed.join(', ')}` });
102
+ body: `${body(taskId, reason)}\nchanged: ${changed.join(', ')}` });
102
103
  }
103
104
  }
104
105
  }
package/src/todo-cli.mjs CHANGED
@@ -202,6 +202,7 @@ import {
202
202
  readTodoNoteEvents,
203
203
  readTodoPlanNotesForStatus,
204
204
  } from './todo-note-store.mjs';
205
+ import { dependencyNoteBody, todoAddNoteBody } from './todo-revision-note.mjs';
205
206
  import { readTodoParallelCandidatesForStatus } from './todo-parallel-candidates.mjs';
206
207
  import { commitTodoStoreMutation } from './todo-store-git-transaction.mjs';
207
208
  import { repairTodoStoreWorktreeEol } from './todo-store-worktree-eol.mjs';
@@ -1832,7 +1833,7 @@ async function dependencyRevision({
1832
1833
  applied = await applyPlanRevision({
1833
1834
  repoRoot, env, input: { schema: 'lattice.plan_revise_input.v1', desired },
1834
1835
  notes: [{ task_id: fromTaskId,
1835
- body: `dependency ${operation} ${fromTaskId}→${toTaskId}: ${reason}` }],
1836
+ body: dependencyNoteBody(operation, fromTaskId, toTaskId, reason) }],
1836
1837
  });
1837
1838
  } catch (error) {
1838
1839
  // a18: the new edge closes a cycle; nothing stored is inconsistent, so name the edge and the path.
@@ -1904,7 +1905,7 @@ async function addTask({ repoRoot, env, planKey, flags }) {
1904
1905
  const reason = typeof flags.reason === 'string' ? flags.reason : null;
1905
1906
  const applied = await applyPlanRevision({
1906
1907
  repoRoot, env, input: { schema: 'lattice.plan_revise_input.v1', desired },
1907
- notes: [{ task_id: taskId, body: `todo add ${taskId}${reason === null ? '' : `: ${reason}`}` }],
1908
+ notes: [{ task_id: taskId, body: todoAddNoteBody(taskId, reason) }],
1908
1909
  });
1909
1910
  const result = {
1910
1911
  schema: 'lattice.todo_task_add_result.v1', project_id: store.project_id, plan_key: planKey,
@@ -225,7 +225,9 @@ export function validateTodoNoteContext(value) {
225
225
  const scoped = (scope) => value.notes.some((note) => note.scope === scope);
226
226
  if (value.overflow_count === 0) {
227
227
  if (scoped('task') !== (value.note_head_digest !== null)) return false;
228
- if (scoped('plan') !== (value.plan_note_head_digest !== null)) return false;
228
+ // n3: revision records about other tasks are left out by design, so a plan head may stand
229
+ // with no plan note shown; a shown plan note still needs its head.
230
+ if (scoped('plan') && value.plan_note_head_digest === null) return false;
229
231
  } else if (value.note_head_digest === null && value.plan_note_head_digest === null) {
230
232
  return false;
231
233
  }
@@ -24,6 +24,7 @@ import {
24
24
  validateTodoNoteEvent,
25
25
  } from './todo-contracts.mjs';
26
26
  import { validatePhaseTodoRevision, validateTodoRevision } from './todo-revision.mjs';
27
+ import { revisionRecordTaskIds } from './todo-revision-note.mjs';
27
28
 
28
29
  const NOTE_ROOT_REF = '.lattice/todo/notes';
29
30
  const SEALED_NAME = /^(\d{12})-(\d{12})-([0-9a-f]{64})-([0-9a-f]{64})\.jsonl$/u;
@@ -436,10 +437,16 @@ export function projectTodoNoteContext(options = {}) {
436
437
  // task固有のものより文脈が広いので先に読ませる。
437
438
  const current = [...planCurrent, ...taskCurrent];
438
439
  archived.reverse();
440
+ // n3: Lattice's own revision records about other tasks would fill the cap and push out every
441
+ // human handoff (546 on bellteam-dev-added); they stay in history and note list.
442
+ const offered = current.filter((entry) => entry.scope !== 'plan'
443
+ || (revisionRecordTaskIds(entry.body)?.includes(options.currentTaskId) ?? true));
439
444
 
440
445
  const notes = [];
441
446
  let usedBytes = 0;
442
- for (const entry of current) {
447
+ for (const entry of offered) {
448
+ // 件数もvalidatorと同じ上限で切る。byteに収まる短いnoteが溜まると、自分の出力が自分の検証で落ちる。
449
+ if (notes.length >= TODO_LIMITS.tasksPerPlan) break;
443
450
  const bytes = Buffer.byteLength(entry.body, 'utf8');
444
451
  if (usedBytes + bytes > TODO_LIMITS.noteContextBytes) continue;
445
452
  notes.push(entry);
@@ -456,7 +463,7 @@ export function projectTodoNoteContext(options = {}) {
456
463
  note_head_digest: taskCurrent[0]?.event_digest ?? null,
457
464
  plan_note_head_digest: planCurrent[0]?.event_digest ?? null,
458
465
  // overflowはcontext全体の予算の話でchainの性質ではないので、ここは合成でよい。
459
- overflow_count: current.length - notes.length,
466
+ overflow_count: offered.length - notes.length,
460
467
  // plan noteを載せる以上、案内はplan全体を返す形でなければ「full」ではない。
461
468
  full_history_command: `lattice todo note list --plan ${options.planKey} --json`,
462
469
  context_digest: '',
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Lattice's own revision-record note bodies (Plan owns their meaning). Writers build them here and
3
+ * Store's note projection parses them here, so the two cannot drift. No imports: Store reads this
4
+ * module without importing Plan upward (n3, 2026-11-15).
5
+ */
6
+
7
+ export const todoAddNoteBody = (taskId, reason) => `todo add ${taskId}${reason === null ? '' : `: ${reason}`}`;
8
+
9
+ export const dependencyNoteBody = (operation, fromTaskId, toTaskId, reason) => (
10
+ `dependency ${operation} ${fromTaskId}→${toTaskId}: ${reason}`);
11
+
12
+ export const planReviseNoteBody = (fromVersion, toVersion, taskId, reason) => (
13
+ `plan revise ${fromVersion}→${toVersion} ${taskId}: ${reason}`);
14
+
15
+ const TODO_ADD = /^todo add (\S+?)(?::[ \n][\s\S]*)?$/u;
16
+ // Either side may be written however a route spells it (another chart, plan/task); a task is named
17
+ // only by an exact side, so a reader matches its own id however the other side is written.
18
+ const DEPENDENCY = /^dependency (?:connect|disconnect) (\S+?)→(\S+?): [\s\S]*$/u;
19
+ const PLAN_REVISE = /^plan revise \S+?→\S+ (\S+?): [\s\S]*$/u;
20
+
21
+ /** The task ids a revision-record body names, or null when the body is not a revision record. */
22
+ export function revisionRecordTaskIds(body) {
23
+ const add = TODO_ADD.exec(body);
24
+ if (add !== null) return [add[1]];
25
+ const dependency = DEPENDENCY.exec(body);
26
+ if (dependency !== null) return [dependency[1], dependency[2]];
27
+ const revise = PLAN_REVISE.exec(body);
28
+ return revise === null ? null : [revise[1]];
29
+ }
@@ -291,10 +291,9 @@ function parseJournalSegment(bytes, ref = null) {
291
291
  });
292
292
  }
293
293
 
294
- async function readJournal(repoRoot, journalRef) {
295
- const state = await pathState(repoRoot, journalRef, 'STORE_CORRUPT');
296
- const directory = path.dirname(state.absolute);
297
- const sealedDirectory = path.join(directory, 'sealed');
294
+ /** Sealed segments of one chain, in order, each checked for name, digest, range and link. */
295
+ async function readSealedSegments(repoRoot, journalRef, directoryName) {
296
+ const sealedDirectory = path.resolve(repoRoot, path.dirname(journalRef), directoryName);
298
297
  const segments = [];
299
298
  try {
300
299
  const sealedStats = await lstat(sealedDirectory);
@@ -304,7 +303,7 @@ async function readJournal(repoRoot, journalRef) {
304
303
  if (!/^\d{12}-\d{12}-[0-9a-f]{64}-[0-9a-f]{64}\.jsonl$/u.test(name)) {
305
304
  fail('STORE_CORRUPT', 'sealed_segment_name_invalid', { name });
306
305
  }
307
- const ref = path.posix.join(path.posix.dirname(journalRef), 'sealed', name);
306
+ const ref = path.posix.join(path.posix.dirname(journalRef), directoryName, name);
308
307
  const sealed = await pathState(repoRoot, ref, 'STORE_CORRUPT');
309
308
  const bytes = normalizeCheckoutEol(await readFile(sealed.absolute));
310
309
  const [, startText, endText, previousDigest, segmentDigest] = name.match(
@@ -324,6 +323,12 @@ async function readJournal(repoRoot, journalRef) {
324
323
  if (error instanceof TodoStoreError) throw error;
325
324
  if (error?.code !== 'ENOENT') fail('STORE_CORRUPT', 'sealed_segment_read_failed');
326
325
  }
326
+ return segments;
327
+ }
328
+
329
+ async function readJournal(repoRoot, journalRef) {
330
+ const state = await pathState(repoRoot, journalRef, 'STORE_CORRUPT');
331
+ const segments = await readSealedSegments(repoRoot, journalRef, 'sealed');
327
332
  const activeBytes = normalizeCheckoutEol(await readFile(state.absolute));
328
333
  const duplicateActive = segments.at(-1)?.bytes.equals(activeBytes) === true;
329
334
  if (!duplicateActive) {
@@ -376,6 +381,8 @@ async function readJournal(repoRoot, journalRef) {
376
381
  * (`independence.json`が同じ性質で既に出荷されている・ADR 0127 Decision 1)。したがって
377
382
  * 兄弟fileを置いても旧CLIは存在に気づかず、互換もrollbackも保たれる。
378
383
  */
384
+ const PLAN_SCOPED_SEALED_DIRECTORY = 'plan-scoped-sealed';
385
+
379
386
  function planScopedJournalRef(journalRef) {
380
387
  return path.posix.join(path.posix.dirname(journalRef), 'plan-scoped.jsonl');
381
388
  }
@@ -389,17 +396,22 @@ function planScopedJournalRef(journalRef) {
389
396
  async function readPlanScopedJournal(repoRoot, journalRef) {
390
397
  const ref = planScopedJournalRef(journalRef);
391
398
  const absolute = path.resolve(repoRoot, ref);
392
- let bytes;
399
+ // s1-seal: sealed segments first, then the active file (same rules as the lifecycle journal).
400
+ const segments = await readSealedSegments(repoRoot, journalRef, PLAN_SCOPED_SEALED_DIRECTORY);
401
+ let bytes = null;
393
402
  try {
394
403
  const state = await lstat(absolute);
395
404
  if (state.isSymbolicLink() || !state.isFile()) fail('STORE_CORRUPT', 'plan_scoped_journal_unsafe');
396
405
  bytes = normalizeCheckoutEol(await readFile(absolute));
397
406
  } catch (error) {
398
407
  if (error instanceof TodoStoreError) throw error;
399
- if (error?.code === 'ENOENT') return { ref, events: [], activeBytes: Buffer.alloc(0) };
400
- fail('STORE_CORRUPT', 'plan_scoped_journal_read_failed');
408
+ if (error?.code !== 'ENOENT') fail('STORE_CORRUPT', 'plan_scoped_journal_read_failed');
401
409
  }
402
- const events = parseJournalSegment(bytes, ref);
410
+ if (bytes === null && segments.length === 0) return { ref, events: [], activeBytes: Buffer.alloc(0), sealed: [] };
411
+ // A crash between sealing and the active replacement leaves an active equal to the newest sealed segment.
412
+ const redundant = bytes === null || segments.at(-1)?.bytes.equals(bytes) === true;
413
+ const events = [...segments.flatMap(({ events: entries }) => entries),
414
+ ...(redundant ? [] : parseJournalSegment(bytes, ref))];
403
415
  if (!events.every(({ kind }) => TODO_PLAN_SCOPED_EVENT_KINDS.includes(kind))) {
404
416
  fail('STORE_CORRUPT', 'plan_scoped_journal_kind_invalid');
405
417
  }
@@ -412,7 +424,7 @@ async function readPlanScopedJournal(repoRoot, journalRef) {
412
424
  if (failures.size > 0) {
413
425
  fail('STORE_CORRUPT', [...failures].sort()[0], { failed_conditions: [...failures].sort() });
414
426
  }
415
- return { ref, events, activeBytes: bytes };
427
+ return { ref, events, activeBytes: redundant ? Buffer.alloc(0) : bytes, sealed: [] };
416
428
  }
417
429
 
418
430
  function taskState(taskId) {
@@ -1842,11 +1854,10 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
1842
1854
  const mapped = await carriedSourceTask(repoRoot, source, dependency.from, versionsCache);
1843
1855
  if (mapped === null) continue;
1844
1856
  if (!staged.has(owner)) {
1845
- staged.set(owner, { ...owner, plan_scoped: { ...owner.plan_scoped,
1846
- events: [...owner.plan_scoped.events], activeBytes: owner.plan_scoped.activeBytes } });
1857
+ staged.set(owner, { ...owner, plan_scoped: stagePlanScopedChain(owner.plan_scoped) });
1847
1858
  }
1848
1859
  const target = staged.get(owner);
1849
- const before = { events: target.plan_scoped.events.length, activeBytes: target.plan_scoped.activeBytes };
1860
+ const before = stagePlanScopedChain(target.plan_scoped);
1850
1861
  const inputs = [{ kind: 'cross_plan_dependency_removed', payload: {
1851
1862
  target_event_digest: dependency.event_digest,
1852
1863
  reason: `source ${source.plan.plan_key} ${source.plan.plan_version} ${mapped === 'removed'
@@ -1858,9 +1869,7 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
1858
1869
  } });
1859
1870
  for (const input of inputs) {
1860
1871
  const event = buildPlanScopedEvent(target, { ...input, actor, recorded_at: recordedAt });
1861
- target.plan_scoped.activeBytes = Buffer.concat([target.plan_scoped.activeBytes,
1862
- planScopedEventBytes(target, event)]);
1863
- target.plan_scoped.events.push(event);
1872
+ pushPlanScopedEvent(target.plan_scoped, event);
1864
1873
  }
1865
1874
  const prospective = store.members.map((member) => staged.get(member) ?? member);
1866
1875
  const keys = projectTodoCrossPlanDependencies(prospective)
@@ -1870,8 +1879,7 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
1870
1879
  findings = validateMergedGraph(prospective);
1871
1880
  } catch (error) {
1872
1881
  if (!(error instanceof TodoStoreError)) throw error;
1873
- target.plan_scoped.events.length = before.events;
1874
- target.plan_scoped.activeBytes = before.activeBytes;
1882
+ target.plan_scoped = before;
1875
1883
  continue;
1876
1884
  }
1877
1885
  repairs.push({ owner_plan_key: owner.plan.plan_key, original_event_digest: dependency.event_digest,
@@ -1882,7 +1890,7 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
1882
1890
  await assertHeld();
1883
1891
  for (const [owner, target] of staged) {
1884
1892
  if (target.plan_scoped.events.length === owner.plan_scoped.events.length) continue;
1885
- await atomicWrite(path.resolve(repoRoot, owner.plan_scoped.ref), target.plan_scoped.activeBytes);
1893
+ await writePlanScopedChain(repoRoot, target.plan_scoped);
1886
1894
  owner.plan_scoped = target.plan_scoped;
1887
1895
  owner.coordination = projectTodoCoordination(target.plan_scoped.events) ?? owner.coordination;
1888
1896
  }
@@ -2582,25 +2590,60 @@ function buildPlanScopedEvent(member, input) {
2582
2590
  return event;
2583
2591
  }
2584
2592
 
2585
- function planScopedEventBytes(member, event) {
2593
+ /**
2594
+ * s1-seal: append one event to an in-memory chain, sealing the active bytes first when the event would push them past
2595
+ * a segment. Sealed segments stay pending in `chain.sealed` until `writePlanScopedChain` writes them.
2596
+ */
2597
+ function pushPlanScopedEvent(chain, event) {
2586
2598
  const bytes = canonicalLine(event);
2587
- if (member.plan_scoped.activeBytes.length + bytes.length > TODO_LIMITS.journalSegmentBytes) {
2588
- // 宣言は1 planあたり数件の想定なので封緘機構は持たない。上限へ達したら黙って捨てず、
2589
- // typedに止めて「この設計では足りない」ことを表に出す。
2590
- fail('STORE_WRITE_REFUSED', 'plan_scoped_journal_segment_limit_exceeded', {
2591
- ref: member.plan_scoped.ref, limit: TODO_LIMITS.journalSegmentBytes,
2599
+ if (bytes.length > TODO_LIMITS.journalSegmentBytes) {
2600
+ // No segment can hold it, so no reader could read it back.
2601
+ fail('STORE_WRITE_REFUSED', 'plan_scoped_event_exceeds_segment', {
2602
+ ref: chain.ref, limit: TODO_LIMITS.journalSegmentBytes,
2592
2603
  });
2593
2604
  }
2594
- return bytes;
2605
+ if (chain.activeBytes.length > 0 && chain.activeBytes.length + bytes.length > TODO_LIMITS.journalSegmentBytes) {
2606
+ const count = chain.activeBytes.reduce((lines, byte) => lines + (byte === 0x0a ? 1 : 0), 0);
2607
+ const active = chain.events.slice(-count);
2608
+ const previous = chain.events.at(-count - 1)?.event_digest ?? '0'.repeat(64);
2609
+ const sequence = (value) => String(value).padStart(12, '0');
2610
+ chain.sealed = [...(chain.sealed ?? []), {
2611
+ name: `${sequence(active[0].sequence)}-${sequence(active.at(-1).sequence)}-${previous}-${sha256Bytes(chain.activeBytes)}.jsonl`,
2612
+ bytes: chain.activeBytes,
2613
+ }];
2614
+ chain.activeBytes = bytes;
2615
+ } else {
2616
+ chain.activeBytes = Buffer.concat([chain.activeBytes, bytes]);
2617
+ }
2618
+ chain.events = [...chain.events, event];
2619
+ }
2620
+
2621
+ /** Copy a chain so a staged change never touches the read one. */
2622
+ function stagePlanScopedChain(chain) {
2623
+ return { ...chain, events: [...chain.events], sealed: [...(chain.sealed ?? [])] };
2624
+ }
2625
+
2626
+ /**
2627
+ * Pending sealed segments first, then the active file. The first pending segment holds the bytes already active, so a
2628
+ * crash in between reads identically (redundant active). `fresh`: a not-yet-active version clears earlier attempts.
2629
+ */
2630
+ async function writePlanScopedChain(repoRoot, chain, { fresh = false } = {}) {
2631
+ const directory = path.resolve(repoRoot, path.dirname(chain.ref), PLAN_SCOPED_SEALED_DIRECTORY);
2632
+ if (fresh) await rm(directory, { recursive: true, force: true });
2633
+ for (const { name, bytes } of chain.sealed ?? []) await atomicWrite(path.join(directory, name), bytes);
2634
+ chain.sealed = [];
2635
+ const absolute = path.resolve(repoRoot, chain.ref);
2636
+ if (chain.events.length === 0) await rm(absolute, { force: true });
2637
+ else await atomicWrite(absolute, chain.activeBytes);
2595
2638
  }
2596
2639
 
2597
2640
  async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2598
2641
  const event = buildPlanScopedEvent(member, input);
2599
- const bytes = planScopedEventBytes(member, event);
2642
+ const chain = stagePlanScopedChain(member.plan_scoped);
2643
+ pushPlanScopedEvent(chain, event);
2600
2644
  await assertHeld();
2601
- await atomicWrite(path.resolve(repoRoot, member.plan_scoped.ref),
2602
- Buffer.concat([member.plan_scoped.activeBytes, bytes]));
2603
- const events = [...member.plan_scoped.events, event];
2645
+ await writePlanScopedChain(repoRoot, chain);
2646
+ const { events } = chain;
2604
2647
  return {
2605
2648
  event, plan: member.plan, snapshot: member.snapshot,
2606
2649
  plan_scoped_head_digest: event.event_digest,
@@ -2625,7 +2668,8 @@ function carriedPlanScopedChain(store, previous, plan, journalRef, taskMigration
2625
2668
  return taskId === undefined || taskId === 'removed' ? null
2626
2669
  : { ...ref, task_id: taskId, expected_topology_digest: plan.topology_digest };
2627
2670
  };
2628
- const successor = { plan, plan_scoped: { ref: planScopedJournalRef(journalRef), events: [], activeBytes: Buffer.alloc(0) } };
2671
+ const successor = { plan, plan_scoped: {
2672
+ ref: planScopedJournalRef(journalRef), events: [], activeBytes: Buffer.alloc(0), sealed: [] } };
2629
2673
  const seen = new Set();
2630
2674
  for (const event of previous.plan_scoped?.events ?? []) {
2631
2675
  if (event.kind !== 'cross_plan_dependency' || !live.has(event.event_digest)) continue;
@@ -2637,18 +2681,14 @@ function carriedPlanScopedChain(store, previous, plan, journalRef, taskMigration
2637
2681
  const carried = buildPlanScopedEvent(successor, { kind: event.kind, actor: event.actor,
2638
2682
  recorded_at: event.recorded_at, provenance: event.provenance,
2639
2683
  payload: { from, to, reason: event.payload.reason } });
2640
- successor.plan_scoped.activeBytes = Buffer.concat([successor.plan_scoped.activeBytes,
2641
- planScopedEventBytes(successor, carried)]);
2642
- successor.plan_scoped.events.push(carried);
2684
+ pushPlanScopedEvent(successor.plan_scoped, carried);
2643
2685
  }
2644
2686
  return successor.plan_scoped;
2645
2687
  }
2646
2688
 
2647
2689
  /** Written before the manifest switch; the version is not active yet, so a retry rewrites it from the current predecessor. */
2648
2690
  async function writeCarriedPlanScopedChain(repoRoot, chain) {
2649
- const absolute = path.resolve(repoRoot, chain.ref);
2650
- if (chain.events.length === 0) await rm(absolute, { force: true });
2651
- else await atomicWrite(absolute, chain.activeBytes);
2691
+ await writePlanScopedChain(repoRoot, { ...chain, sealed: [...(chain.sealed ?? [])] }, { fresh: true });
2652
2692
  }
2653
2693
 
2654
2694
  /** Rebind existing connections to a carried source without changing their endpoints. */
@@ -2705,8 +2745,7 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2705
2745
  fail(validation.code, reason, detail);
2706
2746
  }
2707
2747
  if (validation?.ok !== true) throw new TypeError('binding carry validator must return an ok result');
2708
- const staged = { ...owner, plan_scoped: { ...owner.plan_scoped,
2709
- events: [...owner.plan_scoped.events] } };
2748
+ const staged = { ...owner, plan_scoped: stagePlanScopedChain(owner.plan_scoped) };
2710
2749
  const replacements = [];
2711
2750
  for (const dependency of dependencies) {
2712
2751
  for (const input of [
@@ -2720,9 +2759,7 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2720
2759
  ]) {
2721
2760
  const event = buildPlanScopedEvent(staged, { ...input, actor: options.actor,
2722
2761
  recorded_at: options.recordedAt ?? new Date().toISOString() });
2723
- const bytes = planScopedEventBytes(staged, event);
2724
- staged.plan_scoped.events.push(event);
2725
- staged.plan_scoped.activeBytes = Buffer.concat([staged.plan_scoped.activeBytes, bytes]);
2762
+ pushPlanScopedEvent(staged.plan_scoped, event);
2726
2763
  }
2727
2764
  replacements.push({ original_event_digest: dependency.event_digest,
2728
2765
  replacement_event_digest: staged.plan_scoped.events.at(-1).event_digest });
@@ -2735,7 +2772,7 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2735
2772
  }
2736
2773
  validateMergedGraph(prospective, projected);
2737
2774
  await protocolStage(options, 'dependency_rebind_validated');
2738
- await atomicWrite(path.resolve(repoRoot, owner.plan_scoped.ref), staged.plan_scoped.activeBytes);
2775
+ await writePlanScopedChain(repoRoot, staged.plan_scoped);
2739
2776
  await protocolStage(options, 'dependency_rebind_published');
2740
2777
  return { schema: 'lattice.todo_dependency_rebind_result.v1', project_id: store.project_id,
2741
2778
  plan_key: owner.plan.plan_key, source_plan_key: source.plan.plan_key,
@@ -3007,6 +3044,7 @@ function cloneImportedDependencyMember(member) {
3007
3044
  ...(member.plan_scoped ?? {}),
3008
3045
  events: [...(member.plan_scoped?.events ?? [])],
3009
3046
  activeBytes: Buffer.from(member.plan_scoped?.activeBytes ?? Buffer.alloc(0)),
3047
+ sealed: [...(member.plan_scoped?.sealed ?? [])],
3010
3048
  },
3011
3049
  };
3012
3050
  }
@@ -3026,7 +3064,7 @@ function prepareCrossPlanDependencies({ store, dependencies, genesis, imported =
3026
3064
  members.push({
3027
3065
  plan: imported.plan, tasks: imported.tasks,
3028
3066
  plan_scoped: {
3029
- ref: planScopedJournalRef(imported.journalRef), events: [], activeBytes: Buffer.alloc(0),
3067
+ ref: planScopedJournalRef(imported.journalRef), events: [], activeBytes: Buffer.alloc(0), sealed: [],
3030
3068
  },
3031
3069
  });
3032
3070
  }
@@ -3049,22 +3087,21 @@ function prepareCrossPlanDependencies({ store, dependencies, genesis, imported =
3049
3087
  const validationStore = { ...store, members };
3050
3088
  validateCrossPlanDependencyTransition(validationStore, target, input);
3051
3089
  const event = buildPlanScopedEvent(target, input);
3052
- const bytes = planScopedEventBytes(target, event);
3053
3090
  const key = target.plan_scoped.ref;
3054
3091
  const artifact = artifacts.get(key) ?? {
3055
- ref: key,
3092
+ ref: key, chain: target.plan_scoped,
3056
3093
  originalBytes: Buffer.from(target.plan_scoped.activeBytes),
3057
- finalBytes: Buffer.from(target.plan_scoped.activeBytes),
3058
3094
  events: [],
3059
3095
  };
3060
- artifact.finalBytes = Buffer.concat([artifact.finalBytes, bytes]);
3096
+ pushPlanScopedEvent(target.plan_scoped, event);
3061
3097
  artifact.events.push(event);
3062
3098
  artifacts.set(key, artifact);
3063
- target.plan_scoped.events.push(event);
3064
- target.plan_scoped.activeBytes = Buffer.concat([target.plan_scoped.activeBytes, bytes]);
3065
3099
  events.push(event);
3066
3100
  }
3067
- return { events, artifacts: [...artifacts.values()] };
3101
+ // finalBytes is the new active; `sealed` the segments to write before it (s1-seal).
3102
+ return { events, artifacts: [...artifacts.values()].map(({ chain, ...artifact }) => ({
3103
+ ...artifact, finalBytes: chain.activeBytes, sealed: chain.sealed ?? [],
3104
+ })) };
3068
3105
  }
3069
3106
 
3070
3107
  function prepareImportedCrossPlanDependencies({ store, plan, tasks, dependencies, genesis, journalRef }) {
@@ -3289,7 +3326,8 @@ async function appendExistingCrossPlanDependency(options) {
3289
3326
  }
3290
3327
  const artifact = prepared.artifacts[0];
3291
3328
  await protocolStage(options, 'cross_plan_connection_validated');
3292
- await atomicWrite(path.resolve(repoRoot, artifact.ref), artifact.finalBytes);
3329
+ await writePlanScopedChain(repoRoot, { ref: artifact.ref, events: artifact.events,
3330
+ activeBytes: artifact.finalBytes, sealed: artifact.sealed });
3293
3331
  await protocolStage(options, 'cross_plan_connection_activated');
3294
3332
  return {
3295
3333
  plan: source.plan, genesis: source.journal.events[0], events: source.journal.events,
@@ -3415,6 +3453,12 @@ async function appendPlanMembership(repoRoot, options, authored) {
3415
3453
  store, plan, tasks, dependencies: options.crossPlanDependencies, genesis, journalRef,
3416
3454
  });
3417
3455
  const hasCrossPlanDependencies = importedCrossPlan.artifacts.length > 0;
3456
+ // The staged import recovery holds one active file per target and no segments; connect after the import instead.
3457
+ const full = importedCrossPlan.artifacts.find(({ sealed }) => sealed.length > 0);
3458
+ if (full !== undefined) {
3459
+ fail('STORE_WRITE_REFUSED', 'cross_plan_import_segment_full', { ref: full.ref,
3460
+ next_action: 'import without this cross-plan edge, then connect it with `lattice todo dependency connect`' });
3461
+ }
3418
3462
  const transactionRef = hasCrossPlanDependencies
3419
3463
  ? `${CROSS_PLAN_IMPORT_TRANSACTIONS_REF}/${transactionDigest}`
3420
3464
  : `${STORE_ROOT_REF}/transactions/${plan.plan_key}-${plan.plan_version}`;