@quolu/lattice 0.104.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.
- package/package.json +1 -1
- package/src/cli-help.mjs +2 -0
- package/src/todo-cli.mjs +10 -1
- package/src/todo-note-store.mjs +20 -2
- package/src/todo-store.mjs +140 -40
- package/src/todo-version-compact.mjs +110 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quolu/lattice",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.105.0",
|
|
4
4
|
"description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Quo / クオ at kitepon.dev",
|
package/src/cli-help.mjs
CHANGED
|
@@ -110,6 +110,7 @@ Read commands:
|
|
|
110
110
|
|
|
111
111
|
Write commands:
|
|
112
112
|
notice ack --lane <lane> --notice <id>[,<id>...] [--json] # 届けた知らせに印を付ける(閉じた知らせはclosedで返す)
|
|
113
|
+
compact [--plan <key>] [--limit <n>] [--json] # 退避済みの版のplan.json・revision.json・snapshot.jsonを、後継との差分(compact.json)だけに置き換える(既定40版まで。続きは再実行)
|
|
113
114
|
repair-eol --json # Git checkoutでCRLF化された既存storeをcanonical LFへ戻し、EOL保護を追加する
|
|
114
115
|
dashboard adopt --json # 衝突したproject_idの配信元rootを現在repoへ明示的に移す
|
|
115
116
|
dashboard ensure --json # daemon生存保証の冪等入口(launchd等の周期実行向け)
|
|
@@ -331,6 +332,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
|
|
|
331
332
|
'todo notice': 'todo notice list [--lane <lane>] [--include-acked] [--json] | ack --lane <lane> --notice <id>[,<id>...] [--json]',
|
|
332
333
|
'todo notice list': 'todo notice list [--lane <lane>] [--include-acked] [--json] # lattice.todo_notice_list_result.v1',
|
|
333
334
|
'todo notice ack': 'todo notice ack --lane <lane> --notice <id>[,<id>...] [--json] # lattice.todo_notice_ack_result.v1 {acked, already, closed}',
|
|
335
|
+
'todo compact': 'todo compact [--plan <key>] [--limit <n>] [--json] # lattice.todo_compact_result.v1 {plans: [{plan_key, compacted, stopped, next_version}]}',
|
|
334
336
|
'todo blockers': 'todo blockers [--json] # lattice.todo_blockers_result.v1 {blockers: [{plan_key, task_id, title, lane, reason, blocked_at, blocked_by, unblock_action}]}',
|
|
335
337
|
'todo wait': 'todo wait --plan <key> --task <id> [--reason <text>] | --cancel [--json] # 廃止予定の別名: todo connect priority',
|
|
336
338
|
'todo bindings': 'todo bindings [--plan <key>] [--json]',
|
package/src/todo-cli.mjs
CHANGED
|
@@ -65,6 +65,7 @@ import {
|
|
|
65
65
|
appendTodoStructureRealization,
|
|
66
66
|
applyPhaseTodoRevision,
|
|
67
67
|
applyTodoRevision,
|
|
68
|
+
compactTodoVersions,
|
|
68
69
|
applyTodoRevisionSet,
|
|
69
70
|
buildTodoPlan,
|
|
70
71
|
createTodoStoreWriter,
|
|
@@ -314,7 +315,7 @@ const TODO_COMMAND_NAMES = Object.freeze([
|
|
|
314
315
|
'status', 'show', 'note', 'bindings', 'display', 'independence', 'structure', 'seam-profile', 'seam-proposal',
|
|
315
316
|
'verify', 'repair-eol', 'snapshot', 'gantt', 'dashboard', 'phase', 'migrate', 'start', 'block',
|
|
316
317
|
'unblock', 'retire', 'done', 'reopen', 'evidence', 'split', 'revise', 'revise-phase', 'revise-set',
|
|
317
|
-
'retract', 'dependency', 'predecessor', 'connect', 'add', 'notice', 'wait', 'blockers',
|
|
318
|
+
'retract', 'dependency', 'predecessor', 'connect', 'add', 'notice', 'wait', 'blockers', 'compact',
|
|
318
319
|
]);
|
|
319
320
|
|
|
320
321
|
function typedArgumentFailure(stderr, code, message, detail, context = {}) {
|
|
@@ -384,6 +385,7 @@ const TODO_FLAG_SPECS = Object.freeze({
|
|
|
384
385
|
'notice list': Object.freeze({ known: ['lane', 'include-acked', 'json'], required: [], booleans: ['include-acked', 'json'] }),
|
|
385
386
|
'notice ack': Object.freeze({ known: ['lane', 'notice', 'json'], required: ['lane', 'notice'], booleans: ['json'] }),
|
|
386
387
|
blockers: Object.freeze({ known: ['json'], required: [], booleans: ['json'] }),
|
|
388
|
+
compact: Object.freeze({ known: ['plan', 'limit', 'json'], required: [], booleans: ['json'] }),
|
|
387
389
|
'connect priority': Object.freeze({ known: ['plan', 'task', 'reason', 'cancel', 'json'], required: ['plan', 'task'], booleans: ['cancel', 'json'] }),
|
|
388
390
|
wait: Object.freeze({ known: ['plan', 'task', 'reason', 'cancel', 'json'], required: ['plan', 'task'], booleans: ['cancel', 'json'] }),
|
|
389
391
|
'note list': Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan'], booleans: ['json'] }),
|
|
@@ -5572,6 +5574,13 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
|
|
|
5572
5574
|
if (isNoticeLane(flags.lane) && ids.length > 0 && ids.every((id) => /^[0-9a-f]{64}$/u.test(id))) {
|
|
5573
5575
|
action = (repoRoot) => noticeAck({ repoRoot, env, lane: flags.lane, ids });
|
|
5574
5576
|
}
|
|
5577
|
+
} else if (argv[0] === 'compact' && matchFlagCommand(argv, ['compact'], TODO_FLAG_SPECS.compact) !== null) {
|
|
5578
|
+
// b10: retained versions keep only their difference from the successor; this finishes the ones written before.
|
|
5579
|
+
const flags = matchFlagCommand(argv, ['compact'], TODO_FLAG_SPECS.compact);
|
|
5580
|
+
if ((flags.plan === undefined || isTodoIdentifier(flags.plan)) && (flags.limit === undefined || /^[1-9]\d{0,5}$/u.test(flags.limit))) {
|
|
5581
|
+
action = (repoRoot) => compactTodoVersions({ repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
|
|
5582
|
+
planKey: flags.plan, limit: flags.limit === undefined ? 40 : Number(flags.limit) });
|
|
5583
|
+
}
|
|
5575
5584
|
} else if (argv[0] === 'blockers' && matchFlagCommand(argv, ['blockers'], TODO_FLAG_SPECS.blockers) !== null) {
|
|
5576
5585
|
action = (repoRoot) => blockerList({ repoRoot });
|
|
5577
5586
|
} else if ((argv[0] === 'connect' && argv[1] === 'priority' || argv[0] === 'wait')
|
package/src/todo-note-store.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
|
|
|
8
8
|
import { syncPublishedFile } from './fs-publish.mjs';
|
|
9
9
|
import { normalizeCheckoutEol } from './todo-store-view.mjs';
|
|
10
10
|
import { memoByFileIdentity } from './todo-version-memo.mjs';
|
|
11
|
+
import { TODO_VERSION_COMPACT_FILE, readVersionCompact } from './todo-version-compact.mjs';
|
|
11
12
|
|
|
12
13
|
import {
|
|
13
14
|
TODO_LIMITS,
|
|
@@ -514,8 +515,25 @@ async function readNoteMigrations(repoRoot, planKey, eventVersions) {
|
|
|
514
515
|
const versionRoot = path.join(base, entry.name);
|
|
515
516
|
const planPath = path.join(versionRoot, 'plan.json');
|
|
516
517
|
const revisionPath = path.join(versionRoot, 'revision.json');
|
|
517
|
-
|
|
518
|
-
|
|
518
|
+
const compactPath = path.join(versionRoot, TODO_VERSION_COMPACT_FILE);
|
|
519
|
+
// perf-store: validated once per process while the files are unchanged (todo-version-memo).
|
|
520
|
+
const version = await memoByFileIdentity([planPath, revisionPath, compactPath], async () => {
|
|
521
|
+
// b10: a superseded version keeps compact.json.gz (its revision, minus the plan it repeats) instead of plan.json/revision.json.
|
|
522
|
+
const compact = await readVersionCompact(versionRoot).catch(() => fail('NOTE_PROJECTION_INVALID',
|
|
523
|
+
'note_historical_plan_invalid', { plan_version: entry.name }));
|
|
524
|
+
if (compact !== null) {
|
|
525
|
+
if (compact.plan_key !== planKey || compact.plan_version !== entry.name) {
|
|
526
|
+
fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
|
|
527
|
+
}
|
|
528
|
+
const migration = compact.revision?.task_migration;
|
|
529
|
+
if (compact.revision === null) return { migration: null };
|
|
530
|
+
if (compact.predecessor_plan_version === null || !Array.isArray(migration)) {
|
|
531
|
+
fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
|
|
532
|
+
}
|
|
533
|
+
return { migration: { from_plan_version: compact.predecessor_plan_version, to_plan_version: entry.name,
|
|
534
|
+
task_migration: migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
|
|
535
|
+
from_task_id: fromTaskId, to_task_id: toTaskId })) } };
|
|
536
|
+
}
|
|
519
537
|
// A revision directory is published before manifest activation. A crash during
|
|
520
538
|
// that window can leave an unreferenced directory containing only a journal
|
|
521
539
|
// stub. It is not a historical plan until its canonical plan artifact exists.
|
package/src/todo-store.mjs
CHANGED
|
@@ -17,10 +17,14 @@ export {
|
|
|
17
17
|
todoTaskCarrySemantics,
|
|
18
18
|
} from './todo-store-view.mjs';
|
|
19
19
|
import { randomBytes } from 'node:crypto';
|
|
20
|
+
import { gunzipSync, gzipSync } from 'node:zlib';
|
|
20
21
|
import { fsyncDirectory } from './fs-dir-sync.mjs';
|
|
21
22
|
import { renamePublishedFile, syncPublishedFile } from './fs-publish.mjs';
|
|
22
23
|
import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
|
|
23
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';
|
|
24
28
|
import {
|
|
25
29
|
lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir,
|
|
26
30
|
} from 'node:fs/promises';
|
|
@@ -328,9 +332,15 @@ async function readSealedSegments(repoRoot, journalRef, directoryName) {
|
|
|
328
332
|
}
|
|
329
333
|
|
|
330
334
|
async function readJournal(repoRoot, journalRef) {
|
|
331
|
-
|
|
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;
|
|
332
338
|
const segments = await readSealedSegments(repoRoot, journalRef, 'sealed');
|
|
333
|
-
|
|
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` }); }
|
|
334
344
|
const duplicateActive = segments.at(-1)?.bytes.equals(activeBytes) === true;
|
|
335
345
|
if (!duplicateActive) {
|
|
336
346
|
segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef) });
|
|
@@ -1706,6 +1716,11 @@ async function readTodoStoreView(options = {}) {
|
|
|
1706
1716
|
* unreadable. perf-store: validated once per process per unchanged plan.json (todo-version-memo).
|
|
1707
1717
|
*/
|
|
1708
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
|
+
}
|
|
1709
1724
|
const ref = `${base}/${version}/plan.json`;
|
|
1710
1725
|
const plan = await memoByFileIdentity([path.resolve(repoRoot, ref)], async () => {
|
|
1711
1726
|
const value = await readArtifact(repoRoot, ref, {
|
|
@@ -1717,6 +1732,110 @@ async function retainedPlanVersion(repoRoot, base, version) {
|
|
|
1717
1732
|
return plan === null ? null : { plan, journalRef: `${base}/${version}/journal/active.jsonl` };
|
|
1718
1733
|
}
|
|
1719
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
|
+
|
|
1720
1839
|
async function retainedVersionNames(repoRoot, base, activePlan) {
|
|
1721
1840
|
let names = [];
|
|
1722
1841
|
try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
|
|
@@ -2264,7 +2383,10 @@ async function withLock(repoRoot, callback, {
|
|
|
2264
2383
|
const result = await callback(assertHeld);
|
|
2265
2384
|
// The successor is already published: a failed repair leaves findings for the next locked write.
|
|
2266
2385
|
try {
|
|
2267
|
-
const
|
|
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,
|
|
2268
2390
|
{ assertHeld, actor: repairAfter.actor, recordedAt: repairAfter.recordedAt ?? new Date().toISOString() });
|
|
2269
2391
|
// Results stay digest-bound; the caller learns the repairs through its own callback.
|
|
2270
2392
|
if (repairs.length > 0 && typeof repairAfter.onRepairs === 'function') await repairAfter.onRepairs(repairs);
|
|
@@ -2764,10 +2886,9 @@ export async function rebindTodoCrossPlanDependencies(options = {}) {
|
|
|
2764
2886
|
))) fail('DEPENDENCY_INVALID', 'dependency_rebind_original_mismatch');
|
|
2765
2887
|
const predecessorBinding = source.revision?.predecessor;
|
|
2766
2888
|
if (!predecessorBinding) fail('DEPENDENCY_INVALID', 'dependency_rebind_predecessor_missing');
|
|
2767
|
-
const predecessor = await
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
});
|
|
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');
|
|
2771
2892
|
if (predecessor.project_id !== source.plan.project_id || predecessor.plan_key !== source.plan.plan_key
|
|
2772
2893
|
|| predecessor.plan_version !== predecessorBinding.plan_version
|
|
2773
2894
|
|| predecessor.plan_digest !== predecessorBinding.plan_digest) {
|
|
@@ -4949,39 +5070,18 @@ async function cleanupPhaseV3Staging(transaction, staged) {
|
|
|
4949
5070
|
|
|
4950
5071
|
export async function predecessorSourceInventory(repoRoot, previous) {
|
|
4951
5072
|
if (previous.revision?.source_inventory !== undefined) return previous.revision.source_inventory;
|
|
4952
|
-
|
|
4953
|
-
const
|
|
4954
|
-
|
|
4955
|
-
|
|
4956
|
-
|
|
4957
|
-
|
|
4958
|
-
|
|
4959
|
-
|
|
4960
|
-
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
}
|
|
4965
|
-
const visited = new Set();
|
|
4966
|
-
let digest = previous.plan.predecessor_plan_digest;
|
|
4967
|
-
while (digest !== null && !visited.has(digest) && visited.size < 512) {
|
|
4968
|
-
visited.add(digest);
|
|
4969
|
-
const candidate = plansByDigest.get(digest);
|
|
4970
|
-
if (candidate === undefined) break;
|
|
4971
|
-
const revisionBytes = await exactFileOrNull(path.join(candidate.directory, 'revision.json'));
|
|
4972
|
-
if (revisionBytes !== null) {
|
|
4973
|
-
let revision;
|
|
4974
|
-
try { revision = JSON.parse(decodeUtf8(revisionBytes,
|
|
4975
|
-
'STORE_INCONSISTENT', 'revision_invalid')); } catch { revision = null; }
|
|
4976
|
-
if (revision !== null && revisionBytes.equals(canonicalLine(revision))
|
|
4977
|
-
&& (validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
|
|
4978
|
-
&& revision.project_id === candidate.plan.project_id
|
|
4979
|
-
&& revision.plan_key === candidate.plan.plan_key
|
|
4980
|
-
&& canonicalizeTodoArtifact(revision.desired_plan)
|
|
4981
|
-
=== canonicalizeTodoArtifact(candidate.plan)
|
|
4982
|
-
&& revision.source_inventory !== undefined) return revision.source_inventory;
|
|
4983
|
-
}
|
|
4984
|
-
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;
|
|
4985
5085
|
}
|
|
4986
5086
|
return { active: [], excluded_tombstones: [] };
|
|
4987
5087
|
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* b10-plan-copy-per-add: a retained plan version keeps only what differs from its successor (Store internal, pure).
|
|
3
|
+
*
|
|
4
|
+
* Every revision used to leave a full plan.json, a revision.json that repeats the same plan, and a snapshot.json
|
|
5
|
+
* in its version directory forever (612 revisions = 475 MB for a 415 KB plan). Once a successor is active, the
|
|
6
|
+
* predecessor's three files are redundant: `compact.json` records the reverse patch (successor plan -> this plan),
|
|
7
|
+
* the revision without its repeated `desired_plan`, and the three digests readers look up. Nothing is dropped:
|
|
8
|
+
* `reconstructPlan` rebuilds the exact canonical plan, checked against `plan_digest` before anything is deleted.
|
|
9
|
+
*/
|
|
10
|
+
import { readFile } from 'node:fs/promises';
|
|
11
|
+
import { gunzipSync, gzipSync } from 'node:zlib';
|
|
12
|
+
import { canonicalizeTodoArtifact, isTodoDigest, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
|
|
13
|
+
|
|
14
|
+
export const TODO_VERSION_COMPACT_SCHEMA = 'lattice.todo_version_compact.v1';
|
|
15
|
+
export const TODO_VERSION_COMPACT_FILE = 'compact.json.gz';
|
|
16
|
+
|
|
17
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
18
|
+
const same = (left, right) => canonicalizeTodoArtifact(left) === canonicalizeTodoArtifact(right);
|
|
19
|
+
|
|
20
|
+
/** Patch node: {"=": value} replace, {"o": {key: node}, "x": [deleted keys]} object edit, {"a": [at, deleted, inserted]} splice. */
|
|
21
|
+
export function diffJson(from, to) {
|
|
22
|
+
if (isObject(from) && isObject(to)) {
|
|
23
|
+
const o = {}; const x = Object.keys(from).filter((key) => !(key in to));
|
|
24
|
+
for (const [key, value] of Object.entries(to)) {
|
|
25
|
+
if (!(key in from)) o[key] = { '=': value };
|
|
26
|
+
else if (!same(from[key], value)) o[key] = diffJson(from[key], value);
|
|
27
|
+
}
|
|
28
|
+
return { o, x };
|
|
29
|
+
}
|
|
30
|
+
if (Array.isArray(from) && Array.isArray(to)) {
|
|
31
|
+
const keys = from.map((item) => canonicalizeTodoArtifact(item)); const next = to.map((item) => canonicalizeTodoArtifact(item));
|
|
32
|
+
let head = 0;
|
|
33
|
+
while (head < keys.length && head < next.length && keys[head] === next[head]) head += 1;
|
|
34
|
+
let tail = 0;
|
|
35
|
+
while (tail < keys.length - head && tail < next.length - head
|
|
36
|
+
&& keys[keys.length - 1 - tail] === next[next.length - 1 - tail]) tail += 1;
|
|
37
|
+
return { a: [head, keys.length - head - tail, to.slice(head, next.length - tail)] };
|
|
38
|
+
}
|
|
39
|
+
return { '=': to };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function applyJsonPatch(from, patch) {
|
|
43
|
+
if ('=' in patch) return patch['='];
|
|
44
|
+
if ('a' in patch) {
|
|
45
|
+
const [at, deleted, inserted] = patch.a;
|
|
46
|
+
return [...from.slice(0, at), ...inserted, ...from.slice(at + deleted)];
|
|
47
|
+
}
|
|
48
|
+
const result = { ...from };
|
|
49
|
+
for (const key of patch.x) delete result[key];
|
|
50
|
+
for (const [key, node] of Object.entries(patch.o)) result[key] = applyJsonPatch(from[key], node);
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The compact record of `retained` once `anchor` (its direct successor, full) is active. Null when the round trip is not exact. */
|
|
55
|
+
export function buildVersionCompact({ retained, anchor, revision }) {
|
|
56
|
+
const patch = diffJson(anchor, retained);
|
|
57
|
+
if (!same(applyJsonPatch(anchor, patch), retained) || anchor.predecessor_plan_digest !== retained.plan_digest) return null;
|
|
58
|
+
const { desired_plan: repeated, ...slim } = revision ?? {};
|
|
59
|
+
if (revision && !same(repeated, retained)) return null;
|
|
60
|
+
const record = {
|
|
61
|
+
schema: TODO_VERSION_COMPACT_SCHEMA, project_id: retained.project_id, plan_key: retained.plan_key,
|
|
62
|
+
plan_version: retained.plan_version, plan_digest: retained.plan_digest,
|
|
63
|
+
predecessor_plan_digest: retained.predecessor_plan_digest ?? null,
|
|
64
|
+
predecessor_plan_version: revision?.predecessor?.plan_version ?? null, topology_digest: retained.topology_digest,
|
|
65
|
+
anchor_plan_version: anchor.plan_version, anchor_plan_digest: anchor.plan_digest,
|
|
66
|
+
plan_patch: patch, revision: revision ? slim : null, compact_digest: '',
|
|
67
|
+
};
|
|
68
|
+
record.compact_digest = todoSelfDigest(record, 'compact_digest');
|
|
69
|
+
return record;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function validateVersionCompact(value) {
|
|
73
|
+
const keys = ['schema', 'project_id', 'plan_key', 'plan_version', 'plan_digest', 'predecessor_plan_digest', 'predecessor_plan_version',
|
|
74
|
+
'topology_digest', 'anchor_plan_version', 'anchor_plan_digest', 'plan_patch', 'revision', 'compact_digest'];
|
|
75
|
+
return isObject(value) && Object.keys(value).length === keys.length && keys.every((key) => key in value)
|
|
76
|
+
&& value.schema === TODO_VERSION_COMPACT_SCHEMA
|
|
77
|
+
&& [value.project_id, value.plan_key, value.plan_version, value.anchor_plan_version].every(isTodoIdentifier)
|
|
78
|
+
&& [value.plan_digest, value.topology_digest, value.anchor_plan_digest, value.compact_digest].every(isTodoDigest)
|
|
79
|
+
&& (value.predecessor_plan_digest === null || isTodoDigest(value.predecessor_plan_digest))
|
|
80
|
+
&& (value.predecessor_plan_version === null || isTodoIdentifier(value.predecessor_plan_version))
|
|
81
|
+
&& isObject(value.plan_patch) && (value.revision === null || isObject(value.revision))
|
|
82
|
+
&& value.compact_digest === todoSelfDigest(value, 'compact_digest');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The exact plan of `record`, from its anchor's full plan. Throws when the result does not match plan_digest's plan. */
|
|
86
|
+
export function reconstructPlan(record, anchorPlan) {
|
|
87
|
+
if (anchorPlan.plan_digest !== record.anchor_plan_digest) throw new Error('compact_anchor_mismatch');
|
|
88
|
+
const plan = applyJsonPatch(anchorPlan, record.plan_patch);
|
|
89
|
+
if (plan.plan_digest !== record.plan_digest || plan.plan_version !== record.plan_version) throw new Error('compact_plan_mismatch');
|
|
90
|
+
return plan;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The revision a compact record stood in for, with its repeated desired_plan put back Null for a genesis version. */
|
|
94
|
+
export const reconstructRevision = (record, plan) => (record.revision === null ? null : { ...record.revision, desired_plan: plan });
|
|
95
|
+
|
|
96
|
+
/** The record as stored: canonical JSON line, gzip-packed (a revision's per-task migration is long and repetitive). */
|
|
97
|
+
export const packVersionCompact = (record) => gzipSync(Buffer.from(`${canonicalizeTodoArtifact(record)}\n`, 'utf8'), { level: 9 });
|
|
98
|
+
|
|
99
|
+
/** The compact record in `directory`, or null when there is none. Throws when the file is not a canonical, digest-true record. */
|
|
100
|
+
export async function readVersionCompact(directory, maxBytes = 8 * 1024 * 1024) {
|
|
101
|
+
let packed;
|
|
102
|
+
try { packed = await readFile(`${directory}/${TODO_VERSION_COMPACT_FILE}`); } catch (error) {
|
|
103
|
+
if (error?.code === 'ENOENT') return null;
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
const text = gunzipSync(packed, { maxOutputLength: maxBytes }).toString('utf8');
|
|
107
|
+
const value = JSON.parse(text);
|
|
108
|
+
if (text !== `${canonicalizeTodoArtifact(value)}\n` || !validateVersionCompact(value)) throw new Error('compact_record_invalid');
|
|
109
|
+
return value;
|
|
110
|
+
}
|