@quolu/lattice 0.82.0 → 0.84.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/README.ja.md +7 -6
- package/README.md +1 -1
- package/bin/lattice-bridge-supervisor.mjs +10 -0
- package/bin/lattice-dashboard.mjs +3 -18
- package/bin/lattice-mcp.mjs +6 -3
- package/bin/lattice.mjs +30 -23
- package/docs/schemas/lattice.plan_create_input.v4.schema.json +5 -11
- package/docs/schemas/lattice.plan_create_input.v5.schema.json +362 -0
- package/docs/schemas/lattice.plan_revise_input.v1.schema.json +38 -11
- package/package.json +2 -1
- package/sensor/dist/db/index.d.ts +1 -0
- package/sensor/dist/db/index.d.ts.map +1 -1
- package/sensor/dist/db/index.js +13 -0
- package/sensor/dist/db/index.js.map +1 -1
- package/sensor/dist/index.d.ts.map +1 -1
- package/sensor/dist/index.js +12 -2
- package/sensor/dist/index.js.map +1 -1
- package/sensor/dist/mcp/answer-freshness.js +1 -1
- package/sensor/dist/mcp/answer-freshness.js.map +1 -1
- package/sensor/dist/mcp/daemon-paths.d.ts +6 -0
- package/sensor/dist/mcp/daemon-paths.d.ts.map +1 -1
- package/sensor/dist/mcp/daemon-paths.js +7 -1
- package/sensor/dist/mcp/daemon-paths.js.map +1 -1
- package/sensor/dist/mcp/engine.d.ts +11 -0
- package/sensor/dist/mcp/engine.d.ts.map +1 -1
- package/sensor/dist/mcp/engine.js +83 -4
- package/sensor/dist/mcp/engine.js.map +1 -1
- package/sensor/dist/mcp/index-repair.d.ts +7 -0
- package/sensor/dist/mcp/index-repair.d.ts.map +1 -0
- package/sensor/dist/mcp/index-repair.js +93 -0
- package/sensor/dist/mcp/index-repair.js.map +1 -0
- package/sensor/dist/mcp/index.d.ts.map +1 -1
- package/sensor/dist/mcp/index.js +12 -7
- package/sensor/dist/mcp/index.js.map +1 -1
- package/sensor/dist/mcp/tools.d.ts +4 -0
- package/sensor/dist/mcp/tools.d.ts.map +1 -1
- package/sensor/dist/mcp/tools.js +29 -9
- package/sensor/dist/mcp/tools.js.map +1 -1
- package/src/bridge-hub-server.mjs +46 -9
- package/src/cli-help.mjs +10 -8
- package/src/cli-refusal-guidance.mjs +354 -0
- package/src/dashboard-delivery.mjs +2 -1
- package/src/dashboard-lifecycle-journal.mjs +42 -20
- package/src/hooks-cli.mjs +30 -6
- package/src/plan-backchain.mjs +95 -41
- package/src/plan-revise.mjs +274 -72
- package/src/project-cli.mjs +301 -163
- package/src/project-identity.mjs +14 -0
- package/src/runtime-cli.mjs +38 -29
- package/src/runtime-control-store.mjs +22 -1
- package/src/runtime-decision-verifier.mjs +27 -8
- package/src/runtime-engine.mjs +34 -5
- package/src/runtime-hold-recompile.mjs +19 -15
- package/src/runtime-kept-worktree.mjs +136 -0
- package/src/runtime-lifecycle-lock.mjs +118 -30
- package/src/runtime-managed-supervisor.mjs +10 -10
- package/src/runtime-pull-intake.mjs +90 -44
- package/src/store-lock.mjs +142 -57
- package/src/todo-authoring-input.mjs +211 -2
- package/src/todo-cli.mjs +554 -200
- package/src/todo-contracts.mjs +22 -6
- package/src/todo-dashboard-registry.mjs +35 -6
- package/src/todo-gantt-display.mjs +259 -0
- package/src/todo-gantt-html-independence.mjs +10 -3
- package/src/todo-gantt-html-shared.mjs +16 -1
- package/src/todo-gantt-html.mjs +74 -53
- package/src/todo-gantt-layout.mjs +137 -59
- package/src/todo-gantt-live.mjs +6 -3
- package/src/todo-independence-guidance.mjs +4 -26
- package/src/todo-note-store.mjs +6 -3
- package/src/todo-readiness.mjs +83 -20
- package/src/todo-revision.mjs +156 -8
- package/src/todo-split.mjs +6 -3
- package/src/todo-status.mjs +141 -54
- package/src/todo-store-cache.mjs +1 -1
- package/src/todo-store-view.mjs +20 -2
- package/src/todo-store.mjs +562 -444
package/src/store-lock.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
-
import { link, lstat, mkdir, open, readFile, readdir, rm, rmdir } from 'node:fs/promises';
|
|
2
|
+
import { link, lstat, mkdir, open, readFile, readdir, rename, rm, rmdir, utimes } from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { fsyncDirectory } from './fs-dir-sync.mjs';
|
|
5
5
|
import { syncPublishedFile } from './fs-publish.mjs';
|
|
@@ -7,6 +7,13 @@ import { observeStartIdentityRaw, observeProcessHostIdentityRaw } from './runtim
|
|
|
7
7
|
|
|
8
8
|
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
9
9
|
const CLAIM = /^([0-9a-f]{64})-([1-9][0-9]*)-([0-9a-f]{64})-([0-9a-f]{16})$/u;
|
|
10
|
+
// u03 N1/N2: an owner that cannot be proven dead (foreign host, legacy, weak) is abandoned once
|
|
11
|
+
// its heartbeat mtime is older than LOCK_STALE_MS; every holder touches its lock and claim.
|
|
12
|
+
export const LOCK_STALE_MS = 10 * 60_000;
|
|
13
|
+
export const LOCK_HEARTBEAT_MS = 30_000;
|
|
14
|
+
// Weak identity when own observation is unavailable: never PID-recovered, only heartbeat-stale.
|
|
15
|
+
const WEAK = 'unobserved';
|
|
16
|
+
const NO_HARD_LINK = ['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS'];
|
|
10
17
|
let ownStart;
|
|
11
18
|
let ownHost;
|
|
12
19
|
|
|
@@ -17,9 +24,7 @@ export class StoreLockError extends Error {
|
|
|
17
24
|
this.reason = reason;
|
|
18
25
|
this.detail = {
|
|
19
26
|
lock_path: lockPath,
|
|
20
|
-
next_action:
|
|
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.`,
|
|
27
|
+
next_action: `Retry after the owner releases ${lockPath}; an owner that stops refreshing it is recovered automatically after ${LOCK_STALE_MS / 60_000} minutes.`,
|
|
23
28
|
...detail,
|
|
24
29
|
};
|
|
25
30
|
}
|
|
@@ -45,46 +50,96 @@ async function processIsDead(pid, startDigest) {
|
|
|
45
50
|
const observed = await observeStartIdentityRaw(pid);
|
|
46
51
|
if (observed) return hash(`${process.platform}:${observed}`) !== startDigest;
|
|
47
52
|
} catch {
|
|
48
|
-
// A failed observation cannot turn an existing PID into a dead owner
|
|
53
|
+
// A failed observation cannot turn an existing PID into a dead owner, but a PID that
|
|
54
|
+
// vanished meanwhile was a short-lived reuser (Windows reuses PIDs at once): the owner is gone.
|
|
55
|
+
try { process.kill(pid, 0); }
|
|
56
|
+
catch (error) { if (error?.code === 'ESRCH') return true; }
|
|
49
57
|
}
|
|
50
58
|
return false;
|
|
51
59
|
}
|
|
52
60
|
|
|
61
|
+
/** Returns null (absent) or {owner (null when unidentified), stale, info: the judged lstat}. */
|
|
53
62
|
async function readOwner(lockPath) {
|
|
54
63
|
try {
|
|
55
64
|
const info = await lstat(lockPath);
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}
|
|
65
|
+
const stale = info.mtimeMs < Date.now() - LOCK_STALE_MS;
|
|
66
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 8192) return { owner: null, stale, info };
|
|
59
67
|
let owner;
|
|
60
68
|
try { owner = JSON.parse(await readFile(lockPath, 'utf8')); }
|
|
61
69
|
catch (error) {
|
|
62
70
|
if (error?.code === 'ENOENT') return null;
|
|
63
71
|
if (!(error instanceof SyntaxError)) throw error;
|
|
64
|
-
|
|
72
|
+
return { owner: null, stale, info };
|
|
65
73
|
}
|
|
66
|
-
|
|
67
|
-
return owner;
|
|
74
|
+
return { owner: identified(owner) ? owner : null, stale, info };
|
|
68
75
|
} catch (error) {
|
|
69
76
|
if (error?.code === 'ENOENT') return null;
|
|
70
77
|
throw error;
|
|
71
78
|
}
|
|
72
79
|
}
|
|
73
80
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
81
|
+
/** A local identified owner is judged by PID + start only; any other owner by heartbeat staleness. */
|
|
82
|
+
async function abandoned({ owner, stale }, host) {
|
|
83
|
+
if (owner !== null && host !== WEAK && owner.host === host
|
|
84
|
+
&& owner.process_start.platform === process.platform) {
|
|
85
|
+
return processIsDead(owner.pid,
|
|
77
86
|
hash(`${owner.process_start.platform}:${owner.process_start.identity}`));
|
|
87
|
+
}
|
|
88
|
+
return stale;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Remove only the entry that was judged abandoned. A stale owner may still be alive and
|
|
93
|
+
* release, letting a new owner link in between judgement and removal; that one goes back.
|
|
94
|
+
*/
|
|
95
|
+
async function removeJudged(lockPath, judged) {
|
|
96
|
+
const quarantine = `${lockPath}.${randomBytes(8).toString('hex')}.stale`;
|
|
97
|
+
try { await rename(lockPath, quarantine); }
|
|
98
|
+
catch (error) { if (error?.code === 'ENOENT') return; throw error; }
|
|
99
|
+
const moved = await lstat(quarantine).catch((error) => {
|
|
100
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
101
|
+
return null;
|
|
102
|
+
});
|
|
103
|
+
// Swept concurrently: only an entry older than LOCK_STALE_MS is swept, so it was abandoned too.
|
|
104
|
+
if (moved === null) return;
|
|
105
|
+
if (moved.dev === judged.dev && moved.ino === judged.ino && moved.size === judged.size
|
|
106
|
+
&& moved.mtimeMs === judged.mtimeMs) {
|
|
107
|
+
await rm(quarantine);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
try { await link(quarantine, lockPath); }
|
|
111
|
+
catch (error) {
|
|
112
|
+
if (error?.code !== 'EEXIST' && !NO_HARD_LINK.includes(error?.code)) throw error;
|
|
113
|
+
// Both owners stay on disk; the displaced one fails its held-check (lock_lost).
|
|
114
|
+
throw new StoreLockError('store_locked', lockPath, {
|
|
115
|
+
cause: 'lock_recovery_raced', quarantine_path: quarantine,
|
|
116
|
+
next_action: `Retry; ${quarantine} keeps the owner displaced by a racing recovery and is removed by hand only after that owner exits.`,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
await rm(quarantine);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function busy(state, lockPath) {
|
|
123
|
+
return new StoreLockError(state.owner === null ? 'lock_owner_unidentified' : 'store_locked', lockPath);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function isStale(entryPath) {
|
|
127
|
+
const info = await lstat(entryPath).catch((error) => {
|
|
128
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
129
|
+
return null;
|
|
130
|
+
});
|
|
131
|
+
return info !== null && info.mtimeMs < Date.now() - LOCK_STALE_MS;
|
|
78
132
|
}
|
|
79
133
|
|
|
80
134
|
async function removeDeadTemporaries(lockPath, hostDigest) {
|
|
81
135
|
const prefix = `${path.basename(lockPath)}.`;
|
|
82
136
|
for (const name of await readdir(path.dirname(lockPath))) {
|
|
83
|
-
if (!name.startsWith(prefix) || !name.endsWith('.tmp')) continue;
|
|
84
|
-
const parsed = name.slice(prefix.length, -4).match(CLAIM);
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
137
|
+
if (!name.startsWith(prefix) || !(name.endsWith('.tmp') || name.endsWith('.stale'))) continue;
|
|
138
|
+
const parsed = name.endsWith('.tmp') ? name.slice(prefix.length, -4).match(CLAIM) : null;
|
|
139
|
+
const temporary = path.join(path.dirname(lockPath), name);
|
|
140
|
+
// A `.stale` quarantine's owner already fails assertHeld; it goes once older than LOCK_STALE_MS.
|
|
141
|
+
const local = parsed && parsed[1] === hostDigest && Number.isSafeInteger(Number(parsed[2]));
|
|
142
|
+
if (local ? await processIsDead(Number(parsed[2]), parsed[3]) : await isStale(temporary)) {
|
|
88
143
|
const info = await lstat(temporary).catch((error) => {
|
|
89
144
|
if (error?.code !== 'ENOENT') throw error;
|
|
90
145
|
return null;
|
|
@@ -107,7 +162,7 @@ async function recoveryClaim(claimsPath, owner, lockPath) {
|
|
|
107
162
|
catch (error) { if (error?.code !== 'ENOENT') throw error; }
|
|
108
163
|
}
|
|
109
164
|
try {
|
|
110
|
-
await removeDeadClaims(claimsPath, hostDigest, lockPath);
|
|
165
|
+
await removeDeadClaims(claimsPath, owner.host === WEAK ? null : hostDigest, lockPath);
|
|
111
166
|
// All claimants publish before inspection; only a sole claimant may recover.
|
|
112
167
|
// Timestamp ordering could let a delayed earlier publisher enter twice.
|
|
113
168
|
const candidates = await readdir(claimsPath);
|
|
@@ -133,9 +188,9 @@ async function removeDeadClaims(claimsPath, hostDigest, lockPath) {
|
|
|
133
188
|
}
|
|
134
189
|
for (const entry of await readdir(claimsPath, { withFileTypes: true })) {
|
|
135
190
|
const parsed = entry.name.match(CLAIM);
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
191
|
+
const local = parsed && parsed[1] === hostDigest && Number.isSafeInteger(Number(parsed[2]));
|
|
192
|
+
if (entry.isDirectory() && (local ? await processIsDead(Number(parsed[2]), parsed[3])
|
|
193
|
+
: await isStale(path.join(claimsPath, entry.name)))) {
|
|
139
194
|
try { await rmdir(path.join(claimsPath, entry.name)); }
|
|
140
195
|
catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
|
|
141
196
|
}
|
|
@@ -161,28 +216,40 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
|
|
|
161
216
|
let identity;
|
|
162
217
|
let host;
|
|
163
218
|
try { [identity, host] = await Promise.all([ownStart, ownHost]); }
|
|
164
|
-
catch {
|
|
165
|
-
|
|
166
|
-
cause: 'lock_identity_unavailable',
|
|
167
|
-
next_action: `Restore platform host-domain and process-start observation, then retry ${lockPath}`,
|
|
168
|
-
});
|
|
169
|
-
}
|
|
170
|
-
const owner = { pid: process.pid,
|
|
219
|
+
catch { identity = WEAK; host = WEAK; }
|
|
220
|
+
let owner = { pid: process.pid,
|
|
171
221
|
process_start: { platform: process.platform, identity }, host };
|
|
172
|
-
if (!identified(owner))
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
}
|
|
222
|
+
if (!identified(owner)) {
|
|
223
|
+
host = WEAK;
|
|
224
|
+
owner = { pid: process.pid, process_start: { platform: process.platform, identity: WEAK }, host };
|
|
225
|
+
}
|
|
176
226
|
const ownerBytes = `${JSON.stringify(owner)}\n`;
|
|
177
227
|
const temporary = `${lockPath}.${hash(host)}-${owner.pid}-${hash(`${owner.process_start.platform}:${owner.process_start.identity}`)}-${randomBytes(8).toString('hex')}.tmp`;
|
|
178
228
|
let claimPath = null;
|
|
179
229
|
let acquired = false;
|
|
180
230
|
let fileIdentity = null;
|
|
181
231
|
let callbackEntered = false;
|
|
232
|
+
let heartbeat = null;
|
|
233
|
+
let lost = false;
|
|
234
|
+
const stillOwned = async (current) => {
|
|
235
|
+
if (current === null || !acquired) return false;
|
|
236
|
+
const info = await lstat(current).catch((error) => {
|
|
237
|
+
if (error?.code === 'ENOENT') return null;
|
|
238
|
+
throw error;
|
|
239
|
+
});
|
|
240
|
+
return info !== null && info.isFile() && !info.isSymbolicLink()
|
|
241
|
+
&& info.dev === fileIdentity.dev && info.ino === fileIdentity.ino
|
|
242
|
+
&& await readFile(current, 'utf8').catch((error) => {
|
|
243
|
+
if (error?.code === 'ENOENT') return null;
|
|
244
|
+
throw error;
|
|
245
|
+
}) === ownerBytes;
|
|
246
|
+
};
|
|
182
247
|
try {
|
|
183
|
-
|
|
248
|
+
// A weak writer cannot prove anyone dead by PID; it only clears stale entries.
|
|
249
|
+
const hostDigest = host === WEAK ? null : hash(host);
|
|
250
|
+
await removeDeadTemporaries(lockPath, hostDigest);
|
|
184
251
|
for (const claimsPath of new Set([recoveryClaimsPath, `${lockPath}.recovery`])) {
|
|
185
|
-
await removeDeadClaims(claimsPath,
|
|
252
|
+
await removeDeadClaims(claimsPath, hostDigest, lockPath);
|
|
186
253
|
try { await rmdir(claimsPath); }
|
|
187
254
|
catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
|
|
188
255
|
}
|
|
@@ -195,31 +262,57 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
|
|
|
195
262
|
for (;;) {
|
|
196
263
|
try { await link(temporary, lockPath); acquired = true; break; }
|
|
197
264
|
catch (error) {
|
|
198
|
-
if (
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
265
|
+
if (NO_HARD_LINK.includes(error?.code)) {
|
|
266
|
+
// u03: without hard links publish in place; a torn record reads as unidentified and goes stale.
|
|
267
|
+
let direct = null;
|
|
268
|
+
try { direct = await open(lockPath, 'wx', 0o600); }
|
|
269
|
+
catch (openError) { if (openError?.code !== 'EEXIST') throw openError; }
|
|
270
|
+
if (direct !== null) {
|
|
271
|
+
try {
|
|
272
|
+
await direct.writeFile(ownerBytes); await syncPublishedFile(direct, lockPath);
|
|
273
|
+
fileIdentity = await direct.stat();
|
|
274
|
+
} finally { await direct.close(); }
|
|
275
|
+
acquired = true;
|
|
276
|
+
break;
|
|
277
|
+
}
|
|
278
|
+
} else if (error?.code !== 'EEXIST') throw error;
|
|
205
279
|
}
|
|
206
280
|
const existing = await readOwner(lockPath);
|
|
207
281
|
if (existing === null) continue;
|
|
208
|
-
if (!await
|
|
282
|
+
if (!await abandoned(existing, host)) throw busy(existing, lockPath);
|
|
209
283
|
if (claimPath === null) {
|
|
210
284
|
claimPath = await recoveryClaim(recoveryClaimsPath, owner, lockPath);
|
|
211
285
|
if (onRecoveryClaim) await onRecoveryClaim();
|
|
212
286
|
}
|
|
213
287
|
const fresh = await readOwner(lockPath);
|
|
214
288
|
if (fresh !== null) {
|
|
215
|
-
if (!await
|
|
216
|
-
await
|
|
289
|
+
if (!await abandoned(fresh, host)) throw busy(fresh, lockPath);
|
|
290
|
+
await removeJudged(lockPath, fresh.info);
|
|
217
291
|
}
|
|
218
292
|
}
|
|
219
293
|
await rm(temporary);
|
|
220
294
|
await fsyncDirectory(path.dirname(lockPath));
|
|
295
|
+
// Touch only our own entry: a resumed old holder must not keep a replacement lock fresh.
|
|
296
|
+
heartbeat = setInterval(() => {
|
|
297
|
+
Promise.resolve(releasePath()).then(async (current) => {
|
|
298
|
+
if (current === null) return;
|
|
299
|
+
if (!await stillOwned(current)) { lost = true; clearInterval(heartbeat); return; }
|
|
300
|
+
const now = new Date();
|
|
301
|
+
await Promise.all([utimes(current, now, now),
|
|
302
|
+
claimPath === null ? null : utimes(claimPath, now, now)]);
|
|
303
|
+
}).catch(() => {});
|
|
304
|
+
}, LOCK_HEARTBEAT_MS);
|
|
305
|
+
heartbeat.unref();
|
|
221
306
|
callbackEntered = true;
|
|
222
|
-
|
|
307
|
+
// Callers check right before publishing; the check-to-rename gap is a named residual.
|
|
308
|
+
return await callback(async () => {
|
|
309
|
+
if (!lost && await stillOwned(await releasePath())) return;
|
|
310
|
+
lost = true;
|
|
311
|
+
throw new StoreLockError('store_locked', lockPath, {
|
|
312
|
+
cause: 'lock_lost',
|
|
313
|
+
next_action: `Retry; ${lockPath} was recovered by another writer while this one held it, and nothing was published after the check.`,
|
|
314
|
+
});
|
|
315
|
+
});
|
|
223
316
|
} catch (error) {
|
|
224
317
|
if (!callbackEntered && error?.code === 'ENOENT') {
|
|
225
318
|
throw new StoreLockError('store_locked', lockPath, {
|
|
@@ -229,18 +322,10 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
|
|
|
229
322
|
}
|
|
230
323
|
throw error;
|
|
231
324
|
} finally {
|
|
325
|
+
clearInterval(heartbeat);
|
|
232
326
|
try {
|
|
233
327
|
const currentLockPath = await releasePath();
|
|
234
|
-
|
|
235
|
-
if (error?.code === 'ENOENT') return null;
|
|
236
|
-
throw error;
|
|
237
|
-
});
|
|
238
|
-
if (acquired && currentIdentity?.isFile() && !currentIdentity.isSymbolicLink()
|
|
239
|
-
&& currentIdentity.dev === fileIdentity.dev && currentIdentity.ino === fileIdentity.ino
|
|
240
|
-
&& await readFile(currentLockPath, 'utf8').catch((error) => {
|
|
241
|
-
if (error?.code === 'ENOENT') return null;
|
|
242
|
-
throw error;
|
|
243
|
-
}) === ownerBytes) {
|
|
328
|
+
if (await stillOwned(currentLockPath)) {
|
|
244
329
|
await rm(currentLockPath);
|
|
245
330
|
await fsyncDirectory(path.dirname(currentLockPath));
|
|
246
331
|
}
|
|
@@ -10,10 +10,40 @@ import { lstat, readFile, realpath } from 'node:fs/promises';
|
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import { parseTree } from 'jsonc-parser';
|
|
12
12
|
|
|
13
|
-
import { todoSelfDigest } from './todo-contracts.mjs';
|
|
13
|
+
import { canonicalizeTodoArtifact, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
|
|
14
|
+
import { readOrCreateTerminalIdSync, terminalPublicLabel } from './terminal-identity.mjs';
|
|
14
15
|
import { TodoStoreError } from './todo-store.mjs';
|
|
15
16
|
|
|
16
17
|
const MAX_AUTHORING_INPUT_BYTES = 8_388_608;
|
|
18
|
+
function sanitizeActorIdentifier(raw, fallback) {
|
|
19
|
+
const compact = String(raw ?? '').replace(/[^0-9A-Za-z._-]/gu, '-').replace(/^-+/u, '').slice(0, 128);
|
|
20
|
+
return isTodoIdentifier(compact) ? compact : fallback;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 名乗りの無い操作のhost(ADR 0197)。journalは公開repositoryへcommitされるので、OSのhost名は
|
|
25
|
+
* 書かない——host名はOSが決めた自由文で、持ち主の名前を含むことがある。端末ごとの識別子から
|
|
26
|
+
* 一方向に導いたlabelを使い、端末の区別は保つ。識別子を読めず作れない端末は`host`になる。
|
|
27
|
+
*/
|
|
28
|
+
function defaultActorHost(env) {
|
|
29
|
+
const terminalId = readOrCreateTerminalIdSync({ env });
|
|
30
|
+
return terminalId === null ? 'host' : terminalPublicLabel(terminalId);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// u03s A57: a set but non-identifier value is treated like an unset one (no refusal).
|
|
34
|
+
export function resolveTodoActor(env) {
|
|
35
|
+
return {
|
|
36
|
+
host: isTodoIdentifier(env.LATTICE_TODO_ACTOR_HOST)
|
|
37
|
+
? env.LATTICE_TODO_ACTOR_HOST
|
|
38
|
+
: defaultActorHost(env),
|
|
39
|
+
session: isTodoIdentifier(env.LATTICE_TODO_ACTOR_SESSION)
|
|
40
|
+
? env.LATTICE_TODO_ACTOR_SESSION
|
|
41
|
+
: 'session',
|
|
42
|
+
agent: isTodoIdentifier(env.LATTICE_TODO_ACTOR_AGENT)
|
|
43
|
+
? env.LATTICE_TODO_ACTOR_AGENT
|
|
44
|
+
: sanitizeActorIdentifier(env.USER ?? env.LOGNAME, 'agent'),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
17
47
|
|
|
18
48
|
export const AUTHORING_DIGEST_FIELDS = Object.freeze({
|
|
19
49
|
'lattice.plan_backchain.v1': 'chain_digest',
|
|
@@ -29,6 +59,7 @@ export const AUTHORING_DIGEST_FIELDS = Object.freeze({
|
|
|
29
59
|
'lattice.plan_create_input.v2': 'input_digest',
|
|
30
60
|
'lattice.plan_create_input.v3': 'input_digest',
|
|
31
61
|
'lattice.plan_create_input.v4': 'input_digest',
|
|
62
|
+
'lattice.plan_create_input.v5': 'input_digest',
|
|
32
63
|
'lattice.todo_revision.v1': 'revision_digest',
|
|
33
64
|
'lattice.todo_revision.v2': 'revision_digest',
|
|
34
65
|
'lattice.phase_todo_revision.v1': 'revision_digest',
|
|
@@ -85,15 +116,174 @@ export function parseAuthoringJson(text, { invalidCode = 'INVALID_JSON' } = {})
|
|
|
85
116
|
return null;
|
|
86
117
|
}
|
|
87
118
|
|
|
119
|
+
// todo-contractsのcompareText/refKey/phaseRefKeyと同じ比較。validatorが要求する正準順そのもの。
|
|
120
|
+
const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
121
|
+
const refKey = (value) => `${value?.project_id}\0${value?.plan_key}\0${value?.task_id}`;
|
|
122
|
+
const phaseRefKey = (value) => `${value?.project_id}\0${value?.plan_key}\0${value?.phase_id}`;
|
|
123
|
+
|
|
124
|
+
/** 正準順へ整列し、完全一致の重複だけを落とす。同じkeyで内容が違うものは残し、validatorに拒否させる。 */
|
|
125
|
+
function sortUnique(list, key) {
|
|
126
|
+
if (!Array.isArray(list)) return list;
|
|
127
|
+
const seen = new Set();
|
|
128
|
+
const kept = [];
|
|
129
|
+
for (const entry of list) {
|
|
130
|
+
const identity = canonicalizeTodoArtifact(entry);
|
|
131
|
+
if (seen.has(identity)) continue;
|
|
132
|
+
seen.add(identity);
|
|
133
|
+
kept.push({ entry, sortKey: key(entry), index: kept.length });
|
|
134
|
+
}
|
|
135
|
+
return kept.sort((left, right) => compareText(left.sortKey, right.sortKey) || left.index - right.index)
|
|
136
|
+
.map(({ entry }) => entry);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
140
|
+
|
|
141
|
+
const CREATE_INPUT_SCHEMA = /^lattice\.plan_create_input\.v[1-5]$/u;
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* plan_create_input.v1〜v5: 並びに作成者の意味が無い集合を、入力順に依らず正準形へ寄せる(u03p A81s)。
|
|
145
|
+
* 形が壊れていれば触らず、validatorの指摘に任せる。
|
|
146
|
+
*/
|
|
147
|
+
function normalizeCreateInput(value) {
|
|
148
|
+
const normalizers = {
|
|
149
|
+
tasks: (list) => sortUnique(list, (task) => task?.task_id),
|
|
150
|
+
hard_dependencies: (list) => sortUnique(list, (edge) => `${refKey(edge?.from)}\0${refKey(edge?.to)}`),
|
|
151
|
+
phase_accept_dependencies: (list) => sortUnique(list,
|
|
152
|
+
(edge) => `${phaseRefKey(edge?.from)}\0${refKey(edge?.to)}`),
|
|
153
|
+
joins: (list) => (Array.isArray(list)
|
|
154
|
+
? sortUnique(list.map((join) => (isRecord(join)
|
|
155
|
+
? { ...join, after: sortUnique(join.after, refKey) } : join)), (join) => join?.id) : list),
|
|
156
|
+
phases: (list) => (Array.isArray(list)
|
|
157
|
+
? sortUnique(list.map((phase) => (isRecord(phase) ? {
|
|
158
|
+
...phase,
|
|
159
|
+
predecessor_phase_ids: sortUnique(phase.predecessor_phase_ids, (id) => id),
|
|
160
|
+
required_evidence_slots: sortUnique(phase.required_evidence_slots, (id) => id),
|
|
161
|
+
} : phase)), (phase) => phase?.phase_id) : list),
|
|
162
|
+
};
|
|
163
|
+
try {
|
|
164
|
+
const next = { ...value };
|
|
165
|
+
for (const [field, normalize] of Object.entries(normalizers)) {
|
|
166
|
+
if (field in next) next[field] = normalize(next[field]);
|
|
167
|
+
}
|
|
168
|
+
return next;
|
|
169
|
+
} catch {
|
|
170
|
+
return value;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
88
174
|
export function repairAuthoringArtifact(value) {
|
|
89
175
|
if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;
|
|
90
176
|
const field = AUTHORING_DIGEST_FIELDS[value.schema];
|
|
91
177
|
if (field === undefined) return value;
|
|
92
|
-
const
|
|
178
|
+
const base = CREATE_INPUT_SCHEMA.test(value.schema) ? normalizeCreateInput(value) : value;
|
|
179
|
+
const next = { ...base, [field]: typeof base[field] === 'string' ? base[field] : '' };
|
|
93
180
|
next[field] = todoSelfDigest(next, field);
|
|
94
181
|
return next;
|
|
95
182
|
}
|
|
96
183
|
|
|
184
|
+
/**
|
|
185
|
+
* 機械が出せる事実を作成入力へ補う(u03p A81/A80)。AIは意図(tasks・依存)だけを書く:
|
|
186
|
+
* actorは席の解決値、recorded_atは現在時刻、v4/v5の空の設計メモはNO_PLAN、配列は正準順、
|
|
187
|
+
* input_digestは再計算。作成入力でない値と、レコードでない値はそのまま返す。
|
|
188
|
+
*/
|
|
189
|
+
export const DEFAULT_EVIDENCE_SLOT = 'acceptance';
|
|
190
|
+
export const DEFAULT_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v5';
|
|
191
|
+
const DEFAULT_LANE = 'main';
|
|
192
|
+
const DEFAULT_GATE_POLICY = 'heavy';
|
|
193
|
+
// 時差を明示したISO時刻だけを読む。時差の無い文字列はhostの現地時刻になり、hostごとに値が変わる。
|
|
194
|
+
const ZONED_ISO = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]{2})(?:\.[0-9]+)?)?(Z|([+-])([0-9]{2}):([0-9]{2}))$/u;
|
|
195
|
+
|
|
196
|
+
/** 書いた暦の欄がそのまま残る時差付きISO時刻ならUTCミリ秒へ。2月30日のような繰り上がりや時差無しはnull。 */
|
|
197
|
+
function normalizeZonedTimestamp(text) {
|
|
198
|
+
const match = ZONED_ISO.exec(text);
|
|
199
|
+
if (match === null) return null;
|
|
200
|
+
const [, year, month, day, hour, minute, second = '00', zone, sign, offsetHour, offsetMinute] = match;
|
|
201
|
+
const parsed = new Date(text);
|
|
202
|
+
if (Number.isNaN(parsed.getTime())) return null;
|
|
203
|
+
const offset = zone === 'Z' ? 0 : (sign === '-' ? -1 : 1) * (Number(offsetHour) * 60 + Number(offsetMinute));
|
|
204
|
+
const local = new Date(parsed.getTime() + offset * 60_000);
|
|
205
|
+
const written = [year, month, day, hour, minute, second].map(Number);
|
|
206
|
+
const read = [local.getUTCFullYear(), local.getUTCMonth() + 1, local.getUTCDate(),
|
|
207
|
+
local.getUTCHours(), local.getUTCMinutes(), local.getUTCSeconds()];
|
|
208
|
+
return written.every((value, index) => value === read[index]) ? parsed.toISOString() : null;
|
|
209
|
+
}
|
|
210
|
+
const absent = (value) => value === undefined || value === null;
|
|
211
|
+
|
|
212
|
+
// a11: 辺の参照が同じplanを指すなら、作成者はtask_id/phase_idだけ書けばよい。レコードでない参照はvalidatorへ。
|
|
213
|
+
function fillRef(ref, projectId, planKey) {
|
|
214
|
+
if (!isRecord(ref)) return ref;
|
|
215
|
+
const filled = { ...ref };
|
|
216
|
+
if (filled.project_id === undefined && projectId !== undefined) filled.project_id = projectId;
|
|
217
|
+
if (filled.plan_key === undefined && planKey !== undefined) filled.plan_key = planKey;
|
|
218
|
+
return filled;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// 配列の各レコードだけを補う。配列でない値・レコードでない要素は触らず、validatorの指摘に任せる。
|
|
222
|
+
function fillEach(next, key, fill) {
|
|
223
|
+
if (!Array.isArray(next[key])) return;
|
|
224
|
+
next[key] = next[key].map((entry) => (isRecord(entry) ? fill(entry) : entry));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function completeCreateInput(value, { env, now }) {
|
|
228
|
+
if (!isRecord(value)) return value;
|
|
229
|
+
const next = { ...value };
|
|
230
|
+
// a11: schemaを書かなければ現行のcreate入力(v5)。他のschemaを持つ値は作成入力でないのでそのまま返す。
|
|
231
|
+
if (absent(next.schema)) next.schema = DEFAULT_CREATE_INPUT_SCHEMA;
|
|
232
|
+
if (typeof next.schema !== 'string' || !CREATE_INPUT_SCHEMA.test(next.schema)) return value;
|
|
233
|
+
const fillNode = (ref) => fillRef(ref, next.project_id, next.plan_key);
|
|
234
|
+
const phaseInput = next.schema !== 'lattice.plan_create_input.v1';
|
|
235
|
+
const memoInput = ['lattice.plan_create_input.v4', 'lattice.plan_create_input.v5'].includes(next.schema);
|
|
236
|
+
const decoupled = !['lattice.plan_create_input.v1', 'lattice.plan_create_input.v2'].includes(next.schema);
|
|
237
|
+
if (absent(next.actor)) next.actor = resolveTodoActor(env);
|
|
238
|
+
if (absent(next.recorded_at)) next.recorded_at = now.toISOString();
|
|
239
|
+
else if (typeof next.recorded_at === 'string') {
|
|
240
|
+
// 厳密形でなくても読める時刻はUTCミリ秒へ寄せる。読めない文字列はそのまま残し、validatorが拒否する。
|
|
241
|
+
next.recorded_at = normalizeZonedTimestamp(next.recorded_at) ?? next.recorded_at;
|
|
242
|
+
}
|
|
243
|
+
if (absent(next.hard_dependencies)) next.hard_dependencies = [];
|
|
244
|
+
if (absent(next.joins)) next.joins = [];
|
|
245
|
+
if (decoupled && absent(next.phase_accept_dependencies)) next.phase_accept_dependencies = [];
|
|
246
|
+
fillEach(next, 'hard_dependencies', (edge) => ({ ...edge, from: fillNode(edge.from), to: fillNode(edge.to) }));
|
|
247
|
+
fillEach(next, 'joins', (join) => ({
|
|
248
|
+
...join,
|
|
249
|
+
...(Array.isArray(join.after) ? { after: join.after.map(fillNode) } : {}),
|
|
250
|
+
...('before' in join ? { before: fillNode(join.before) } : {}),
|
|
251
|
+
}));
|
|
252
|
+
if (decoupled) {
|
|
253
|
+
fillEach(next, 'phase_accept_dependencies',
|
|
254
|
+
(edge) => ({ ...edge, from: fillNode(edge.from), to: fillNode(edge.to) }));
|
|
255
|
+
}
|
|
256
|
+
fillEach(next, 'tasks', (task) => {
|
|
257
|
+
const filled = { ...task };
|
|
258
|
+
for (const key of ['narrative_anchor', 'compile_binding', 'parent_task_id', 'narrative_ref']) {
|
|
259
|
+
if (filled[key] === undefined) filled[key] = null;
|
|
260
|
+
}
|
|
261
|
+
if (absent(filled.lane)) filled.lane = DEFAULT_LANE;
|
|
262
|
+
if (next.schema === DEFAULT_CREATE_INPUT_SCHEMA && filled.done_condition === undefined) {
|
|
263
|
+
filled.done_condition = null;
|
|
264
|
+
}
|
|
265
|
+
if (memoInput && (absent(filled.design_memo)
|
|
266
|
+
|| (typeof filled.design_memo === 'string' && filled.design_memo.trim() === ''))) {
|
|
267
|
+
filled.design_memo = 'NO_PLAN';
|
|
268
|
+
}
|
|
269
|
+
return filled;
|
|
270
|
+
});
|
|
271
|
+
if (phaseInput) {
|
|
272
|
+
fillEach(next, 'phases', (phase) => {
|
|
273
|
+
const filled = { ...phase };
|
|
274
|
+
if (absent(filled.gate_policy)) filled.gate_policy = DEFAULT_GATE_POLICY;
|
|
275
|
+
if (absent(filled.predecessor_phase_ids)) filled.predecessor_phase_ids = [];
|
|
276
|
+
// 段が要求する証拠の種類を書かなければ、受入の証拠1つ(acceptance)を求める。
|
|
277
|
+
if (absent(filled.required_evidence_slots)
|
|
278
|
+
|| (Array.isArray(filled.required_evidence_slots) && filled.required_evidence_slots.length === 0)) {
|
|
279
|
+
filled.required_evidence_slots = [DEFAULT_EVIDENCE_SLOT];
|
|
280
|
+
}
|
|
281
|
+
return filled;
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
return repairAuthoringArtifact(next);
|
|
285
|
+
}
|
|
286
|
+
|
|
97
287
|
/**
|
|
98
288
|
* 渡された値がpathでなく本文そのものに見えるか。
|
|
99
289
|
* `--input`/`--evidence`はfileを取るが、AIも人もインラインの文章を渡して詰まる。
|
|
@@ -214,3 +404,22 @@ export function matchFlagCommand(argv, head, { known, required = [], booleans =
|
|
|
214
404
|
}
|
|
215
405
|
return flags;
|
|
216
406
|
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* matchFlagCommand が null を返す理由を、最初に落ちた flag と規則で返す。通るなら null。
|
|
410
|
+
* 規則は matchFlagCommand と同じ順で判定する(未知flag・位置引数、必須flag、boolean)。
|
|
411
|
+
*/
|
|
412
|
+
export function explainFlagCommand(argv, head, { known, required = [], booleans = [] } = {}) {
|
|
413
|
+
if (!Array.isArray(argv) || !Array.isArray(head) || head.some((token, index) => argv[index] !== token)) {
|
|
414
|
+
return null;
|
|
415
|
+
}
|
|
416
|
+
const { flags, rest } = parseFlagMap(argv.slice(head.length));
|
|
417
|
+
if (rest.length > 0) return { pointer: String(rest[0]), rule: 'flag_unknown' };
|
|
418
|
+
const unknown = Object.keys(flags).find((key) => !known.includes(key));
|
|
419
|
+
if (unknown !== undefined) return { pointer: `--${unknown}`, rule: 'flag_unknown' };
|
|
420
|
+
const missing = required.find((key) => typeof flags[key] !== 'string' || flags[key].length === 0);
|
|
421
|
+
if (missing !== undefined) return { pointer: `--${missing}`, rule: 'flag_missing' };
|
|
422
|
+
const valued = booleans.find((key) => flags[key] !== undefined && flags[key] !== true);
|
|
423
|
+
if (valued !== undefined) return { pointer: `--${valued}`, rule: 'flag_takes_no_value' };
|
|
424
|
+
return null;
|
|
425
|
+
}
|