@quolu/lattice 0.79.5 → 0.80.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 (51) 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/fs-publish.mjs +9 -0
  6. package/src/mcp-startup-receipt.mjs +3 -3
  7. package/src/project-cli.mjs +2 -2
  8. package/src/runtime-os-observation.mjs +18 -1
  9. package/src/store-lock.mjs +250 -0
  10. package/src/todo-cli.mjs +6 -0
  11. package/src/todo-contracts.mjs +95 -50
  12. package/src/todo-migration.mjs +35 -10
  13. package/src/todo-note-store.mjs +45 -12
  14. package/src/todo-readiness.mjs +154 -0
  15. package/src/todo-status.mjs +4 -33
  16. package/src/todo-store-git-transaction.mjs +11 -6
  17. package/src/todo-store-view.mjs +47 -0
  18. package/src/todo-store.mjs +597 -398
  19. package/src/artifact-contracts-v2.mjs +0 -325
  20. package/src/boundary-compiler.mjs +0 -712
  21. package/src/bounded-seam.mjs +0 -230
  22. package/src/control-compiler.mjs +0 -532
  23. package/src/rc1-black-box-oracle.mjs +0 -906
  24. package/src/rc1-comparison.mjs +0 -154
  25. package/src/rc1-evidence-bundle.mjs +0 -456
  26. package/src/rc1-v4-campaign.mjs +0 -708
  27. package/src/rc1-v4-transform.mjs +0 -467
  28. package/src/rc1-v5-artifact-set.mjs +0 -855
  29. package/src/rc1-v5-behavior-evidence.mjs +0 -594
  30. package/src/rc1-v5-campaign.mjs +0 -797
  31. package/src/rc1-v5-transform.mjs +0 -421
  32. package/src/rc1-v6-artifact-set.mjs +0 -807
  33. package/src/rc1-v6-behavior-evidence.mjs +0 -273
  34. package/src/rc1-v6-campaign.mjs +0 -623
  35. package/src/rc1-v6-causal-binding.mjs +0 -473
  36. package/src/rc1-v6-measurement.mjs +0 -313
  37. package/src/rc2-artifact-set.mjs +0 -1584
  38. package/src/rc2-campaign.mjs +0 -1495
  39. package/src/rc2-delivery-policy-front-end.mjs +0 -1079
  40. package/src/rc2-delivery-policy-oracle.mjs +0 -134
  41. package/src/rc2-delivery-policy-transform.mjs +0 -1127
  42. package/src/rc2-rc1-transfer-front-end.mjs +0 -511
  43. package/src/rc3-actual-dogfood.mjs +0 -652
  44. package/src/rc3-dogfood-scaffold.mjs +0 -315
  45. package/src/rc3-scripted-campaign.mjs +0 -1383
  46. package/src/rc4-stage1-dogfood.mjs +0 -673
  47. package/src/runtime-scripted-executor.mjs +0 -163
  48. package/src/runtime-worktree-executor.mjs +0 -199
  49. package/src/seam-transform.mjs +0 -554
  50. package/src/treatment-compiler.mjs +0 -728
  51. package/src/treatment-runner.mjs +0 -656
@@ -62,21 +62,24 @@
62
62
  "maxItems": 2048,
63
63
  "items": {
64
64
  "$ref": "#/$defs/edge"
65
- }
65
+ },
66
+ "description": "from、toの順に、各参照を(project_id, plan_key, task_id)の組として辞書順に並べる。同じfrom/toの組は重複できない。expected_topology_digestは並び順に含めない。"
66
67
  },
67
68
  "joins": {
68
69
  "type": "array",
69
70
  "maxItems": 128,
70
71
  "items": {
71
72
  "$ref": "#/$defs/join"
72
- }
73
+ },
74
+ "description": "joinをidの昇順・重複なしで並べる。各joinのafterは(project_id, plan_key, task_id)の組の辞書順・重複なしで並べ、expected_topology_digestは並び順に含めない。"
73
75
  },
74
76
  "phase_accept_dependencies": {
75
77
  "type": "array",
76
78
  "maxItems": 2048,
77
79
  "items": {
78
80
  "$ref": "#/$defs/phaseAcceptDependency"
79
- }
81
+ },
82
+ "description": "from phase参照を(project_id, plan_key, phase_id)、to task参照を(project_id, plan_key, task_id)の組として、from、toの順に辞書順で並べる。同じfrom/toの組は重複できない。expected_topology_digestは並び順に含めない。"
80
83
  },
81
84
  "input_digest": {
82
85
  "$ref": "#/$defs/authoringDigest"
@@ -341,7 +344,8 @@
341
344
  "maxItems": 512,
342
345
  "items": {
343
346
  "$ref": "#/$defs/nodeRef"
344
- }
347
+ },
348
+ "description": "参照を(project_id, plan_key, task_id)の組の辞書順・重複なしで並べる。expected_topology_digestは並び順に含めない。"
345
349
  },
346
350
  "before": {
347
351
  "$ref": "#/$defs/nodeRef"
@@ -17,7 +17,7 @@
17
17
  "plan_version": { "$ref": "#/$defs/identifier" },
18
18
  "actor": { "$ref": "#/$defs/actor" },
19
19
  "recorded_at": { "$ref": "#/$defs/strictTimestamp" },
20
- "tasks": { "type": "array", "minItems": 1, "maxItems": 512, "items": { "$ref": "#/$defs/task" } },
20
+ "tasks": { "type": "array", "minItems": 1, "maxItems": 512, "items": { "$ref": "#/$defs/task" }, "description": "Sort by task_id ascending; task_id values must be unique." },
21
21
  "hard_dependencies": {
22
22
  "type": "array", "maxItems": 2048,
23
23
  "items": {
@@ -27,7 +27,8 @@
27
27
  "to": { "$ref": "#/$defs/nodeRef" },
28
28
  "reason": { "$ref": "#/$defs/text" }
29
29
  }
30
- }
30
+ },
31
+ "description": "Sort by from then to ascending, comparing each reference as the tuple (project_id, plan_key, task_id). Duplicate from/to pairs are not allowed. expected_topology_digest is excluded from the sort key."
31
32
  },
32
33
  "joins": {
33
34
  "type": "array", "maxItems": 128,
@@ -38,7 +39,8 @@
38
39
  "after": { "type": "array", "minItems": 1, "maxItems": 512, "items": { "$ref": "#/$defs/nodeRef" } },
39
40
  "before": { "$ref": "#/$defs/nodeRef" }
40
41
  }
41
- }
42
+ },
43
+ "description": "Sort joins by id ascending with no duplicate ids. In each join, sort after references by the tuple (project_id, plan_key, task_id) ascending with no duplicates; expected_topology_digest is excluded from the sort key."
42
44
  },
43
45
  "extraction_digest": { "$ref": "#/$defs/digest" }
44
46
  },
@@ -17,7 +17,7 @@
17
17
  "plan_version": { "$ref": "#/$defs/identifier" },
18
18
  "actor": { "$ref": "#/$defs/actor" },
19
19
  "recorded_at": { "$ref": "#/$defs/strictTimestamp" },
20
- "tasks": { "type": "array", "minItems": 0, "maxItems": 512, "items": { "$ref": "#/$defs/task" } },
20
+ "tasks": { "type": "array", "minItems": 0, "maxItems": 512, "items": { "$ref": "#/$defs/task" }, "description": "Sort by task_id ascending; task_id values must be unique." },
21
21
  "hard_dependencies": {
22
22
  "type": "array", "maxItems": 2048,
23
23
  "items": {
@@ -27,7 +27,8 @@
27
27
  "to": { "$ref": "#/$defs/nodeRef" },
28
28
  "reason": { "$ref": "#/$defs/text" }
29
29
  }
30
- }
30
+ },
31
+ "description": "Sort by from then to ascending, comparing each reference as the tuple (project_id, plan_key, task_id). Duplicate from/to pairs are not allowed. expected_topology_digest is excluded from the sort key."
31
32
  },
32
33
  "joins": {
33
34
  "type": "array", "maxItems": 128,
@@ -38,7 +39,8 @@
38
39
  "after": { "type": "array", "minItems": 1, "maxItems": 512, "items": { "$ref": "#/$defs/nodeRef" } },
39
40
  "before": { "$ref": "#/$defs/nodeRef" }
40
41
  }
41
- }
42
+ },
43
+ "description": "Sort joins by id ascending with no duplicate ids. In each join, sort after references by the tuple (project_id, plan_key, task_id) ascending with no duplicates; expected_topology_digest is excluded from the sort key."
42
44
  },
43
45
  "extraction_digest": { "$ref": "#/$defs/digest" }
44
46
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.79.5",
3
+ "version": "0.80.0",
4
4
  "description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
5
5
  "author": {
6
6
  "name": "Quo / クオ at kitepon.dev",
@@ -1,6 +1,15 @@
1
1
  import { rename } from 'node:fs/promises';
2
2
  import { setTimeout } from 'node:timers/promises';
3
3
 
4
+ /** Same file-sync policy for Store artifacts and transient ownership records. */
5
+ export async function syncPublishedFile(handle, absolute, { platform = process.platform } = {}) {
6
+ try { await handle.sync(); }
7
+ catch (error) {
8
+ if (!(platform === 'linux' && /^\/mnt\//u.test(absolute) && error?.code === 'EIO')) throw error;
9
+ process.stderr.write(`lattice: fsync skipped (WSL2/NTFS EIO) ${absolute}\n`);
10
+ }
11
+ }
12
+
4
13
  /** Windowsは読み手が開いている宛先へのrenameを一時的にEPERMで拒否する。
5
14
  * 同じatomic renameを待って再実行し、恒久的な拒否は元のエラーで返す。 */
6
15
  export async function renamePublishedFile(source, destination, {
@@ -2,8 +2,8 @@ import { Worker, isMainThread, parentPort, workerData } from 'node:worker_thread
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { homedir } from 'node:os';
4
4
  import path from 'node:path';
5
- import { lstatSync, mkdirSync, openSync, writeFileSync, closeSync, renameSync, readdirSync } from 'node:fs';
6
- import { ensureSafeDir, ensureSafeFile } from './runtime-errors.mjs';
5
+ import { lstatSync, mkdirSync, openSync, writeFileSync, closeSync, readdirSync } from 'node:fs';
6
+ import { ensureSafeDir, ensureSafeFile, replaceStoreFile } from './runtime-errors.mjs';
7
7
  import { observeDashboardProcess } from './dashboard-process-control.mjs';
8
8
  import { isAclScratchName } from './windows-owner-only.mjs';
9
9
 
@@ -91,7 +91,7 @@ if (!isMainThread && workerData?.receipt === true) {
91
91
  const fd = openSync(temporary, 'wx', 0o600);
92
92
  try { writeFileSync(fd, bytes); } finally { closeSync(fd); }
93
93
  ensureSafeFile(temporary, slot);
94
- renameSync(temporary, target);
94
+ replaceStoreFile(temporary, target);
95
95
  }
96
96
  parentPort.on('message', message => {
97
97
  queue = queue.then(() => receive(message)).catch(() => { disabled = true; parentPort.close(); });
@@ -583,11 +583,11 @@ function describeCreateInputViolation(value) {
583
583
  ...(decoupledPhaseInput ? { phase_accept_dependencies: value.phase_accept_dependencies } : {}),
584
584
  });
585
585
  } catch (error) {
586
- // buildTodoPlanは通否しか返さない。authorが書いた形を自分で診てpointerを出す。
586
+ // Author-specific fields keep their existing diagnostic priority.
587
587
  const shape = describePlanShapeViolation(value, { phaseInput });
588
588
  if (shape !== null) return shape;
589
589
  return {
590
- violation_kind: error?.reason ?? error?.code ?? 'topology_invalid',
590
+ violation_kind: error?.detail?.violation_kind ?? error?.reason ?? error?.code ?? 'topology_invalid',
591
591
  pointer: error?.detail?.pointer ?? '/',
592
592
  expected: error?.detail?.expected ?? { schema: value.schema },
593
593
  actual: error?.detail?.actual ?? { message: String(error?.message ?? error) },
@@ -1,5 +1,5 @@
1
1
  import { execFile } from 'node:child_process';
2
- import { realpath } from 'node:fs/promises';
2
+ import { readFile, readlink, realpath } from 'node:fs/promises';
3
3
  import { promisify } from 'node:util';
4
4
 
5
5
  const execFileAsync = promisify(execFile);
@@ -16,6 +16,23 @@ const WINDOWS_TICKS_PER_MILLISECOND = 10_000n;
16
16
  // 非ASCIIを可逆に表現するため、この劣化は起きない。
17
17
  export function osObservationEnvironment() { return { ...process.env, LC_ALL: 'C' }; }
18
18
 
19
+ /** Host/PID domain for local ownership checks; never a hostname or public actor. */
20
+ export async function observeProcessHostIdentityRaw() {
21
+ if (process.platform === 'linux') {
22
+ const [boot, namespace] = await Promise.all([
23
+ readFile('/proc/sys/kernel/random/boot_id', 'utf8'), readlink('/proc/self/ns/pid'),
24
+ ]);
25
+ return `${boot.trim()}:${namespace}`;
26
+ }
27
+ const executable = process.platform === 'win32' ? 'pwsh.exe' : '/usr/sbin/sysctl';
28
+ const args = process.platform === 'win32'
29
+ ? ['-NoProfile', '-NonInteractive', '-Command',
30
+ "[Microsoft.Win32.Registry]::GetValue('HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography','MachineGuid',$null)"]
31
+ : ['-n', 'kern.bootsessionuuid'];
32
+ const { stdout } = await execFileAsync(executable, args, { encoding: 'utf8', env: osObservationEnvironment() });
33
+ return stdout.trim();
34
+ }
35
+
19
36
  /** processのstart identity(darwin/linuxはps lstart、win32はPowerShell StartTime Ticks)の生文字列を返す。 */
20
37
  export async function observeStartIdentityRaw(pid) {
21
38
  const executable = process.platform === 'win32' ? 'pwsh.exe' : '/bin/ps';
@@ -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); }