@quolu/lattice 0.103.0 → 0.105.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.
@@ -139,7 +139,7 @@ function validSourceCutoverBatch(value, revision) {
139
139
  if (!exactRecord(value, ['batch_id', 'archive_ref', 'operations', 'batch_digest'])
140
140
  || !isTodoIdentifier(value.batch_id) || !isTodoRef(value.archive_ref)
141
141
  || !value.archive_ref.endsWith('.md') || parseTodoSourceRef(value.archive_ref) !== null
142
- || !Array.isArray(value.operations) || value.operations.length < 1 || value.operations.length > 512
142
+ || !Array.isArray(value.operations) || value.operations.length < 1
143
143
  || !isTodoDigest(value.batch_digest)
144
144
  || value.batch_digest !== todoSelfDigest(value, 'batch_digest')) return false;
145
145
  const sourceRefs = new Set();
@@ -183,7 +183,7 @@ function validTaskMigration(value) {
183
183
  const activeTargets = Array.isArray(value)
184
184
  ? value.filter(({ to_task_id }) => to_task_id !== 'removed').map(({ to_task_id }) => to_task_id)
185
185
  : [];
186
- return Array.isArray(value) && value.length > 0 && value.length <= 512
186
+ return Array.isArray(value) && value.length > 0
187
187
  && value.every((entry) => exactRecord(entry, [
188
188
  'from_task_id', 'to_task_id', 'state_policy',
189
189
  ]) && isTodoIdentifier(entry.from_task_id)
@@ -198,7 +198,7 @@ function validTaskMigration(value) {
198
198
  }
199
199
 
200
200
  function validPhaseMigration(value, desiredPlan) {
201
- if (!Array.isArray(value) || value.length === 0 || value.length > 512
201
+ if (!Array.isArray(value) || value.length === 0
202
202
  || !value.every((entry) => exactRecord(entry, [
203
203
  'from_phase_id', 'to_phase_id', 'state_policy',
204
204
  ]) && (entry.from_phase_id === null || isTodoIdentifier(entry.from_phase_id))
@@ -227,7 +227,7 @@ export function todoTaskMigrationDigest(taskMigration) {
227
227
  function validRuntimeTaskMigration(value) {
228
228
  if (!exactRecord(value, ['schema', 'entries', 'migration_digest'])
229
229
  || value.schema !== 'lattice.runtime_task_migration.v1'
230
- || !Array.isArray(value.entries) || value.entries.length < 1 || value.entries.length > 512
230
+ || !Array.isArray(value.entries) || value.entries.length < 1
231
231
  || !isTodoDigest(value.migration_digest)
232
232
  || value.migration_digest !== todoSelfDigest(value, 'migration_digest')) return false;
233
233
  const targets = [];
@@ -238,7 +238,7 @@ function validRuntimeTaskMigration(value) {
238
238
  'predecessor_task_id', 'disposition', 'successor_task_ids', 'reason', 'evidence_digests',
239
239
  ]) || !isTodoIdentifier(entry.predecessor_task_id)
240
240
  || !['carry', 'stay', 'replace', 'split', 'retire'].includes(entry.disposition)
241
- || !Array.isArray(entry.successor_task_ids) || entry.successor_task_ids.length > 512
241
+ || !Array.isArray(entry.successor_task_ids)
242
242
  || !entry.successor_task_ids.every(isTodoIdentifier)
243
243
  || new Set(entry.successor_task_ids).size !== entry.successor_task_ids.length
244
244
  || successorTail.some((id, targetIndex) => targetIndex > 0
@@ -374,7 +374,6 @@ export function validatePhaseTodoRevision(value) {
374
374
  function validSourceInventory(value, desiredPlan, { requireNarrativeRef = false } = {}) {
375
375
  if (!exactRecord(value, ['active', 'excluded_tombstones'])
376
376
  || !Array.isArray(value.active) || !Array.isArray(value.excluded_tombstones)
377
- || value.active.length > 512 || value.excluded_tombstones.length > 2_048
378
377
  || !value.active.every((entry) => exactRecord(entry, ['task_id', 'source_ref', 'source_digest'])
379
378
  && isTodoIdentifier(entry.task_id) && parseTodoSourceRef(entry.source_ref) !== null
380
379
  && isTodoDigest(entry.source_digest))
@@ -476,7 +475,7 @@ function explainPredecessor(value, at = '/predecessor') {
476
475
  * 可否を変えずに1件ずつ言い当てる。
477
476
  */
478
477
  function explainTaskMigration(value, at = '/task_migration') {
479
- if (!Array.isArray(value) || value.length === 0 || value.length > 512) {
478
+ if (!Array.isArray(value) || value.length === 0) {
480
479
  return reject('bounded_collection_violation', at);
481
480
  }
482
481
  for (const [index, entry] of value.entries()) {
@@ -509,7 +508,7 @@ function explainTaskMigration(value, at = '/task_migration') {
509
508
  }
510
509
 
511
510
  function explainPhaseMigration(value, desiredPlan, at = '/phase_migration') {
512
- if (!Array.isArray(value) || value.length === 0 || value.length > 512) {
511
+ if (!Array.isArray(value) || value.length === 0) {
513
512
  return reject('bounded_collection_violation', at);
514
513
  }
515
514
  for (const [index, entry] of value.entries()) {
@@ -554,7 +553,7 @@ function explainRuntimeTaskMigration(value, taskMigration, desiredPlan, at = '/r
554
553
  const keyCheck = explainKeys(value, ['schema', 'entries', 'migration_digest'], at);
555
554
  if (!keyCheck.valid) return keyCheck;
556
555
  if (value.schema !== 'lattice.runtime_task_migration.v1') return reject('schema_mismatch', `${at}/schema`);
557
- if (!Array.isArray(value.entries) || value.entries.length === 0 || value.entries.length > 512) {
556
+ if (!Array.isArray(value.entries) || value.entries.length === 0) {
558
557
  return reject('bounded_collection_violation', `${at}/entries`);
559
558
  }
560
559
  const targets = [];
@@ -569,7 +568,7 @@ function explainRuntimeTaskMigration(value, taskMigration, desiredPlan, at = '/r
569
568
  if (!['carry', 'stay', 'replace', 'split', 'retire'].includes(entry.disposition)) {
570
569
  return reject('invalid_disposition', `${entryAt}/disposition`);
571
570
  }
572
- if (!Array.isArray(entry.successor_task_ids) || entry.successor_task_ids.length > 512
571
+ if (!Array.isArray(entry.successor_task_ids)
573
572
  || !entry.successor_task_ids.every(isTodoIdentifier)) {
574
573
  return reject('invalid_successor_task_ids', `${entryAt}/successor_task_ids`);
575
574
  }
@@ -631,10 +630,10 @@ function explainRuntimeTaskMigration(value, taskMigration, desiredPlan, at = '/r
631
630
  function explainSourceInventory(value, desiredPlan, { requireNarrativeRef = false } = {}, at = '/source_inventory') {
632
631
  const keyCheck = explainKeys(value, ['active', 'excluded_tombstones'], at);
633
632
  if (!keyCheck.valid) return keyCheck;
634
- if (!Array.isArray(value.active) || value.active.length > 512) {
633
+ if (!Array.isArray(value.active)) {
635
634
  return reject('bounded_collection_violation', `${at}/active`);
636
635
  }
637
- if (!Array.isArray(value.excluded_tombstones) || value.excluded_tombstones.length > 2_048) {
636
+ if (!Array.isArray(value.excluded_tombstones)) {
638
637
  return reject('bounded_collection_violation', `${at}/excluded_tombstones`);
639
638
  }
640
639
  for (const [index, entry] of value.active.entries()) {
@@ -693,7 +692,7 @@ function explainSourceCutoverBatch(value, revision, at = '/source_cutover_batch'
693
692
  || parseTodoSourceRef(value.archive_ref) !== null) {
694
693
  return reject('invalid_archive_ref', `${at}/archive_ref`);
695
694
  }
696
- if (!Array.isArray(value.operations) || value.operations.length === 0 || value.operations.length > 512) {
695
+ if (!Array.isArray(value.operations) || value.operations.length === 0) {
697
696
  return reject('bounded_collection_violation', `${at}/operations`);
698
697
  }
699
698
  const sourceRefs = new Set();
@@ -31,7 +31,8 @@ import {
31
31
  * plan単位noteは工程に属する義務で、taskへ着手した人のcontextには届くが、**まだ誰も
32
32
  * 着手していない工程の義務は、この欄が無いとどこにも出ない**。
33
33
  */
34
- export const TODO_STATUS_SCHEMA = 'lattice.todo_status_result.v9';
34
+ export const TODO_STATUS_SCHEMA = 'lattice.todo_status_result.v10';
35
+ /** v10: `active_set[].connections` and `connection_pending[]` carry the one `connections` list: open 他条件に接続 and 優先接続 entries. */
35
36
  /** v9 (u03 A77): `truncated: [{list, total, shown}]` records every cut of an output list. */
36
37
  /** v8: cross_plan_findingsは件数だけ全数、本文は先頭からこの件数まで(statusを止めない)。 */
37
38
  export const TODO_STATUS_FINDING_LIMIT = 32;
@@ -130,11 +131,31 @@ function taskRefEntry(value) {
130
131
  && isTodoIdentifier(value.plan_key) && isTodoIdentifier(value.task_id);
131
132
  }
132
133
 
134
+ function connectionEntry(value) {
135
+ if (exactRecord(value, ['kind', 'agent', 'since', 'reason'])) {
136
+ return value.kind === 'priority' && isTodoStatusBoundedText(value.agent, TODO_STATUS_LABEL_LIMIT)
137
+ && typeof value.since === 'string' && (value.reason === null || isTodoStatusBoundedText(value.reason, TODO_STATUS_REASON_LIMIT));
138
+ }
139
+ return (exactRecord(value, ['kind', 'ref', 'state', 'reason', 'since'])
140
+ || exactRecord(value, ['kind', 'ref', 'state', 'reason', 'since', 'state_reason']))
141
+ && ['task', 'schedule'].includes(value.kind) && value.state === 'open'
142
+ && isTodoStatusBoundedText(value.ref, TODO_STATUS_REASON_LIMIT)
143
+ && isTodoStatusBoundedText(value.reason, TODO_STATUS_REASON_LIMIT) && typeof value.since === 'string'
144
+ && (value.state_reason === undefined || isTodoStatusBoundedText(value.state_reason, TODO_STATUS_LABEL_LIMIT));
145
+ }
146
+
133
147
  function activeTaskEntry(value) {
134
- return exactRecord(value, ['plan_key', 'task_id', 'label', 'unmet_dependencies'])
148
+ return exactRecord(value, ['plan_key', 'task_id', 'label', 'unmet_dependencies', 'connections'])
149
+ && isTodoIdentifier(value.plan_key) && isTodoIdentifier(value.task_id)
150
+ && isTodoStatusBoundedText(value.label, TODO_STATUS_LABEL_LIMIT)
151
+ && boundedList(value.unmet_dependencies, taskRefEntry) && boundedList(value.connections, connectionEntry);
152
+ }
153
+
154
+ function connectionPendingEntry(value) {
155
+ return exactRecord(value, ['plan_key', 'task_id', 'label', 'connections'])
135
156
  && isTodoIdentifier(value.plan_key) && isTodoIdentifier(value.task_id)
136
157
  && isTodoStatusBoundedText(value.label, TODO_STATUS_LABEL_LIMIT)
137
- && boundedList(value.unmet_dependencies, taskRefEntry);
158
+ && boundedList(value.connections, connectionEntry) && value.connections.length > 0;
138
159
  }
139
160
 
140
161
  function blockedEntry(value) {
@@ -356,13 +377,13 @@ export function validateTodoStatusResult(value) {
356
377
  try {
357
378
  return exactRecord(value, [
358
379
  'schema', 'project_id', 'active_set', 'next_ready', 'dispatch_frontier',
359
- 'blocked', 'audit_pending', 'structure_finalization_pending', 'plan_notes',
380
+ 'blocked', 'connection_pending', 'audit_pending', 'structure_finalization_pending', 'plan_notes',
360
381
  'coordination', 'parallel_candidates', 'cross_plan_findings',
361
382
  'member_heads', 'truncated', 'result_digest',
362
383
  ]) && value.schema === TODO_STATUS_SCHEMA && isTodoIdentifier(value.project_id)
363
384
  && boundedList(value.active_set, activeTaskEntry) && boundedList(value.next_ready, taskEntry)
364
385
  && dispatchFrontierEntry(value.dispatch_frontier, value.project_id, value.next_ready)
365
- && boundedList(value.blocked, blockedEntry) && boundedList(value.audit_pending, auditPendingEntry)
386
+ && boundedList(value.blocked, blockedEntry) && boundedList(value.connection_pending, connectionPendingEntry) && boundedList(value.audit_pending, auditPendingEntry)
366
387
  && boundedList(value.structure_finalization_pending, structureFinalizationPendingEntry)
367
388
  && boundedList(value.plan_notes, planNoteEntry)
368
389
  && boundedList(value.coordination, coordinationEntry)
@@ -625,8 +646,23 @@ export function projectTodoStatus(readModel, options = undefined) {
625
646
  const activeSet = [];
626
647
  const nextReady = [];
627
648
  const blocked = [];
649
+ const connectionPending = [];
650
+ // One `connections` list (the Owner's one place): open 他条件に接続 entries and 優先接続 entries. Settled ones are
651
+ // history that `todo show` lists.
652
+ const openConnections = (key) => graph.readiness.allConnections(key)
653
+ .filter((entry) => entry.kind === 'priority' || entry.state === 'open')
654
+ .map((entry) => entry.kind === 'priority'
655
+ ? { kind: 'priority', agent: displayText(entry.agent, 'unknown', TODO_STATUS_LABEL_LIMIT), since: entry.since,
656
+ reason: entry.reason === null ? null : displayText(entry.reason, 'priority', TODO_STATUS_REASON_LIMIT) }
657
+ : { kind: entry.kind, ref: entry.ref, state: 'open', reason: displayText(entry.reason, 'connection', TODO_STATUS_REASON_LIMIT),
658
+ since: entry.since,
659
+ ...(entry.state_reason === undefined ? {} : { state_reason: displayText(entry.state_reason, 'chart_not_read', TODO_STATUS_LABEL_LIMIT) }) });
628
660
  for (const node of nodes.values()) {
629
661
  const task = { plan_key: node.plan_key, task_id: node.task_id, label: node.label };
662
+ if (node.status === 'pending') {
663
+ const connections = openConnections(node.key);
664
+ if (connections.length > 0) connectionPending.push({ ...task, connections });
665
+ }
630
666
  if (node.status === 'in-progress') {
631
667
  const unmetDependencies = [...incoming.get(node.key)]
632
668
  .filter((key) => !nodes.get(key).finished)
@@ -641,7 +677,7 @@ export function projectTodoStatus(readModel, options = undefined) {
641
677
  const entry = truncated.get('active_set.unmet_dependencies');
642
678
  entry.total += unmetDependencies.length; entry.shown += shownDependencies.length;
643
679
  }
644
- activeSet.push({ ...task, unmet_dependencies: shownDependencies });
680
+ activeSet.push({ ...task, unmet_dependencies: shownDependencies, connections: openConnections(node.key) });
645
681
  }
646
682
  if (isNodeReady(node, graph)) nextReady.push({ ...task, done_condition: node.done_condition });
647
683
  if (node.status === 'blocked') {
@@ -655,9 +691,11 @@ export function projectTodoStatus(readModel, options = undefined) {
655
691
  activeSet.sort(compareTaskEntries);
656
692
  nextReady.sort(compareTaskEntries);
657
693
  blocked.sort(compareTaskEntries);
694
+ connectionPending.sort(compareTaskEntries);
658
695
  memberHeads.sort((left, right) => left.plan_key < right.plan_key ? -1 : left.plan_key > right.plan_key ? 1 : 0);
659
696
  const lists = {
660
- active_set: activeSet, next_ready: nextReady, blocked, audit_pending: auditPending,
697
+ active_set: activeSet, next_ready: nextReady, blocked, connection_pending: connectionPending,
698
+ audit_pending: auditPending,
661
699
  structure_finalization_pending: structureFinalizations, plan_notes: planNotes,
662
700
  coordination, parallel_candidates: parallelCandidates, member_heads: memberHeads,
663
701
  };
@@ -678,6 +716,7 @@ export function projectTodoStatus(readModel, options = undefined) {
678
716
  next_ready: lists.next_ready,
679
717
  dispatch_frontier: dispatchFrontier(readModel.project_id, lists.next_ready),
680
718
  blocked: lists.blocked,
719
+ connection_pending: lists.connection_pending,
681
720
  // 監査待ちは`member.phases`だけから作った別の列で、dispatch(next_ready/dispatch_frontier)へは
682
721
  // 影響しない。監査が進んでもfrontier_digestは動かない。
683
722
  audit_pending: lists.audit_pending,
@@ -75,6 +75,65 @@ export function projectTodoCrossPlanDependencies(members) {
75
75
  });
76
76
  }
77
77
 
78
+ /**
79
+ * 接続 (schedule): one plan chain's connection_added events with how each ended. `ended` is 'removed' or
80
+ * 'resolved' (an add has at most one end, which Store append enforces); a state of 'removed' is not shown.
81
+ */
82
+ export function projectTodoScheduleConnections(events) {
83
+ const ends = new Map();
84
+ for (const event of events ?? []) {
85
+ if (event.kind === 'connection_removed') ends.set(event.payload.target_event_digest, { ended: 'removed', event });
86
+ if (event.kind === 'connection_resolved') ends.set(event.payload.target_event_digest, { ended: 'resolved', event });
87
+ }
88
+ return (events ?? []).filter((event) => event.kind === 'connection_added').map((event) => {
89
+ const end = ends.get(event.event_digest);
90
+ return { kind: 'schedule', task_id: event.payload.task_id, ref: event.payload.to.id,
91
+ state: end === undefined ? 'open' : end.ended === 'resolved' ? 'settled' : 'removed',
92
+ reason: event.payload.reason, since: event.recorded_at, event_digest: event.event_digest,
93
+ actor: event.actor, provenance: event.provenance, ended: end?.ended ?? null,
94
+ ...(end?.ended === 'resolved' ? { settled_at: end.event.recorded_at, evidence: end.event.payload.evidence } : {}) };
95
+ });
96
+ }
97
+
98
+ const connectionTaskKey = (projectId, planKey, taskId) => `${projectId}\0${planKey}\0${taskId}`;
99
+ export { connectionTaskKey as todoConnectionTaskKey };
100
+
101
+ /**
102
+ * 接続 per task, keyed `project\0plan\0task`: schedule connections from the plan chain, and task connections from
103
+ * today's cross-chart ledger edges (settled once that task is done or retired, open while its chart is unread).
104
+ * Pure; a removed connection is not listed. Entry: {kind, ref, state, reason, since, event_digest, settled_at?,
105
+ * evidence?, state_reason?}, sorted by since then digest.
106
+ */
107
+ export function projectTodoConnections(members, externalTasks = []) {
108
+ const external = new Map(externalTasks.map((entry) => [connectionTaskKey(entry.project_id, entry.plan_key, entry.task_id), entry]));
109
+ const byTask = new Map();
110
+ const push = (key, entry) => byTask.set(key, [...(byTask.get(key) ?? []), entry]);
111
+ for (const member of members) {
112
+ const { plan } = member;
113
+ for (const entry of projectTodoScheduleConnections(member.plan_scoped?.events)) {
114
+ if (entry.state === 'removed') continue;
115
+ const { task_id: taskId, actor: _actor, provenance: _provenance, ended: _ended, ...shown } = entry;
116
+ push(connectionTaskKey(plan.project_id, plan.plan_key, taskId), shown);
117
+ }
118
+ }
119
+ for (const dependency of projectTodoCrossPlanDependencies(members)) {
120
+ if (dependency.from.project_id === dependency.to.project_id) continue;
121
+ const { from, to } = dependency;
122
+ const source = external.get(connectionTaskKey(from.project_id, from.plan_key, from.task_id));
123
+ const settled = source?.finished === true;
124
+ push(connectionTaskKey(to.project_id, to.plan_key, to.task_id), {
125
+ kind: 'task', ref: `${from.project_id}/${from.plan_key}/${from.task_id}`,
126
+ state: settled ? 'settled' : 'open', reason: dependency.reason, since: dependency.connected_at,
127
+ event_digest: dependency.event_digest,
128
+ ...(!settled && (source === undefined || source.status === null || source.status === undefined)
129
+ ? { state_reason: source?.reason ?? 'chart_not_read' } : {}) });
130
+ }
131
+ for (const [key, entries] of byTask) {
132
+ byTask.set(key, entries.sort((left, right) => (left.since + left.event_digest < right.since + right.event_digest ? -1 : 1)));
133
+ }
134
+ return byTask;
135
+ }
136
+
78
137
  function mappedNodeRef(ref, plan, idMap) {
79
138
  if (ref.project_id !== plan.project_id || ref.plan_key !== plan.plan_key) return ref;
80
139
  return { ...ref, task_id: idMap.get(ref.task_id) ?? ref.task_id };
@@ -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,
@@ -16,10 +17,14 @@ export {
16
17
  todoTaskCarrySemantics,
17
18
  } from './todo-store-view.mjs';
18
19
  import { randomBytes } from 'node:crypto';
20
+ import { gunzipSync, gzipSync } from 'node:zlib';
19
21
  import { fsyncDirectory } from './fs-dir-sync.mjs';
20
22
  import { renamePublishedFile, syncPublishedFile } from './fs-publish.mjs';
21
23
  import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
22
24
  import { memoByFileIdentity } from './todo-version-memo.mjs';
25
+ import {
26
+ TODO_VERSION_COMPACT_FILE, buildVersionCompact, packVersionCompact, readVersionCompact, reconstructPlan, reconstructRevision,
27
+ } from './todo-version-compact.mjs';
23
28
  import {
24
29
  lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir,
25
30
  } from 'node:fs/promises';
@@ -327,9 +332,15 @@ async function readSealedSegments(repoRoot, journalRef, directoryName) {
327
332
  }
328
333
 
329
334
  async function readJournal(repoRoot, journalRef) {
330
- const state = await pathState(repoRoot, journalRef, 'STORE_CORRUPT');
335
+ // b10: a retained version's active segment may be kept gzip-packed as `active.jsonl.gz` (same bytes once unpacked).
336
+ const state = await pathState(repoRoot, journalRef, 'STORE_CORRUPT', { missing: true });
337
+ const packed = state === null ? await pathState(repoRoot, `${journalRef}.gz`, 'STORE_CORRUPT') : null;
331
338
  const segments = await readSealedSegments(repoRoot, journalRef, 'sealed');
332
- const activeBytes = normalizeCheckoutEol(await readFile(state.absolute));
339
+ let activeBytes;
340
+ try {
341
+ activeBytes = state === null ? gunzipSync(await readFile(packed.absolute), { maxOutputLength: TODO_LIMITS.journalSegmentBytes })
342
+ : normalizeCheckoutEol(await readFile(state.absolute));
343
+ } catch { fail('STORE_CORRUPT', 'journal_gzip_invalid', { ref: `${journalRef}.gz` }); }
333
344
  const duplicateActive = segments.at(-1)?.bytes.equals(activeBytes) === true;
334
345
  if (!duplicateActive) {
335
346
  segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef) });
@@ -1095,7 +1106,7 @@ function crossPlanDependencyTask(store, ref) {
1095
1106
  }
1096
1107
 
1097
1108
  /**
1098
- * xchart S3: only `todo dependency connect` (appendTodoEvent, `foreignFrom`) may record a predecessor on another
1109
+ * xchart S3: only `todo connect condition add` (`dependency connect --from-project`, retired alias) (appendTodoEvent, `foreignFrom`) may record a predecessor on another
1099
1110
  * chart; Plan checked it there just before. Genesis, import and connectionOnly keep refusing a foreign from.
1100
1111
  */
1101
1112
  function validateCrossPlanDependencyTransition(store, owner, input, { foreignFrom = false } = {}) {
@@ -1437,7 +1448,7 @@ function materializeImportedNarrativeAnchors(repoRoot, planInput, sources, cache
1437
1448
  if (sources === undefined) return planInput;
1438
1449
  if (!['lattice.todo_plan.v2', 'lattice.todo_plan.v6'].includes(planInput?.schema)
1439
1450
  || !Array.isArray(sources)
1440
- || sources.length > TODO_LIMITS.tasksPerPlan || !sources.every(narrativeAnchorSource)) {
1451
+ || !sources.every(narrativeAnchorSource)) {
1441
1452
  throw new TypeError('imported narrative anchor sources are invalid');
1442
1453
  }
1443
1454
  const byTask = new Map(sources.map((source) => [source.task_id, source]));
@@ -1705,6 +1716,11 @@ async function readTodoStoreView(options = {}) {
1705
1716
  * unreadable. perf-store: validated once per process per unchanged plan.json (todo-version-memo).
1706
1717
  */
1707
1718
  async function retainedPlanVersion(repoRoot, base, version) {
1719
+ const compact = await readCompactRecord(repoRoot, base, version).catch(() => null);
1720
+ if (compact !== null) {
1721
+ return { plan: { plan_digest: compact.plan_digest, predecessor_plan_digest: compact.predecessor_plan_digest,
1722
+ topology_digest: compact.topology_digest }, journalRef: `${base}/${version}/journal/active.jsonl` };
1723
+ }
1708
1724
  const ref = `${base}/${version}/plan.json`;
1709
1725
  const plan = await memoByFileIdentity([path.resolve(repoRoot, ref)], async () => {
1710
1726
  const value = await readArtifact(repoRoot, ref, {
@@ -1716,6 +1732,110 @@ async function retainedPlanVersion(repoRoot, base, version) {
1716
1732
  return plan === null ? null : { plan, journalRef: `${base}/${version}/journal/active.jsonl` };
1717
1733
  }
1718
1734
 
1735
+ /** b10: a retained version's compact record (see todo-version-compact), or null while it still holds its own files. */
1736
+ async function readCompactRecord(repoRoot, base, version) {
1737
+ const directory = path.resolve(repoRoot, base, version);
1738
+ return memoByFileIdentity([path.join(directory, TODO_VERSION_COMPACT_FILE)], () => readVersionCompact(directory)
1739
+ .catch(() => fail('STORE_INCONSISTENT', 'compact_record_invalid', { ref: `${base}/${version}/${TODO_VERSION_COMPACT_FILE}` })));
1740
+ }
1741
+
1742
+ /** b10: one retained version's full `{plan, revision}` (revision null for a genesis version): its own files or its compact record. */
1743
+ export async function readRetainedVersion(repoRoot, base, version, active, cache = new Map()) {
1744
+ if (version === active.plan_version) return { plan: active, revision: null };
1745
+ if (cache.has(version)) return cache.get(version);
1746
+ const plan = await readArtifact(repoRoot, `${base}/${version}/plan.json`, {
1747
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
1748
+ });
1749
+ let result = null;
1750
+ if (plan !== null) {
1751
+ const revision = await readArtifact(repoRoot, `${base}/${version}/revision.json`, {
1752
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, missing: true,
1753
+ validate: (value) => validateTodoRevision(value) || validatePhaseTodoRevision(value),
1754
+ }).catch(() => null);
1755
+ result = { plan, revision };
1756
+ } else {
1757
+ const record = await readCompactRecord(repoRoot, base, version);
1758
+ if (record !== null) {
1759
+ const anchor = await readRetainedVersion(repoRoot, base, record.anchor_plan_version, active, cache);
1760
+ if (anchor === null) fail('STORE_INCONSISTENT', 'compact_anchor_missing', { version });
1761
+ let rebuilt;
1762
+ try { rebuilt = reconstructPlan(record, anchor.plan); } catch { fail('STORE_INCONSISTENT', 'compact_plan_mismatch', { version }); }
1763
+ if (!validateTodoPlan(rebuilt)) fail('STORE_INCONSISTENT', 'compact_plan_invalid', { version });
1764
+ result = { plan: rebuilt, revision: reconstructRevision(record, rebuilt) };
1765
+ }
1766
+ }
1767
+ cache.set(version, result);
1768
+ return result;
1769
+ }
1770
+
1771
+ /** b10: keep a retained version's active journal segment as gzip (`active.jsonl.gz`); it is read back byte for byte. */
1772
+ async function packRetainedJournal(plain) {
1773
+ const bytes = await exactFileOrNull(plain);
1774
+ if (bytes === null) return;
1775
+ await atomicWrite(`${plain}.gz`, gzipSync(bytes, { level: 9 }));
1776
+ await rm(plain);
1777
+ await fsyncDirectory(path.dirname(plain));
1778
+ }
1779
+
1780
+ /**
1781
+ * b10: replace the plan.json, revision.json and snapshot.json of the versions a member's active version superseded with one
1782
+ * compact.json each (reverse patch to its successor; the journal segment is gzip-packed). `hook` compacts only the direct predecessor (after every successor write);
1783
+ * `sweep` walks the whole predecessor chain, also finishing a half-done compaction. Lock held by the caller. Returns the versions
1784
+ * compacted and, when the walk could not continue, why. History stays: the three digests, the revision and the exact plan rebuild.
1785
+ */
1786
+ async function compactSupersededVersions(repoRoot, member, { sweep = false, limit = Infinity } = {}) {
1787
+ const base = `${STORE_ROOT_REF}/plans/${member.plan.plan_key}`;
1788
+ const compacted = [];
1789
+ let anchor = member.plan;
1790
+ let version = member.revision?.predecessor?.plan_version ?? null;
1791
+ while (version !== null) {
1792
+ const directory = path.resolve(repoRoot, base, version);
1793
+ const originals = ['plan.json', 'revision.json', 'snapshot.json'].map((name) => path.join(directory, name));
1794
+ const removeOriginals = async () => {
1795
+ for (const file of originals) await rm(file, { force: true });
1796
+ await packRetainedJournal(path.join(directory, 'journal', 'active.jsonl'));
1797
+ await fsyncDirectory(directory);
1798
+ };
1799
+ const record = await readCompactRecord(repoRoot, base, version);
1800
+ if (record !== null) {
1801
+ if (await exactFileOrNull(originals[0]) !== null) await removeOriginals(); // a compaction cut short after compact.json.gz
1802
+ else if (!sweep) break;
1803
+ try { anchor = reconstructPlan(record, anchor); } catch { return { compacted, stopped: 'compact_anchor_mismatch', version }; }
1804
+ version = record.predecessor_plan_version;
1805
+ } else {
1806
+ const retained = await readRetainedVersion(repoRoot, base, version, member.plan).catch(() => null);
1807
+ if (retained === null) return { compacted, stopped: 'version_unreadable', version };
1808
+ const built = buildVersionCompact({ retained: retained.plan, anchor, revision: retained.revision });
1809
+ if (built === null) return { compacted, stopped: 'round_trip_mismatch', version };
1810
+ await atomicWrite(path.join(directory, TODO_VERSION_COMPACT_FILE), packVersionCompact(built));
1811
+ await removeOriginals();
1812
+ compacted.push(version);
1813
+ anchor = retained.plan;
1814
+ version = built.predecessor_plan_version;
1815
+ }
1816
+ if (!sweep) break;
1817
+ if (compacted.length >= limit && version !== null) return { compacted, stopped: 'limit', version };
1818
+ }
1819
+ return { compacted, stopped: null, version: null };
1820
+ }
1821
+
1822
+ /** b10: `lattice todo compact`: compact the retained versions of every member (or `planKey`), at most `limit` per call. */
1823
+ export async function compactTodoVersions(options = {}) {
1824
+ requireWriter(options.writer, 'g5-authoring');
1825
+ const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
1826
+ return withLock(repoRoot, async () => {
1827
+ const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
1828
+ const plans = [];
1829
+ for (const member of store.members) {
1830
+ if (options.planKey !== undefined && member.plan.plan_key !== options.planKey) continue;
1831
+ const result = await compactSupersededVersions(repoRoot, member, { sweep: true, limit: options.limit });
1832
+ plans.push({ plan_key: member.plan.plan_key, compacted: result.compacted.length, stopped: result.stopped,
1833
+ next_version: result.version });
1834
+ }
1835
+ return { schema: 'lattice.todo_compact_result.v1', project_id: store.project_id, plans };
1836
+ }, { lockCapability: options[STORE_LOCK_HELD] });
1837
+ }
1838
+
1719
1839
  async function retainedVersionNames(repoRoot, base, activePlan) {
1720
1840
  let names = [];
1721
1841
  try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
@@ -2263,7 +2383,10 @@ async function withLock(repoRoot, callback, {
2263
2383
  const result = await callback(assertHeld);
2264
2384
  // The successor is already published: a failed repair leaves findings for the next locked write.
2265
2385
  try {
2266
- const repairs = await repairCrossPlanBindings(repoRoot, await readTodoStoreView({ repoRoot }),
2386
+ const view = await readTodoStoreView({ repoRoot });
2387
+ // b10: the version this write superseded keeps only its difference; a failure leaves the full files, retried next write.
2388
+ for (const member of view.members) await compactSupersededVersions(repoRoot, member).catch(() => {});
2389
+ const repairs = await repairCrossPlanBindings(repoRoot, view,
2267
2390
  { assertHeld, actor: repairAfter.actor, recordedAt: repairAfter.recordedAt ?? new Date().toISOString() });
2268
2391
  // Results stay digest-bound; the caller learns the repairs through its own callback.
2269
2392
  if (repairs.length > 0 && typeof repairAfter.onRepairs === 'function') await repairAfter.onRepairs(repairs);
@@ -2448,6 +2571,30 @@ function resolveCanonicalTaskId(plan, requestedTaskId) {
2448
2571
  return matches[0].task_id;
2449
2572
  }
2450
2573
 
2574
+ /**
2575
+ * 接続: every write is idempotent so a retry after an unknown outcome replays to the same state. Returns
2576
+ * `{unchanged: true, target_event_digest}` (nothing is appended) for: an add whose task + schedule is already open,
2577
+ * a resolve of an entry already settled (the first evidence wins), a remove when the entry is not open. Anything
2578
+ * else that cannot apply is refused.
2579
+ */
2580
+ function validateConnectionTransition(member, event) {
2581
+ if (!['connection_added', 'connection_removed', 'connection_resolved'].includes(event.kind)) return null;
2582
+ const entries = projectTodoScheduleConnections(member.plan_scoped?.events ?? []);
2583
+ if (event.kind === 'connection_added') {
2584
+ const { task_id: taskId, to } = event.payload;
2585
+ const open = entries.find((entry) => entry.state === 'open' && entry.task_id === taskId && entry.ref === to.id);
2586
+ return open === undefined ? null : { unchanged: true, target_event_digest: open.event_digest };
2587
+ }
2588
+ const digest = event.payload.target_event_digest;
2589
+ const entry = entries.find((candidate) => candidate.event_digest === digest);
2590
+ if (entry === undefined) fail('DEPENDENCY_NOT_FOUND', 'connection_not_found', { target_event_digest: digest });
2591
+ if (event.kind === 'connection_removed') {
2592
+ return entry.state === 'open' ? null : { unchanged: true, target_event_digest: digest };
2593
+ }
2594
+ if (entry.ended === 'removed') fail('DEPENDENCY_INVALID', 'connection_already_removed', { target_event_digest: digest });
2595
+ return entry.state === 'settled' ? { unchanged: true, target_event_digest: digest } : null;
2596
+ }
2597
+
2451
2598
  export async function appendTodoEvent(options = {}) {
2452
2599
  requireWriter(options.writer, 'g5-authoring');
2453
2600
  if (typeof options.validateProspectiveEvent !== 'function') {
@@ -2482,9 +2629,15 @@ export async function appendTodoEvent(options = {}) {
2482
2629
  fail('DEPENDENCY_INVALID', 'cross_plan_dependency_already_removed', { target_event_digest: digest });
2483
2630
  }
2484
2631
  }
2632
+ const event = options.event.kind === 'connection_added'
2633
+ ? { ...options.event, payload: { ...options.event.payload,
2634
+ task_id: resolveCanonicalTaskId(member.plan, options.event.payload.task_id) } }
2635
+ : options.event;
2636
+ const unchanged = validateConnectionTransition(member, event);
2637
+ if (unchanged !== null) return { cross_plan_repairs: store.cross_plan_repairs, ...unchanged };
2485
2638
  return { cross_plan_repairs: store.cross_plan_repairs, ...await appendPlanScopedEvent({
2486
2639
  repoRoot, member, assertHeld,
2487
- input: { ...options.event, recorded_at: options.event.recorded_at ?? new Date().toISOString() },
2640
+ input: { ...event, recorded_at: event.recorded_at ?? new Date().toISOString() },
2488
2641
  }) };
2489
2642
  }
2490
2643
  const input = resolveTargetedEvent({
@@ -2683,6 +2836,14 @@ function carriedPlanScopedChain(store, previous, plan, journalRef, taskMigration
2683
2836
  payload: { from, to, reason: event.payload.reason } });
2684
2837
  pushPlanScopedEvent(successor.plan_scoped, carried);
2685
2838
  }
2839
+ // 接続: only the schedule connections still open travel; a settled or removed one equals no connection.
2840
+ for (const entry of projectTodoScheduleConnections(previous.plan_scoped?.events ?? [])) {
2841
+ const taskId = ids.get(entry.task_id);
2842
+ if (entry.state !== 'open' || taskId === undefined || taskId === 'removed') continue;
2843
+ pushPlanScopedEvent(successor.plan_scoped, buildPlanScopedEvent(successor, { kind: 'connection_added',
2844
+ actor: entry.actor, recorded_at: entry.since, provenance: entry.provenance,
2845
+ payload: { task_id: taskId, to: { kind: 'schedule', id: entry.ref }, reason: entry.reason } }));
2846
+ }
2686
2847
  return successor.plan_scoped;
2687
2848
  }
2688
2849
 
@@ -2725,10 +2886,9 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
2725
2886
  ))) fail('DEPENDENCY_INVALID', 'dependency_rebind_original_mismatch');
2726
2887
  const predecessorBinding = source.revision?.predecessor;
2727
2888
  if (!predecessorBinding) fail('DEPENDENCY_INVALID', 'dependency_rebind_predecessor_missing');
2728
- const predecessor = await readArtifact(repoRoot,
2729
- `${STORE_ROOT_REF}/plans/${source.plan.plan_key}/${predecessorBinding.plan_version}/plan.json`, {
2730
- code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan,
2731
- });
2889
+ const predecessor = (await readRetainedVersion(repoRoot, `${STORE_ROOT_REF}/plans/${source.plan.plan_key}`,
2890
+ predecessorBinding.plan_version, source.plan))?.plan;
2891
+ if (!predecessor) fail('STORE_INCONSISTENT', 'artifact_missing');
2732
2892
  if (predecessor.project_id !== source.plan.project_id || predecessor.plan_key !== source.plan.plan_key
2733
2893
  || predecessor.plan_version !== predecessorBinding.plan_version
2734
2894
  || predecessor.plan_digest !== predecessorBinding.plan_digest) {
@@ -2910,7 +3070,7 @@ function buildHistoricalStart(plan, previous, input, genesis) {
2910
3070
  function historicalImportInputs(value, timestampKey) {
2911
3071
  const required = ['task_id', timestampKey, 'evidence'];
2912
3072
  const allowed = new Set([...required, 'actor', 'recorded_at', 'provenance']);
2913
- return Array.isArray(value) && value.length <= TODO_LIMITS.tasksPerPlan
3073
+ return Array.isArray(value)
2914
3074
  && value.every((entry) => entry !== null && typeof entry === 'object' && !Array.isArray(entry)
2915
3075
  && Object.getPrototypeOf(entry) === Object.prototype
2916
3076
  && required.every((key) => Object.hasOwn(entry, key))
@@ -3457,7 +3617,7 @@ async function appendPlanMembership(repoRoot, options, authored) {
3457
3617
  const full = importedCrossPlan.artifacts.find(({ sealed }) => sealed.length > 0);
3458
3618
  if (full !== undefined) {
3459
3619
  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`' });
3620
+ next_action: 'import without this cross-plan edge, then add it with `lattice todo predecessor add`' });
3461
3621
  }
3462
3622
  const transactionRef = hasCrossPlanDependencies
3463
3623
  ? `${CROSS_PLAN_IMPORT_TRANSACTIONS_REF}/${transactionDigest}`
@@ -4910,39 +5070,18 @@ async function cleanupPhaseV3Staging(transaction, staged) {
4910
5070
 
4911
5071
  export async function predecessorSourceInventory(repoRoot, previous) {
4912
5072
  if (previous.revision?.source_inventory !== undefined) return previous.revision.source_inventory;
4913
- const versionsRoot = path.join(repoRoot, STORE_ROOT_REF, 'plans', previous.plan.plan_key);
4914
- const plansByDigest = new Map();
4915
- for (const entry of await readdir(versionsRoot, { withFileTypes: true })) {
4916
- if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
4917
- const planBytes = await exactFileOrNull(path.join(versionsRoot, entry.name, 'plan.json'));
4918
- if (planBytes === null) continue;
4919
- let plan;
4920
- try { plan = JSON.parse(decodeUtf8(planBytes, 'STORE_INCONSISTENT', 'plan_invalid')); }
4921
- catch { continue; }
4922
- if (!planBytes.equals(canonicalLine(plan)) || !validateTodoPlan(plan)
4923
- || plan.plan_key !== previous.plan.plan_key) continue;
4924
- plansByDigest.set(plan.plan_digest, { plan, directory: path.join(versionsRoot, entry.name) });
4925
- }
4926
- const visited = new Set();
4927
- let digest = previous.plan.predecessor_plan_digest;
4928
- while (digest !== null && !visited.has(digest) && visited.size < 512) {
4929
- visited.add(digest);
4930
- const candidate = plansByDigest.get(digest);
4931
- if (candidate === undefined) break;
4932
- const revisionBytes = await exactFileOrNull(path.join(candidate.directory, 'revision.json'));
4933
- if (revisionBytes !== null) {
4934
- let revision;
4935
- try { revision = JSON.parse(decodeUtf8(revisionBytes,
4936
- 'STORE_INCONSISTENT', 'revision_invalid')); } catch { revision = null; }
4937
- if (revision !== null && revisionBytes.equals(canonicalLine(revision))
4938
- && (validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
4939
- && revision.project_id === candidate.plan.project_id
4940
- && revision.plan_key === candidate.plan.plan_key
4941
- && canonicalizeTodoArtifact(revision.desired_plan)
4942
- === canonicalizeTodoArtifact(candidate.plan)
4943
- && revision.source_inventory !== undefined) return revision.source_inventory;
4944
- }
4945
- digest = candidate.plan.predecessor_plan_digest;
5073
+ // b10: walk the revision bindings (no scan of every retained version); a compacted version is rebuilt exactly.
5074
+ const base = `${STORE_ROOT_REF}/plans/${previous.plan.plan_key}`;
5075
+ const cache = new Map(); const visited = new Set();
5076
+ for (let version = previous.revision?.predecessor?.plan_version ?? null; version !== null && !visited.has(version);) {
5077
+ visited.add(version);
5078
+ const candidate = await readRetainedVersion(repoRoot, base, version, previous.plan, cache).catch(() => null);
5079
+ const { plan, revision } = candidate ?? {};
5080
+ if (!plan || plan.plan_key !== previous.plan.plan_key) break;
5081
+ if (revision && revision.project_id === plan.project_id && revision.plan_key === plan.plan_key
5082
+ && canonicalizeTodoArtifact(revision.desired_plan) === canonicalizeTodoArtifact(plan)
5083
+ && revision.source_inventory !== undefined) return revision.source_inventory;
5084
+ version = revision?.predecessor?.plan_version ?? null;
4946
5085
  }
4947
5086
  return { active: [], excluded_tombstones: [] };
4948
5087
  }