@quolu/lattice 0.79.5 → 0.81.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/schemas/lattice.plan_create_input.v4.schema.json +8 -4
- package/docs/schemas/lattice.todo_extraction.v3.schema.json +5 -3
- package/docs/schemas/lattice.todo_extraction.v4.schema.json +5 -3
- package/package.json +1 -1
- package/src/bridge-config.mjs +6 -7
- package/src/fs-publish.mjs +9 -0
- package/src/mcp-startup-receipt.mjs +3 -3
- package/src/plan-backchain.mjs +4 -3
- package/src/project-cli.mjs +22 -10
- package/src/runtime-multi-epoch-store.mjs +53 -13
- package/src/runtime-os-observation.mjs +18 -1
- package/src/seat-identity.mjs +23 -0
- package/src/store-lock.mjs +250 -0
- package/src/todo-cli.mjs +6 -0
- package/src/todo-contracts.mjs +95 -50
- package/src/todo-migration.mjs +35 -10
- package/src/todo-note-store.mjs +45 -12
- package/src/todo-readiness.mjs +154 -0
- package/src/todo-revision.mjs +7 -5
- package/src/todo-status.mjs +4 -33
- package/src/todo-store-git-transaction.mjs +11 -6
- package/src/todo-store-view.mjs +105 -0
- package/src/todo-store.mjs +602 -455
- package/src/artifact-contracts-v2.mjs +0 -325
- package/src/boundary-compiler.mjs +0 -712
- package/src/bounded-seam.mjs +0 -230
- package/src/control-compiler.mjs +0 -532
- package/src/rc1-black-box-oracle.mjs +0 -906
- package/src/rc1-comparison.mjs +0 -154
- package/src/rc1-evidence-bundle.mjs +0 -456
- package/src/rc1-v4-campaign.mjs +0 -708
- package/src/rc1-v4-transform.mjs +0 -467
- package/src/rc1-v5-artifact-set.mjs +0 -855
- package/src/rc1-v5-behavior-evidence.mjs +0 -594
- package/src/rc1-v5-campaign.mjs +0 -797
- package/src/rc1-v5-transform.mjs +0 -421
- package/src/rc1-v6-artifact-set.mjs +0 -807
- package/src/rc1-v6-behavior-evidence.mjs +0 -273
- package/src/rc1-v6-campaign.mjs +0 -623
- package/src/rc1-v6-causal-binding.mjs +0 -473
- package/src/rc1-v6-measurement.mjs +0 -313
- package/src/rc2-artifact-set.mjs +0 -1584
- package/src/rc2-campaign.mjs +0 -1495
- package/src/rc2-delivery-policy-front-end.mjs +0 -1079
- package/src/rc2-delivery-policy-oracle.mjs +0 -134
- package/src/rc2-delivery-policy-transform.mjs +0 -1127
- package/src/rc2-rc1-transfer-front-end.mjs +0 -511
- package/src/rc3-actual-dogfood.mjs +0 -652
- package/src/rc3-dogfood-scaffold.mjs +0 -315
- package/src/rc3-scripted-campaign.mjs +0 -1383
- package/src/rc4-stage1-dogfood.mjs +0 -673
- package/src/runtime-scripted-executor.mjs +0 -163
- package/src/runtime-worktree-executor.mjs +0 -199
- package/src/seam-transform.mjs +0 -554
- package/src/treatment-compiler.mjs +0 -728
- package/src/treatment-runner.mjs +0 -656
package/src/todo-store.mjs
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isDecoupledPhaseTodoPlanSchema,
|
|
3
|
+
isPhaseTodoPlanSchema,
|
|
4
|
+
isPhaselessTodoPlanSchema,
|
|
5
|
+
projectTodoCrossPlanDependencies,
|
|
6
|
+
localTaskRef,
|
|
7
|
+
removedTaskRef,
|
|
8
|
+
todoTaskCarrySemantics as taskSemantics,
|
|
9
|
+
} from './todo-store-view.mjs';
|
|
10
|
+
export {
|
|
11
|
+
isDecoupledPhaseTodoPlanSchema,
|
|
12
|
+
isPhaseTodoPlanSchema,
|
|
13
|
+
isPhaselessTodoPlanSchema,
|
|
14
|
+
projectTodoCrossPlanDependencies,
|
|
15
|
+
todoTaskCarrySemantics,
|
|
16
|
+
} from './todo-store-view.mjs';
|
|
1
17
|
import { randomBytes } from 'node:crypto';
|
|
2
18
|
import { fsyncDirectory } from './fs-dir-sync.mjs';
|
|
3
|
-
import { renamePublishedFile } from './fs-publish.mjs';
|
|
19
|
+
import { renamePublishedFile, syncPublishedFile } from './fs-publish.mjs';
|
|
20
|
+
import { StoreLockError, withStoreLock } from './store-lock.mjs';
|
|
4
21
|
import {
|
|
5
22
|
lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir,
|
|
6
23
|
} from 'node:fs/promises';
|
|
@@ -11,6 +28,7 @@ import {
|
|
|
11
28
|
TODO_PLAN_SCOPED_EVENT_KINDS,
|
|
12
29
|
canonicalizeTodoArtifact,
|
|
13
30
|
digestTodoArtifact,
|
|
31
|
+
explainTodoPlan,
|
|
14
32
|
exactRecord,
|
|
15
33
|
isStrictTodoTimestamp,
|
|
16
34
|
isTodoDigest,
|
|
@@ -62,6 +80,7 @@ const CROSS_PLAN_RECOVERY_CLAIMS_REF = `${STORE_ROOT_REF}/.cross-plan-recovery`;
|
|
|
62
80
|
const CROSS_PLAN_IMPORT_TRANSACTION_SCHEMA = 'lattice.todo_cross_plan_import_transaction.v1';
|
|
63
81
|
const SOURCE_CUTOVER_BARRIER_REF = `${STORE_ROOT_REF}/source-cutover-recovery.json`;
|
|
64
82
|
const SOURCE_CUTOVER_RECOVERY_CAPABILITY = Symbol('lattice.todo.source-cutover-recovery');
|
|
83
|
+
const STORE_LOCK_HELD = Symbol('lattice.todo.lock-held');
|
|
65
84
|
const MAX_FUTURE_SKEW_MS = 5 * 60 * 1_000;
|
|
66
85
|
const WRITER_CALLERS = new Set(['g4-migration', 'g5-authoring']);
|
|
67
86
|
const TODO_REVISION_SCHEMAS = Object.freeze([
|
|
@@ -70,6 +89,7 @@ const TODO_REVISION_SCHEMAS = Object.freeze([
|
|
|
70
89
|
const PHASE_TODO_REVISION_SCHEMAS = Object.freeze([
|
|
71
90
|
'lattice.phase_todo_revision.v1', 'lattice.phase_todo_revision.v2',
|
|
72
91
|
'lattice.phase_todo_revision.v3', 'lattice.phase_todo_revision.v4',
|
|
92
|
+
'lattice.phase_todo_revision.v5',
|
|
73
93
|
]);
|
|
74
94
|
|
|
75
95
|
export class TodoStoreError extends Error {
|
|
@@ -238,7 +258,10 @@ async function readJournal(repoRoot, journalRef) {
|
|
|
238
258
|
if (error?.code !== 'ENOENT') fail('STORE_CORRUPT', 'sealed_segment_read_failed');
|
|
239
259
|
}
|
|
240
260
|
const activeBytes = await readFile(state.absolute);
|
|
241
|
-
segments.
|
|
261
|
+
const duplicateActive = segments.at(-1)?.bytes.equals(activeBytes) === true;
|
|
262
|
+
if (!duplicateActive) {
|
|
263
|
+
segments.push({ ref: journalRef, bytes: activeBytes, events: parseJournalSegment(activeBytes, journalRef) });
|
|
264
|
+
}
|
|
242
265
|
const events = segments.flatMap(({ events: entries }) => entries);
|
|
243
266
|
const failures = verifyLinearHashChain({
|
|
244
267
|
entries: events,
|
|
@@ -271,7 +294,7 @@ async function readJournal(repoRoot, journalRef) {
|
|
|
271
294
|
? event.schema !== 'lattice.todo_event.v1' : !legacyOrImplicitPhaseTail(event)))) {
|
|
272
295
|
fail('STORE_CORRUPT', 'journal_schema_sequence_invalid');
|
|
273
296
|
}
|
|
274
|
-
return { segments, events, activeBytes };
|
|
297
|
+
return { segments, events, activeBytes: duplicateActive ? Buffer.alloc(0) : activeBytes };
|
|
275
298
|
}
|
|
276
299
|
|
|
277
300
|
/**
|
|
@@ -342,20 +365,6 @@ function emptyPhaseState(phaseId) {
|
|
|
342
365
|
// と衝突しない予約名として固定する。
|
|
343
366
|
export const TERMINAL_AUDIT_PHASE_ID = 'terminal-audit';
|
|
344
367
|
|
|
345
|
-
export function isPhaseTodoPlanSchema(schema) {
|
|
346
|
-
return ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(schema);
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
export function isDecoupledPhaseTodoPlanSchema(schema) {
|
|
350
|
-
return ['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(schema);
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
// CLI側(migrate/plan create/最後のdone)が「終端重監査が要る」ことを通知するために
|
|
354
|
-
// 同じ判定を再利用する。判定基準を二重管理しないよう、ここから公開する。
|
|
355
|
-
export function isPhaselessTodoPlanSchema(schema) {
|
|
356
|
-
return !isPhaseTodoPlanSchema(schema);
|
|
357
|
-
}
|
|
358
|
-
|
|
359
368
|
function terminalAuditPhase() {
|
|
360
369
|
return { phase_id: TERMINAL_AUDIT_PHASE_ID, title: '終端重監査', gate_policy: 'terminal-audit',
|
|
361
370
|
predecessor_phase_ids: [], required_evidence_slots: ['terminal-audit'] };
|
|
@@ -400,38 +409,6 @@ export function projectTodoCoordination(events) {
|
|
|
400
409
|
};
|
|
401
410
|
}
|
|
402
411
|
|
|
403
|
-
/**
|
|
404
|
-
* active plan群へ接続済みのplan跨ぎ依存線を投影する。
|
|
405
|
-
*
|
|
406
|
-
* eventはconsumer(to)planのplan-scoped chainへ積まれる。自動発見も暗黙補完もせず、
|
|
407
|
-
* 記録された線だけを返す。順序はtask identityで固定し、status/Ganttが同じ入力を見る。
|
|
408
|
-
*/
|
|
409
|
-
export function projectTodoCrossPlanDependencies(members) {
|
|
410
|
-
// 除去tombstoneを先に集め、指された接続を線として数えない(歴史は両eventとも残る)
|
|
411
|
-
const removed = new Set();
|
|
412
|
-
for (const member of members) for (const event of member.plan_scoped?.events ?? []) {
|
|
413
|
-
if (event.kind === 'cross_plan_dependency_removed') removed.add(event.payload.target_event_digest);
|
|
414
|
-
}
|
|
415
|
-
const dependencies = [];
|
|
416
|
-
for (const member of members) for (const event of member.plan_scoped?.events ?? []) {
|
|
417
|
-
if (event.kind !== 'cross_plan_dependency') continue;
|
|
418
|
-
if (removed.has(event.event_digest)) continue;
|
|
419
|
-
dependencies.push({
|
|
420
|
-
from: event.payload.from,
|
|
421
|
-
to: event.payload.to,
|
|
422
|
-
reason: event.payload.reason,
|
|
423
|
-
connected_by: event.actor,
|
|
424
|
-
connected_at: event.recorded_at,
|
|
425
|
-
event_digest: event.event_digest,
|
|
426
|
-
});
|
|
427
|
-
}
|
|
428
|
-
return dependencies.sort((left, right) => {
|
|
429
|
-
const key = (entry) => `${entry.from.project_id}\0${entry.from.plan_key}\0${entry.from.task_id}`
|
|
430
|
-
+ `\0${entry.to.project_id}\0${entry.to.plan_key}\0${entry.to.task_id}\0${entry.event_digest}`;
|
|
431
|
-
return key(left) < key(right) ? -1 : key(left) > key(right) ? 1 : 0;
|
|
432
|
-
});
|
|
433
|
-
}
|
|
434
|
-
|
|
435
412
|
function derivedPhaseStatus(plan, taskStates, phaseStates, phaseId) {
|
|
436
413
|
const state = phaseStates.get(phaseId);
|
|
437
414
|
// ADR 0148: closed_unauditedも他の終端状態と同じく確定済みとして扱う。ここへ足さないと、
|
|
@@ -1046,132 +1023,7 @@ function mergedTaskKey(refValue) {
|
|
|
1046
1023
|
return `${refValue.project_id}\0${refValue.plan_key}\0${refValue.task_id}`;
|
|
1047
1024
|
}
|
|
1048
1025
|
|
|
1049
|
-
|
|
1050
|
-
return new Map(store.members.flatMap((member) => member.tasks.map((taskValue) => ([
|
|
1051
|
-
mergedTaskKey({
|
|
1052
|
-
project_id: member.plan.project_id, plan_key: member.plan.plan_key, task_id: taskValue.task_id,
|
|
1053
|
-
}),
|
|
1054
|
-
taskValue.status,
|
|
1055
|
-
]))));
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
function mergedTaskPhase(store, taskKey) {
|
|
1059
|
-
for (const member of store.members) {
|
|
1060
|
-
const task = member.plan.tasks.find((entry) => mergedTaskKey({
|
|
1061
|
-
project_id: member.plan.project_id, plan_key: member.plan.plan_key, task_id: entry.task_id,
|
|
1062
|
-
}) === taskKey);
|
|
1063
|
-
if (task === undefined) continue;
|
|
1064
|
-
if (!isPhaseTodoPlanSchema(member.plan.schema)) return null;
|
|
1065
|
-
return { schema: member.plan.schema, plan_key: member.plan.plan_key, phase_id: task.phase_id,
|
|
1066
|
-
status: member.snapshot.phases.find(({ phase_id }) => phase_id === task.phase_id)?.status };
|
|
1067
|
-
}
|
|
1068
|
-
return undefined;
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
function mergedDependencyPhaseReady(store, predecessorKey, targetKey) {
|
|
1072
|
-
const predecessor = mergedTaskPhase(store, predecessorKey);
|
|
1073
|
-
const target = mergedTaskPhase(store, targetKey);
|
|
1074
|
-
if (predecessor === undefined) return false;
|
|
1075
|
-
if (predecessor === null) return true;
|
|
1076
|
-
if (isDecoupledPhaseTodoPlanSchema(predecessor.schema)) return true;
|
|
1077
|
-
if (target !== null && target !== undefined && predecessor.plan_key === target.plan_key
|
|
1078
|
-
&& predecessor.phase_id === target.phase_id) return true;
|
|
1079
|
-
return predecessor.status === 'accepted';
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
function mergedPhaseAcceptReady(store, targetKey) {
|
|
1083
|
-
for (const member of store.members) {
|
|
1084
|
-
if (!isDecoupledPhaseTodoPlanSchema(member.plan.schema)) continue;
|
|
1085
|
-
for (const edge of member.plan.phase_accept_dependencies) {
|
|
1086
|
-
if (mergedTaskKey(edge.to) !== targetKey) continue;
|
|
1087
|
-
const source = store.members.find((candidate) => candidate.plan.project_id === edge.from.project_id
|
|
1088
|
-
&& candidate.plan.plan_key === edge.from.plan_key);
|
|
1089
|
-
if (source?.snapshot.phases.find(({ phase_id }) => phase_id === edge.from.phase_id)?.status !== 'accepted') {
|
|
1090
|
-
return false;
|
|
1091
|
-
}
|
|
1092
|
-
}
|
|
1093
|
-
}
|
|
1094
|
-
return true;
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
function mergedPredecessorKeys(store, targetKey) {
|
|
1098
|
-
const result = [];
|
|
1099
|
-
for (const member of store.members) {
|
|
1100
|
-
for (const edge of member.plan.hard_dependencies) {
|
|
1101
|
-
if (mergedTaskKey(edge.to) === targetKey) result.push(mergedTaskKey(edge.from));
|
|
1102
|
-
}
|
|
1103
|
-
for (const join of member.plan.joins) {
|
|
1104
|
-
if (mergedTaskKey(join.before) === targetKey) {
|
|
1105
|
-
for (const after of join.after) result.push(mergedTaskKey(after));
|
|
1106
|
-
}
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1109
|
-
for (const dependency of projectTodoCrossPlanDependencies(store.members)) {
|
|
1110
|
-
if (mergedTaskKey(dependency.to) === targetKey) result.push(mergedTaskKey(dependency.from));
|
|
1111
|
-
}
|
|
1112
|
-
return [...new Set(result)];
|
|
1113
|
-
}
|
|
1114
|
-
|
|
1115
|
-
function mergedSuccessorKeys(store, targetKey) {
|
|
1116
|
-
const result = [];
|
|
1117
|
-
for (const member of store.members) {
|
|
1118
|
-
for (const edge of member.plan.hard_dependencies) {
|
|
1119
|
-
if (mergedTaskKey(edge.from) === targetKey) result.push(mergedTaskKey(edge.to));
|
|
1120
|
-
}
|
|
1121
|
-
for (const join of member.plan.joins) {
|
|
1122
|
-
if (join.after.some((after) => mergedTaskKey(after) === targetKey)) {
|
|
1123
|
-
result.push(mergedTaskKey(join.before));
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
}
|
|
1127
|
-
for (const dependency of projectTodoCrossPlanDependencies(store.members)) {
|
|
1128
|
-
if (mergedTaskKey(dependency.from) === targetKey) result.push(mergedTaskKey(dependency.to));
|
|
1129
|
-
}
|
|
1130
|
-
return [...new Set(result)];
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
function validateMergedTransition(store, member, event) {
|
|
1134
|
-
const targetKey = mergedTaskKey({
|
|
1135
|
-
project_id: member.plan.project_id, plan_key: member.plan.plan_key, task_id: event.task_id,
|
|
1136
|
-
});
|
|
1137
|
-
const states = mergedTaskStates(store);
|
|
1138
|
-
const taskDependenciesDone = mergedPredecessorKeys(store, targetKey)
|
|
1139
|
-
.every((key) => states.get(key) === 'done' && mergedDependencyPhaseReady(store, key, targetKey));
|
|
1140
|
-
const phaseAcceptReady = mergedPhaseAcceptReady(store, targetKey);
|
|
1141
|
-
const dependenciesDone = taskDependenciesDone && phaseAcceptReady;
|
|
1142
|
-
if (event.kind === 'start' && event.payload.start_mode !== 'historical_import'
|
|
1143
|
-
&& event.payload.start_mode !== 'rebind'
|
|
1144
|
-
&& (!phaseAcceptReady || (!taskDependenciesDone && event.payload.override_reason === null))) {
|
|
1145
|
-
fail('STORE_INCONSISTENT', 'invalid_start_transition');
|
|
1146
|
-
}
|
|
1147
|
-
if (event.kind === 'done' && event.payload.done_mode === 'authored' && !dependenciesDone) {
|
|
1148
|
-
fail('STORE_INCONSISTENT', 'invalid_done_transition');
|
|
1149
|
-
}
|
|
1150
|
-
if (event.kind === 'reopen' && event.payload.override_reason === null) {
|
|
1151
|
-
const startedSuccessor = mergedSuccessorKeys(store, targetKey)
|
|
1152
|
-
.some((key) => states.get(key) !== 'pending');
|
|
1153
|
-
if (startedSuccessor) {
|
|
1154
|
-
fail('STORE_INCONSISTENT', 'reopen_has_started_successor', {
|
|
1155
|
-
next_action: `lattice todo split --plan ${member.plan.plan_key} --input <file>`,
|
|
1156
|
-
});
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
if (event.kind === 'phase_reopen' && event.payload.override_reason === null) {
|
|
1160
|
-
const startedSuccessor = member.plan.schema === 'lattice.todo_plan.v4'
|
|
1161
|
-
? member.plan.tasks.filter(({ phase_id }) => phase_id === event.phase_id)
|
|
1162
|
-
.map(({ task_id }) => mergedTaskKey({ project_id: member.plan.project_id,
|
|
1163
|
-
plan_key: member.plan.plan_key, task_id }))
|
|
1164
|
-
.flatMap((key) => mergedSuccessorKeys(store, key))
|
|
1165
|
-
.some((key) => states.get(key) !== 'pending')
|
|
1166
|
-
: store.members.some((candidate) => isDecoupledPhaseTodoPlanSchema(candidate.plan.schema)
|
|
1167
|
-
&& candidate.plan.phase_accept_dependencies.some((edge) => (
|
|
1168
|
-
edge.from.project_id === member.plan.project_id
|
|
1169
|
-
&& edge.from.plan_key === member.plan.plan_key && edge.from.phase_id === event.phase_id
|
|
1170
|
-
&& states.get(mergedTaskKey(edge.to)) !== 'pending'
|
|
1171
|
-
)));
|
|
1172
|
-
if (startedSuccessor) fail('STORE_INCONSISTENT', 'phase_reopen_has_started_successor');
|
|
1173
|
-
}
|
|
1174
|
-
}
|
|
1026
|
+
// Temporary adapter until Store receives the Plan callback from its caller.
|
|
1175
1027
|
|
|
1176
1028
|
/**
|
|
1177
1029
|
* refsから辿れるobject idの集合。repositoryごとに1度だけ数え、以後は使い回す。
|
|
@@ -1505,7 +1357,61 @@ function verifyPlanNarrativeAnchors(repoRoot, plan, trustedPlan = null, cache =
|
|
|
1505
1357
|
}
|
|
1506
1358
|
}
|
|
1507
1359
|
|
|
1360
|
+
function recoverableReadError(error) {
|
|
1361
|
+
return error instanceof TodoStoreError && [
|
|
1362
|
+
'manifest_journal_head_mismatch', 'snapshot_stale',
|
|
1363
|
+
'source_cutover_recovery_required', 'cross_plan_import_recovery_required',
|
|
1364
|
+
].includes(error.detail.reason);
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1508
1367
|
export async function readTodoStore(options = {}) {
|
|
1368
|
+
const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
|
|
1369
|
+
let view;
|
|
1370
|
+
let observedError;
|
|
1371
|
+
try {
|
|
1372
|
+
view = await readTodoStoreView(options);
|
|
1373
|
+
const lockPresent = await lstat(path.join(repoRoot, STORE_ROOT_REF, '.write.lock'))
|
|
1374
|
+
.then(() => true, (error) => { if (error?.code === 'ENOENT') return false; throw error; });
|
|
1375
|
+
if (!view.snapshot_stale && !lockPresent) return view;
|
|
1376
|
+
} catch (error) {
|
|
1377
|
+
if (!recoverableReadError(error)) throw error;
|
|
1378
|
+
observedError = error;
|
|
1379
|
+
}
|
|
1380
|
+
try { return await withLock(repoRoot, () => readTodoStoreLocked(options)); }
|
|
1381
|
+
catch (error) {
|
|
1382
|
+
// A concurrent writer owns its publication window; stable readers retry it.
|
|
1383
|
+
if (error instanceof TodoStoreError && error.code === 'STORE_WRITE_CONFLICT') {
|
|
1384
|
+
if (view) return view;
|
|
1385
|
+
if (error.detail.reason !== 'store_locked' || error.detail.cause) throw error;
|
|
1386
|
+
if (observedError) throw observedError;
|
|
1387
|
+
}
|
|
1388
|
+
throw error;
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
async function readTodoStoreLocked(options = {}) {
|
|
1393
|
+
const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
|
|
1394
|
+
if (options.sourceCutoverRecoveryCapability !== SOURCE_CUTOVER_RECOVERY_CAPABILITY) {
|
|
1395
|
+
await recoverSourceCutover(repoRoot, options.now);
|
|
1396
|
+
}
|
|
1397
|
+
await recoverCrossPlanImports(repoRoot);
|
|
1398
|
+
const recovery = { manifestDirty: false };
|
|
1399
|
+
const store = await readTodoStoreView({ ...options, recovery });
|
|
1400
|
+
// Every member and merged graph has validated before any derived publication.
|
|
1401
|
+
for (const member of store.members) {
|
|
1402
|
+
if (!member.snapshot_stale) continue;
|
|
1403
|
+
await atomicWrite(path.resolve(repoRoot, member.descriptor.snapshot_ref), canonicalLine(member.snapshot));
|
|
1404
|
+
member.snapshot_stale = false;
|
|
1405
|
+
}
|
|
1406
|
+
if (recovery.manifestDirty) {
|
|
1407
|
+
store.manifest.manifest_digest = todoSelfDigest(store.manifest, 'manifest_digest');
|
|
1408
|
+
await atomicWrite(path.resolve(repoRoot, MANIFEST_REF), canonicalLine(store.manifest));
|
|
1409
|
+
}
|
|
1410
|
+
store.snapshot_stale = false;
|
|
1411
|
+
return store;
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
async function readTodoStoreView(options = {}) {
|
|
1509
1415
|
const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
|
|
1510
1416
|
const barrier = await exactFileOrNull(path.resolve(repoRoot, SOURCE_CUTOVER_BARRIER_REF));
|
|
1511
1417
|
if (barrier !== null) {
|
|
@@ -1540,7 +1446,12 @@ export async function readTodoStore(options = {}) {
|
|
|
1540
1446
|
}
|
|
1541
1447
|
const journal = await readJournal(repoRoot, descriptor.journal_ref);
|
|
1542
1448
|
if (journal.events.at(-1).event_digest !== descriptor.journal_head_digest) {
|
|
1543
|
-
|
|
1449
|
+
if (!options.recovery || !journal.events.some(({ event_digest: digest }) => (
|
|
1450
|
+
digest === descriptor.journal_head_digest))) {
|
|
1451
|
+
fail('STORE_INCONSISTENT', 'manifest_journal_head_mismatch');
|
|
1452
|
+
}
|
|
1453
|
+
options.recovery.manifestDirty = true;
|
|
1454
|
+
descriptor.journal_head_digest = journal.events.at(-1).event_digest;
|
|
1544
1455
|
}
|
|
1545
1456
|
let revision = null;
|
|
1546
1457
|
const genesis = journal.events[0];
|
|
@@ -1625,7 +1536,7 @@ export async function readTodoStore(options = {}) {
|
|
|
1625
1536
|
'artifact_eol_converted'].includes(error.detail.reason)) snapshotStale = true;
|
|
1626
1537
|
else throw error;
|
|
1627
1538
|
}
|
|
1628
|
-
if (options.forWrite === true && snapshotStale) fail('STORE_WRITE_REFUSED', 'snapshot_stale');
|
|
1539
|
+
if (options.forWrite === true && snapshotStale && !options.recovery) fail('STORE_WRITE_REFUSED', 'snapshot_stale');
|
|
1629
1540
|
// 導出済みphase状態(ADR 0147)。snapshot artifactの形式(v1/v2)には縛られず、v4/v5・
|
|
1630
1541
|
// phase無しplanのどちらでも同じ形(暗黙のterminal-audit Phase込み)で常に埋める。
|
|
1631
1542
|
// 消費者はここを読み、snapshot.phases(v1には存在しない)を直接読まない。
|
|
@@ -1701,11 +1612,7 @@ async function atomicWrite(absolute, bytes) {
|
|
|
1701
1612
|
try {
|
|
1702
1613
|
handle = await open(temporary, 'wx', 0o600);
|
|
1703
1614
|
await handle.writeFile(bytes);
|
|
1704
|
-
|
|
1705
|
-
try { await handle.sync(); } catch (syncError) {
|
|
1706
|
-
if (!(process.platform === 'linux' && /^\/mnt\//.test(absolute) && syncError?.code === 'EIO')) throw syncError;
|
|
1707
|
-
process.stderr.write(`lattice: fsync skipped (WSL2/NTFS EIO) ${absolute}\n`);
|
|
1708
|
-
}
|
|
1615
|
+
await syncPublishedFile(handle, absolute);
|
|
1709
1616
|
await handle.close(); handle = null;
|
|
1710
1617
|
await renamePublishedFile(temporary, absolute);
|
|
1711
1618
|
await fsyncDirectory(path.dirname(absolute));
|
|
@@ -1723,10 +1630,7 @@ async function atomicWriteMode(absolute, bytes, mode) {
|
|
|
1723
1630
|
try {
|
|
1724
1631
|
handle = await open(temporary, 'wx', mode);
|
|
1725
1632
|
await handle.writeFile(bytes); await handle.chmod(mode);
|
|
1726
|
-
|
|
1727
|
-
if (!(process.platform === 'linux' && /^\/mnt\//.test(absolute) && syncError?.code === 'EIO')) throw syncError;
|
|
1728
|
-
process.stderr.write(`lattice: fsync skipped (WSL2/NTFS EIO) ${absolute}\n`);
|
|
1729
|
-
}
|
|
1633
|
+
await syncPublishedFile(handle, absolute);
|
|
1730
1634
|
await handle.close(); handle = null;
|
|
1731
1635
|
await renamePublishedFile(temporary, absolute);
|
|
1732
1636
|
await fsyncDirectory(path.dirname(absolute));
|
|
@@ -1737,105 +1641,42 @@ async function atomicWriteMode(absolute, bytes, mode) {
|
|
|
1737
1641
|
}
|
|
1738
1642
|
|
|
1739
1643
|
|
|
1740
|
-
async function
|
|
1741
|
-
|
|
1742
|
-
|
|
1644
|
+
async function withLock(repoRoot, callback, {
|
|
1645
|
+
onProtocolStage = null, lockCapability = null, initialize = false,
|
|
1646
|
+
} = {}) {
|
|
1647
|
+
if (lockCapability === STORE_LOCK_HELD) return callback();
|
|
1743
1648
|
try {
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1649
|
+
if (!initialize) {
|
|
1650
|
+
const root = await lstat(path.join(repoRoot, STORE_ROOT_REF)).catch((error) => {
|
|
1651
|
+
if (error?.code === 'ENOENT') fail('STORE_INCONSISTENT', 'artifact_missing', { ref: MANIFEST_REF });
|
|
1652
|
+
throw error;
|
|
1653
|
+
});
|
|
1654
|
+
const parent = await lstat(path.join(repoRoot, '.lattice')).catch((error) => {
|
|
1655
|
+
if (error?.code === 'ENOENT') fail('STORE_INCONSISTENT', 'artifact_missing', { ref: MANIFEST_REF });
|
|
1656
|
+
throw error;
|
|
1657
|
+
});
|
|
1658
|
+
if (!root.isDirectory() || root.isSymbolicLink()
|
|
1659
|
+
|| !parent.isDirectory() || parent.isSymbolicLink()) {
|
|
1660
|
+
fail('STORE_INCONSISTENT', 'unsafe_artifact_path', { ref: STORE_ROOT_REF });
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
return await withStoreLock({
|
|
1664
|
+
lockPath: path.join(repoRoot, STORE_ROOT_REF, '.write.lock'),
|
|
1665
|
+
createParent: initialize,
|
|
1666
|
+
recoveryClaimsPath: path.join(repoRoot, CROSS_PLAN_RECOVERY_CLAIMS_REF),
|
|
1667
|
+
onRecoveryClaim: typeof onProtocolStage === 'function'
|
|
1668
|
+
? () => onProtocolStage('cross_plan_lock_recovery_mutex_acquired') : null,
|
|
1669
|
+
}, callback);
|
|
1747
1670
|
} catch (error) {
|
|
1748
|
-
|
|
1749
|
-
await rm(lockRef, { force: true });
|
|
1671
|
+
if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
|
|
1750
1672
|
throw error;
|
|
1751
1673
|
}
|
|
1752
1674
|
}
|
|
1753
1675
|
|
|
1754
|
-
async function staleWriteLockOwner(lockRef) {
|
|
1755
|
-
let record;
|
|
1756
|
-
try { record = JSON.parse((await readFile(lockRef)).toString('utf8')); }
|
|
1757
|
-
catch { return false; }
|
|
1758
|
-
if (!exactRecord(record, ['pid']) || !Number.isSafeInteger(record.pid) || record.pid <= 0) return false;
|
|
1759
|
-
try {
|
|
1760
|
-
process.kill(record.pid, 0);
|
|
1761
|
-
return false;
|
|
1762
|
-
} catch (error) {
|
|
1763
|
-
return error?.code === 'ESRCH';
|
|
1764
|
-
}
|
|
1765
|
-
}
|
|
1766
|
-
|
|
1767
|
-
function processIsDead(pid) {
|
|
1768
|
-
try {
|
|
1769
|
-
process.kill(pid, 0);
|
|
1770
|
-
return false;
|
|
1771
|
-
} catch (error) {
|
|
1772
|
-
return error?.code === 'ESRCH';
|
|
1773
|
-
}
|
|
1774
|
-
}
|
|
1775
|
-
|
|
1776
|
-
async function acquireCrossPlanRecoveryClaim(recoveryClaimsRef) {
|
|
1777
|
-
await mkdir(recoveryClaimsRef, { recursive: true, mode: 0o700 });
|
|
1778
|
-
const claimOrder = process.hrtime.bigint().toString().padStart(20, '0');
|
|
1779
|
-
const claimName = `${claimOrder}-${process.pid}-${randomBytes(8).toString('hex')}`;
|
|
1780
|
-
const claimRef = path.join(recoveryClaimsRef, claimName);
|
|
1781
|
-
await mkdir(claimRef, { mode: 0o700 });
|
|
1782
|
-
for (const entry of await readdir(recoveryClaimsRef, { withFileTypes: true })) {
|
|
1783
|
-
if (!entry.isDirectory() || entry.name === claimName) continue;
|
|
1784
|
-
const parts = entry.name.split('-', 3);
|
|
1785
|
-
const pid = Number(parts.length === 2 ? parts[0] : parts[1]);
|
|
1786
|
-
if (Number.isSafeInteger(pid) && pid > 0 && processIsDead(pid)) {
|
|
1787
|
-
await rm(path.join(recoveryClaimsRef, entry.name), { recursive: true, force: true });
|
|
1788
|
-
}
|
|
1789
|
-
}
|
|
1790
|
-
const candidates = (await readdir(recoveryClaimsRef)).sort();
|
|
1791
|
-
if (candidates[0] === claimName) return claimRef;
|
|
1792
|
-
await rmdir(claimRef);
|
|
1793
|
-
return null;
|
|
1794
|
-
}
|
|
1795
|
-
|
|
1796
|
-
async function recoverCrossPlanWriteLock(lockRef, recoveryClaimsRef, onProtocolStage) {
|
|
1797
|
-
const claimRef = await acquireCrossPlanRecoveryClaim(recoveryClaimsRef);
|
|
1798
|
-
if (claimRef === null) return undefined;
|
|
1799
|
-
try {
|
|
1800
|
-
if (typeof onProtocolStage === 'function') await onProtocolStage('cross_plan_lock_recovery_mutex_acquired');
|
|
1801
|
-
if (!await staleWriteLockOwner(lockRef)) return undefined;
|
|
1802
|
-
await rm(lockRef, { force: true });
|
|
1803
|
-
try { return await createWriteLock(lockRef, { recordOwner: true }); }
|
|
1804
|
-
catch (error) {
|
|
1805
|
-
if (error?.code === 'EEXIST') return undefined;
|
|
1806
|
-
throw error;
|
|
1807
|
-
}
|
|
1808
|
-
} finally {
|
|
1809
|
-
await rm(claimRef, { recursive: true, force: true });
|
|
1810
|
-
try { await rmdir(recoveryClaimsRef); }
|
|
1811
|
-
catch (error) {
|
|
1812
|
-
if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error;
|
|
1813
|
-
}
|
|
1814
|
-
}
|
|
1815
|
-
}
|
|
1816
|
-
|
|
1817
|
-
async function withLock(repoRoot, callback, { recoverDeadLock = false, onProtocolStage = null } = {}) {
|
|
1818
|
-
const root = path.join(repoRoot, STORE_ROOT_REF);
|
|
1819
|
-
await mkdir(root, { recursive: true });
|
|
1820
|
-
const lockRef = path.join(root, '.write.lock');
|
|
1821
|
-
const recoveryClaimsRef = path.join(repoRoot, CROSS_PLAN_RECOVERY_CLAIMS_REF);
|
|
1822
|
-
let handle;
|
|
1823
|
-
try { handle = await createWriteLock(lockRef, { recordOwner: recoverDeadLock }); }
|
|
1824
|
-
catch (error) {
|
|
1825
|
-
if (error?.code !== 'EEXIST') throw error;
|
|
1826
|
-
if (recoverDeadLock) {
|
|
1827
|
-
handle = await recoverCrossPlanWriteLock(lockRef, recoveryClaimsRef, onProtocolStage);
|
|
1828
|
-
}
|
|
1829
|
-
}
|
|
1830
|
-
if (handle === undefined) fail('STORE_WRITE_CONFLICT', 'store_locked');
|
|
1831
|
-
try { return await callback(); }
|
|
1832
|
-
finally { await handle.close(); await rm(lockRef, { force: true }); }
|
|
1833
|
-
}
|
|
1834
|
-
|
|
1835
1676
|
export async function rebuildTodoSnapshot(options = {}) {
|
|
1836
1677
|
const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
|
|
1837
1678
|
return withLock(repoRoot, async () => {
|
|
1838
|
-
const store = await
|
|
1679
|
+
const store = await readTodoStoreLocked({ repoRoot, now: options.now });
|
|
1839
1680
|
const member = store.members.find(({ descriptor }) => descriptor.plan_key === options.planKey);
|
|
1840
1681
|
if (!member) fail('STORE_INCONSISTENT', 'plan_not_active');
|
|
1841
1682
|
await atomicWrite(path.resolve(repoRoot, member.descriptor.snapshot_ref), canonicalLine(member.snapshot));
|
|
@@ -2038,9 +1879,12 @@ async function enforceTodoStructureLifecycleGate(repoRoot, member, eventInput) {
|
|
|
2038
1879
|
|
|
2039
1880
|
export async function appendTodoEvent(options = {}) {
|
|
2040
1881
|
requireWriter(options.writer, 'g5-authoring');
|
|
1882
|
+
if (typeof options.validateProspectiveEvent !== 'function') {
|
|
1883
|
+
throw new TypeError('appendTodoEvent requires a Plan-supplied validateProspectiveEvent');
|
|
1884
|
+
}
|
|
2041
1885
|
const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
|
|
2042
1886
|
return withLock(repoRoot, async () => {
|
|
2043
|
-
const store = await
|
|
1887
|
+
const store = await readTodoStoreLocked({
|
|
2044
1888
|
repoRoot, forWrite: true, now: options.now,
|
|
2045
1889
|
// 修理扉は除去event(tombstone)の書込みだけに開く。それ以外の書込みは従来どおり
|
|
2046
1890
|
// binding_stale で fail closed する(validateMergedGraph の注記を参照)
|
|
@@ -2086,7 +1930,12 @@ export async function appendTodoEvent(options = {}) {
|
|
|
2086
1930
|
fail('STORE_WRITE_CONFLICT', 'historical_import_writer_required');
|
|
2087
1931
|
}
|
|
2088
1932
|
// Validate the prospective history, including hard evidence and transitions, before any write.
|
|
2089
|
-
|
|
1933
|
+
const validation = options.validateProspectiveEvent({ store, member, event });
|
|
1934
|
+
if (validation?.ok === false) {
|
|
1935
|
+
const { reason, ...detail } = validation.detail;
|
|
1936
|
+
fail(validation.code, reason, detail);
|
|
1937
|
+
}
|
|
1938
|
+
if (validation?.ok !== true) throw new TypeError('prospective validator must return an ok result');
|
|
2090
1939
|
const appendSourceCache = { commits: new Set(), blobs: new Map() };
|
|
2091
1940
|
prefetchVerificationObjects(store.manifest, repoRoot,
|
|
2092
1941
|
[...member.journal.events, event], appendSourceCache);
|
|
@@ -2122,6 +1971,7 @@ export async function appendTodoEvent(options = {}) {
|
|
|
2122
1971
|
} else {
|
|
2123
1972
|
await atomicWrite(activeAbsolute, Buffer.concat([member.journal.activeBytes, eventBytes]));
|
|
2124
1973
|
}
|
|
1974
|
+
await protocolStage(options, 'event_journal_published');
|
|
2125
1975
|
const tasks = replay(member.plan, [...member.journal.events, event], {
|
|
2126
1976
|
now: options.now ? new Date(options.now) : new Date(),
|
|
2127
1977
|
verifyEvidence: evidenceVerifier(store.manifest, repoRoot, false),
|
|
@@ -2129,9 +1979,11 @@ export async function appendTodoEvent(options = {}) {
|
|
|
2129
1979
|
});
|
|
2130
1980
|
const snapshot = snapshotFor(member.plan, [...member.journal.events, event], tasks);
|
|
2131
1981
|
await atomicWrite(path.resolve(repoRoot, member.descriptor.snapshot_ref), canonicalLine(snapshot));
|
|
1982
|
+
await protocolStage(options, 'event_snapshot_published');
|
|
2132
1983
|
member.descriptor.journal_head_digest = event.event_digest;
|
|
2133
1984
|
store.manifest.manifest_digest = todoSelfDigest(store.manifest, 'manifest_digest');
|
|
2134
1985
|
await atomicWrite(path.resolve(repoRoot, MANIFEST_REF), canonicalLine(store.manifest));
|
|
1986
|
+
await protocolStage(options, 'event_manifest_published');
|
|
2135
1987
|
// snapshot artifactの形式(v1/v2)はplanのschemaで決まったまま変えない。呼び出し側
|
|
2136
1988
|
// (todo-cli.mjsのphaseMutation・done advisory)がPhase状態(暗黙のterminal-audit含む)を
|
|
2137
1989
|
// 見るための導出ビューは、snapshotと分けてここで別途返す。
|
|
@@ -2203,7 +2055,12 @@ export function buildTodoPlan(input) {
|
|
|
2203
2055
|
? { phase_accept_dependencies: plan.phase_accept_dependencies } : {}),
|
|
2204
2056
|
});
|
|
2205
2057
|
plan.plan_digest = todoSelfDigest(plan, 'plan_digest');
|
|
2206
|
-
if (!validateTodoPlan(plan))
|
|
2058
|
+
if (!validateTodoPlan(plan)) {
|
|
2059
|
+
const { reason, path: pointer, ...values } = explainTodoPlan(plan);
|
|
2060
|
+
throw Object.assign(new TypeError('todo plan input violates its declared schema'), {
|
|
2061
|
+
detail: { violation_kind: reason, pointer, ...values },
|
|
2062
|
+
});
|
|
2063
|
+
}
|
|
2207
2064
|
return plan;
|
|
2208
2065
|
}
|
|
2209
2066
|
|
|
@@ -2622,7 +2479,17 @@ async function finalizeVisibleCrossPlanImport(repoRoot, transaction, { removeTra
|
|
|
2622
2479
|
ref: artifact.staged_ref,
|
|
2623
2480
|
});
|
|
2624
2481
|
}
|
|
2625
|
-
|
|
2482
|
+
const eventBytes = canonicalLine(transaction.marker.events[0]);
|
|
2483
|
+
if (!bytes.subarray(-eventBytes.length).equals(eventBytes)) {
|
|
2484
|
+
fail('STORE_INCONSISTENT', 'cross_plan_transaction_staging_digest_mismatch', { ref: artifact.staged_ref });
|
|
2485
|
+
}
|
|
2486
|
+
const target = await pathState(repoRoot, artifact.ref, 'STORE_INCONSISTENT', { missing: true });
|
|
2487
|
+
const current = target === null ? Buffer.alloc(0) : await readFile(target.absolute);
|
|
2488
|
+
const before = bytes.subarray(0, bytes.length - eventBytes.length);
|
|
2489
|
+
if (!current.equals(before) && !current.equals(bytes)) {
|
|
2490
|
+
fail('STORE_INCONSISTENT', 'cross_plan_transaction_staging_digest_mismatch', { ref: artifact.ref });
|
|
2491
|
+
}
|
|
2492
|
+
if (!current.equals(bytes)) await atomicWrite(path.resolve(repoRoot, artifact.ref), bytes);
|
|
2626
2493
|
}
|
|
2627
2494
|
if (removeTransaction) {
|
|
2628
2495
|
await rm(path.resolve(repoRoot, transaction.transactionRef), { recursive: true, force: true });
|
|
@@ -2648,16 +2515,13 @@ async function assertNoCrossPlanImportRecoveryNeeded(repoRoot) {
|
|
|
2648
2515
|
plan_key: transaction.marker.descriptor.plan_key,
|
|
2649
2516
|
transaction_digest: transaction.marker.transaction_digest,
|
|
2650
2517
|
state: visible ? 'manifest_activated' : 'pre_activation',
|
|
2651
|
-
next_action: '
|
|
2518
|
+
next_action: 'lattice todo status --json',
|
|
2652
2519
|
});
|
|
2653
2520
|
}
|
|
2654
2521
|
|
|
2655
|
-
async function recoverCrossPlanImports(repoRoot
|
|
2522
|
+
async function recoverCrossPlanImports(repoRoot) {
|
|
2656
2523
|
const transactions = await crossPlanImportTransactions(repoRoot);
|
|
2657
2524
|
if (transactions.length === 0) return [];
|
|
2658
|
-
if (!transactions.every(({ marker }) => marker.transaction_digest === expectedTransactionDigest)) {
|
|
2659
|
-
await assertNoCrossPlanImportRecoveryNeeded(repoRoot);
|
|
2660
|
-
}
|
|
2661
2525
|
let manifest;
|
|
2662
2526
|
try {
|
|
2663
2527
|
manifest = await readArtifact(repoRoot, MANIFEST_REF, {
|
|
@@ -2686,7 +2550,7 @@ async function recoverCrossPlanImports(repoRoot, { expectedTransactionDigest })
|
|
|
2686
2550
|
}
|
|
2687
2551
|
|
|
2688
2552
|
async function recoveredImportedPlanResult(repoRoot, marker, now) {
|
|
2689
|
-
const store = await
|
|
2553
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now });
|
|
2690
2554
|
const member = store.members.find(({ descriptor }) => descriptor.plan_key === marker.descriptor.plan_key);
|
|
2691
2555
|
if (member === undefined) fail('STORE_INCONSISTENT', 'cross_plan_transaction_recovery_missing_plan');
|
|
2692
2556
|
return {
|
|
@@ -2706,7 +2570,7 @@ async function appendExistingCrossPlanDependency(options) {
|
|
|
2706
2570
|
}
|
|
2707
2571
|
const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
|
|
2708
2572
|
return withLock(repoRoot, async () => {
|
|
2709
|
-
const store = await
|
|
2573
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
2710
2574
|
const source = store.members.find(({ plan }) => plan.project_id === options.connectionPlan.project_id
|
|
2711
2575
|
&& plan.plan_key === options.connectionPlan.plan_key);
|
|
2712
2576
|
if (source === undefined) {
|
|
@@ -2733,7 +2597,7 @@ async function appendExistingCrossPlanDependency(options) {
|
|
|
2733
2597
|
snapshot: source.snapshot, descriptor: source.descriptor,
|
|
2734
2598
|
crossPlanDependencies: prepared.events, connectionOnly: true,
|
|
2735
2599
|
};
|
|
2736
|
-
}, {
|
|
2600
|
+
}, { onProtocolStage: options.onProtocolStage });
|
|
2737
2601
|
}
|
|
2738
2602
|
|
|
2739
2603
|
/** G4-only atomic import, with optional all-or-nothing store bootstrap. */
|
|
@@ -2750,28 +2614,95 @@ export async function appendImportedPlan(options = {}) {
|
|
|
2750
2614
|
if (error?.code === 'ENOENT') return bootstrapImportedPlan(repoRoot, options);
|
|
2751
2615
|
throw error;
|
|
2752
2616
|
}
|
|
2617
|
+
if (await isUninitializedTodoStore({ repoRoot })) {
|
|
2618
|
+
fail('STORE_INCONSISTENT', 'artifact_missing', {
|
|
2619
|
+
ref: MANIFEST_REF,
|
|
2620
|
+
next_action: `Confirm no writer, then clear only abandoned lock/tmp residue from ${path.join(repoRoot, STORE_ROOT_REF)} and retry the same migration input; preserve any member or note data.`,
|
|
2621
|
+
});
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
return appendPlanMembership(repoRoot, options, false);
|
|
2625
|
+
}
|
|
2626
|
+
|
|
2627
|
+
/** G5-only new membership; existing keys are never revisions or idempotent creates. */
|
|
2628
|
+
export async function appendAuthoredTodoPlan(options = {}) {
|
|
2629
|
+
requireWriter(options.writer, 'g5-authoring');
|
|
2630
|
+
const keys = ['repoRoot', 'writer', 'plan', 'genesis'];
|
|
2631
|
+
if (options.featureChain !== undefined) keys.push('featureChain');
|
|
2632
|
+
if (options.onProtocolStage !== undefined) keys.push('onProtocolStage');
|
|
2633
|
+
if (!exactRecord(options, keys)
|
|
2634
|
+
|| (options.onProtocolStage !== undefined && typeof options.onProtocolStage !== 'function')
|
|
2635
|
+
|| !(exactRecord(options.genesis, ['actor', 'recorded_at'])
|
|
2636
|
+
|| exactRecord(options.genesis, ['actor', 'recorded_at', 'provenance']))) {
|
|
2637
|
+
throw new TypeError('authored plan addition input invalid');
|
|
2638
|
+
}
|
|
2639
|
+
return appendPlanMembership(path.resolve(options.repoRoot), options, true);
|
|
2640
|
+
}
|
|
2641
|
+
|
|
2642
|
+
function prepareAuthoredArtifacts(repoRoot, options, store) {
|
|
2643
|
+
if (!validateTodoPlan(options.plan) || options.plan.predecessor_plan_digest !== null) {
|
|
2644
|
+
throw new TypeError('authored plan must be a valid genesis plan');
|
|
2645
|
+
}
|
|
2646
|
+
const plan = options.plan;
|
|
2647
|
+
if (plan.project_id !== store.project_id) fail('STORE_WRITE_CONFLICT', 'project_id_mismatch', {
|
|
2648
|
+
expected: store.project_id, actual: plan.project_id,
|
|
2649
|
+
});
|
|
2650
|
+
verifyPlanNarrativeAnchors(repoRoot, plan);
|
|
2651
|
+
const genesis = buildPlanGenesis(plan, options.genesis);
|
|
2652
|
+
const events = [genesis];
|
|
2653
|
+
const tasks = replay(plan, events);
|
|
2654
|
+
validateMergedGraph([...store.members, { plan }]);
|
|
2655
|
+
return { plan, genesis, events, tasks, snapshot: snapshotFor(plan, events, tasks) };
|
|
2656
|
+
}
|
|
2657
|
+
|
|
2658
|
+
async function assertUnpublishedPlanFiles(directory, expected) {
|
|
2659
|
+
const occupied = (ref) => fail('REVISION_CONFLICT', 'revision_bytes_conflict', {
|
|
2660
|
+
ref,
|
|
2661
|
+
next_action: `Restore the expected unpublished files at ${directory} or use another plan key/version; existing bytes were preserved.`,
|
|
2662
|
+
});
|
|
2663
|
+
async function visit(current, prefix = '') {
|
|
2664
|
+
const state = await lstat(current).catch((error) => {
|
|
2665
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
2666
|
+
return null;
|
|
2667
|
+
});
|
|
2668
|
+
if (state === null) return;
|
|
2669
|
+
if (state.isSymbolicLink() || !state.isDirectory()) occupied(current);
|
|
2670
|
+
for (const entry of await readdir(current, { withFileTypes: true })) {
|
|
2671
|
+
const relative = `${prefix}${entry.name}`;
|
|
2672
|
+
if (entry.isDirectory() && [...expected.keys()].some((ref) => ref.startsWith(`${relative}/`))) {
|
|
2673
|
+
await visit(path.join(current, entry.name), `${relative}/`);
|
|
2674
|
+
} else if (!entry.isFile() || !expected.has(relative)
|
|
2675
|
+
|| !(await readFile(path.join(current, entry.name))).equals(expected.get(relative))) {
|
|
2676
|
+
occupied(path.join(directory, relative));
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
if (!sameDirectoryIdentity(state, await lstat(current))) occupied(current);
|
|
2753
2680
|
}
|
|
2754
|
-
|
|
2681
|
+
await visit(directory);
|
|
2682
|
+
}
|
|
2683
|
+
|
|
2684
|
+
async function appendPlanMembership(repoRoot, options, authored) {
|
|
2685
|
+
const transactionDigest = authored ? null : importedPlanTransactionDigest(options);
|
|
2755
2686
|
return withLock(repoRoot, async () => {
|
|
2756
|
-
const recovered = await recoverCrossPlanImports(repoRoot
|
|
2687
|
+
const recovered = await recoverCrossPlanImports(repoRoot);
|
|
2757
2688
|
const recoveredOwnTransaction = recovered.find((marker) => marker.transaction_digest === transactionDigest);
|
|
2758
|
-
if (recoveredOwnTransaction !== undefined) {
|
|
2689
|
+
if (!authored && recoveredOwnTransaction !== undefined) {
|
|
2759
2690
|
return recoveredImportedPlanResult(repoRoot, recoveredOwnTransaction, options.now);
|
|
2760
2691
|
}
|
|
2761
2692
|
// 1. Validate canonical manifest bytes and every current member before preparing output.
|
|
2762
|
-
const store = await
|
|
2693
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
2763
2694
|
const expectedManifestDigest = store.manifest.manifest_digest;
|
|
2764
2695
|
await protocolStage(options, 'manifest_validated');
|
|
2765
2696
|
|
|
2766
2697
|
// 2. A plan key is never overwritten, merged, or treated as an idempotent success.
|
|
2767
2698
|
const existing = store.members.find(({ descriptor }) => descriptor.plan_key === options.plan?.plan_key);
|
|
2768
2699
|
if (existing) {
|
|
2769
|
-
const imported = existing.journal.events[0]?.payload.historical_import === true;
|
|
2700
|
+
const imported = !authored && existing.journal.events[0]?.payload.historical_import === true;
|
|
2770
2701
|
fail('STORE_WRITE_CONFLICT', imported ? 'plan_key_already_imported' : 'plan_key_already_exists');
|
|
2771
2702
|
}
|
|
2772
2703
|
await protocolStage(options, 'plan_key_absent');
|
|
2773
2704
|
|
|
2774
|
-
const prepared = prepareImportedArtifacts(
|
|
2705
|
+
const prepared = authored ? prepareAuthoredArtifacts(repoRoot, options, store) : prepareImportedArtifacts(
|
|
2775
2706
|
repoRoot, options, store.project_id, store.members.map(({ plan: memberPlan }) => ({ plan: memberPlan })),
|
|
2776
2707
|
);
|
|
2777
2708
|
const { plan, genesis, events, snapshot, tasks } = prepared;
|
|
@@ -2781,7 +2712,7 @@ export async function appendImportedPlan(options = {}) {
|
|
|
2781
2712
|
const planRef = `${base}/plan.json`;
|
|
2782
2713
|
const journalRef = `${base}/journal/active.jsonl`;
|
|
2783
2714
|
const snapshotRef = `${base}/snapshot.json`;
|
|
2784
|
-
const importedCrossPlan = prepareImportedCrossPlanDependencies({
|
|
2715
|
+
const importedCrossPlan = authored ? { artifacts: [], events: [] } : prepareImportedCrossPlanDependencies({
|
|
2785
2716
|
store, plan, tasks, dependencies: options.crossPlanDependencies, genesis, journalRef,
|
|
2786
2717
|
});
|
|
2787
2718
|
const hasCrossPlanDependencies = importedCrossPlan.artifacts.length > 0;
|
|
@@ -2790,7 +2721,23 @@ export async function appendImportedPlan(options = {}) {
|
|
|
2790
2721
|
: `${STORE_ROOT_REF}/transactions/${plan.plan_key}-${plan.plan_version}`;
|
|
2791
2722
|
const transactionAbsolute = path.resolve(repoRoot, transactionRef);
|
|
2792
2723
|
const finalBaseAbsolute = path.resolve(repoRoot, base);
|
|
2793
|
-
|
|
2724
|
+
await ensureSafeStoreDirectory(repoRoot, path.dirname(transactionAbsolute));
|
|
2725
|
+
await ensureSafeStoreDirectory(repoRoot, path.dirname(finalBaseAbsolute));
|
|
2726
|
+
const expected = new Map([
|
|
2727
|
+
['plan.json', canonicalLine(plan)], ['journal/active.jsonl', Buffer.concat(events.map(canonicalLine))],
|
|
2728
|
+
['snapshot.json', canonicalLine(snapshot)],
|
|
2729
|
+
...(backchain === null ? [] : [['backchain.json', canonicalLine(backchain)]]),
|
|
2730
|
+
]);
|
|
2731
|
+
const stagedExpected = new Map([...expected].map(([ref, bytes]) => [
|
|
2732
|
+
hasCrossPlanDependencies ? `plan/${ref}` : ref === 'journal/active.jsonl' ? 'active.jsonl' : ref,
|
|
2733
|
+
bytes,
|
|
2734
|
+
]));
|
|
2735
|
+
for (const [index, artifact] of importedCrossPlan.artifacts.entries()) {
|
|
2736
|
+
stagedExpected.set(`plan-scoped/${index}.jsonl`, artifact.finalBytes);
|
|
2737
|
+
}
|
|
2738
|
+
await assertUnpublishedPlanFiles(transactionAbsolute, stagedExpected);
|
|
2739
|
+
await assertUnpublishedPlanFiles(finalBaseAbsolute, expected);
|
|
2740
|
+
// Only enumerated, byte-identical unpublished artifacts can be replaced.
|
|
2794
2741
|
await rm(transactionAbsolute, { recursive: true, force: true });
|
|
2795
2742
|
await rm(finalBaseAbsolute, { recursive: true, force: true });
|
|
2796
2743
|
|
|
@@ -2870,6 +2817,7 @@ export async function appendImportedPlan(options = {}) {
|
|
|
2870
2817
|
await protocolStage(options, 'cross_plan_dependencies_activated');
|
|
2871
2818
|
}
|
|
2872
2819
|
await rm(transactionAbsolute, { recursive: true, force: true });
|
|
2820
|
+
if (authored) return readTodoStoreLocked({ repoRoot, forWrite: true });
|
|
2873
2821
|
return {
|
|
2874
2822
|
plan, genesis, events, snapshot, descriptor,
|
|
2875
2823
|
crossPlanDependencies: importedCrossPlan.events,
|
|
@@ -2894,8 +2842,7 @@ export async function appendImportedPlan(options = {}) {
|
|
|
2894
2842
|
}
|
|
2895
2843
|
throw error;
|
|
2896
2844
|
}
|
|
2897
|
-
}, {
|
|
2898
|
-
&& options.crossPlanDependencies.length > 0, onProtocolStage: options.onProtocolStage });
|
|
2845
|
+
}, { onProtocolStage: options.onProtocolStage });
|
|
2899
2846
|
}
|
|
2900
2847
|
|
|
2901
2848
|
export async function initializeTodoStore(options = {}) {
|
|
@@ -2927,8 +2874,141 @@ export async function initializeTodoStore(options = {}) {
|
|
|
2927
2874
|
if (!validateTodoManifest(manifest)) throw new TypeError('manifest input violates lattice.todo_manifest.v1');
|
|
2928
2875
|
// Activation is last: a crash before this point leaves the new store/version unpublished.
|
|
2929
2876
|
await atomicWrite(path.resolve(repoRoot, MANIFEST_REF), canonicalLine(manifest));
|
|
2930
|
-
return
|
|
2877
|
+
return readTodoStoreLocked({ repoRoot, now: options.now });
|
|
2878
|
+
}, { initialize: true });
|
|
2879
|
+
}
|
|
2880
|
+
|
|
2881
|
+
const sameDirectoryIdentity = (left, right) => left !== null && right !== null
|
|
2882
|
+
&& left.dev === right.dev && left.ino === right.ino;
|
|
2883
|
+
|
|
2884
|
+
async function transientStoreDirectory(root, allowNotes = true) {
|
|
2885
|
+
for (const entry of await readdir(root, { withFileTypes: true })) {
|
|
2886
|
+
if (entry.isFile() && (entry.name === '.write.lock' || /^\.write\.lock\..+\.tmp$/u.test(entry.name))) continue;
|
|
2887
|
+
if (!entry.isDirectory()) return false;
|
|
2888
|
+
const child = path.join(root, entry.name);
|
|
2889
|
+
if (allowNotes && entry.name === 'notes') {
|
|
2890
|
+
if (!await transientStoreDirectory(child, false)) return false;
|
|
2891
|
+
} else if (['.cross-plan-recovery', '.write.lock.recovery'].includes(entry.name)) {
|
|
2892
|
+
for (const claim of await readdir(child, { withFileTypes: true })) {
|
|
2893
|
+
if (!claim.isDirectory() || (await readdir(path.join(child, claim.name))).length !== 0) return false;
|
|
2894
|
+
}
|
|
2895
|
+
} else return false;
|
|
2896
|
+
}
|
|
2897
|
+
return true;
|
|
2898
|
+
}
|
|
2899
|
+
|
|
2900
|
+
async function uninitializedStoreLayout(repoRoot) {
|
|
2901
|
+
const parent = await lstat(path.join(repoRoot, '.lattice')).catch((error) => {
|
|
2902
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
2903
|
+
return null;
|
|
2904
|
+
});
|
|
2905
|
+
if (parent === null) return { uninitialized: true, identity: null };
|
|
2906
|
+
if (parent.isSymbolicLink() || !parent.isDirectory()) {
|
|
2907
|
+
return { uninitialized: false, identity: null, unsafeParent: true };
|
|
2908
|
+
}
|
|
2909
|
+
const root = path.join(repoRoot, STORE_ROOT_REF);
|
|
2910
|
+
const identity = await lstat(root).catch((error) => {
|
|
2911
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
2912
|
+
return null;
|
|
2913
|
+
});
|
|
2914
|
+
if (identity === null) return { uninitialized: true, identity };
|
|
2915
|
+
if (identity.isSymbolicLink() || !identity.isDirectory()) return { uninitialized: false, identity };
|
|
2916
|
+
try { return { identity, uninitialized: await transientStoreDirectory(root) }; }
|
|
2917
|
+
catch (error) {
|
|
2918
|
+
if (error?.code === 'ENOENT' && await lstat(root).catch((missing) => {
|
|
2919
|
+
if (missing?.code !== 'ENOENT') throw missing;
|
|
2920
|
+
return null;
|
|
2921
|
+
}) === null) return { uninitialized: true, identity: null };
|
|
2922
|
+
throw error;
|
|
2923
|
+
}
|
|
2924
|
+
}
|
|
2925
|
+
|
|
2926
|
+
/** Discovery only; liveness and the final publication decision stay in the transaction. */
|
|
2927
|
+
export async function isUninitializedTodoStore({ repoRoot = process.cwd() } = {}) {
|
|
2928
|
+
return (await uninitializedStoreLayout(path.resolve(repoRoot))).uninitialized;
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
async function prepareAuthoredStoreRoot(repoRoot, options) {
|
|
2932
|
+
const observed = await uninitializedStoreLayout(repoRoot);
|
|
2933
|
+
if (observed.unsafeParent) fail('STORE_INCONSISTENT', 'unsafe_lattice_root');
|
|
2934
|
+
if (!observed.uninitialized) fail('STORE_WRITE_CONFLICT', 'store_already_exists');
|
|
2935
|
+
if (observed.identity === null) return;
|
|
2936
|
+
const root = path.join(repoRoot, STORE_ROOT_REF);
|
|
2937
|
+
try { await withLock(repoRoot, async () => {
|
|
2938
|
+
const fresh = await uninitializedStoreLayout(repoRoot);
|
|
2939
|
+
if (!sameDirectoryIdentity(observed.identity, fresh.identity)) {
|
|
2940
|
+
fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
|
|
2941
|
+
}
|
|
2942
|
+
if (!fresh.uninitialized) fail('STORE_WRITE_CONFLICT', 'store_already_exists');
|
|
2943
|
+
const notes = path.join(root, 'notes');
|
|
2944
|
+
const notesIdentity = await lstat(notes).catch((error) => {
|
|
2945
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
2946
|
+
return null;
|
|
2947
|
+
});
|
|
2948
|
+
if (notesIdentity !== null) {
|
|
2949
|
+
await withStoreLock({ lockPath: path.join(notes, '.write.lock'), createParent: false }, async () => {
|
|
2950
|
+
if (!sameDirectoryIdentity(notesIdentity, await lstat(notes))
|
|
2951
|
+
|| !await transientStoreDirectory(notes, false)) {
|
|
2952
|
+
fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
|
|
2953
|
+
}
|
|
2954
|
+
});
|
|
2955
|
+
if (!sameDirectoryIdentity(notesIdentity, await lstat(notes))) {
|
|
2956
|
+
fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
|
|
2957
|
+
}
|
|
2958
|
+
try { await rmdir(notes); }
|
|
2959
|
+
catch (error) {
|
|
2960
|
+
if (!['ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error;
|
|
2961
|
+
throw new StoreLockError('store_locked', path.join(notes, '.write.lock'), {
|
|
2962
|
+
next_action: `Confirm no writer before clearing abandoned host-local note lock residue in ${notes}`,
|
|
2963
|
+
});
|
|
2964
|
+
}
|
|
2965
|
+
}
|
|
2966
|
+
await protocolStage(options, 'authoring_residue_locked');
|
|
2967
|
+
}); } catch (error) {
|
|
2968
|
+
const gone = (await uninitializedStoreLayout(repoRoot)).identity === null;
|
|
2969
|
+
if (gone && error instanceof TodoStoreError
|
|
2970
|
+
&& ['store_locked', 'artifact_missing'].includes(error.detail.reason)) return;
|
|
2971
|
+
throw error;
|
|
2972
|
+
}
|
|
2973
|
+
await protocolStage(options, 'authoring_residue_released');
|
|
2974
|
+
const fresh = await uninitializedStoreLayout(repoRoot);
|
|
2975
|
+
if (fresh.identity === null && fresh.uninitialized) return;
|
|
2976
|
+
if (!sameDirectoryIdentity(observed.identity, fresh.identity)) {
|
|
2977
|
+
if (!fresh.uninitialized) fail('STORE_WRITE_CONFLICT', 'store_bootstrap_raced');
|
|
2978
|
+
fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
|
|
2979
|
+
}
|
|
2980
|
+
const busy = () => fail('STORE_WRITE_CONFLICT', 'store_locked', {
|
|
2981
|
+
lock_path: path.join(root, '.write.lock'),
|
|
2982
|
+
next_action: `Retry after writers exit; confirm no writer before manually clearing unidentified host-local residue in ${root}`,
|
|
2983
|
+
});
|
|
2984
|
+
if (!fresh.uninitialized) fail('STORE_WRITE_CONFLICT', 'store_already_exists');
|
|
2985
|
+
const entries = await readdir(root).catch((error) => {
|
|
2986
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
2987
|
+
return null;
|
|
2988
|
+
});
|
|
2989
|
+
if (entries === null) return;
|
|
2990
|
+
if (entries.length !== 0) busy();
|
|
2991
|
+
try { await rmdir(root); }
|
|
2992
|
+
catch (error) {
|
|
2993
|
+
if (['ENOTEMPTY', 'EEXIST'].includes(error?.code)) busy();
|
|
2994
|
+
if (error?.code === 'ENOENT') return;
|
|
2995
|
+
throw error;
|
|
2996
|
+
}
|
|
2997
|
+
await fsyncDirectory(path.dirname(root));
|
|
2998
|
+
}
|
|
2999
|
+
|
|
3000
|
+
async function withInitialStoreLocks(stage, currentRoot, callback) {
|
|
3001
|
+
await mkdir(path.join(stage, 'notes'));
|
|
3002
|
+
const lockOptions = (relative) => ({
|
|
3003
|
+
lockPath: path.join(stage, relative), createParent: false,
|
|
3004
|
+
releasePath: async () => {
|
|
3005
|
+
const root = await currentRoot();
|
|
3006
|
+
return root === null ? null : path.join(root, relative);
|
|
3007
|
+
},
|
|
2931
3008
|
});
|
|
3009
|
+
return withStoreLock(lockOptions('.write.lock'), () => (
|
|
3010
|
+
withStoreLock(lockOptions('notes/.write.lock'), callback)
|
|
3011
|
+
));
|
|
2932
3012
|
}
|
|
2933
3013
|
|
|
2934
3014
|
/** G5-only initial authoring transaction. Store membership appears by one final directory rename. */
|
|
@@ -2977,93 +3057,145 @@ export async function initializeAuthoredTodoStore(options = {}) {
|
|
|
2977
3057
|
let activated = false;
|
|
2978
3058
|
let stageIdentity = null;
|
|
2979
3059
|
let latticeIdentity = null;
|
|
2980
|
-
const sameIdentity =
|
|
2981
|
-
|
|
3060
|
+
const sameIdentity = sameDirectoryIdentity;
|
|
3061
|
+
await prepareAuthoredStoreRoot(repoRoot, options);
|
|
3062
|
+
await mkdir(stage, { mode: 0o700 });
|
|
3063
|
+
stageIdentity = await lstat(stage);
|
|
2982
3064
|
try {
|
|
2983
|
-
|
|
2984
|
-
|
|
2985
|
-
|
|
2986
|
-
|
|
2987
|
-
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
await atomicWrite(path.join(stage, base, 'journal', 'active.jsonl'), canonicalLine(genesis));
|
|
2993
|
-
await atomicWrite(path.join(stage, base, 'snapshot.json'), canonicalLine(snapshot));
|
|
2994
|
-
if (backchain !== null) await atomicWrite(path.join(stage, base, 'backchain.json'), canonicalLine(backchain));
|
|
2995
|
-
await atomicWrite(path.join(stage, 'manifest.json'), canonicalLine(manifest));
|
|
2996
|
-
|
|
2997
|
-
try {
|
|
2998
|
-
const state = await lstat(latticeRoot);
|
|
2999
|
-
if (state.isSymbolicLink() || !state.isDirectory()) fail('STORE_INCONSISTENT', 'unsafe_lattice_root');
|
|
3000
|
-
} catch (error) {
|
|
3001
|
-
if (error instanceof TodoStoreError) throw error;
|
|
3002
|
-
if (error?.code !== 'ENOENT') throw error;
|
|
3003
|
-
await mkdir(latticeRoot, { mode: 0o700 });
|
|
3004
|
-
createdLatticeRoot = true;
|
|
3005
|
-
await fsyncDirectory(repoRoot);
|
|
3006
|
-
}
|
|
3007
|
-
await ensureLatticeEolProtection(latticeRoot);
|
|
3008
|
-
latticeIdentity = await lstat(latticeRoot);
|
|
3009
|
-
const stagedBeforeRename = await lstat(stage);
|
|
3010
|
-
const parentBeforeRename = await lstat(latticeRoot);
|
|
3011
|
-
if (!sameIdentity(stageIdentity, stagedBeforeRename)
|
|
3012
|
-
|| !sameIdentity(latticeIdentity, parentBeforeRename)
|
|
3013
|
-
|| stagedBeforeRename.isSymbolicLink() || !stagedBeforeRename.isDirectory()
|
|
3014
|
-
|| parentBeforeRename.isSymbolicLink() || !parentBeforeRename.isDirectory()) {
|
|
3015
|
-
fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
|
|
3016
|
-
}
|
|
3017
|
-
try { await rename(stage, storeRoot); }
|
|
3018
|
-
catch (error) {
|
|
3019
|
-
if (['EEXIST', 'ENOTEMPTY'].includes(error?.code)) fail('STORE_WRITE_CONFLICT', 'store_bootstrap_raced');
|
|
3020
|
-
throw error;
|
|
3021
|
-
}
|
|
3022
|
-
renamed = true;
|
|
3023
|
-
await fsyncDirectory(latticeRoot);
|
|
3024
|
-
if (typeof options.onProtocolStage === 'function') await options.onProtocolStage('authoring_renamed');
|
|
3025
|
-
const activatedStore = await lstat(storeRoot);
|
|
3026
|
-
const activatedParent = await lstat(latticeRoot);
|
|
3027
|
-
if (!sameIdentity(stageIdentity, activatedStore)
|
|
3028
|
-
|| !sameIdentity(latticeIdentity, activatedParent)
|
|
3029
|
-
|| activatedStore.isSymbolicLink() || !activatedStore.isDirectory()
|
|
3030
|
-
|| activatedParent.isSymbolicLink() || !activatedParent.isDirectory()) {
|
|
3031
|
-
fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
|
|
3032
|
-
}
|
|
3033
|
-
const store = await readTodoStore({ repoRoot });
|
|
3034
|
-
const member = store.members[0];
|
|
3035
|
-
if (store.project_id !== options.projectId || store.members.length !== 1
|
|
3036
|
-
|| store.snapshot_stale !== false || member?.journal?.events?.length !== 1
|
|
3037
|
-
|| canonicalizeTodoArtifact(store.manifest) !== canonicalizeTodoArtifact(manifest)
|
|
3038
|
-
|| canonicalizeTodoArtifact(member?.descriptor) !== canonicalizeTodoArtifact(descriptor)
|
|
3039
|
-
|| canonicalizeTodoArtifact(member?.plan) !== canonicalizeTodoArtifact(plan)
|
|
3040
|
-
|| canonicalizeTodoArtifact(member?.journal?.events?.[0]) !== canonicalizeTodoArtifact(genesis)
|
|
3041
|
-
|| canonicalizeTodoArtifact(member?.snapshot) !== canonicalizeTodoArtifact(snapshot)) {
|
|
3042
|
-
fail('STORE_WRITE_CONFLICT', 'authoring_activation_verification_failed');
|
|
3043
|
-
}
|
|
3044
|
-
activated = true;
|
|
3045
|
-
return store;
|
|
3046
|
-
} finally {
|
|
3047
|
-
if (renamed && !activated) {
|
|
3065
|
+
return await withInitialStoreLocks(stage, async () => {
|
|
3066
|
+
const current = renamed ? storeRoot : stage;
|
|
3067
|
+
const identity = await lstat(current).catch((error) => {
|
|
3068
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
3069
|
+
return null;
|
|
3070
|
+
});
|
|
3071
|
+
return sameIdentity(stageIdentity, identity) && identity.isDirectory() && !identity.isSymbolicLink()
|
|
3072
|
+
? current : null;
|
|
3073
|
+
}, async () => {
|
|
3048
3074
|
try {
|
|
3049
|
-
|
|
3050
|
-
|
|
3051
|
-
|
|
3052
|
-
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
3075
|
+
stageIdentity = await lstat(stage);
|
|
3076
|
+
await atomicWrite(path.join(stage, base, 'plan.json'), canonicalLine(plan));
|
|
3077
|
+
await atomicWrite(path.join(stage, base, 'journal', 'active.jsonl'), canonicalLine(genesis));
|
|
3078
|
+
await atomicWrite(path.join(stage, base, 'snapshot.json'), canonicalLine(snapshot));
|
|
3079
|
+
if (backchain !== null) await atomicWrite(path.join(stage, base, 'backchain.json'), canonicalLine(backchain));
|
|
3080
|
+
await atomicWrite(path.join(stage, 'manifest.json'), canonicalLine(manifest));
|
|
3081
|
+
|
|
3082
|
+
try {
|
|
3083
|
+
const state = await lstat(latticeRoot);
|
|
3084
|
+
if (state.isSymbolicLink() || !state.isDirectory()) fail('STORE_INCONSISTENT', 'unsafe_lattice_root');
|
|
3085
|
+
} catch (error) {
|
|
3086
|
+
if (error instanceof TodoStoreError) throw error;
|
|
3087
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
3088
|
+
try { await mkdir(latticeRoot, { mode: 0o700 }); createdLatticeRoot = true; }
|
|
3089
|
+
catch (race) { if (race?.code !== 'EEXIST') throw race; }
|
|
3090
|
+
await fsyncDirectory(repoRoot);
|
|
3091
|
+
}
|
|
3092
|
+
await ensureLatticeEolProtection(latticeRoot);
|
|
3093
|
+
latticeIdentity = await lstat(latticeRoot);
|
|
3094
|
+
const stagedBeforeRename = await lstat(stage);
|
|
3095
|
+
const parentBeforeRename = await lstat(latticeRoot);
|
|
3096
|
+
if (!sameIdentity(stageIdentity, stagedBeforeRename)
|
|
3097
|
+
|| !sameIdentity(latticeIdentity, parentBeforeRename)
|
|
3098
|
+
|| stagedBeforeRename.isSymbolicLink() || !stagedBeforeRename.isDirectory()
|
|
3099
|
+
|| parentBeforeRename.isSymbolicLink() || !parentBeforeRename.isDirectory()) {
|
|
3100
|
+
fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
|
|
3101
|
+
}
|
|
3102
|
+
try { await rename(stage, storeRoot); }
|
|
3103
|
+
catch (error) {
|
|
3104
|
+
if (['EEXIST', 'ENOTEMPTY'].includes(error?.code)) fail('STORE_WRITE_CONFLICT', 'store_bootstrap_raced');
|
|
3105
|
+
if (error?.code === 'EPERM') {
|
|
3106
|
+
const remainingStage = await lstat(stage).catch(() => null);
|
|
3107
|
+
if (sameIdentity(stageIdentity, remainingStage)
|
|
3108
|
+
&& remainingStage.isDirectory() && !remainingStage.isSymbolicLink()) {
|
|
3109
|
+
const destination = await lstat(storeRoot).catch(() => null);
|
|
3110
|
+
if (destination !== null) {
|
|
3111
|
+
let complete = false;
|
|
3112
|
+
if (destination.isDirectory() && !destination.isSymbolicLink()) {
|
|
3113
|
+
try {
|
|
3114
|
+
await readArtifact(repoRoot, MANIFEST_REF, {
|
|
3115
|
+
code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes,
|
|
3116
|
+
validate: validateTodoManifest,
|
|
3117
|
+
});
|
|
3118
|
+
complete = sameIdentity(destination, await lstat(storeRoot));
|
|
3119
|
+
} catch { /* An unreadable manifest cannot prove a completed publisher. */ }
|
|
3120
|
+
}
|
|
3121
|
+
const reason = complete ? 'store_bootstrap_raced' : 'bootstrap_destination_incomplete';
|
|
3122
|
+
const layout = complete ? null : await uninitializedStoreLayout(repoRoot).catch(() => null);
|
|
3123
|
+
const nextAction = complete
|
|
3124
|
+
? `Read the published Store at ${storeRoot}; add further membership with a new plan key.`
|
|
3125
|
+
: layout?.uninitialized
|
|
3126
|
+
? `Retry the same initial operation after the writer exits; transient residue at ${storeRoot} recovers automatically.`
|
|
3127
|
+
: `Finish or restore the original bootstrap at ${storeRoot}, preserving existing data, then retry.`;
|
|
3128
|
+
throw Object.assign(new TodoStoreError('STORE_WRITE_CONFLICT', reason, reason, {
|
|
3129
|
+
ref: STORE_ROOT_REF, cause: error.code, next_action: nextAction,
|
|
3130
|
+
}), { cause: error });
|
|
3131
|
+
}
|
|
3132
|
+
}
|
|
3133
|
+
}
|
|
3134
|
+
throw error;
|
|
3135
|
+
}
|
|
3136
|
+
renamed = true;
|
|
3137
|
+
await fsyncDirectory(latticeRoot);
|
|
3138
|
+
if (typeof options.onProtocolStage === 'function') await options.onProtocolStage('authoring_renamed');
|
|
3139
|
+
const activatedStore = await lstat(storeRoot);
|
|
3140
|
+
const activatedParent = await lstat(latticeRoot);
|
|
3141
|
+
if (!sameIdentity(stageIdentity, activatedStore)
|
|
3142
|
+
|| !sameIdentity(latticeIdentity, activatedParent)
|
|
3143
|
+
|| activatedStore.isSymbolicLink() || !activatedStore.isDirectory()
|
|
3144
|
+
|| activatedParent.isSymbolicLink() || !activatedParent.isDirectory()) {
|
|
3145
|
+
fail('STORE_WRITE_CONFLICT', 'authoring_activation_path_changed');
|
|
3146
|
+
}
|
|
3147
|
+
const store = await readTodoStoreView({ repoRoot });
|
|
3148
|
+
const member = store.members[0];
|
|
3149
|
+
if (store.project_id !== options.projectId || store.members.length !== 1
|
|
3150
|
+
|| store.snapshot_stale !== false || member?.journal?.events?.length !== 1
|
|
3151
|
+
|| canonicalizeTodoArtifact(store.manifest) !== canonicalizeTodoArtifact(manifest)
|
|
3152
|
+
|| canonicalizeTodoArtifact(member?.descriptor) !== canonicalizeTodoArtifact(descriptor)
|
|
3153
|
+
|| canonicalizeTodoArtifact(member?.plan) !== canonicalizeTodoArtifact(plan)
|
|
3154
|
+
|| canonicalizeTodoArtifact(member?.journal?.events?.[0]) !== canonicalizeTodoArtifact(genesis)
|
|
3155
|
+
|| canonicalizeTodoArtifact(member?.snapshot) !== canonicalizeTodoArtifact(snapshot)) {
|
|
3156
|
+
fail('STORE_WRITE_CONFLICT', 'authoring_activation_verification_failed');
|
|
3157
|
+
}
|
|
3158
|
+
activated = true;
|
|
3159
|
+
return store;
|
|
3160
|
+
} finally {
|
|
3161
|
+
if (renamed && !activated) {
|
|
3162
|
+
try {
|
|
3163
|
+
const currentParent = await lstat(latticeRoot);
|
|
3164
|
+
const currentStore = await lstat(storeRoot);
|
|
3165
|
+
if (sameIdentity(latticeIdentity, currentParent) && sameIdentity(stageIdentity, currentStore)
|
|
3166
|
+
&& !currentParent.isSymbolicLink() && currentParent.isDirectory()
|
|
3167
|
+
&& !currentStore.isSymbolicLink() && currentStore.isDirectory()) {
|
|
3168
|
+
await rm(storeRoot, { recursive: true, force: true });
|
|
3169
|
+
await fsyncDirectory(latticeRoot);
|
|
3170
|
+
}
|
|
3171
|
+
} catch (error) {
|
|
3172
|
+
if (!['ENOENT', 'ENOTDIR'].includes(error?.code)) throw error;
|
|
3173
|
+
}
|
|
3174
|
+
}
|
|
3175
|
+
const published = await lstat(storeRoot).catch((error) => {
|
|
3176
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
3177
|
+
return null;
|
|
3178
|
+
});
|
|
3179
|
+
if (!activated && createdLatticeRoot && published === null) {
|
|
3180
|
+
// 自分で作ったroot直下の同梱.gitattributesを先に消さないとrmdirがENOTEMPTYで残る。
|
|
3181
|
+
await rm(path.join(latticeRoot, '.gitattributes'), { force: true });
|
|
3182
|
+
try { await rmdir(latticeRoot); }
|
|
3183
|
+
catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
|
|
3056
3184
|
}
|
|
3057
|
-
} catch (error) {
|
|
3058
|
-
if (!['ENOENT', 'ENOTDIR'].includes(error?.code)) throw error;
|
|
3059
3185
|
}
|
|
3060
|
-
}
|
|
3061
|
-
|
|
3062
|
-
if (
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3186
|
+
});
|
|
3187
|
+
} catch (error) {
|
|
3188
|
+
if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
|
|
3189
|
+
throw error;
|
|
3190
|
+
} finally {
|
|
3191
|
+
if (!renamed) {
|
|
3192
|
+
const currentStage = await lstat(stage).catch((error) => {
|
|
3193
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
3194
|
+
return null;
|
|
3195
|
+
});
|
|
3196
|
+
if (sameIdentity(stageIdentity, currentStage) && currentStage.isDirectory() && !currentStage.isSymbolicLink()) {
|
|
3197
|
+
await rm(stage, { recursive: true, force: true });
|
|
3198
|
+
}
|
|
3067
3199
|
}
|
|
3068
3200
|
}
|
|
3069
3201
|
}
|
|
@@ -3136,69 +3268,12 @@ export async function verifyPhaseTodoRevisionSources(options = {}) {
|
|
|
3136
3268
|
return true;
|
|
3137
3269
|
}
|
|
3138
3270
|
|
|
3139
|
-
function mappedNodeRef(ref, plan, idMap) {
|
|
3140
|
-
if (ref.project_id !== plan.project_id || ref.plan_key !== plan.plan_key) return ref;
|
|
3141
|
-
return { ...ref, task_id: idMap.get(ref.task_id) ?? ref.task_id };
|
|
3142
|
-
}
|
|
3143
|
-
|
|
3144
|
-
function localTaskRef(ref, plan, taskId) {
|
|
3145
|
-
return ref.project_id === plan.project_id && ref.plan_key === plan.plan_key
|
|
3146
|
-
&& ref.task_id === taskId;
|
|
3147
|
-
}
|
|
3148
|
-
|
|
3149
3271
|
function removedTaskIdsFor(revision) {
|
|
3150
3272
|
return new Set(revision.task_migration
|
|
3151
3273
|
.filter(({ to_task_id, state_policy }) => to_task_id === 'removed' && state_policy === 'removed')
|
|
3152
3274
|
.map(({ from_task_id }) => from_task_id));
|
|
3153
3275
|
}
|
|
3154
3276
|
|
|
3155
|
-
function removedTaskRef(ref, plan, removedTaskIds) {
|
|
3156
|
-
return ref.project_id === plan.project_id && ref.plan_key === plan.plan_key
|
|
3157
|
-
&& removedTaskIds.has(ref.task_id);
|
|
3158
|
-
}
|
|
3159
|
-
|
|
3160
|
-
function taskSemantics(plan, taskId, idMap, {
|
|
3161
|
-
reconciliationMetadata = false, includeDesignMemo = false, removedTaskIds = new Set(),
|
|
3162
|
-
} = {}) {
|
|
3163
|
-
const task = plan.tasks.find(({ task_id }) => task_id === taskId);
|
|
3164
|
-
if (!task) return null;
|
|
3165
|
-
const mapId = (id) => id === null ? null : idMap.get(id) ?? id;
|
|
3166
|
-
const normalizedTask = reconciliationMetadata ? {
|
|
3167
|
-
task_id: mapId(task.task_id), title: task.title, lane: task.lane,
|
|
3168
|
-
compile_binding: task.compile_binding,
|
|
3169
|
-
} : {
|
|
3170
|
-
task_id: mapId(task.task_id), title: task.title, lane: task.lane,
|
|
3171
|
-
...(includeDesignMemo ? { design_memo: task.design_memo } : {}),
|
|
3172
|
-
narrative_ref: task.narrative_ref, narrative_anchor: task.narrative_anchor ?? null,
|
|
3173
|
-
compile_binding: task.compile_binding, parent_task_id: mapId(task.parent_task_id ?? null),
|
|
3174
|
-
};
|
|
3175
|
-
const edges = plan.hard_dependencies
|
|
3176
|
-
.filter(({ from, to }) => !removedTaskRef(from, plan, removedTaskIds)
|
|
3177
|
-
&& !removedTaskRef(to, plan, removedTaskIds)
|
|
3178
|
-
&& (localTaskRef(from, plan, taskId) || localTaskRef(to, plan, taskId)))
|
|
3179
|
-
.map(({ from, to }) => ({ from: mappedNodeRef(from, plan, idMap), to: mappedNodeRef(to, plan, idMap) }))
|
|
3180
|
-
.sort((left, right) => canonicalizeTodoArtifact(left) < canonicalizeTodoArtifact(right) ? -1 : 1);
|
|
3181
|
-
const joins = plan.joins
|
|
3182
|
-
.flatMap((join) => {
|
|
3183
|
-
if (removedTaskRef(join.before, plan, removedTaskIds)) return [];
|
|
3184
|
-
const after = join.after.filter((ref) => !removedTaskRef(ref, plan, removedTaskIds));
|
|
3185
|
-
if (after.length === 0 || (!localTaskRef(join.before, plan, taskId)
|
|
3186
|
-
&& !after.some((ref) => localTaskRef(ref, plan, taskId)))) return [];
|
|
3187
|
-
return [{ ...join,
|
|
3188
|
-
after: after.map((ref) => mappedNodeRef(ref, plan, idMap))
|
|
3189
|
-
.sort((left, right) => canonicalizeTodoArtifact(left) < canonicalizeTodoArtifact(right) ? -1 : 1),
|
|
3190
|
-
before: mappedNodeRef(join.before, plan, idMap),
|
|
3191
|
-
}];
|
|
3192
|
-
}).sort((left, right) => left.id < right.id ? -1 : 1);
|
|
3193
|
-
const phaseAcceptDependencies = isDecoupledPhaseTodoPlanSchema(plan.schema)
|
|
3194
|
-
? plan.phase_accept_dependencies
|
|
3195
|
-
.filter(({ to }) => localTaskRef(to, plan, taskId))
|
|
3196
|
-
.map(({ from, to }) => ({ from, to: mappedNodeRef(to, plan, idMap) }))
|
|
3197
|
-
.sort((left, right) => canonicalizeTodoArtifact(left) < canonicalizeTodoArtifact(right) ? -1 : 1)
|
|
3198
|
-
: [];
|
|
3199
|
-
return { task: normalizedTask, hard_dependencies: edges, joins, phase_accept_dependencies: phaseAcceptDependencies };
|
|
3200
|
-
}
|
|
3201
|
-
|
|
3202
3277
|
function phaseV3CarrySemantics(plan, taskId, taskIdMap, phaseIdMap,
|
|
3203
3278
|
{ reconciliationMetadata = false, includeDesignMemo = false, removedTaskIds = new Set() } = {}) {
|
|
3204
3279
|
const task = plan.tasks.find(({ task_id: id }) => id === taskId);
|
|
@@ -3752,6 +3827,78 @@ function parseRevisionSetMarker(bytes) {
|
|
|
3752
3827
|
});
|
|
3753
3828
|
}
|
|
3754
3829
|
|
|
3830
|
+
async function recoverSourceCutover(repoRoot, now) {
|
|
3831
|
+
const barrierBytes = await exactFileOrNull(path.resolve(repoRoot, SOURCE_CUTOVER_BARRIER_REF));
|
|
3832
|
+
if (barrierBytes === null) return;
|
|
3833
|
+
const barrier = parseCanonicalJsonLine(barrierBytes, {
|
|
3834
|
+
code: 'SOURCE_CUTOVER_RECOVERY_REQUIRED', reason: 'barrier_invalid',
|
|
3835
|
+
maxBytes: TODO_LIMITS.snapshotBytes,
|
|
3836
|
+
validate: (value) => (exactRecord(value, ['schema', 'revision_digest'])
|
|
3837
|
+
&& value.schema === 'lattice.todo_source_cutover_barrier.v1' && isTodoDigest(value.revision_digest))
|
|
3838
|
+
|| (exactRecord(value, ['schema', 'revision_set_digest', 'revision_digests'])
|
|
3839
|
+
&& value.schema === 'lattice.todo_source_cutover_set_barrier.v1'
|
|
3840
|
+
&& isTodoDigest(value.revision_set_digest) && Array.isArray(value.revision_digests)
|
|
3841
|
+
&& value.revision_digests.every(isTodoDigest)),
|
|
3842
|
+
});
|
|
3843
|
+
const isSet = barrier.schema === 'lattice.todo_source_cutover_set_barrier.v1';
|
|
3844
|
+
const matches = [];
|
|
3845
|
+
async function visit(ref, depth, parse) {
|
|
3846
|
+
const directory = path.resolve(repoRoot, ref);
|
|
3847
|
+
let entries;
|
|
3848
|
+
try {
|
|
3849
|
+
const state = await lstat(directory);
|
|
3850
|
+
if (!state.isDirectory() || state.isSymbolicLink()) fail('REVISION_CONFLICT', 'revision_directory_unsafe');
|
|
3851
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
3852
|
+
} catch (error) { if (error?.code === 'ENOENT') return; throw error; }
|
|
3853
|
+
for (const entry of entries) {
|
|
3854
|
+
if (!isTodoIdentifier(entry.name) || !entry.isDirectory() || entry.isSymbolicLink()) {
|
|
3855
|
+
fail('REVISION_CONFLICT', 'revision_directory_unsafe');
|
|
3856
|
+
}
|
|
3857
|
+
const childRef = path.posix.join(ref, entry.name);
|
|
3858
|
+
if (depth > 1) { await visit(childRef, depth - 1, parse); continue; }
|
|
3859
|
+
const markerState = await pathState(repoRoot, `${childRef}/marker.json`, 'REVISION_CONFLICT', { missing: true });
|
|
3860
|
+
if (markerState === null) continue;
|
|
3861
|
+
const bytes = await exactFileOrNull(markerState.absolute);
|
|
3862
|
+
if (bytes === null) continue;
|
|
3863
|
+
const marker = parse(bytes);
|
|
3864
|
+
if ((isSet ? marker.revision_set_digest : marker.revision.revision_digest)
|
|
3865
|
+
=== (isSet ? barrier.revision_set_digest : barrier.revision_digest)) matches.push(marker);
|
|
3866
|
+
}
|
|
3867
|
+
}
|
|
3868
|
+
if (isSet) {
|
|
3869
|
+
await visit(`${STORE_ROOT_REF}/transactions/revision-sets`, 1, parseRevisionSetMarker);
|
|
3870
|
+
} else {
|
|
3871
|
+
await visit(`${STORE_ROOT_REF}/transactions/revisions`, 2, parseRevisionMarker);
|
|
3872
|
+
await visit(`${STORE_ROOT_REF}/transactions/phase-v3`, 2, parsePhaseRevisionMarker);
|
|
3873
|
+
}
|
|
3874
|
+
if (matches.length !== 1) fail('SOURCE_CUTOVER_RECOVERY_REQUIRED', 'source_cutover_recovery_required');
|
|
3875
|
+
const marker = matches[0];
|
|
3876
|
+
const genesis = isSet ? marker.entries[0].genesis : marker.genesis;
|
|
3877
|
+
const options = { repoRoot, now, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
|
|
3878
|
+
actor: genesis.actor, recordedAt: genesis.recorded_at, provenance: genesis.provenance,
|
|
3879
|
+
[STORE_LOCK_HELD]: STORE_LOCK_HELD };
|
|
3880
|
+
if (!isSet) {
|
|
3881
|
+
const apply = marker.revision.schema.startsWith('lattice.phase_')
|
|
3882
|
+
? applyPhaseTodoRevision : applyTodoRevision;
|
|
3883
|
+
await apply({ ...options, revision: marker.revision });
|
|
3884
|
+
return;
|
|
3885
|
+
}
|
|
3886
|
+
const revisions = marker.entries.map(({ revision }) => revision);
|
|
3887
|
+
if (canonicalizeTodoArtifact(barrier.revision_digests) !== canonicalizeTodoArtifact(revisions
|
|
3888
|
+
.filter(({ schema }) => schema === 'lattice.todo_revision.v2').map(({ revision_digest: digest }) => digest))) {
|
|
3889
|
+
fail('SOURCE_CUTOVER_RECOVERY_REQUIRED', 'barrier_invalid');
|
|
3890
|
+
}
|
|
3891
|
+
for (const schema of ['lattice.todo_revision_set.v1', 'lattice.todo_revision_set.v2', 'lattice.todo_revision_set.v3']) {
|
|
3892
|
+
const revisionSet = { schema, project_id: marker.project_id, revisions, revision_set_digest: '' };
|
|
3893
|
+
revisionSet.revision_set_digest = todoSelfDigest(revisionSet, 'revision_set_digest');
|
|
3894
|
+
if (revisionSet.revision_set_digest === marker.revision_set_digest && validateTodoRevisionSet(revisionSet)) {
|
|
3895
|
+
await applyTodoRevisionSet({ ...options, revisionSet });
|
|
3896
|
+
return;
|
|
3897
|
+
}
|
|
3898
|
+
}
|
|
3899
|
+
fail('SOURCE_CUTOVER_RECOVERY_REQUIRED', 'source_cutover_recovery_required');
|
|
3900
|
+
}
|
|
3901
|
+
|
|
3755
3902
|
async function rejectCompetingRevisionTransaction(repoRoot, revision) {
|
|
3756
3903
|
const root = path.join(repoRoot, STORE_ROOT_REF, 'transactions', 'revisions', revision.plan_key);
|
|
3757
3904
|
let names;
|
|
@@ -4261,7 +4408,7 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
|
|
|
4261
4408
|
}
|
|
4262
4409
|
recovering = true;
|
|
4263
4410
|
}
|
|
4264
|
-
const store = await
|
|
4411
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now,
|
|
4265
4412
|
...(recovering ? { allowSourceCutoverRevisionDigest: revision.revision_digest,
|
|
4266
4413
|
sourceCutoverRecoveryCapability: SOURCE_CUTOVER_RECOVERY_CAPABILITY } : {}) });
|
|
4267
4414
|
const previous = store.members.find(({ descriptor }) => descriptor.plan_key === revision.plan_key);
|
|
@@ -4450,7 +4597,7 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
|
|
|
4450
4597
|
await fsyncDirectory(path.dirname(barrierAbsolute));
|
|
4451
4598
|
await rm(transaction, { recursive: true, force: true });
|
|
4452
4599
|
return commitReceipt;
|
|
4453
|
-
});
|
|
4600
|
+
}, { lockCapability: options[STORE_LOCK_HELD] });
|
|
4454
4601
|
}
|
|
4455
4602
|
|
|
4456
4603
|
/** Native successor transaction for first-class Phase plans; no Markdown source inventory is involved. */
|
|
@@ -4463,7 +4610,7 @@ export async function applyPhaseTodoRevision(options = {}) {
|
|
|
4463
4610
|
return applyPhaseTodoRevisionV3(options, revision, repoRoot);
|
|
4464
4611
|
}
|
|
4465
4612
|
return withLock(repoRoot, async () => {
|
|
4466
|
-
const store = await
|
|
4613
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
4467
4614
|
const previous = store.members.find(({ descriptor }) => descriptor.plan_key === revision.plan_key);
|
|
4468
4615
|
if (!previous || revision.project_id !== store.project_id) fail('STORE_INCONSISTENT', 'plan_not_active');
|
|
4469
4616
|
const transaction = path.join(repoRoot, STORE_ROOT_REF, 'transactions', 'phase-revisions',
|
|
@@ -4560,7 +4707,7 @@ export async function applyPhaseTodoRevision(options = {}) {
|
|
|
4560
4707
|
await protocolStage(options, 'phase_revision_manifest_activated');
|
|
4561
4708
|
await rm(transaction, { recursive: true, force: true });
|
|
4562
4709
|
return phaseRevisionResult(revision, genesis, false);
|
|
4563
|
-
});
|
|
4710
|
+
}, { lockCapability: options[STORE_LOCK_HELD] });
|
|
4564
4711
|
}
|
|
4565
4712
|
|
|
4566
4713
|
/** G5 revision transaction: exact successor, state migration, and manifest-CAS activation. */
|
|
@@ -4587,7 +4734,7 @@ export async function applyTodoRevision(options = {}) {
|
|
|
4587
4734
|
}
|
|
4588
4735
|
recovering = true;
|
|
4589
4736
|
}
|
|
4590
|
-
const store = await
|
|
4737
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now,
|
|
4591
4738
|
...(recovering ? { allowSourceCutoverRevisionDigest: revision.revision_digest,
|
|
4592
4739
|
sourceCutoverRecoveryCapability: SOURCE_CUTOVER_RECOVERY_CAPABILITY } : {}) });
|
|
4593
4740
|
const previous = store.members.find(({ descriptor }) => descriptor.plan_key === revision.plan_key);
|
|
@@ -4748,7 +4895,7 @@ export async function applyTodoRevision(options = {}) {
|
|
|
4748
4895
|
}
|
|
4749
4896
|
await rm(transaction, { recursive: true, force: true });
|
|
4750
4897
|
return revisionResult(revision, genesis, { recovered: recovering });
|
|
4751
|
-
});
|
|
4898
|
+
}, { lockCapability: options[STORE_LOCK_HELD] });
|
|
4752
4899
|
}
|
|
4753
4900
|
|
|
4754
4901
|
function revisionSetResult(projectId, revisionSetDigest, entries, { recovered }) {
|
|
@@ -4822,7 +4969,7 @@ export async function applyTodoRevisionSet(options = {}) {
|
|
|
4822
4969
|
}
|
|
4823
4970
|
recovering = true;
|
|
4824
4971
|
}
|
|
4825
|
-
const store = await
|
|
4972
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now,
|
|
4826
4973
|
...(recovering ? {
|
|
4827
4974
|
allowSourceCutoverRevisionSetDigest: revisionSetDigest,
|
|
4828
4975
|
sourceCutoverRecoveryCapability: SOURCE_CUTOVER_RECOVERY_CAPABILITY,
|
|
@@ -5055,7 +5202,7 @@ export async function applyTodoRevisionSet(options = {}) {
|
|
|
5055
5202
|
}
|
|
5056
5203
|
await rm(transaction, { recursive: true, force: true });
|
|
5057
5204
|
return revisionSetResult(projectId, revisionSetDigest, prepared, { recovered: recovering });
|
|
5058
|
-
});
|
|
5205
|
+
}, { lockCapability: options[STORE_LOCK_HELD] });
|
|
5059
5206
|
}
|
|
5060
5207
|
|
|
5061
5208
|
/** G5 revise primitive: topology changes only by publishing a successor version. */
|
|
@@ -5063,7 +5210,7 @@ export async function createSuccessorTodoPlan(options = {}) {
|
|
|
5063
5210
|
requireWriter(options.writer, 'g5-authoring');
|
|
5064
5211
|
const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
|
|
5065
5212
|
return withLock(repoRoot, async () => {
|
|
5066
|
-
const store = await
|
|
5213
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
5067
5214
|
const previous = store.members.find(({ descriptor }) => descriptor.plan_key === options.planKey);
|
|
5068
5215
|
if (!previous) fail('STORE_INCONSISTENT', 'plan_not_active');
|
|
5069
5216
|
if (options.plan.predecessor_plan_digest !== previous.plan.plan_digest
|
|
@@ -5156,7 +5303,7 @@ export async function writeTodoIndependenceArtifact(options = {}) {
|
|
|
5156
5303
|
fail('INDEPENDENCE_ARTIFACT_INVALID', 'independence_artifact_invalid');
|
|
5157
5304
|
}
|
|
5158
5305
|
return withLock(repoRoot, async () => {
|
|
5159
|
-
const store = await
|
|
5306
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
5160
5307
|
if (store.project_id !== artifact.project_id) {
|
|
5161
5308
|
fail('INDEPENDENCE_BINDING_MISMATCH', 'project_id_mismatch', {
|
|
5162
5309
|
expected: store.project_id, actual: artifact.project_id,
|
|
@@ -5249,7 +5396,7 @@ export async function writeTodoSeamProposalArtifact(options = {}) {
|
|
|
5249
5396
|
fail('SEAM_PROPOSAL_ARTIFACT_INVALID', 'seam_proposal_artifact_invalid');
|
|
5250
5397
|
}
|
|
5251
5398
|
return withLock(repoRoot, async () => {
|
|
5252
|
-
const store = await
|
|
5399
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
5253
5400
|
if (store.project_id !== artifact.project_id) {
|
|
5254
5401
|
fail('SEAM_PROPOSAL_BINDING_MISMATCH', 'project_id_mismatch', {
|
|
5255
5402
|
expected: store.project_id, actual: artifact.project_id,
|
|
@@ -5414,7 +5561,7 @@ export async function writeTodoStructureSource(options = {}) {
|
|
|
5414
5561
|
fail('INVALID_TODO_STRUCTURE_SET', explained.reason, { path: explained.path });
|
|
5415
5562
|
}
|
|
5416
5563
|
return withLock(repoRoot, async () => {
|
|
5417
|
-
const store = await
|
|
5564
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
5418
5565
|
if (store.project_id !== structureSet.project_id) {
|
|
5419
5566
|
fail('STRUCTURE_BINDING_MISMATCH', 'project_id_mismatch', {
|
|
5420
5567
|
expected: store.project_id, actual: structureSet.project_id,
|
|
@@ -5510,7 +5657,7 @@ export async function writeTodoStructureCompileArtifact(options = {}) {
|
|
|
5510
5657
|
fail('INVALID_TODO_STRUCTURE_COMPILE_ARTIFACT', 'compile_artifact_invalid');
|
|
5511
5658
|
}
|
|
5512
5659
|
return withLock(repoRoot, async () => {
|
|
5513
|
-
const store = await
|
|
5660
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
5514
5661
|
if (store.project_id !== artifact.project_id) {
|
|
5515
5662
|
fail('STRUCTURE_BINDING_MISMATCH', 'project_id_mismatch');
|
|
5516
5663
|
}
|
|
@@ -5576,7 +5723,7 @@ export async function writeTodoStructureBinding(options = {}) {
|
|
|
5576
5723
|
fail('INVALID_TODO_STRUCTURE_BINDING', 'structure_binding_invalid');
|
|
5577
5724
|
}
|
|
5578
5725
|
return withLock(repoRoot, async () => {
|
|
5579
|
-
const store = await
|
|
5726
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
5580
5727
|
if (store.project_id !== binding.project_id) {
|
|
5581
5728
|
fail('STRUCTURE_BINDING_MISMATCH', 'project_id_mismatch');
|
|
5582
5729
|
}
|
|
@@ -5640,7 +5787,7 @@ export async function writeTodoStructureFinalization(options = {}) {
|
|
|
5640
5787
|
fail('INVALID_TODO_STRUCTURE_FINALIZATION', 'finalization_not_consistent');
|
|
5641
5788
|
}
|
|
5642
5789
|
return withLock(repoRoot, async () => {
|
|
5643
|
-
const store = await
|
|
5790
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
5644
5791
|
const member = activeMember(store, artifact.plan_key);
|
|
5645
5792
|
if (store.project_id !== artifact.project_id || member.plan.project_id !== artifact.project_id) {
|
|
5646
5793
|
fail('STRUCTURE_BINDING_MISMATCH', 'project_id_mismatch');
|
|
@@ -5756,7 +5903,7 @@ export async function appendTodoStructureRealization(options = {}) {
|
|
|
5756
5903
|
fail('INVALID_TODO_STRUCTURE_REALIZATION', initial.reason, { path: initial.path });
|
|
5757
5904
|
}
|
|
5758
5905
|
return withLock(repoRoot, async () => {
|
|
5759
|
-
const store = await
|
|
5906
|
+
const store = await readTodoStoreLocked({ repoRoot, forWrite: true, now: options.now });
|
|
5760
5907
|
const member = activeMember(store, realization.plan_key);
|
|
5761
5908
|
if (store.project_id !== realization.project_id
|
|
5762
5909
|
|| member.plan.plan_version !== realization.plan_version) {
|