@quolu/lattice 0.102.1 → 0.104.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.
@@ -3,6 +3,7 @@ import {
3
3
  isPhaseTodoPlanSchema,
4
4
  isPhaselessTodoPlanSchema,
5
5
  projectTodoCrossPlanDependencies,
6
+ projectTodoScheduleConnections,
6
7
  normalizeCheckoutEol,
7
8
  isFinishedTodoTaskState,
8
9
  stepTodoReopenedPending,
@@ -291,10 +292,9 @@ function parseJournalSegment(bytes, ref = null) {
291
292
  });
292
293
  }
293
294
 
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');
295
+ /** Sealed segments of one chain, in order, each checked for name, digest, range and link. */
296
+ async function readSealedSegments(repoRoot, journalRef, directoryName) {
297
+ const sealedDirectory = path.resolve(repoRoot, path.dirname(journalRef), directoryName);
298
298
  const segments = [];
299
299
  try {
300
300
  const sealedStats = await lstat(sealedDirectory);
@@ -304,7 +304,7 @@ async function readJournal(repoRoot, journalRef) {
304
304
  if (!/^\d{12}-\d{12}-[0-9a-f]{64}-[0-9a-f]{64}\.jsonl$/u.test(name)) {
305
305
  fail('STORE_CORRUPT', 'sealed_segment_name_invalid', { name });
306
306
  }
307
- const ref = path.posix.join(path.posix.dirname(journalRef), 'sealed', name);
307
+ const ref = path.posix.join(path.posix.dirname(journalRef), directoryName, name);
308
308
  const sealed = await pathState(repoRoot, ref, 'STORE_CORRUPT');
309
309
  const bytes = normalizeCheckoutEol(await readFile(sealed.absolute));
310
310
  const [, startText, endText, previousDigest, segmentDigest] = name.match(
@@ -324,6 +324,12 @@ async function readJournal(repoRoot, journalRef) {
324
324
  if (error instanceof TodoStoreError) throw error;
325
325
  if (error?.code !== 'ENOENT') fail('STORE_CORRUPT', 'sealed_segment_read_failed');
326
326
  }
327
+ return segments;
328
+ }
329
+
330
+ async function readJournal(repoRoot, journalRef) {
331
+ const state = await pathState(repoRoot, journalRef, 'STORE_CORRUPT');
332
+ const segments = await readSealedSegments(repoRoot, journalRef, 'sealed');
327
333
  const activeBytes = normalizeCheckoutEol(await readFile(state.absolute));
328
334
  const duplicateActive = segments.at(-1)?.bytes.equals(activeBytes) === true;
329
335
  if (!duplicateActive) {
@@ -376,6 +382,8 @@ async function readJournal(repoRoot, journalRef) {
376
382
  * (`independence.json`が同じ性質で既に出荷されている・ADR 0127 Decision 1)。したがって
377
383
  * 兄弟fileを置いても旧CLIは存在に気づかず、互換もrollbackも保たれる。
378
384
  */
385
+ const PLAN_SCOPED_SEALED_DIRECTORY = 'plan-scoped-sealed';
386
+
379
387
  function planScopedJournalRef(journalRef) {
380
388
  return path.posix.join(path.posix.dirname(journalRef), 'plan-scoped.jsonl');
381
389
  }
@@ -389,17 +397,22 @@ function planScopedJournalRef(journalRef) {
389
397
  async function readPlanScopedJournal(repoRoot, journalRef) {
390
398
  const ref = planScopedJournalRef(journalRef);
391
399
  const absolute = path.resolve(repoRoot, ref);
392
- let bytes;
400
+ // s1-seal: sealed segments first, then the active file (same rules as the lifecycle journal).
401
+ const segments = await readSealedSegments(repoRoot, journalRef, PLAN_SCOPED_SEALED_DIRECTORY);
402
+ let bytes = null;
393
403
  try {
394
404
  const state = await lstat(absolute);
395
405
  if (state.isSymbolicLink() || !state.isFile()) fail('STORE_CORRUPT', 'plan_scoped_journal_unsafe');
396
406
  bytes = normalizeCheckoutEol(await readFile(absolute));
397
407
  } catch (error) {
398
408
  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');
409
+ if (error?.code !== 'ENOENT') fail('STORE_CORRUPT', 'plan_scoped_journal_read_failed');
401
410
  }
402
- const events = parseJournalSegment(bytes, ref);
411
+ if (bytes === null && segments.length === 0) return { ref, events: [], activeBytes: Buffer.alloc(0), sealed: [] };
412
+ // A crash between sealing and the active replacement leaves an active equal to the newest sealed segment.
413
+ const redundant = bytes === null || segments.at(-1)?.bytes.equals(bytes) === true;
414
+ const events = [...segments.flatMap(({ events: entries }) => entries),
415
+ ...(redundant ? [] : parseJournalSegment(bytes, ref))];
403
416
  if (!events.every(({ kind }) => TODO_PLAN_SCOPED_EVENT_KINDS.includes(kind))) {
404
417
  fail('STORE_CORRUPT', 'plan_scoped_journal_kind_invalid');
405
418
  }
@@ -412,7 +425,7 @@ async function readPlanScopedJournal(repoRoot, journalRef) {
412
425
  if (failures.size > 0) {
413
426
  fail('STORE_CORRUPT', [...failures].sort()[0], { failed_conditions: [...failures].sort() });
414
427
  }
415
- return { ref, events, activeBytes: bytes };
428
+ return { ref, events, activeBytes: redundant ? Buffer.alloc(0) : bytes, sealed: [] };
416
429
  }
417
430
 
418
431
  function taskState(taskId) {
@@ -1083,7 +1096,7 @@ function crossPlanDependencyTask(store, ref) {
1083
1096
  }
1084
1097
 
1085
1098
  /**
1086
- * xchart S3: only `todo dependency connect` (appendTodoEvent, `foreignFrom`) may record a predecessor on another
1099
+ * xchart S3: only `todo connect condition add` (`dependency connect --from-project`, retired alias) (appendTodoEvent, `foreignFrom`) may record a predecessor on another
1087
1100
  * chart; Plan checked it there just before. Genesis, import and connectionOnly keep refusing a foreign from.
1088
1101
  */
1089
1102
  function validateCrossPlanDependencyTransition(store, owner, input, { foreignFrom = false } = {}) {
@@ -1425,7 +1438,7 @@ function materializeImportedNarrativeAnchors(repoRoot, planInput, sources, cache
1425
1438
  if (sources === undefined) return planInput;
1426
1439
  if (!['lattice.todo_plan.v2', 'lattice.todo_plan.v6'].includes(planInput?.schema)
1427
1440
  || !Array.isArray(sources)
1428
- || sources.length > TODO_LIMITS.tasksPerPlan || !sources.every(narrativeAnchorSource)) {
1441
+ || !sources.every(narrativeAnchorSource)) {
1429
1442
  throw new TypeError('imported narrative anchor sources are invalid');
1430
1443
  }
1431
1444
  const byTask = new Map(sources.map((source) => [source.task_id, source]));
@@ -1842,11 +1855,10 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
1842
1855
  const mapped = await carriedSourceTask(repoRoot, source, dependency.from, versionsCache);
1843
1856
  if (mapped === null) continue;
1844
1857
  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 } });
1858
+ staged.set(owner, { ...owner, plan_scoped: stagePlanScopedChain(owner.plan_scoped) });
1847
1859
  }
1848
1860
  const target = staged.get(owner);
1849
- const before = { events: target.plan_scoped.events.length, activeBytes: target.plan_scoped.activeBytes };
1861
+ const before = stagePlanScopedChain(target.plan_scoped);
1850
1862
  const inputs = [{ kind: 'cross_plan_dependency_removed', payload: {
1851
1863
  target_event_digest: dependency.event_digest,
1852
1864
  reason: `source ${source.plan.plan_key} ${source.plan.plan_version} ${mapped === 'removed'
@@ -1858,9 +1870,7 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
1858
1870
  } });
1859
1871
  for (const input of inputs) {
1860
1872
  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);
1873
+ pushPlanScopedEvent(target.plan_scoped, event);
1864
1874
  }
1865
1875
  const prospective = store.members.map((member) => staged.get(member) ?? member);
1866
1876
  const keys = projectTodoCrossPlanDependencies(prospective)
@@ -1870,8 +1880,7 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
1870
1880
  findings = validateMergedGraph(prospective);
1871
1881
  } catch (error) {
1872
1882
  if (!(error instanceof TodoStoreError)) throw error;
1873
- target.plan_scoped.events.length = before.events;
1874
- target.plan_scoped.activeBytes = before.activeBytes;
1883
+ target.plan_scoped = before;
1875
1884
  continue;
1876
1885
  }
1877
1886
  repairs.push({ owner_plan_key: owner.plan.plan_key, original_event_digest: dependency.event_digest,
@@ -1882,7 +1891,7 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
1882
1891
  await assertHeld();
1883
1892
  for (const [owner, target] of staged) {
1884
1893
  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);
1894
+ await writePlanScopedChain(repoRoot, target.plan_scoped);
1886
1895
  owner.plan_scoped = target.plan_scoped;
1887
1896
  owner.coordination = projectTodoCoordination(target.plan_scoped.events) ?? owner.coordination;
1888
1897
  }
@@ -2440,6 +2449,30 @@ function resolveCanonicalTaskId(plan, requestedTaskId) {
2440
2449
  return matches[0].task_id;
2441
2450
  }
2442
2451
 
2452
+ /**
2453
+ * 接続: every write is idempotent so a retry after an unknown outcome replays to the same state. Returns
2454
+ * `{unchanged: true, target_event_digest}` (nothing is appended) for: an add whose task + schedule is already open,
2455
+ * a resolve of an entry already settled (the first evidence wins), a remove when the entry is not open. Anything
2456
+ * else that cannot apply is refused.
2457
+ */
2458
+ function validateConnectionTransition(member, event) {
2459
+ if (!['connection_added', 'connection_removed', 'connection_resolved'].includes(event.kind)) return null;
2460
+ const entries = projectTodoScheduleConnections(member.plan_scoped?.events ?? []);
2461
+ if (event.kind === 'connection_added') {
2462
+ const { task_id: taskId, to } = event.payload;
2463
+ const open = entries.find((entry) => entry.state === 'open' && entry.task_id === taskId && entry.ref === to.id);
2464
+ return open === undefined ? null : { unchanged: true, target_event_digest: open.event_digest };
2465
+ }
2466
+ const digest = event.payload.target_event_digest;
2467
+ const entry = entries.find((candidate) => candidate.event_digest === digest);
2468
+ if (entry === undefined) fail('DEPENDENCY_NOT_FOUND', 'connection_not_found', { target_event_digest: digest });
2469
+ if (event.kind === 'connection_removed') {
2470
+ return entry.state === 'open' ? null : { unchanged: true, target_event_digest: digest };
2471
+ }
2472
+ if (entry.ended === 'removed') fail('DEPENDENCY_INVALID', 'connection_already_removed', { target_event_digest: digest });
2473
+ return entry.state === 'settled' ? { unchanged: true, target_event_digest: digest } : null;
2474
+ }
2475
+
2443
2476
  export async function appendTodoEvent(options = {}) {
2444
2477
  requireWriter(options.writer, 'g5-authoring');
2445
2478
  if (typeof options.validateProspectiveEvent !== 'function') {
@@ -2474,9 +2507,15 @@ export async function appendTodoEvent(options = {}) {
2474
2507
  fail('DEPENDENCY_INVALID', 'cross_plan_dependency_already_removed', { target_event_digest: digest });
2475
2508
  }
2476
2509
  }
2510
+ const event = options.event.kind === 'connection_added'
2511
+ ? { ...options.event, payload: { ...options.event.payload,
2512
+ task_id: resolveCanonicalTaskId(member.plan, options.event.payload.task_id) } }
2513
+ : options.event;
2514
+ const unchanged = validateConnectionTransition(member, event);
2515
+ if (unchanged !== null) return { cross_plan_repairs: store.cross_plan_repairs, ...unchanged };
2477
2516
  return { cross_plan_repairs: store.cross_plan_repairs, ...await appendPlanScopedEvent({
2478
2517
  repoRoot, member, assertHeld,
2479
- input: { ...options.event, recorded_at: options.event.recorded_at ?? new Date().toISOString() },
2518
+ input: { ...event, recorded_at: event.recorded_at ?? new Date().toISOString() },
2480
2519
  }) };
2481
2520
  }
2482
2521
  const input = resolveTargetedEvent({
@@ -2582,25 +2621,60 @@ function buildPlanScopedEvent(member, input) {
2582
2621
  return event;
2583
2622
  }
2584
2623
 
2585
- function planScopedEventBytes(member, event) {
2624
+ /**
2625
+ * s1-seal: append one event to an in-memory chain, sealing the active bytes first when the event would push them past
2626
+ * a segment. Sealed segments stay pending in `chain.sealed` until `writePlanScopedChain` writes them.
2627
+ */
2628
+ function pushPlanScopedEvent(chain, event) {
2586
2629
  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,
2630
+ if (bytes.length > TODO_LIMITS.journalSegmentBytes) {
2631
+ // No segment can hold it, so no reader could read it back.
2632
+ fail('STORE_WRITE_REFUSED', 'plan_scoped_event_exceeds_segment', {
2633
+ ref: chain.ref, limit: TODO_LIMITS.journalSegmentBytes,
2592
2634
  });
2593
2635
  }
2594
- return bytes;
2636
+ if (chain.activeBytes.length > 0 && chain.activeBytes.length + bytes.length > TODO_LIMITS.journalSegmentBytes) {
2637
+ const count = chain.activeBytes.reduce((lines, byte) => lines + (byte === 0x0a ? 1 : 0), 0);
2638
+ const active = chain.events.slice(-count);
2639
+ const previous = chain.events.at(-count - 1)?.event_digest ?? '0'.repeat(64);
2640
+ const sequence = (value) => String(value).padStart(12, '0');
2641
+ chain.sealed = [...(chain.sealed ?? []), {
2642
+ name: `${sequence(active[0].sequence)}-${sequence(active.at(-1).sequence)}-${previous}-${sha256Bytes(chain.activeBytes)}.jsonl`,
2643
+ bytes: chain.activeBytes,
2644
+ }];
2645
+ chain.activeBytes = bytes;
2646
+ } else {
2647
+ chain.activeBytes = Buffer.concat([chain.activeBytes, bytes]);
2648
+ }
2649
+ chain.events = [...chain.events, event];
2650
+ }
2651
+
2652
+ /** Copy a chain so a staged change never touches the read one. */
2653
+ function stagePlanScopedChain(chain) {
2654
+ return { ...chain, events: [...chain.events], sealed: [...(chain.sealed ?? [])] };
2655
+ }
2656
+
2657
+ /**
2658
+ * Pending sealed segments first, then the active file. The first pending segment holds the bytes already active, so a
2659
+ * crash in between reads identically (redundant active). `fresh`: a not-yet-active version clears earlier attempts.
2660
+ */
2661
+ async function writePlanScopedChain(repoRoot, chain, { fresh = false } = {}) {
2662
+ const directory = path.resolve(repoRoot, path.dirname(chain.ref), PLAN_SCOPED_SEALED_DIRECTORY);
2663
+ if (fresh) await rm(directory, { recursive: true, force: true });
2664
+ for (const { name, bytes } of chain.sealed ?? []) await atomicWrite(path.join(directory, name), bytes);
2665
+ chain.sealed = [];
2666
+ const absolute = path.resolve(repoRoot, chain.ref);
2667
+ if (chain.events.length === 0) await rm(absolute, { force: true });
2668
+ else await atomicWrite(absolute, chain.activeBytes);
2595
2669
  }
2596
2670
 
2597
2671
  async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2598
2672
  const event = buildPlanScopedEvent(member, input);
2599
- const bytes = planScopedEventBytes(member, event);
2673
+ const chain = stagePlanScopedChain(member.plan_scoped);
2674
+ pushPlanScopedEvent(chain, event);
2600
2675
  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];
2676
+ await writePlanScopedChain(repoRoot, chain);
2677
+ const { events } = chain;
2604
2678
  return {
2605
2679
  event, plan: member.plan, snapshot: member.snapshot,
2606
2680
  plan_scoped_head_digest: event.event_digest,
@@ -2625,7 +2699,8 @@ function carriedPlanScopedChain(store, previous, plan, journalRef, taskMigration
2625
2699
  return taskId === undefined || taskId === 'removed' ? null
2626
2700
  : { ...ref, task_id: taskId, expected_topology_digest: plan.topology_digest };
2627
2701
  };
2628
- const successor = { plan, plan_scoped: { ref: planScopedJournalRef(journalRef), events: [], activeBytes: Buffer.alloc(0) } };
2702
+ const successor = { plan, plan_scoped: {
2703
+ ref: planScopedJournalRef(journalRef), events: [], activeBytes: Buffer.alloc(0), sealed: [] } };
2629
2704
  const seen = new Set();
2630
2705
  for (const event of previous.plan_scoped?.events ?? []) {
2631
2706
  if (event.kind !== 'cross_plan_dependency' || !live.has(event.event_digest)) continue;
@@ -2637,18 +2712,22 @@ function carriedPlanScopedChain(store, previous, plan, journalRef, taskMigration
2637
2712
  const carried = buildPlanScopedEvent(successor, { kind: event.kind, actor: event.actor,
2638
2713
  recorded_at: event.recorded_at, provenance: event.provenance,
2639
2714
  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);
2715
+ pushPlanScopedEvent(successor.plan_scoped, carried);
2716
+ }
2717
+ // 接続: only the schedule connections still open travel; a settled or removed one equals no connection.
2718
+ for (const entry of projectTodoScheduleConnections(previous.plan_scoped?.events ?? [])) {
2719
+ const taskId = ids.get(entry.task_id);
2720
+ if (entry.state !== 'open' || taskId === undefined || taskId === 'removed') continue;
2721
+ pushPlanScopedEvent(successor.plan_scoped, buildPlanScopedEvent(successor, { kind: 'connection_added',
2722
+ actor: entry.actor, recorded_at: entry.since, provenance: entry.provenance,
2723
+ payload: { task_id: taskId, to: { kind: 'schedule', id: entry.ref }, reason: entry.reason } }));
2643
2724
  }
2644
2725
  return successor.plan_scoped;
2645
2726
  }
2646
2727
 
2647
2728
  /** Written before the manifest switch; the version is not active yet, so a retry rewrites it from the current predecessor. */
2648
2729
  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);
2730
+ await writePlanScopedChain(repoRoot, { ...chain, sealed: [...(chain.sealed ?? [])] }, { fresh: true });
2652
2731
  }
2653
2732
 
2654
2733
  /** Rebind existing connections to a carried source without changing their endpoints. */
@@ -2705,8 +2784,7 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2705
2784
  fail(validation.code, reason, detail);
2706
2785
  }
2707
2786
  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] } };
2787
+ const staged = { ...owner, plan_scoped: stagePlanScopedChain(owner.plan_scoped) };
2710
2788
  const replacements = [];
2711
2789
  for (const dependency of dependencies) {
2712
2790
  for (const input of [
@@ -2720,9 +2798,7 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2720
2798
  ]) {
2721
2799
  const event = buildPlanScopedEvent(staged, { ...input, actor: options.actor,
2722
2800
  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]);
2801
+ pushPlanScopedEvent(staged.plan_scoped, event);
2726
2802
  }
2727
2803
  replacements.push({ original_event_digest: dependency.event_digest,
2728
2804
  replacement_event_digest: staged.plan_scoped.events.at(-1).event_digest });
@@ -2735,7 +2811,7 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2735
2811
  }
2736
2812
  validateMergedGraph(prospective, projected);
2737
2813
  await protocolStage(options, 'dependency_rebind_validated');
2738
- await atomicWrite(path.resolve(repoRoot, owner.plan_scoped.ref), staged.plan_scoped.activeBytes);
2814
+ await writePlanScopedChain(repoRoot, staged.plan_scoped);
2739
2815
  await protocolStage(options, 'dependency_rebind_published');
2740
2816
  return { schema: 'lattice.todo_dependency_rebind_result.v1', project_id: store.project_id,
2741
2817
  plan_key: owner.plan.plan_key, source_plan_key: source.plan.plan_key,
@@ -2873,7 +2949,7 @@ function buildHistoricalStart(plan, previous, input, genesis) {
2873
2949
  function historicalImportInputs(value, timestampKey) {
2874
2950
  const required = ['task_id', timestampKey, 'evidence'];
2875
2951
  const allowed = new Set([...required, 'actor', 'recorded_at', 'provenance']);
2876
- return Array.isArray(value) && value.length <= TODO_LIMITS.tasksPerPlan
2952
+ return Array.isArray(value)
2877
2953
  && value.every((entry) => entry !== null && typeof entry === 'object' && !Array.isArray(entry)
2878
2954
  && Object.getPrototypeOf(entry) === Object.prototype
2879
2955
  && required.every((key) => Object.hasOwn(entry, key))
@@ -3007,6 +3083,7 @@ function cloneImportedDependencyMember(member) {
3007
3083
  ...(member.plan_scoped ?? {}),
3008
3084
  events: [...(member.plan_scoped?.events ?? [])],
3009
3085
  activeBytes: Buffer.from(member.plan_scoped?.activeBytes ?? Buffer.alloc(0)),
3086
+ sealed: [...(member.plan_scoped?.sealed ?? [])],
3010
3087
  },
3011
3088
  };
3012
3089
  }
@@ -3026,7 +3103,7 @@ function prepareCrossPlanDependencies({ store, dependencies, genesis, imported =
3026
3103
  members.push({
3027
3104
  plan: imported.plan, tasks: imported.tasks,
3028
3105
  plan_scoped: {
3029
- ref: planScopedJournalRef(imported.journalRef), events: [], activeBytes: Buffer.alloc(0),
3106
+ ref: planScopedJournalRef(imported.journalRef), events: [], activeBytes: Buffer.alloc(0), sealed: [],
3030
3107
  },
3031
3108
  });
3032
3109
  }
@@ -3049,22 +3126,21 @@ function prepareCrossPlanDependencies({ store, dependencies, genesis, imported =
3049
3126
  const validationStore = { ...store, members };
3050
3127
  validateCrossPlanDependencyTransition(validationStore, target, input);
3051
3128
  const event = buildPlanScopedEvent(target, input);
3052
- const bytes = planScopedEventBytes(target, event);
3053
3129
  const key = target.plan_scoped.ref;
3054
3130
  const artifact = artifacts.get(key) ?? {
3055
- ref: key,
3131
+ ref: key, chain: target.plan_scoped,
3056
3132
  originalBytes: Buffer.from(target.plan_scoped.activeBytes),
3057
- finalBytes: Buffer.from(target.plan_scoped.activeBytes),
3058
3133
  events: [],
3059
3134
  };
3060
- artifact.finalBytes = Buffer.concat([artifact.finalBytes, bytes]);
3135
+ pushPlanScopedEvent(target.plan_scoped, event);
3061
3136
  artifact.events.push(event);
3062
3137
  artifacts.set(key, artifact);
3063
- target.plan_scoped.events.push(event);
3064
- target.plan_scoped.activeBytes = Buffer.concat([target.plan_scoped.activeBytes, bytes]);
3065
3138
  events.push(event);
3066
3139
  }
3067
- return { events, artifacts: [...artifacts.values()] };
3140
+ // finalBytes is the new active; `sealed` the segments to write before it (s1-seal).
3141
+ return { events, artifacts: [...artifacts.values()].map(({ chain, ...artifact }) => ({
3142
+ ...artifact, finalBytes: chain.activeBytes, sealed: chain.sealed ?? [],
3143
+ })) };
3068
3144
  }
3069
3145
 
3070
3146
  function prepareImportedCrossPlanDependencies({ store, plan, tasks, dependencies, genesis, journalRef }) {
@@ -3289,7 +3365,8 @@ async function appendExistingCrossPlanDependency(options) {
3289
3365
  }
3290
3366
  const artifact = prepared.artifacts[0];
3291
3367
  await protocolStage(options, 'cross_plan_connection_validated');
3292
- await atomicWrite(path.resolve(repoRoot, artifact.ref), artifact.finalBytes);
3368
+ await writePlanScopedChain(repoRoot, { ref: artifact.ref, events: artifact.events,
3369
+ activeBytes: artifact.finalBytes, sealed: artifact.sealed });
3293
3370
  await protocolStage(options, 'cross_plan_connection_activated');
3294
3371
  return {
3295
3372
  plan: source.plan, genesis: source.journal.events[0], events: source.journal.events,
@@ -3415,6 +3492,12 @@ async function appendPlanMembership(repoRoot, options, authored) {
3415
3492
  store, plan, tasks, dependencies: options.crossPlanDependencies, genesis, journalRef,
3416
3493
  });
3417
3494
  const hasCrossPlanDependencies = importedCrossPlan.artifacts.length > 0;
3495
+ // The staged import recovery holds one active file per target and no segments; connect after the import instead.
3496
+ const full = importedCrossPlan.artifacts.find(({ sealed }) => sealed.length > 0);
3497
+ if (full !== undefined) {
3498
+ fail('STORE_WRITE_REFUSED', 'cross_plan_import_segment_full', { ref: full.ref,
3499
+ next_action: 'import without this cross-plan edge, then add it with `lattice todo predecessor add`' });
3500
+ }
3418
3501
  const transactionRef = hasCrossPlanDependencies
3419
3502
  ? `${CROSS_PLAN_IMPORT_TRANSACTIONS_REF}/${transactionDigest}`
3420
3503
  : `${STORE_ROOT_REF}/transactions/${plan.plan_key}-${plan.plan_version}`;