@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.
Files changed (56) hide show
  1. package/docs/schemas/lattice.plan_create_input.v4.schema.json +8 -4
  2. package/docs/schemas/lattice.todo_extraction.v3.schema.json +5 -3
  3. package/docs/schemas/lattice.todo_extraction.v4.schema.json +5 -3
  4. package/package.json +1 -1
  5. package/src/bridge-config.mjs +6 -7
  6. package/src/fs-publish.mjs +9 -0
  7. package/src/mcp-startup-receipt.mjs +3 -3
  8. package/src/plan-backchain.mjs +4 -3
  9. package/src/project-cli.mjs +22 -10
  10. package/src/runtime-multi-epoch-store.mjs +53 -13
  11. package/src/runtime-os-observation.mjs +18 -1
  12. package/src/seat-identity.mjs +23 -0
  13. package/src/store-lock.mjs +250 -0
  14. package/src/todo-cli.mjs +6 -0
  15. package/src/todo-contracts.mjs +95 -50
  16. package/src/todo-migration.mjs +35 -10
  17. package/src/todo-note-store.mjs +45 -12
  18. package/src/todo-readiness.mjs +154 -0
  19. package/src/todo-revision.mjs +7 -5
  20. package/src/todo-status.mjs +4 -33
  21. package/src/todo-store-git-transaction.mjs +11 -6
  22. package/src/todo-store-view.mjs +105 -0
  23. package/src/todo-store.mjs +602 -455
  24. package/src/artifact-contracts-v2.mjs +0 -325
  25. package/src/boundary-compiler.mjs +0 -712
  26. package/src/bounded-seam.mjs +0 -230
  27. package/src/control-compiler.mjs +0 -532
  28. package/src/rc1-black-box-oracle.mjs +0 -906
  29. package/src/rc1-comparison.mjs +0 -154
  30. package/src/rc1-evidence-bundle.mjs +0 -456
  31. package/src/rc1-v4-campaign.mjs +0 -708
  32. package/src/rc1-v4-transform.mjs +0 -467
  33. package/src/rc1-v5-artifact-set.mjs +0 -855
  34. package/src/rc1-v5-behavior-evidence.mjs +0 -594
  35. package/src/rc1-v5-campaign.mjs +0 -797
  36. package/src/rc1-v5-transform.mjs +0 -421
  37. package/src/rc1-v6-artifact-set.mjs +0 -807
  38. package/src/rc1-v6-behavior-evidence.mjs +0 -273
  39. package/src/rc1-v6-campaign.mjs +0 -623
  40. package/src/rc1-v6-causal-binding.mjs +0 -473
  41. package/src/rc1-v6-measurement.mjs +0 -313
  42. package/src/rc2-artifact-set.mjs +0 -1584
  43. package/src/rc2-campaign.mjs +0 -1495
  44. package/src/rc2-delivery-policy-front-end.mjs +0 -1079
  45. package/src/rc2-delivery-policy-oracle.mjs +0 -134
  46. package/src/rc2-delivery-policy-transform.mjs +0 -1127
  47. package/src/rc2-rc1-transfer-front-end.mjs +0 -511
  48. package/src/rc3-actual-dogfood.mjs +0 -652
  49. package/src/rc3-dogfood-scaffold.mjs +0 -315
  50. package/src/rc3-scripted-campaign.mjs +0 -1383
  51. package/src/rc4-stage1-dogfood.mjs +0 -673
  52. package/src/runtime-scripted-executor.mjs +0 -163
  53. package/src/runtime-worktree-executor.mjs +0 -199
  54. package/src/seam-transform.mjs +0 -554
  55. package/src/treatment-compiler.mjs +0 -728
  56. package/src/treatment-runner.mjs +0 -656
@@ -0,0 +1,250 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { link, lstat, mkdir, open, readFile, readdir, rm, rmdir } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fsyncDirectory } from './fs-dir-sync.mjs';
5
+ import { syncPublishedFile } from './fs-publish.mjs';
6
+ import { observeStartIdentityRaw, observeProcessHostIdentityRaw } from './runtime-os-observation.mjs';
7
+
8
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
9
+ const CLAIM = /^([0-9a-f]{64})-([1-9][0-9]*)-([0-9a-f]{64})-([0-9a-f]{16})$/u;
10
+ let ownStart;
11
+ let ownHost;
12
+
13
+ export class StoreLockError extends Error {
14
+ constructor(reason, lockPath, detail = {}) {
15
+ super(reason);
16
+ this.name = 'StoreLockError';
17
+ this.reason = reason;
18
+ this.detail = {
19
+ lock_path: lockPath,
20
+ next_action: reason === 'lock_owner_unidentified'
21
+ ? `Confirm no writer is running, then manually remove the unidentified lock: ${lockPath}`
22
+ : `Retry after the owner releases ${lockPath}; if it cannot, confirm no writer on the recorded host before manually clearing the abandoned lock.`,
23
+ ...detail,
24
+ };
25
+ }
26
+ }
27
+
28
+ function identified(owner) {
29
+ return owner !== null && typeof owner === 'object'
30
+ && Object.keys(owner).sort().join(',') === 'host,pid,process_start'
31
+ && Number.isSafeInteger(owner.pid) && owner.pid > 0
32
+ && typeof owner.host === 'string' && owner.host.length > 0 && owner.host.length <= 255
33
+ && owner.process_start !== null && typeof owner.process_start === 'object'
34
+ && Object.keys(owner.process_start).sort().join(',') === 'identity,platform'
35
+ && typeof owner.process_start.platform === 'string' && owner.process_start.platform.length > 0
36
+ && typeof owner.process_start.identity === 'string'
37
+ && owner.process_start.identity.length > 0 && owner.process_start.identity.length <= 1024;
38
+ }
39
+
40
+ async function processIsDead(pid, startDigest) {
41
+ try {
42
+ const observed = await observeStartIdentityRaw(pid);
43
+ if (observed) return hash(`${process.platform}:${observed}`) !== startDigest;
44
+ } catch {
45
+ // A failed observation cannot turn an existing PID into a dead owner.
46
+ }
47
+ try { process.kill(pid, 0); return false; }
48
+ catch (error) { return error?.code === 'ESRCH'; }
49
+ }
50
+
51
+ async function readOwner(lockPath) {
52
+ try {
53
+ const info = await lstat(lockPath);
54
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 8192) {
55
+ throw new StoreLockError('lock_owner_unidentified', lockPath);
56
+ }
57
+ let owner;
58
+ try { owner = JSON.parse(await readFile(lockPath, 'utf8')); }
59
+ catch (error) {
60
+ if (error?.code === 'ENOENT') return null;
61
+ if (!(error instanceof SyntaxError)) throw error;
62
+ throw new StoreLockError('lock_owner_unidentified', lockPath);
63
+ }
64
+ if (!identified(owner)) throw new StoreLockError('lock_owner_unidentified', lockPath);
65
+ return owner;
66
+ } catch (error) {
67
+ if (error?.code === 'ENOENT') return null;
68
+ throw error;
69
+ }
70
+ }
71
+
72
+ async function ownerIsDead(owner, host) {
73
+ return owner.host === host && owner.process_start.platform === process.platform
74
+ && processIsDead(owner.pid,
75
+ hash(`${owner.process_start.platform}:${owner.process_start.identity}`));
76
+ }
77
+
78
+ async function removeDeadTemporaries(lockPath, hostDigest) {
79
+ const prefix = `${path.basename(lockPath)}.`;
80
+ for (const name of await readdir(path.dirname(lockPath))) {
81
+ if (!name.startsWith(prefix) || !name.endsWith('.tmp')) continue;
82
+ const parsed = name.slice(prefix.length, -4).match(CLAIM);
83
+ if (parsed && parsed[1] === hostDigest && Number.isSafeInteger(Number(parsed[2]))
84
+ && await processIsDead(Number(parsed[2]), parsed[3])) {
85
+ const temporary = path.join(path.dirname(lockPath), name);
86
+ const info = await lstat(temporary).catch((error) => {
87
+ if (error?.code !== 'ENOENT') throw error;
88
+ return null;
89
+ });
90
+ if (info?.isFile() && !info.isSymbolicLink()) await rm(temporary, { force: true });
91
+ }
92
+ }
93
+ }
94
+
95
+ async function recoveryClaim(claimsPath, owner, lockPath) {
96
+ const hostDigest = hash(owner.host);
97
+ const name = `${hostDigest}-${owner.pid}-${hash(`${owner.process_start.platform}:${owner.process_start.identity}`)}-${randomBytes(8).toString('hex')}`;
98
+ const claimPath = path.join(claimsPath, name);
99
+ // A releasing claimant may remove the empty parent between these mkdir calls.
100
+ for (;;) {
101
+ await mkdir(claimsPath, { recursive: true, mode: 0o700 });
102
+ const parent = await lstat(claimsPath);
103
+ if (!parent.isDirectory() || parent.isSymbolicLink()) throw new StoreLockError('store_locked', lockPath);
104
+ try { await mkdir(claimPath, { mode: 0o700 }); break; }
105
+ catch (error) { if (error?.code !== 'ENOENT') throw error; }
106
+ }
107
+ try {
108
+ await removeDeadClaims(claimsPath, hostDigest, lockPath);
109
+ // All claimants publish before inspection; only a sole claimant may recover.
110
+ // Timestamp ordering could let a delayed earlier publisher enter twice.
111
+ const candidates = await readdir(claimsPath);
112
+ if (candidates.length === 1 && candidates[0] === name) return claimPath;
113
+ throw new StoreLockError('store_locked', lockPath, {
114
+ recovery_claims_path: claimsPath,
115
+ next_action: `Retry after recovery claimants exit; for foreign or unidentified claims, confirm no writer on their recorded host before clearing only abandoned entries in ${claimsPath}`,
116
+ });
117
+ } catch (error) {
118
+ await rmdir(claimPath);
119
+ throw error;
120
+ }
121
+ }
122
+
123
+ async function removeDeadClaims(claimsPath, hostDigest, lockPath) {
124
+ const state = await lstat(claimsPath).catch((error) => {
125
+ if (error?.code !== 'ENOENT') throw error;
126
+ return null;
127
+ });
128
+ if (state === null) return;
129
+ if (!state.isDirectory() || state.isSymbolicLink()) {
130
+ throw new StoreLockError('store_locked', lockPath, { recovery_claims_path: claimsPath });
131
+ }
132
+ for (const entry of await readdir(claimsPath, { withFileTypes: true })) {
133
+ const parsed = entry.name.match(CLAIM);
134
+ if (entry.isDirectory() && parsed && parsed[1] === hostDigest
135
+ && Number.isSafeInteger(Number(parsed[2]))
136
+ && await processIsDead(Number(parsed[2]), parsed[3])) {
137
+ try { await rmdir(path.join(claimsPath, entry.name)); }
138
+ catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
139
+ }
140
+ }
141
+ }
142
+
143
+ async function removeClaim(claimPath, claimsPath) {
144
+ try { await rmdir(claimPath); }
145
+ catch (error) { if (error?.code !== 'ENOENT') throw error; }
146
+ try { await rmdir(claimsPath); }
147
+ catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
148
+ }
149
+
150
+ /** Complete ownership is linked atomically; recovery never removes a live owner. */
151
+ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath}.recovery`,
152
+ onRecoveryClaim = null, createParent = true, releasePath = () => lockPath }, callback) {
153
+ if (createParent) await mkdir(path.dirname(lockPath), { recursive: true });
154
+ ownStart ??= observeStartIdentityRaw(process.pid).catch((error) => { ownStart = undefined; throw error; });
155
+ ownHost ??= observeProcessHostIdentityRaw().then((value) => {
156
+ if (!value) throw new Error('process host domain unavailable');
157
+ return `${process.platform}:${hash(value)}`;
158
+ }).catch((error) => { ownHost = undefined; throw error; });
159
+ let identity;
160
+ let host;
161
+ try { [identity, host] = await Promise.all([ownStart, ownHost]); }
162
+ catch {
163
+ throw new StoreLockError('store_locked', lockPath, {
164
+ cause: 'lock_identity_unavailable',
165
+ next_action: `Restore platform host-domain and process-start observation, then retry ${lockPath}`,
166
+ });
167
+ }
168
+ const owner = { pid: process.pid,
169
+ process_start: { platform: process.platform, identity }, host };
170
+ if (!identified(owner)) throw new StoreLockError('store_locked', lockPath, {
171
+ cause: 'lock_identity_unavailable',
172
+ next_action: `Restore platform host-domain and process-start observation, then retry ${lockPath}`,
173
+ });
174
+ const ownerBytes = `${JSON.stringify(owner)}\n`;
175
+ const temporary = `${lockPath}.${hash(host)}-${owner.pid}-${hash(`${owner.process_start.platform}:${owner.process_start.identity}`)}-${randomBytes(8).toString('hex')}.tmp`;
176
+ let claimPath = null;
177
+ let acquired = false;
178
+ let fileIdentity = null;
179
+ let callbackEntered = false;
180
+ try {
181
+ await removeDeadTemporaries(lockPath, hash(host));
182
+ for (const claimsPath of new Set([recoveryClaimsPath, `${lockPath}.recovery`])) {
183
+ await removeDeadClaims(claimsPath, hash(host), lockPath);
184
+ try { await rmdir(claimsPath); }
185
+ catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
186
+ }
187
+ const handle = await open(temporary, 'wx', 0o600);
188
+ try {
189
+ await handle.writeFile(ownerBytes); await syncPublishedFile(handle, lockPath);
190
+ fileIdentity = await handle.stat();
191
+ }
192
+ finally { await handle.close(); }
193
+ for (;;) {
194
+ try { await link(temporary, lockPath); acquired = true; break; }
195
+ catch (error) {
196
+ if (['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS'].includes(error?.code)) {
197
+ throw new StoreLockError('store_locked', lockPath, {
198
+ cause: 'lock_publication_unavailable',
199
+ next_action: `Use a filesystem permitting atomic hard-link publication for ${lockPath}, then retry`,
200
+ });
201
+ }
202
+ if (error?.code !== 'EEXIST') throw error;
203
+ }
204
+ const existing = await readOwner(lockPath);
205
+ if (existing === null) continue;
206
+ if (!await ownerIsDead(existing, host)) throw new StoreLockError('store_locked', lockPath);
207
+ if (claimPath === null) {
208
+ claimPath = await recoveryClaim(recoveryClaimsPath, owner, lockPath);
209
+ if (onRecoveryClaim) await onRecoveryClaim();
210
+ }
211
+ const fresh = await readOwner(lockPath);
212
+ if (fresh !== null) {
213
+ if (!await ownerIsDead(fresh, host)) throw new StoreLockError('store_locked', lockPath);
214
+ await rm(lockPath);
215
+ }
216
+ }
217
+ await rm(temporary);
218
+ await fsyncDirectory(path.dirname(lockPath));
219
+ callbackEntered = true;
220
+ return await callback();
221
+ } catch (error) {
222
+ if (!callbackEntered && error?.code === 'ENOENT') {
223
+ throw new StoreLockError('store_locked', lockPath, {
224
+ cause: 'lock_parent_missing',
225
+ next_action: `Retry after initialization or recovery finishes publishing ${path.dirname(lockPath)}`,
226
+ });
227
+ }
228
+ throw error;
229
+ } finally {
230
+ try {
231
+ const currentLockPath = await releasePath();
232
+ const currentIdentity = currentLockPath === null ? null : await lstat(currentLockPath).catch((error) => {
233
+ if (error?.code === 'ENOENT') return null;
234
+ throw error;
235
+ });
236
+ if (acquired && currentIdentity?.isFile() && !currentIdentity.isSymbolicLink()
237
+ && currentIdentity.dev === fileIdentity.dev && currentIdentity.ino === fileIdentity.ino
238
+ && await readFile(currentLockPath, 'utf8').catch((error) => {
239
+ if (error?.code === 'ENOENT') return null;
240
+ throw error;
241
+ }) === ownerBytes) {
242
+ await rm(currentLockPath);
243
+ await fsyncDirectory(path.dirname(currentLockPath));
244
+ }
245
+ } finally {
246
+ await rm(temporary, { force: true });
247
+ if (claimPath !== null) await removeClaim(claimPath, recoveryClaimsPath);
248
+ }
249
+ }
250
+ }
package/src/todo-cli.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { validateProspectiveEvent } from './todo-readiness.mjs';
1
2
  import { cliCommandKind } from './cli-command-kind.mjs';
2
3
  import { cliFailureClass } from './cli-failure-class.mjs';
3
4
  import { readTaskBackchainContext } from './plan-backchain.mjs';
@@ -666,6 +667,7 @@ async function mutate({
666
667
  eventPayload = { done_mode: 'evidence_promotion', evidence };
667
668
  }
668
669
  const { event, snapshot, plan, phases } = await appendTodoEvent({
670
+ validateProspectiveEvent,
669
671
  repoRoot,
670
672
  writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
671
673
  planKey,
@@ -1078,6 +1080,7 @@ async function phaseDecisionFromEvidence({ repoRoot, env, planKey, phaseId, outc
1078
1080
 
1079
1081
  async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload }) {
1080
1082
  const { event, snapshot, phases } = await appendTodoEvent({
1083
+ validateProspectiveEvent,
1081
1084
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey,
1082
1085
  event: { kind, phase_id: phaseId, actor: mutationActor(env), payload },
1083
1086
  });
@@ -1105,6 +1108,7 @@ async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload })
1105
1108
  */
1106
1109
  async function independenceMode({ repoRoot, env, planKey, mode, reason }) {
1107
1110
  const { event } = await appendTodoEvent({
1111
+ validateProspectiveEvent,
1108
1112
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey,
1109
1113
  event: { kind: 'coordination_mode', actor: mutationActor(env), payload: { mode, reason } },
1110
1114
  });
@@ -1158,6 +1162,7 @@ async function dependencyConnect({
1158
1162
  expected_topology_digest: target.plan.topology_digest,
1159
1163
  };
1160
1164
  const { event } = await appendTodoEvent({
1165
+ validateProspectiveEvent,
1161
1166
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey: toPlanKey,
1162
1167
  event: {
1163
1168
  kind: 'cross_plan_dependency', actor: mutationActor(env), payload: { from, to, reason },
@@ -1195,6 +1200,7 @@ async function dependencyDisconnect({
1195
1200
  const owner = store.members.find((member) => (member.plan_scoped?.events ?? [])
1196
1201
  .some((event) => event.event_digest === target.event_digest));
1197
1202
  const { event } = await appendTodoEvent({
1203
+ validateProspectiveEvent,
1198
1204
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey: owner.plan.plan_key,
1199
1205
  tolerateStaleBindings: true,
1200
1206
  event: {
@@ -425,7 +425,20 @@ function validParentGraph(tasks) {
425
425
  return true;
426
426
  }
427
427
 
428
- export function validateTodoPlan(value) {
428
+ export function explainTodoOrder(values, key, pointer) {
429
+ for (let index = 1; index < values.length; index += 1) {
430
+ const previous = key(values[index - 1]);
431
+ const actual = key(values[index]);
432
+ if (compareText(previous, actual) >= 0) {
433
+ return { reason: 'unsorted_or_duplicate_collection', path: `${pointer}/${index}`,
434
+ expected: { order: 'ascending_unique', greater_than: previous }, actual };
435
+ }
436
+ }
437
+ return null;
438
+ }
439
+
440
+ export function explainTodoPlan(value) {
441
+ const reject = (reason, pointer) => ({ reason, path: pointer });
429
442
  try {
430
443
  const taskValidator = value?.schema === 'lattice.todo_plan.v1' ? taskV1
431
444
  : value?.schema === 'lattice.todo_plan.v2' ? taskV2
@@ -437,60 +450,92 @@ export function validateTodoPlan(value) {
437
450
  'schema', 'project_id', 'plan_key', 'plan_version', 'predecessor_plan_digest',
438
451
  'tasks', 'hard_dependencies', 'joins', 'topology_digest', 'plan_digest',
439
452
  ];
440
- if (['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7']
441
- .includes(value?.schema)) planKeys.push('phases');
442
- if (['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value?.schema)) {
443
- planKeys.push('phase_accept_dependencies');
453
+ const phased = ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7']
454
+ .includes(value?.schema);
455
+ const decoupled = ['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value?.schema);
456
+ if (phased) planKeys.push('phases');
457
+ if (decoupled) planKeys.push('phase_accept_dependencies');
458
+ if (!exactRecord(value, planKeys)) return reject('unexpected_or_missing_keys', '/');
459
+ if (taskValidator === null) return reject('schema_mismatch', '/schema');
460
+ for (const field of ['project_id', 'plan_key', 'plan_version']) {
461
+ if (!isTodoIdentifier(value[field])) return reject('identifier_invalid', `/${field}`);
462
+ }
463
+ if (!nullableDigest(value.predecessor_plan_digest)) return reject('digest_invalid', '/predecessor_plan_digest');
464
+ if (!Array.isArray(value.tasks) || value.tasks.length === 0
465
+ || value.tasks.length > TODO_LIMITS.tasksPerPlan) return reject('bounded_collection_violation', '/tasks');
466
+ const invalidTask = value.tasks.findIndex((task) => !taskValidator(task));
467
+ if (invalidTask >= 0) return reject('task_shape_invalid', `/tasks/${invalidTask}`);
468
+ if (new Set(value.tasks.map(({ task_id }) => task_id)).size !== value.tasks.length) {
469
+ return reject('duplicate_task_id', '/tasks');
470
+ }
471
+ if (!Array.isArray(value.hard_dependencies) || value.hard_dependencies.length > TODO_LIMITS.edgesPerPlan) {
472
+ return reject('bounded_collection_violation', '/hard_dependencies');
473
+ }
474
+ const invalidEdge = value.hard_dependencies.findIndex((edge) => !exactRecord(edge, ['from', 'to'])
475
+ || !nodeRef(edge.from) || !nodeRef(edge.to));
476
+ if (invalidEdge >= 0) return reject('edge_shape_invalid', `/hard_dependencies/${invalidEdge}`);
477
+ if (!Array.isArray(value.joins) || value.joins.length > TODO_LIMITS.joinsPerPlan) {
478
+ return reject('bounded_collection_violation', '/joins');
479
+ }
480
+ const invalidJoin = value.joins.findIndex((join) => !exactRecord(join, ['id', 'after', 'before'])
481
+ || !isTodoIdentifier(join.id) || !Array.isArray(join.after) || join.after.length === 0
482
+ || join.after.length > TODO_LIMITS.tasksPerPlan || !join.after.every(nodeRef) || !nodeRef(join.before));
483
+ if (invalidJoin >= 0) return reject('join_shape_invalid', `/joins/${invalidJoin}`);
484
+ for (const field of ['topology_digest', 'plan_digest']) {
485
+ if (!isTodoDigest(value[field])) return reject('digest_invalid', `/${field}`);
486
+ }
487
+ if (['lattice.todo_plan.v3', 'lattice.todo_plan.v4', 'lattice.todo_plan.v5',
488
+ 'lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(value.schema)
489
+ && !validParentGraph(value.tasks)) return reject('parent_graph_invalid', '/tasks');
490
+ if (phased) {
491
+ if (!Array.isArray(value.phases) || value.phases.length === 0
492
+ || value.phases.length > TODO_LIMITS.tasksPerPlan) return reject('bounded_collection_violation', '/phases');
493
+ const invalidPhase = value.phases.findIndex((phase) => !phaseV1(phase));
494
+ if (invalidPhase >= 0) return reject('phase_shape_invalid', `/phases/${invalidPhase}`);
495
+ const order = explainTodoOrder(value.phases, (phase) => phase.phase_id, '/phases');
496
+ if (order !== null) return order;
497
+ const orphanTask = value.tasks.findIndex(({ phase_id }) => !value.phases.some((phase) => phase.phase_id === phase_id));
498
+ if (orphanTask >= 0) return reject('unknown_phase_reference', `/tasks/${orphanTask}/phase_id`);
499
+ if (!validPhaseGraph(value.phases)) return reject('phase_graph_invalid', '/phases');
500
+ }
501
+ if (decoupled) {
502
+ if (!Array.isArray(value.phase_accept_dependencies)
503
+ || value.phase_accept_dependencies.length > TODO_LIMITS.edgesPerPlan) {
504
+ return reject('bounded_collection_violation', '/phase_accept_dependencies');
505
+ }
506
+ const invalid = value.phase_accept_dependencies.findIndex((edge) => !exactRecord(edge, ['from', 'to'])
507
+ || !phaseRef(edge.from) || !nodeRef(edge.to));
508
+ if (invalid >= 0) return reject('edge_shape_invalid', `/phase_accept_dependencies/${invalid}`);
509
+ const order = explainTodoOrder(value.phase_accept_dependencies,
510
+ (edge) => `${phaseRefKey(edge.from)}\0${refKey(edge.to)}`, '/phase_accept_dependencies');
511
+ if (order !== null) return order;
512
+ }
513
+ for (const [values, key, pointer] of [
514
+ [value.tasks, (task) => task.task_id, '/tasks'],
515
+ [value.hard_dependencies, (edge) => `${refKey(edge.from)}\0${refKey(edge.to)}`, '/hard_dependencies'],
516
+ [value.joins, (join) => join.id, '/joins'],
517
+ ]) {
518
+ const order = explainTodoOrder(values, key, pointer);
519
+ if (order !== null) return order;
520
+ }
521
+ for (const [index, join] of value.joins.entries()) {
522
+ const order = explainTodoOrder(join.after, refKey, `/joins/${index}/after`);
523
+ if (order !== null) return order;
444
524
  }
445
- if (!exactRecord(value, planKeys) || taskValidator === null || !isTodoIdentifier(value.project_id)
446
- || !isTodoIdentifier(value.plan_key) || !isTodoIdentifier(value.plan_version)
447
- || !nullableDigest(value.predecessor_plan_digest) || !Array.isArray(value.tasks)
448
- || value.tasks.length === 0 || value.tasks.length > TODO_LIMITS.tasksPerPlan
449
- || !value.tasks.every(taskValidator) || new Set(value.tasks.map(({ task_id }) => task_id)).size !== value.tasks.length
450
- || !Array.isArray(value.hard_dependencies) || value.hard_dependencies.length > TODO_LIMITS.edgesPerPlan
451
- || !value.hard_dependencies.every((edge) => exactRecord(edge, ['from', 'to']) && nodeRef(edge.from) && nodeRef(edge.to))
452
- || !Array.isArray(value.joins) || value.joins.length > TODO_LIMITS.joinsPerPlan
453
- || !value.joins.every((join) => exactRecord(join, ['id', 'after', 'before']) && isTodoIdentifier(join.id)
454
- && Array.isArray(join.after) && join.after.length > 0 && join.after.length <= TODO_LIMITS.tasksPerPlan
455
- && join.after.every(nodeRef) && nodeRef(join.before))
456
- || !isTodoDigest(value.topology_digest) || !isTodoDigest(value.plan_digest)
457
- || (['lattice.todo_plan.v3', 'lattice.todo_plan.v4', 'lattice.todo_plan.v5',
458
- 'lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(value.schema)
459
- && !validParentGraph(value.tasks))) return false;
460
- if (['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
461
- && (!Array.isArray(value.phases) || value.phases.length === 0
462
- || value.phases.length > TODO_LIMITS.tasksPerPlan || !value.phases.every(phaseV1)
463
- || value.phases.some((entry, index) => index > 0
464
- && compareText(value.phases[index - 1].phase_id, entry.phase_id) >= 0)
465
- || new Set(value.phases.map(({ phase_id }) => phase_id)).size !== value.phases.length
466
- || value.tasks.some(({ phase_id }) => !value.phases.some((phase) => phase.phase_id === phase_id))
467
- || !validPhaseGraph(value.phases))) return false;
468
- if (['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
469
- && (!Array.isArray(value.phase_accept_dependencies)
470
- || value.phase_accept_dependencies.length > TODO_LIMITS.edgesPerPlan
471
- || !value.phase_accept_dependencies.every((edge) => exactRecord(edge, ['from', 'to'])
472
- && phaseRef(edge.from) && nodeRef(edge.to))
473
- || value.phase_accept_dependencies.some((edge, index) => index > 0
474
- && compareText(`${phaseRefKey(value.phase_accept_dependencies[index - 1].from)}\0${refKey(value.phase_accept_dependencies[index - 1].to)}`,
475
- `${phaseRefKey(edge.from)}\0${refKey(edge.to)}`) >= 0))) return false;
476
- if (value.tasks.some((entry, index) => index > 0 && compareText(value.tasks[index - 1].task_id, entry.task_id) >= 0)
477
- || value.hard_dependencies.some((edge, index) => index > 0
478
- && compareText(`${refKey(value.hard_dependencies[index - 1].from)}\0${refKey(value.hard_dependencies[index - 1].to)}`,
479
- `${refKey(edge.from)}\0${refKey(edge.to)}`) >= 0)
480
- || value.joins.some((join, index) => index > 0 && compareText(value.joins[index - 1].id, join.id) >= 0)
481
- || value.joins.some((join) => join.after.some((entry, index) => index > 0
482
- && compareText(refKey(join.after[index - 1]), refKey(entry)) >= 0))) return false;
483
525
  const topology = {
484
526
  project_id: value.project_id, plan_key: value.plan_key, plan_version: value.plan_version,
485
527
  tasks: value.tasks, hard_dependencies: value.hard_dependencies, joins: value.joins,
486
- ...(['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
487
- ? { phases: value.phases } : {}),
488
- ...(['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.schema)
489
- ? { phase_accept_dependencies: value.phase_accept_dependencies } : {}),
528
+ ...(phased ? { phases: value.phases } : {}),
529
+ ...(decoupled ? { phase_accept_dependencies: value.phase_accept_dependencies } : {}),
490
530
  };
491
- return value.topology_digest === digestTodoArtifact(topology)
492
- && value.plan_digest === todoSelfDigest(value, 'plan_digest');
493
- } catch { return false; }
531
+ if (value.topology_digest !== digestTodoArtifact(topology)) return reject('topology_digest_mismatch', '/topology_digest');
532
+ if (value.plan_digest !== todoSelfDigest(value, 'plan_digest')) return reject('plan_digest_mismatch', '/plan_digest');
533
+ return null;
534
+ } catch { return reject('diagnosis_failed', '/'); }
535
+ }
536
+
537
+ export function validateTodoPlan(value) {
538
+ return explainTodoPlan(value) === null;
494
539
  }
495
540
 
496
541
  export function validateEvidenceDescriptor(value) { return evidence(value); }
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  TODO_LIMITS,
3
3
  exactRecord,
4
+ explainTodoOrder,
4
5
  isStrictTodoTimestamp,
5
6
  isTodoDigest,
6
7
  isTodoDesignMemo,
@@ -56,7 +57,7 @@ function refKey(value) {
56
57
  }
57
58
 
58
59
  function sortedStrictly(values, key = (value) => value) {
59
- return values.every((value, index) => index === 0 || key(values[index - 1]) < key(value));
60
+ return explainTodoOrder(values, key, '') === null;
60
61
  }
61
62
 
62
63
  function sourceLocation(value) {
@@ -191,12 +192,9 @@ function explainKeys(value, requiredKeys, at) {
191
192
  }
192
193
 
193
194
  function explainSortedStrictly(values, key, at) {
194
- for (let index = 1; index < values.length; index += 1) {
195
- if (!(key(values[index - 1]) < key(values[index]))) {
196
- return reject('unsorted_or_duplicate_collection', `${at}/${index}`);
197
- }
198
- }
199
- return { valid: true };
195
+ const violation = explainTodoOrder(values, key, at);
196
+ return violation === null ? { valid: true }
197
+ : { valid: false, ...violation };
200
198
  }
201
199
 
202
200
  /**
@@ -275,8 +273,27 @@ export function explainTodoExtraction(value) {
275
273
  if (new Set(value.tasks.map(({ task_id: taskId }) => taskId)).size !== value.tasks.length) {
276
274
  return reject('duplicate_task_id', '/tasks');
277
275
  }
278
- if (!validateEdges(value.hard_dependencies, schema)) return reject('hard_dependencies_invalid', '/hard_dependencies');
279
- if (!validateJoins(value.joins)) return reject('joins_invalid', '/joins');
276
+ if (!validateEdges(value.hard_dependencies, schema)) {
277
+ if (Array.isArray(value.hard_dependencies)
278
+ && value.hard_dependencies.every((edge) => nodeRef(edge?.from) && nodeRef(edge?.to))) {
279
+ const order = explainSortedStrictly(value.hard_dependencies,
280
+ (edge) => `${refKey(edge.from)}\0${refKey(edge.to)}`, '/hard_dependencies');
281
+ if (!order.valid) return order;
282
+ }
283
+ return reject('hard_dependencies_invalid', '/hard_dependencies');
284
+ }
285
+ if (!validateJoins(value.joins)) {
286
+ if (Array.isArray(value.joins) && value.joins.every((join) => isTodoIdentifier(join?.id)
287
+ && Array.isArray(join.after) && join.after.every(nodeRef))) {
288
+ const order = explainSortedStrictly(value.joins, (join) => join.id, '/joins');
289
+ if (!order.valid) return order;
290
+ for (const [index, join] of value.joins.entries()) {
291
+ const afterOrder = explainSortedStrictly(join.after, refKey, `/joins/${index}/after`);
292
+ if (!afterOrder.valid) return afterOrder;
293
+ }
294
+ }
295
+ return reject('joins_invalid', '/joins');
296
+ }
280
297
  if (!isTodoDigest(value.extraction_digest)) return reject('invalid_digest', '/extraction_digest');
281
298
  const expectedDigest = todoSelfDigest(value, 'extraction_digest');
282
299
  if (value.extraction_digest !== expectedDigest) {
@@ -520,5 +537,13 @@ export function compileTodoExtraction(value, repoRoot) {
520
537
 
521
538
  export async function appendTodoExtraction({ repoRoot, extraction }) {
522
539
  const request = compileTodoExtraction(extraction, repoRoot);
523
- return appendImportedPlan(request);
540
+ try { return await appendImportedPlan(request); }
541
+ catch (error) {
542
+ if (!(error instanceof TypeError) || error.detail?.pointer === undefined) throw error;
543
+ const index = /^\/tasks\/(\d+)(?:\/|$)/u.exec(error.detail.pointer)?.[1];
544
+ throw new TodoStoreError('INVALID_TODO_EXTRACTION', 'schema_invalid', undefined, {
545
+ ...error.detail, pointer_space: 'todo_plan',
546
+ ...(index === undefined ? {} : { task_id: request.plan.tasks[Number(index)].task_id }),
547
+ });
548
+ }
524
549
  }
@@ -1,9 +1,11 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import { fsyncDirectory } from './fs-dir-sync.mjs';
3
3
  import {
4
- mkdir, open, readFile, readdir, rename, rm, stat,
4
+ lstat, mkdir, open, readFile, readdir, rename, rm, stat,
5
5
  } from 'node:fs/promises';
6
6
  import path from 'node:path';
7
+ import { StoreLockError, withStoreLock } from './store-lock.mjs';
8
+ import { syncPublishedFile } from './fs-publish.mjs';
7
9
 
8
10
  import {
9
11
  TODO_LIMITS,
@@ -151,6 +153,7 @@ export async function readTodoNoteEvents(options = {}) {
151
153
  const names = await sealedFiles(sealed);
152
154
  const events = [];
153
155
  let previousSegmentDigest = ZERO_DIGEST;
156
+ let lastSealedBytes = null;
154
157
  for (const name of names) {
155
158
  const match = name.match(SEALED_NAME);
156
159
  const bytes = await readOptionalBounded(path.join(sealed, name));
@@ -163,9 +166,11 @@ export async function readTodoNoteEvents(options = {}) {
163
166
  }
164
167
  events.push(...segmentEvents);
165
168
  previousSegmentDigest = segmentDigest;
169
+ lastSealedBytes = bytes;
166
170
  }
167
171
  const activeBytes = await readOptionalBounded(active, { missing: true });
168
- if (activeBytes !== null) events.push(...parseCanonicalSegment(activeBytes, active));
172
+ const duplicateActive = activeBytes !== null && lastSealedBytes?.equals(activeBytes) === true;
173
+ if (activeBytes !== null && !duplicateActive) events.push(...parseCanonicalSegment(activeBytes, active));
169
174
  // chainの分離は「そのfileへ何が積まれるか」で守る。混ざったchainは分離の意味を失うので
170
175
  // 黙って受けず、読んだ時点でtypedに落とす。
171
176
  if (events.some((event) => event.schema !== schema)) {
@@ -177,20 +182,19 @@ export async function readTodoNoteEvents(options = {}) {
177
182
  return {
178
183
  events,
179
184
  head_digest: events.at(-1)?.event_digest ?? null,
180
- active_bytes: activeBytes ?? Buffer.alloc(0),
185
+ active_bytes: duplicateActive ? Buffer.alloc(0) : activeBytes ?? Buffer.alloc(0),
181
186
  previous_segment_digest: previousSegmentDigest,
182
187
  };
183
188
  }
184
189
 
185
190
  async function atomicWrite(ref, bytes) {
186
- await mkdir(path.dirname(ref), { recursive: true });
187
191
  const temporary = path.join(path.dirname(ref),
188
192
  `.${path.basename(ref)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
189
193
  let handle;
190
194
  try {
191
195
  handle = await open(temporary, 'wx', 0o600);
192
196
  await handle.writeFile(bytes);
193
- await handle.sync();
197
+ await syncPublishedFile(handle, ref);
194
198
  await handle.close();
195
199
  handle = null;
196
200
  await rename(temporary, ref);
@@ -201,18 +205,45 @@ async function atomicWrite(ref, bytes) {
201
205
  }
202
206
  }
203
207
 
208
+ async function ensureNoteDirectory(root) {
209
+ try { await mkdir(root); }
210
+ catch (error) {
211
+ if (error?.code === 'ENOENT') fail('NOTE_WRITE_CONFLICT', 'note_store_locked', {
212
+ next_action: 'Retry after initialization or recovery finishes publishing the Todo Store.',
213
+ });
214
+ if (error?.code !== 'EEXIST') throw error;
215
+ }
216
+ const state = await lstat(root);
217
+ if (state.isSymbolicLink() || !state.isDirectory()) fail('NOTE_WRITE_CONFLICT', 'note_store_locked', {
218
+ next_action: `Restore a real note directory at ${root}, then retry.`,
219
+ });
220
+ }
221
+
204
222
  async function withNoteLock(repoRoot, callback) {
205
223
  const root = path.resolve(repoRoot, NOTE_ROOT_REF);
206
- await mkdir(root, { recursive: true });
207
- const lockRef = path.join(root, '.write.lock');
208
- let handle;
209
- try { handle = await open(lockRef, 'wx', 0o600); }
224
+ try {
225
+ for (const ref of ['.lattice', '.lattice/todo', '.lattice/todo/manifest.json']) {
226
+ const state = await lstat(path.resolve(repoRoot, ref)).catch((error) => {
227
+ if (error?.code !== 'ENOENT') throw error;
228
+ return null;
229
+ });
230
+ if (state === null || state.isSymbolicLink()
231
+ || (ref.endsWith('.json') ? !state.isFile() : !state.isDirectory())) {
232
+ fail('NOTE_WRITE_CONFLICT', 'note_store_locked', {
233
+ next_action: 'Initialize a published Todo Store before writing notes, then retry.',
234
+ });
235
+ }
236
+ }
237
+ await ensureNoteDirectory(root);
238
+ return await withStoreLock({ lockPath: path.join(root, '.write.lock'), createParent: false }, callback);
239
+ }
210
240
  catch (error) {
211
- if (error?.code === 'EEXIST') fail('NOTE_WRITE_CONFLICT', 'note_store_locked');
241
+ if (error instanceof StoreLockError) {
242
+ fail('NOTE_WRITE_CONFLICT', error.reason === 'store_locked' ? 'note_store_locked' : error.reason,
243
+ error.detail);
244
+ }
212
245
  throw error;
213
246
  }
214
- try { return await callback(); }
215
- finally { await handle.close(); await rm(lockRef, { force: true }); }
216
247
  }
217
248
 
218
249
  /** lifecycle artifactsへ触れず、独立note chainだけへ1 eventを追記する。 */
@@ -266,6 +297,7 @@ export async function appendTodoNote(options = {}) {
266
297
  if (!validateTodoNoteEvent(event)) throw new TypeError('todo note event input invalid');
267
298
 
268
299
  const paths = chainRefs(repoRoot, options.planKey, scope);
300
+ await ensureNoteDirectory(path.dirname(paths.active));
269
301
  const eventBytes = canonicalLine(event);
270
302
  if (chain.active_bytes.length > 0
271
303
  && chain.active_bytes.length + eventBytes.length > TODO_LIMITS.journalSegmentBytes) {
@@ -274,6 +306,7 @@ export async function appendTodoNote(options = {}) {
274
306
  const name = `${String(activeEvents[0].sequence).padStart(12, '0')}`
275
307
  + `-${String(activeEvents.at(-1).sequence).padStart(12, '0')}`
276
308
  + `-${chain.previous_segment_digest}-${segmentDigest}.jsonl`;
309
+ await ensureNoteDirectory(paths.sealed);
277
310
  await atomicWrite(path.join(paths.sealed, name), chain.active_bytes);
278
311
  await atomicWrite(paths.active, eventBytes);
279
312
  } else {