@promptdriven/runtime-client 0.0.0-stage → 1.1.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/LICENSE +7 -0
- package/README.md +42 -2
- package/package.json +28 -4
- package/src/index.mjs +1 -0
- package/src/runtime/agent-ask.mjs +187 -0
- package/src/runtime/agent-chat.mjs +152 -0
- package/src/runtime/agent-coverage.mjs +97 -0
- package/src/runtime/agent-guide.mjs +152 -0
- package/src/runtime/agent-judge.mjs +71 -0
- package/src/runtime/agent-packet.mjs +62 -0
- package/src/runtime/agent-project.mjs +93 -0
- package/src/runtime/contract-refs.mjs +519 -0
- package/src/runtime/contracts.mjs +138 -0
- package/src/runtime/index.mjs +974 -0
- package/src/runtime/lint-call-preflight.mjs +19 -0
- package/src/runtime/lint-compatibility-display.mjs +62 -0
- package/src/runtime/live-local-bridge.mjs +178 -0
- package/src/runtime/live-local.mjs +181 -0
- package/src/runtime/product-composition.mjs +384 -0
- package/src/runtime/run-program.mjs +797 -0
- package/src/runtime/runtime-binding-plan.mjs +145 -0
- package/src/runtime/runtime-bindings.mjs +81 -0
- package/src/runtime/runtime-check-plan.mjs +411 -0
- package/src/runtime/runtime-client.mjs +8114 -0
- package/src/runtime/runtime-lint-receipt.mjs +25 -0
- package/src/runtime/runtime-markdown.mjs +215 -0
- package/src/runtime/runtime-outcome.mjs +468 -0
- package/src/runtime/runtime-output.mjs +752 -0
- package/src/runtime/runtime-preflight.mjs +3832 -0
- package/src/runtime/runtime-slots.mjs +462 -0
- package/src/runtime/runtime-workspace-migration.mjs +70 -0
- package/src/runtime/runtime-workspace.mjs +52 -0
- package/src/runtime/scenario-json.mjs +257 -0
- package/src/runtime/secret-redaction.mjs +54 -0
- package/src/runtime/try-doors.mjs +597 -0
- package/src/runtime/try-http.mjs +285 -0
- package/src/runtime/try-mcp.mjs +223 -0
- package/src/runtime/try-session.mjs +95 -0
- package/src/runtime/try-update-policy.mjs +43 -0
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
// Generated from prompts/cli/runtime-slots.prompt.md (sha256: e0182fc1c83cee3fc27303922cc5a393577f34d650f65610324ccaa7ca06c669).
|
|
2
|
+
import { chmodSync, closeSync, lstatSync, mkdirSync, linkSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync, fsyncSync, utimesSync } from 'node:fs';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { runtimeOrigin } from './runtime-client.mjs';
|
|
7
|
+
|
|
8
|
+
const HEARTBEAT_MS = 5000, EXPIRED_MS = 60_000, LEASE_MS = 1_800_000, PROBE_MS = 15_000;
|
|
9
|
+
const unavailable = error => Object.assign(new Error(`Local interpreter state unavailable: ${String(error?.message ?? error).split('\n')[0]}`), { code: 'local-state-unavailable' });
|
|
10
|
+
const alive = pid => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== 'ESRCH'; } };
|
|
11
|
+
const order = (a, b) => a.started_at - b.started_at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
12
|
+
const snapshotKey = row => JSON.stringify([row.id, row.pid, row.state, row.kind, row.started_at, row.request_ids]);
|
|
13
|
+
const nativeSnapshotKey = row => row.state === undefined ? JSON.stringify([row.id, row.pid, row.choosing, row.number]) : snapshotKey(row);
|
|
14
|
+
const rememberNativeOwnership = Symbol('rememberNativeOwnership');
|
|
15
|
+
const commitCheckRegistration = Symbol('commitCheckRegistration');
|
|
16
|
+
const directoryFor = ({ stateDir, origin }) => join(stateDir, 'slots', encodeURIComponent(new URL(origin).host));
|
|
17
|
+
const nativeInterrupt = handler => {
|
|
18
|
+
const signals = ['SIGINT', 'SIGHUP', 'SIGTERM'];
|
|
19
|
+
for (const signal of signals) process.on(signal, handler);
|
|
20
|
+
return () => { for (const signal of signals) process.off(signal, handler); };
|
|
21
|
+
};
|
|
22
|
+
function ensure(directory) { mkdirSync(directory, { recursive: true, mode: 0o700 }); chmodSync(directory, 0o700); }
|
|
23
|
+
function readRecord(path) {
|
|
24
|
+
const stat = lstatSync(path);
|
|
25
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Slot record is not a regular file');
|
|
26
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
27
|
+
}
|
|
28
|
+
function publishExclusive(path, record) {
|
|
29
|
+
const temporary = `${path}.${randomUUID()}.tmp`, fd = openSync(temporary, 'wx', 0o600);
|
|
30
|
+
try { writeFileSync(fd, `${JSON.stringify(record)}\n`); fsyncSync(fd); } finally { closeSync(fd); }
|
|
31
|
+
try { try { linkSync(temporary, path); return true; } catch (error) { if (error.code === 'EEXIST') return false; throw error; } }
|
|
32
|
+
finally { unlinkSync(temporary); }
|
|
33
|
+
}
|
|
34
|
+
let claimSequence = 0;
|
|
35
|
+
// Each claimant has its own never-reused path. Removing an abandoned claimant
|
|
36
|
+
// cannot unlink a successor, unlike deleting and recreating a shared lock path.
|
|
37
|
+
function nativeFilePort(ports) {
|
|
38
|
+
const heldClaims = new Map(), owned = new Map();
|
|
39
|
+
const remember = (path, record) => owned.set(path, nativeSnapshotKey(record));
|
|
40
|
+
const actual = path => path.endsWith('/claim.json') ? heldClaims.get(path) : path;
|
|
41
|
+
const files = {
|
|
42
|
+
[rememberNativeOwnership]: (path, record) => owned.set(path, nativeSnapshotKey(record)),
|
|
43
|
+
listRecords({ directory }) {
|
|
44
|
+
let names;
|
|
45
|
+
try { names = readdirSync(directory); } catch (error) { if (error.code === 'ENOENT') return { jobs: [] }; throw error; }
|
|
46
|
+
const jobs = [];
|
|
47
|
+
for (const name of names.filter(name => name.endsWith('.json') && name !== 'claim.json')) {
|
|
48
|
+
let row;
|
|
49
|
+
try { row = readRecord(join(directory, name)); } catch (error) { if (error.code === 'ENOENT') continue; throw error; }
|
|
50
|
+
if (typeof row.id !== 'string' || name !== `${row.id}.json` || !['active', 'waiting'].includes(row.state)
|
|
51
|
+
|| !Number.isSafeInteger(row.pid) || row.pid < 1 || !['check', 'lint', 'try'].includes(row.kind)
|
|
52
|
+
|| !Number.isSafeInteger(row.started_at) || row.started_at < 0 || !Array.isArray(row.request_ids) || row.request_ids.some(id => typeof id !== 'string')) throw new Error('Invalid slot record');
|
|
53
|
+
jobs.push({ id: row.id, state: row.state, pid: row.pid, kind: row.kind, started_at: row.started_at, request_ids: row.request_ids });
|
|
54
|
+
}
|
|
55
|
+
return { jobs };
|
|
56
|
+
},
|
|
57
|
+
exclusiveCreate(path, record) {
|
|
58
|
+
ensure(resolve(path, '..'));
|
|
59
|
+
if (!path.endsWith('/claim.json')) { const created = publishExclusive(path, record); if (created) { remember(path, record); files.touch(path); } return created; }
|
|
60
|
+
const directory = resolve(path, '..'), id = `${record.pid}-${ports.randomUUID()}-${++claimSequence}`, mine = join(directory, `.claim-${id}.lock`);
|
|
61
|
+
const contenders = () => {
|
|
62
|
+
const live = [];
|
|
63
|
+
for (const name of readdirSync(directory).filter(name => /^\.claim-.*\.lock$/.test(name))) {
|
|
64
|
+
const file = join(directory, name); let row, modified;
|
|
65
|
+
try { row = readRecord(file); modified = files.modifiedAt(file); } catch (error) { if (error.code === 'ENOENT') continue; throw error; }
|
|
66
|
+
if (typeof row.id !== 'string' || !Number.isSafeInteger(row.pid) || row.pid < 1 || typeof row.choosing !== 'boolean'
|
|
67
|
+
|| !row.choosing && (!Number.isSafeInteger(row.number) || row.number < 1)) throw new Error('Invalid runtime claim');
|
|
68
|
+
if (!ports.isAlive(row.pid) || modified === null || ports.now() - modified >= EXPIRED_MS) files.unlink(file);
|
|
69
|
+
else live.push(row);
|
|
70
|
+
}
|
|
71
|
+
return live;
|
|
72
|
+
};
|
|
73
|
+
const choosing = { id, pid: record.pid, choosing: true };
|
|
74
|
+
publishExclusive(mine, choosing); remember(mine, choosing); files.touch(mine);
|
|
75
|
+
let held = false;
|
|
76
|
+
try {
|
|
77
|
+
const number = 1 + Math.max(0, ...contenders().filter(row => row.id !== id).map(row => row.number || 0));
|
|
78
|
+
files.writeAtomic(mine, { id, pid: record.pid, number, choosing: false });
|
|
79
|
+
if (contenders().some(row => row.id !== id && (row.choosing || row.number < number || row.number === number && row.id < id))) return false;
|
|
80
|
+
heldClaims.set(path, mine); held = true; return true;
|
|
81
|
+
} finally { if (!held) files.unlink(mine); }
|
|
82
|
+
},
|
|
83
|
+
writeAtomic(path, record) {
|
|
84
|
+
const temporary = `${path}.${randomUUID()}.tmp`, fd = openSync(temporary, 'wx', 0o600);
|
|
85
|
+
try { writeFileSync(fd, `${JSON.stringify(record)}\n`); fsyncSync(fd); } finally { closeSync(fd); }
|
|
86
|
+
renameSync(temporary, path); remember(path, record); files.touch(path);
|
|
87
|
+
},
|
|
88
|
+
readCheckStart({ directory }) {
|
|
89
|
+
try {
|
|
90
|
+
const at = readRecord(join(directory, '.check-start')).at;
|
|
91
|
+
if (!Number.isFinite(at) || at < 0) throw new Error('Invalid check pacing state');
|
|
92
|
+
return at;
|
|
93
|
+
}
|
|
94
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
95
|
+
},
|
|
96
|
+
writeCheckStart({ directory, at }) { files.writeAtomic(join(directory, '.check-start'), { at }); },
|
|
97
|
+
[commitCheckRegistration]({ path, previous, next, at }) {
|
|
98
|
+
const pacing = join(resolve(path, '..'), '.check-start');
|
|
99
|
+
let staged = false;
|
|
100
|
+
try {
|
|
101
|
+
// A partial native commit must remain unavailable after process death,
|
|
102
|
+
// rather than leave a recorded ID with an absent or stale start time.
|
|
103
|
+
files.writeAtomic(pacing, { at: null }); staged = true;
|
|
104
|
+
files.writeAtomic(path, next);
|
|
105
|
+
files.writeAtomic(pacing, { at: ports.now() });
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (staged) {
|
|
108
|
+
try {
|
|
109
|
+
const current = readRecord(path);
|
|
110
|
+
if (snapshotKey(current) === snapshotKey(next)) files.writeAtomic(path, previous);
|
|
111
|
+
else if (snapshotKey(current) !== snapshotKey(previous)) throw new Error('Runtime reservation ownership changed');
|
|
112
|
+
if (at === null) files.unlink(pacing);
|
|
113
|
+
else files.writeAtomic(pacing, { at });
|
|
114
|
+
} catch { /* Retain unavailable timing when exact rollback cannot complete. */ }
|
|
115
|
+
}
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
modifiedAt(path) {
|
|
120
|
+
const claim = path.endsWith('/claim.json');
|
|
121
|
+
path = actual(path); if (!path) return null;
|
|
122
|
+
try { const stat = lstatSync(path); if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Slot record is not a regular file');
|
|
123
|
+
if (claim && nativeSnapshotKey(readRecord(path)) !== owned.get(path)) return null;
|
|
124
|
+
return stat.mtimeMs; }
|
|
125
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
126
|
+
},
|
|
127
|
+
touch(path) {
|
|
128
|
+
path = actual(path); if (!path) return false;
|
|
129
|
+
try { const stat = lstatSync(path); if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Slot record is not a regular file'); const identity = owned.get(path), record = readRecord(path);
|
|
130
|
+
if (identity === undefined || nativeSnapshotKey(record) !== identity) return false;
|
|
131
|
+
const time = new Date(ports.now()); utimesSync(path, time, time); return true; }
|
|
132
|
+
catch (error) { if (error.code === 'ENOENT') return false; throw error; }
|
|
133
|
+
},
|
|
134
|
+
unlink(path) {
|
|
135
|
+
const resolved = actual(path); if (!resolved) return;
|
|
136
|
+
if (path.endsWith('/claim.json')) heldClaims.delete(path);
|
|
137
|
+
const identity = owned.get(resolved);
|
|
138
|
+
owned.delete(resolved);
|
|
139
|
+
try {
|
|
140
|
+
if (resolved.endsWith('.lock') && identity !== undefined && nativeSnapshotKey(readRecord(resolved)) !== identity) return;
|
|
141
|
+
unlinkSync(resolved);
|
|
142
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
return files;
|
|
146
|
+
}
|
|
147
|
+
function defaults(given = {}) {
|
|
148
|
+
const ports = { pid: process.pid, isAlive: alive, now: Date.now, randomUUID, random: Math.random,
|
|
149
|
+
timers: { setInterval, clearInterval }, onInterrupt: nativeInterrupt,
|
|
150
|
+
sleep: ms => new Promise(done => setTimeout(done, ms)), interrupted: () => false, readRun: async () => 'unknown', say: () => {}, ...given };
|
|
151
|
+
ports.files = given.files ?? nativeFilePort(ports);
|
|
152
|
+
return ports;
|
|
153
|
+
}
|
|
154
|
+
const nativeFiles = nativeFilePort({ now: Date.now, randomUUID, isAlive: alive });
|
|
155
|
+
const owners = new Map(), reservationOwners = new WeakMap(), probes = new Map(), incompleteCheckStarts = new Map();
|
|
156
|
+
let claimSections = 0;
|
|
157
|
+
const claimWaiters = new Set();
|
|
158
|
+
function leaveClaim() { if (--claimSections === 0) { for (const done of claimWaiters) done(); claimWaiters.clear(); } }
|
|
159
|
+
async function outsideRead(ports, id) {
|
|
160
|
+
while (claimSections) await new Promise(done => claimWaiters.add(done));
|
|
161
|
+
return ports.readRun(id);
|
|
162
|
+
}
|
|
163
|
+
const rows = async (files, directory) => { try { return (await files.listRecords({ directory })).jobs; } catch (error) { throw unavailable(error); } };
|
|
164
|
+
const freshness = async (ports, path) => ports.files.modifiedAt ? await ports.files.modifiedAt(path) : owners.has(path) ? ports.now() : null;
|
|
165
|
+
const expired = (ports, row, modified) => !ports.isAlive(row.pid) || modified === null || ports.now() - modified >= EXPIRED_MS;
|
|
166
|
+
function heartbeat(path, ports, interrupted, retainInterrupt = false) {
|
|
167
|
+
let stopped = false, pending = Promise.resolve(), unsubscribe = () => {};
|
|
168
|
+
const pause = () => { if (!stopped) { stopped = true; ports.timers.clearInterval(timer); } };
|
|
169
|
+
const stop = () => { pause(); unsubscribe(); };
|
|
170
|
+
const missing = () => { if (retainInterrupt) pause(); else stop(); };
|
|
171
|
+
const timer = ports.timers.setInterval(() => {
|
|
172
|
+
pending = pending.then(async () => {
|
|
173
|
+
if (stopped) return;
|
|
174
|
+
if (!ports.files.touch || await ports.files.touch(path) === false) missing();
|
|
175
|
+
}).catch(missing);
|
|
176
|
+
}, HEARTBEAT_MS);
|
|
177
|
+
timer?.unref?.();
|
|
178
|
+
unsubscribe = ports.onInterrupt(() => { stop(); interrupted?.(); });
|
|
179
|
+
if (stopped) unsubscribe();
|
|
180
|
+
return { stop, pause, pending: () => pending };
|
|
181
|
+
}
|
|
182
|
+
async function locked(directory, ports, action) {
|
|
183
|
+
const path = join(directory, 'claim.json');
|
|
184
|
+
claimSections++;
|
|
185
|
+
let claimed;
|
|
186
|
+
try { claimed = await ports.files.exclusiveCreate(path, { pid: ports.pid }); } catch (error) { leaveClaim(); throw error; }
|
|
187
|
+
if (!claimed) { leaveClaim(); return { claimed: false }; }
|
|
188
|
+
let cancelled = false;
|
|
189
|
+
const pulse = heartbeat(path, ports, () => { cancelled = true; void ports.files.unlink(path); });
|
|
190
|
+
const ownsClaim = async () => {
|
|
191
|
+
if (cancelled || ports.interrupted()) return false;
|
|
192
|
+
if (!ports.files.modifiedAt) return true;
|
|
193
|
+
const modified = await freshness(ports, path);
|
|
194
|
+
return modified !== null && ports.now() - modified < EXPIRED_MS;
|
|
195
|
+
};
|
|
196
|
+
try { return { claimed: true, value: await ownsClaim() ? await action(ownsClaim) : false }; }
|
|
197
|
+
finally { pulse.stop(); try { await pulse.pending(); await ports.files.unlink(path); } finally { leaveClaim(); } }
|
|
198
|
+
}
|
|
199
|
+
function retryDelay(ports, failures, follower, remaining) {
|
|
200
|
+
const base = follower ? 8 : Math.min(4, 2 * 2 ** Math.min(failures, 1));
|
|
201
|
+
return Math.min(remaining, base + Math.floor(ports.random() * base));
|
|
202
|
+
}
|
|
203
|
+
async function observe(result, ports, ended, deadline, stopWaiting) {
|
|
204
|
+
let timer, off = () => {};
|
|
205
|
+
try {
|
|
206
|
+
return await Promise.race([result, new Promise(done => {
|
|
207
|
+
const stop = () => { stopWaiting(); done('unknown'); };
|
|
208
|
+
off = ports.onInterrupt(stop);
|
|
209
|
+
if (ended()) { stop(); return; }
|
|
210
|
+
const waitForDeadline = () => {
|
|
211
|
+
if (timer !== undefined) { ports.timers.clearInterval(timer); timer = undefined; }
|
|
212
|
+
if (ended()) { stop(); return; }
|
|
213
|
+
// Native timers overflow on far-future absolute deadlines. Each chunk
|
|
214
|
+
// only wakes this observer to recheck its own deadline and interruption.
|
|
215
|
+
timer = ports.timers.setInterval(waitForDeadline, Math.max(1, Math.min(60_000, deadline - ports.now())));
|
|
216
|
+
};
|
|
217
|
+
if (deadline !== null) waitForDeadline();
|
|
218
|
+
})]);
|
|
219
|
+
} finally {
|
|
220
|
+
if (timer !== undefined) ports.timers.clearInterval(timer);
|
|
221
|
+
off();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
async function inspect(directory, origin, ports, ended, deadline, stopWaiting, waitingTicket, passive = false) {
|
|
225
|
+
const snapshots = [];
|
|
226
|
+
for (const row of await rows(ports.files, directory)) {
|
|
227
|
+
if (ended()) break;
|
|
228
|
+
// This acquisition still owns its original ticket even if wall time jumps
|
|
229
|
+
// before the next heartbeat. Other owners retain ordinary expiry rules.
|
|
230
|
+
if (snapshotKey(row) === snapshotKey(waitingTicket)) continue;
|
|
231
|
+
const path = join(directory, `${row.id}.json`), modified = await freshness(ports, path);
|
|
232
|
+
if (!expired(ports, row, modified)) continue;
|
|
233
|
+
let reclaim = row.state === 'waiting' || !row.request_ids.length || ports.now() - row.started_at >= LEASE_MS;
|
|
234
|
+
if (!reclaim && !passive) {
|
|
235
|
+
const states = [];
|
|
236
|
+
for (const id of row.request_ids) {
|
|
237
|
+
if (ended()) break;
|
|
238
|
+
const key = JSON.stringify([origin, row.kind, id]), cached = probes.get(key), now = ports.now();
|
|
239
|
+
let observation = cached && (cached.pending || now >= cached.at && now - cached.at < PROBE_MS) ? cached : null;
|
|
240
|
+
const shared = !!observation;
|
|
241
|
+
if (!observation) {
|
|
242
|
+
observation = { at: now, pending: true };
|
|
243
|
+
observation.result = Promise.resolve().then(() => outsideRead(ports, id)).catch(() => 'unknown').then(state => { observation.pending = false; observation.at = ports.now(); return state; });
|
|
244
|
+
probes.set(key, observation);
|
|
245
|
+
}
|
|
246
|
+
// The cached GET can belong to a caller with a longer wait. Ending this
|
|
247
|
+
// observer must leave that shared read and its eventual cache intact.
|
|
248
|
+
// The initiating readRun already owns this acquisition's transport
|
|
249
|
+
// deadline. Only observers borrowing that read need a separate timer.
|
|
250
|
+
states.push(await (shared ? observe(observation.result, ports, ended, deadline, stopWaiting) : observation.result));
|
|
251
|
+
}
|
|
252
|
+
reclaim = states.length === row.request_ids.length && states.every(state => state === 'ended');
|
|
253
|
+
}
|
|
254
|
+
if (reclaim) snapshots.push({ row, modified, key: snapshotKey(row) });
|
|
255
|
+
}
|
|
256
|
+
return snapshots;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export async function acquireRuntimeSlot({ stateDir, origin, limit = Infinity, kind, deadline = null }, given = {}) {
|
|
260
|
+
const ports = defaults(given), directory = directoryFor({ stateDir, origin }), id = ports.randomUUID();
|
|
261
|
+
const uncapped = limit === Infinity;
|
|
262
|
+
const ticket = { id, state: uncapped ? 'active' : 'waiting', pid: ports.pid, kind, started_at: ports.now(), request_ids: [] };
|
|
263
|
+
const path = join(directory, `${id}.json`);
|
|
264
|
+
let cancelled = false;
|
|
265
|
+
const ended = () => cancelled || ports.interrupted() || deadline !== null && ports.now() >= deadline;
|
|
266
|
+
if (ended()) return null;
|
|
267
|
+
if (!await ports.files.exclusiveCreate(path, ticket)) throw unavailable(new Error('Duplicate slot identity'));
|
|
268
|
+
let acquired = false, activeTicket = uncapped ? ticket : null, last = '', failures = 0;
|
|
269
|
+
const owner = { posted: false, pulse: null, snapshot: snapshotKey(ticket), [rememberNativeOwnership]: ports.files[rememberNativeOwnership] };
|
|
270
|
+
const interruptOwner = () => {
|
|
271
|
+
cancelled = true;
|
|
272
|
+
if (!owner.posted) void removeUnsent();
|
|
273
|
+
};
|
|
274
|
+
const ownWaiting = row => row && snapshotKey(row) === snapshotKey(ticket);
|
|
275
|
+
const removeUnsent = async () => {
|
|
276
|
+
const current = (await rows(ports.files, directory)).find(row => row.id === id);
|
|
277
|
+
if (ownWaiting(current) || activeTicket && current && snapshotKey(current) === snapshotKey(activeTicket)) await ports.files.unlink(path);
|
|
278
|
+
};
|
|
279
|
+
// Cancellation outlives an absent-file refresh while this wait is pending.
|
|
280
|
+
owner.pulse = heartbeat(path, ports, interruptOwner, true);
|
|
281
|
+
owners.set(path, owner);
|
|
282
|
+
try {
|
|
283
|
+
if (uncapped) {
|
|
284
|
+
// Only local expiry evidence is available here. In particular, a recent
|
|
285
|
+
// uncertain paid lease must not trigger a runtime read or hold admission.
|
|
286
|
+
const snapshots = await inspect(directory, origin, ports, ended, deadline, () => { cancelled = true; }, ticket, true);
|
|
287
|
+
if (snapshots.length && !ended()) await locked(directory, ports, async ownsClaim => {
|
|
288
|
+
const currentJobs = await rows(ports.files, directory);
|
|
289
|
+
for (const item of snapshots) {
|
|
290
|
+
if (ended() || !await ownsClaim()) break;
|
|
291
|
+
const row = currentJobs.find(row => row.id === item.row.id), file = join(directory, `${item.row.id}.json`);
|
|
292
|
+
const modified = await freshness(ports, file);
|
|
293
|
+
if (row && snapshotKey(row) === item.key && modified === item.modified && expired(ports, row, modified) && await ownsClaim())
|
|
294
|
+
await ports.files.unlink(file);
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
if (ended()) return null;
|
|
298
|
+
acquired = true;
|
|
299
|
+
const reservation = { id, directory }; reservationOwners.set(reservation, owner); return reservation;
|
|
300
|
+
}
|
|
301
|
+
while (!ended()) {
|
|
302
|
+
// Probes can block on HTTP. Nothing in this process holds exclusion here.
|
|
303
|
+
const snapshots = await inspect(directory, origin, ports, ended, deadline, () => { cancelled = true; }, ticket);
|
|
304
|
+
if (ended()) break;
|
|
305
|
+
// Dead waiters are safe to remove by immutable ticket path without a claim.
|
|
306
|
+
for (const item of snapshots.filter(item => item.row.state === 'waiting')) {
|
|
307
|
+
const current = (await rows(ports.files, directory)).find(row => row.id === item.row.id);
|
|
308
|
+
if (current && snapshotKey(current) === item.key && await freshness(ports, join(directory, `${current.id}.json`)) === item.modified)
|
|
309
|
+
await ports.files.unlink(join(directory, `${current.id}.json`));
|
|
310
|
+
}
|
|
311
|
+
let jobs = await rows(ports.files, directory);
|
|
312
|
+
if (ended()) break;
|
|
313
|
+
if (!jobs.some(row => row.id === id)) {
|
|
314
|
+
// Only the pending acquisition may restore its immutable waiting ticket.
|
|
315
|
+
// An absent-file heartbeat may already have stopped; retire it before
|
|
316
|
+
// restoring so an old in-flight pulse cannot stop the new lifecycle.
|
|
317
|
+
owner.pulse.pause(); await owner.pulse.pending();
|
|
318
|
+
if (ended()) break;
|
|
319
|
+
if (await ports.files.exclusiveCreate(path, ticket)) {
|
|
320
|
+
const pulse = heartbeat(path, ports, interruptOwner, true);
|
|
321
|
+
owner.pulse.stop(); owner.pulse = pulse;
|
|
322
|
+
}
|
|
323
|
+
if (ended()) break;
|
|
324
|
+
jobs = await rows(ports.files, directory);
|
|
325
|
+
}
|
|
326
|
+
const waiting = jobs.filter(row => row.state === 'waiting').sort(order), active = jobs.filter(row => row.state === 'active');
|
|
327
|
+
const message = `Waiting for a local slot: ${active.length} of ${limit} busy, ${Math.max(0, waiting.findIndex(row => row.id === id))} ahead of you. (Set PDD_MAX_JOBS to change the limit.)`;
|
|
328
|
+
if (ownWaiting(waiting[0])) {
|
|
329
|
+
const attempt = await locked(directory, ports, async ownsClaim => {
|
|
330
|
+
let currentJobs = await rows(ports.files, directory);
|
|
331
|
+
if (!await ownsClaim()) return false;
|
|
332
|
+
for (const item of snapshots.filter(item => item.row.state === 'active')) {
|
|
333
|
+
if (ended()) return false;
|
|
334
|
+
const row = currentJobs.find(row => row.id === item.row.id), file = join(directory, `${item.row.id}.json`);
|
|
335
|
+
const modified = await freshness(ports, file);
|
|
336
|
+
if (row && snapshotKey(row) === item.key && modified === item.modified && expired(ports, row, modified) && await ownsClaim()) {
|
|
337
|
+
await ports.files.unlink(file); currentJobs = currentJobs.filter(other => other.id !== row.id);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (!ended() && await ownsClaim() && currentJobs.filter(row => row.state === 'active').length < limit
|
|
341
|
+
&& ownWaiting(currentJobs.filter(row => row.state === 'waiting').sort(order)[0])) {
|
|
342
|
+
activeTicket = { ...ticket, state: 'active', started_at: ports.now() };
|
|
343
|
+
await ports.files.writeAtomic(path, activeTicket);
|
|
344
|
+
owner.snapshot = snapshotKey(activeTicket);
|
|
345
|
+
return true;
|
|
346
|
+
}
|
|
347
|
+
return false;
|
|
348
|
+
});
|
|
349
|
+
if (attempt.value) { acquired = true; const reservation = { id, directory }; reservationOwners.set(reservation, owner); return reservation; }
|
|
350
|
+
failures++;
|
|
351
|
+
}
|
|
352
|
+
if (message !== last) { ports.say(message); last = message; }
|
|
353
|
+
if (!ended()) await ports.sleep(retryDelay(ports, failures, waiting[0]?.id !== id, deadline === null ? Infinity : Math.max(0, deadline - ports.now())));
|
|
354
|
+
}
|
|
355
|
+
return null;
|
|
356
|
+
} finally {
|
|
357
|
+
if (!acquired) { owner.pulse.stop(); await owner.pulse.pending(); owners.delete(path); await removeUnsent(); }
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
export async function recordRuntimeRequest(reservation, requestId, given = {}) {
|
|
362
|
+
const ports = defaults(given), path = join(reservation.directory, `${reservation.id}.json`);
|
|
363
|
+
let failures = 0, cancelled = false;
|
|
364
|
+
const off = ports.onInterrupt(() => { cancelled = true; });
|
|
365
|
+
const ended = () => cancelled || ports.interrupted() || ports.deadline !== undefined && ports.now() >= ports.deadline;
|
|
366
|
+
try {
|
|
367
|
+
for (;;) {
|
|
368
|
+
if (ended()) return false;
|
|
369
|
+
const result = await locked(reservation.directory, ports, async ownsClaim => {
|
|
370
|
+
if (ended()) return false;
|
|
371
|
+
const row = (await rows(ports.files, reservation.directory)).find(row => row.id === reservation.id);
|
|
372
|
+
if (ended() || !await ownsClaim()) return false;
|
|
373
|
+
const owner = reservationOwners.get(reservation) ?? owners.get(path);
|
|
374
|
+
if (owner && (!row || snapshotKey(row) !== owner.snapshot)) {
|
|
375
|
+
owner.pulse.stop();
|
|
376
|
+
throw unavailable(new Error('Runtime reservation ownership changed'));
|
|
377
|
+
}
|
|
378
|
+
if (!row || row.state !== 'active') throw unavailable(new Error('Missing runtime reservation'));
|
|
379
|
+
const readStart = ports.files.readCheckStart, writeStart = ports.files.writeCheckStart;
|
|
380
|
+
const paced = row.kind === 'check' && (readStart !== undefined || writeStart !== undefined);
|
|
381
|
+
let at;
|
|
382
|
+
if (paced) {
|
|
383
|
+
if (incompleteCheckStarts.has(reservation.directory)) throw unavailable(new Error('Incomplete check pacing commit'));
|
|
384
|
+
if (typeof readStart !== 'function' || typeof writeStart !== 'function') throw unavailable(new Error('Incomplete check pacing storage'));
|
|
385
|
+
try { at = await readStart.call(ports.files, { directory: reservation.directory }); }
|
|
386
|
+
catch (error) { throw unavailable(error); }
|
|
387
|
+
if (at !== null && (!Number.isFinite(at) || at < 0)) throw unavailable(new Error('Invalid check pacing state'));
|
|
388
|
+
}
|
|
389
|
+
if (!row.request_ids.includes(requestId)) {
|
|
390
|
+
if (paced) {
|
|
391
|
+
const wait = at === null ? 0 : Math.max(0, at + 1000 - ports.now());
|
|
392
|
+
if (wait > 0) return { wait };
|
|
393
|
+
}
|
|
394
|
+
if (ended() || !await ownsClaim()) return false;
|
|
395
|
+
const next = { ...row, request_ids: [...row.request_ids, requestId] };
|
|
396
|
+
if (paced && ports.files[commitCheckRegistration]) {
|
|
397
|
+
try { await ports.files[commitCheckRegistration]({ path, previous: row, next, at }); }
|
|
398
|
+
catch (error) { throw unavailable(error); }
|
|
399
|
+
} else {
|
|
400
|
+
await ports.files.writeAtomic(path, next);
|
|
401
|
+
if (owner) { owner.snapshot = snapshotKey(next); owner[rememberNativeOwnership]?.(path, next); }
|
|
402
|
+
if (paced) {
|
|
403
|
+
try { await writeStart.call(ports.files, { directory: reservation.directory, at: ports.now() }); }
|
|
404
|
+
catch (error) {
|
|
405
|
+
incompleteCheckStarts.set(reservation.directory, path);
|
|
406
|
+
try {
|
|
407
|
+
const current = (await rows(ports.files, reservation.directory)).find(item => item.id === row.id);
|
|
408
|
+
if (snapshotKey(current) === snapshotKey(next) && await ownsClaim()) {
|
|
409
|
+
await ports.files.writeAtomic(path, row);
|
|
410
|
+
incompleteCheckStarts.delete(reservation.directory);
|
|
411
|
+
}
|
|
412
|
+
} catch { /* An uncertain predecessor must not become accepted ownership. */
|
|
413
|
+
} finally {
|
|
414
|
+
if (owner) { owner.snapshot = snapshotKey(row); owner[rememberNativeOwnership]?.(path, row); }
|
|
415
|
+
}
|
|
416
|
+
throw unavailable(error);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (owner) { owner.snapshot = snapshotKey(next); owner[rememberNativeOwnership]?.(path, next); }
|
|
421
|
+
}
|
|
422
|
+
if (owner) owner.posted = true;
|
|
423
|
+
});
|
|
424
|
+
if (result.claimed && !result.value?.wait) return result.value !== false;
|
|
425
|
+
const remaining = ports.deadline === undefined ? Infinity : Math.max(0, ports.deadline - ports.now());
|
|
426
|
+
await ports.sleep(Math.min(remaining, result.value?.wait ?? Math.max(10, retryDelay(ports, ++failures, false, remaining))));
|
|
427
|
+
}
|
|
428
|
+
} finally { off(); }
|
|
429
|
+
}
|
|
430
|
+
export async function releaseRuntimeSlot(reservation, { ended }, given = {}) {
|
|
431
|
+
if (!reservation) return;
|
|
432
|
+
const path = join(reservation.directory, `${reservation.id}.json`), owner = reservationOwners.get(reservation) ?? owners.get(path);
|
|
433
|
+
if (owner) { owner.pulse.stop(); await owner.pulse.pending(); if (owners.get(path) === owner) owners.delete(path); }
|
|
434
|
+
if (ended) {
|
|
435
|
+
const ports = defaults(given);
|
|
436
|
+
if (owner) {
|
|
437
|
+
const row = (await rows(ports.files, reservation.directory)).find(row => row.id === reservation.id);
|
|
438
|
+
if (!row || snapshotKey(row) !== owner.snapshot) return;
|
|
439
|
+
}
|
|
440
|
+
await ports.files.unlink(path);
|
|
441
|
+
if (incompleteCheckStarts.get(reservation.directory) === path) incompleteCheckStarts.delete(reservation.directory);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
export async function listRuntimeJobs(options, ports = {}) {
|
|
445
|
+
const jobs = await rows(ports.files ?? nativeFiles, directoryFor(options));
|
|
446
|
+
return { jobs: [...jobs].sort((a, b) => (a.state === 'active' ? 0 : 1) - (b.state === 'active' ? 0 : 1) || order(a, b)) };
|
|
447
|
+
}
|
|
448
|
+
// The saved kind stays `check`, `lint` or `try` (older pdd versions read and write these records); only the printed word is the command name.
|
|
449
|
+
const DEFAULT_COMMANDS = Object.freeze({ test: 'test', lint: 'lint', simulate: 'simulate' });
|
|
450
|
+
export async function runJobs({ env = process.env, client, commands } = {}, { stdout = process.stdout, stderr = process.stderr, files, now = Date.now } = {}) {
|
|
451
|
+
const words = client?.commands ?? commands ?? DEFAULT_COMMANDS;
|
|
452
|
+
const kindWords = Array.isArray(words)
|
|
453
|
+
? { check: words[0] ?? 'test', lint: words[1] ?? 'lint', try: words[2] ?? 'simulate' }
|
|
454
|
+
: { check: words.test ?? 'test', lint: words.lint ?? 'lint', try: words.simulate ?? 'simulate' };
|
|
455
|
+
try {
|
|
456
|
+
const stateDir = resolve(env.PDD_STATE_DIR || join(env.HOME || homedir(), '.pdd', 'runtime'));
|
|
457
|
+
const { jobs } = await listRuntimeJobs({ stateDir, origin: runtimeOrigin(env) }, { files });
|
|
458
|
+
if (!jobs.length) stdout.write('No local interpreter jobs.\n');
|
|
459
|
+
for (const row of jobs) stdout.write(`${row.state} ${kindWords[row.kind] ?? row.kind} · PID ${row.pid} · ${Math.max(0, Math.floor((now() - row.started_at) / 1000))} s · ${row.id} · ${row.request_ids.join(', ') || 'no request yet'}\n`);
|
|
460
|
+
return 0;
|
|
461
|
+
} catch (error) { stderr.write(`${String(error.message).split('\n')[0]}\n`); return 5; }
|
|
462
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Generated from prompts/cli/runtime-workspace-migration.prompt.md (sha256: 0dc120dccecf8d7582c6fb24c0b6e47e900e3ab4c785d5ae0312e4fb0b0b9a38).
|
|
2
|
+
// Implements prompts/cli/runtime-workspace-migration.prompt.md.
|
|
3
|
+
import {realpathSync} from 'node:fs';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
import {loadRuntimeWorkspace,requireRuntimePath} from './runtime-workspace.mjs';
|
|
6
|
+
import {captureSource,sourceFilePort,gitFiles} from './runtime-preflight.mjs';
|
|
7
|
+
import {runtimeWorkspaceMigrationStore,acquireCaseWriteOwnership,applyPendingCase} from './runtime-client.mjs';
|
|
8
|
+
const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
9
|
+
const safe=path=>typeof path==='string'&&path&&!/[\\\x00-\x1f*?]/.test(path)&&!path.startsWith('/')&&!path.split('/').some(p=>!p||p==='.'||p==='..'||p==='.git');
|
|
10
|
+
export async function migrateRuntimeWorkspace({root,projectionRoot,mappings,write=false,signal},ports={}){
|
|
11
|
+
const canonical=ports.realpath??realpathSync;root=canonical(root);projectionRoot=canonical(projectionRoot);
|
|
12
|
+
const result={state:write?'applied':'preview',mappings:Array.isArray(mappings)?mappings.map(x=>({...x})):[],items:[],unresolved:[]};
|
|
13
|
+
const unresolved=(id,reason,recoveryPath=null)=>{result.unresolved.push({id,reason,recoveryPath});if(write)result.state='incomplete';};
|
|
14
|
+
if(!Array.isArray(mappings)||mappings.some(m=>!m||Object.keys(m).length!==2||!safe(m.from)||!safe(m.to))||new Set(mappings.map(m=>m.from)).size!==mappings.length||new Set(mappings.map(m=>m.to)).size!==mappings.length){unresolved('mappings','exact unique safe from/to file mappings are required');result.state='incomplete';return result;}
|
|
15
|
+
const map=new Map(mappings.map(m=>[m.from,m.to])),policy=(ports.loadRuntimeWorkspace??loadRuntimeWorkspace)({root}),store=ports.store??runtimeWorkspaceMigrationStore({root,projectionRoot,env:ports.env});
|
|
16
|
+
const source=ports.sourceFilePort??sourceFilePort,capture=ports.captureSource??((r,opts)=>captureSource(r,opts,ports)),eligibility=ports.evidenceEligibility??ports.readEvidenceEligibility??(() => ({state:'unavailable',reason:'workflow evidence eligibility port is not bound'}));
|
|
17
|
+
let oldFiles,newFiles;
|
|
18
|
+
try{oldFiles=source(projectionRoot,new Set((ports.gitFiles??gitFiles)(projectionRoot)));newFiles=source(root,new Set((ports.gitFiles??gitFiles)(root)));}
|
|
19
|
+
catch(error){unresolved('source',error.message);result.state='incomplete';return result;}
|
|
20
|
+
const checks=new Map();
|
|
21
|
+
for(const {from,to} of mappings){try{requireRuntimePath(policy,{path:to,from});const before=oldFiles.read({path:from}).content,after=newFiles.read({path:to}).content;if(before!==after)throw Error('mapped authored bytes differ; repair the authored source without changing expectations');checks.set(from,true);}catch(error){checks.set(from,false);unresolved(from,error.message);}}
|
|
22
|
+
let inventory;try{inventory=await store.inventory();}catch(error){unresolved('private-state',error.message);result.state='incomplete';return result;}
|
|
23
|
+
const migrationId=(ports.hash??digest)({root,projectionRoot,mappings});
|
|
24
|
+
for(const item of inventory){
|
|
25
|
+
if(signal?.aborted){unresolved(item.id,'migration cancelled; originals and prepared records retained',item.id);if(write)result.state='incomplete';break;}
|
|
26
|
+
const outcome={id:item.id,kind:item.kind,state:'ready',reason:null,recoveryPath:item.id};result.items.push(outcome);
|
|
27
|
+
const record=item.record;
|
|
28
|
+
try{
|
|
29
|
+
const selected=item.kind==='case'?[record.identity?.original?.path]:Array.isArray(record.rows)?record.rows.map(row=>row.test):item.kind==='repo'?Object.keys(record.tries??{}):[record.originalPath??record.test].filter(Boolean);
|
|
30
|
+
if(!selected.length)throw Error('owned source selection is unavailable; preserve the original recovery command');
|
|
31
|
+
for(const path of selected)if(!map.has(path)||!checks.get(path))throw Error(`missing or incompatible exact source mapping: ${path}`);
|
|
32
|
+
const oldCapture=capture(projectionRoot,{tests:selected,appMap:null}),newCapture=capture(root,{tests:selected.map(p=>map.get(p)),appMap:null});
|
|
33
|
+
// Compare the complete closure. Each raw/effective member and used reference
|
|
34
|
+
// must have an explicit exact destination, never a prefix assumption.
|
|
35
|
+
for(const file of oldCapture.sources){const target=map.get(file.path);if(!target||!checks.get(file.path))throw Error(`required source mapping is unresolved: ${file.path}`);const next=newCapture.sources.find(f=>f.path===target);if(!next||!Buffer.from(file.bytes).equals(Buffer.from(next.bytes)))throw Error(`effective source/reference meaning changed: ${file.path}`);}
|
|
36
|
+
if(newCapture.sources.length!==oldCapture.sources.length)throw Error('complete selected source closure differs');
|
|
37
|
+
const owner=eligibility({root,producerRoot:projectionRoot,tests:selected,source_sha256:record.source_sha256??oldCapture.sha256,runId:record.runId??null,stage:record.association?.stage??null},ports.evidencePorts??{});
|
|
38
|
+
outcome.eligibility=owner;outcome.selected=selected;outcome.readCommand=record.readCommand??(record.batch?`pdd test --read ${record.batch}`:record.id?`pdd test --read ${record.id}`:null);
|
|
39
|
+
if(owner.state!=='eligible')throw Error(`evidence/source ownership ${owner.state}: ${owner.reason}`);
|
|
40
|
+
// Archive names are part of source identity, even when mapped bytes agree.
|
|
41
|
+
if(oldCapture.sha256!==newCapture.sha256)throw Error('mapped archive identity changed; historical evidence cannot establish the authored current source');
|
|
42
|
+
if(!write)continue;
|
|
43
|
+
const previous=store.readMapping(migrationId);const done=previous?.items?.[item.id];if(done?.state==='applied'){outcome.state='applied';continue;}
|
|
44
|
+
let lease;try{
|
|
45
|
+
const testPath=map.get(selected[0]),handoff=await ports.handoff?.({root,testPath,signal});
|
|
46
|
+
lease=await (ports.acquireCaseWriteOwnership??acquireCaseWriteOwnership)({root,testPath,handoff,signal},{...ports,env:ports.env,...ports.ownershipPorts});
|
|
47
|
+
const prepared={schema_version:'pdd.workspace-migration.v1',root,projectionRoot,mappings,activeItem:item.id,items:{...(previous?.items??{}),[item.id]:{state:'prepared',kind:item.kind,original:item.raw,record:item.record,selected,eligibility:owner,readCommand:outcome.readCommand}}};
|
|
48
|
+
const location=store.publishMapping(migrationId,prepared);outcome.recoveryPath=location;
|
|
49
|
+
await ports.fault?.('prepared',item);
|
|
50
|
+
if(signal?.aborted){outcome.state='pending';outcome.reason='migration cancelled before publication';unresolved(item.id,outcome.reason,location);break;}
|
|
51
|
+
if(item.kind==='case'){
|
|
52
|
+
const retained=store.transferCase({...item,mappedStory:map.get(record.identity.original.storyPath)},testPath);
|
|
53
|
+
{
|
|
54
|
+
const applied=await (ports.applyPendingCase??applyPendingCase)({root,pendingId:retained.pendingId,writeOwnership:lease,signal},{...ports,env:ports.env,...ports.casePorts});
|
|
55
|
+
if(applied.state!=='committed'){outcome.state=applied.state;outcome.reason=applied.reason;unresolved(item.id,applied.reason,applied.recoveryPath);continue;}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const committed={...prepared,items:{...prepared.items,[item.id]:{...prepared.items[item.id],state:'applied'}}};
|
|
59
|
+
await ports.fault?.('before-publication',item);if(signal?.aborted){outcome.state='pending';unresolved(item.id,'migration cancelled before publication',location);break;}
|
|
60
|
+
store.publishMapping(migrationId,committed);
|
|
61
|
+
await ports.fault?.('published',item);
|
|
62
|
+
const actual=store.readMapping(migrationId);
|
|
63
|
+
if(actual?.items?.[item.id]?.state!=='applied')throw Error('mapping publication is uncertain; retained recovery record required');
|
|
64
|
+
outcome.state='applied';
|
|
65
|
+
}catch(error){if(error?.unboundPort)throw error;const actual=store.readMapping(migrationId);if(actual?.items?.[item.id]?.state==='applied')outcome.state='applied';else throw error;}
|
|
66
|
+
finally{lease?.release();}
|
|
67
|
+
}catch(error){if(error?.unboundPort)throw error;outcome.state=signal?.aborted?'pending':'unavailable';outcome.reason=error.message;unresolved(item.id,error.message,outcome.recoveryPath);}
|
|
68
|
+
}
|
|
69
|
+
if(result.unresolved.length)result.state='incomplete';return result;
|
|
70
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Generated from prompts/cli/runtime-workspace.prompt.md (sha256: 017fa50e714d98d9dd3d6ff283fd3cefbb258964157991a2ff4fc9fc540fc52b).
|
|
2
|
+
// Implements prompts/cli/runtime-workspace.prompt.md.
|
|
3
|
+
import {constants,lstatSync,openSync,fstatSync,readFileSync,closeSync,realpathSync} from 'node:fs';
|
|
4
|
+
import {join,resolve,parse,sep} from 'node:path';
|
|
5
|
+
import {spawnSync} from 'node:child_process';
|
|
6
|
+
const CONTROL='pdd-workspace.json', MAX=10_485_760;
|
|
7
|
+
export class RuntimeWorkspaceError extends Error {
|
|
8
|
+
constructor(code,message){super(`${code}: ${message}`);this.code=code;this.exitCode=4;}
|
|
9
|
+
}
|
|
10
|
+
const fail=(code,reason)=>{throw new RuntimeWorkspaceError(code,`${CONTROL}: ${reason}. Correct this regular local policy file and retry.`);};
|
|
11
|
+
export function nativeWorkspaceFiles(root){
|
|
12
|
+
let observed,canonicalRoot;
|
|
13
|
+
return {
|
|
14
|
+
stat({path}){
|
|
15
|
+
try{
|
|
16
|
+
canonicalRoot=realpathSync(root);
|
|
17
|
+
const full=resolve(canonicalRoot,path);let at=parse(full).root;
|
|
18
|
+
for(const part of full.slice(at.length).split(sep).filter(Boolean)){
|
|
19
|
+
at=join(at,part);const st=lstatSync(at);
|
|
20
|
+
if(st.isSymbolicLink())throw Error('symbolic link');
|
|
21
|
+
if(at!==full&&!st.isDirectory())throw Error('non-directory ancestor');
|
|
22
|
+
if(at===full){if(!st.isFile())throw Error('not regular');observed=st;}
|
|
23
|
+
}
|
|
24
|
+
}catch(error){if(error.code==='ENOENT')return{exists:false,is_symlink:false,size:0};throw error;}
|
|
25
|
+
const git=spawnSync('git',['ls-files','-z','-co','--exclude-standard','--',path],{cwd:canonicalRoot});
|
|
26
|
+
if(git.status!==0||!git.stdout.toString().split('\0').includes(path))throw Error('not Git-visible');
|
|
27
|
+
return{exists:true,is_symlink:false,size:observed.size};
|
|
28
|
+
},
|
|
29
|
+
read({path}){
|
|
30
|
+
const fd=openSync(join(canonicalRoot,path),constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);
|
|
31
|
+
try{const st=fstatSync(fd);if(!observed||!st.isFile()||st.size>MAX||st.ino!==observed.ino||st.dev!==observed.dev||st.mtimeMs!==observed.mtimeMs||st.ctimeMs!==observed.ctimeMs)throw Error('changed');
|
|
32
|
+
const content=new TextDecoder('utf-8',{fatal:true}).decode(readFileSync(fd));
|
|
33
|
+
const after=fstatSync(fd);if(after.size!==st.size||after.mtimeMs!==st.mtimeMs||after.ctimeMs!==st.ctimeMs)throw Error('changed');
|
|
34
|
+
return{content};
|
|
35
|
+
}finally{closeSync(fd);}
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const valid=path=>typeof path==='string'&&!!path&&!/[\\\x00-\x1f\x7f*?\[\]{}:$%]/.test(path)&&!path.startsWith('~')&&!path.startsWith('/')&&!path.replace(/\/$/,'').split('/').some(p=>!p||p==='.'||p==='..'||p==='.git');
|
|
40
|
+
export function loadRuntimeWorkspace({root},files=nativeWorkspaceFiles(root)){
|
|
41
|
+
let stat,text;
|
|
42
|
+
try{stat=files.stat({path:CONTROL});if(!stat.exists)return Object.freeze({configured:false,allowed_paths:Object.freeze([])});if(stat.is_symlink||!Number.isInteger(stat.size)||stat.size<0||stat.size>MAX)fail('workspace-config-unsafe','unsafe or oversized policy');text=files.read({path:CONTROL}).content;}
|
|
43
|
+
catch(error){if(error instanceof RuntimeWorkspaceError)throw error;fail('workspace-config-unsafe','cannot safely read policy');}
|
|
44
|
+
let doc;try{doc=JSON.parse(text);}catch{fail('workspace-config-invalid','expected valid JSON');}
|
|
45
|
+
if(!doc||Array.isArray(doc)||typeof doc!=='object'||Object.keys(doc).length!==1||!Array.isArray(doc.allowed_paths)||!doc.allowed_paths.every(valid))fail('workspace-config-invalid','expected only allowed_paths with safe repository-relative files or directory/ entries');
|
|
46
|
+
return Object.freeze({configured:true,allowed_paths:Object.freeze([...new Set(doc.allowed_paths)])});
|
|
47
|
+
}
|
|
48
|
+
export function allowsRuntimePath(policy,path){return !policy.configured||typeof path==='string'&&policy.allowed_paths.some(p=>p.endsWith('/')?path.startsWith(p)&&path.length>p.length:path===p);}
|
|
49
|
+
export function requireRuntimePath(policy,{path,from='Source',chain=[],role='source'}){
|
|
50
|
+
if(!allowsRuntimePath(policy,path))throw new RuntimeWorkspaceError('workspace-path-outside',`${[...chain,from,path].filter(Boolean).join(' -> ')}: required ${role} is outside ${CONTROL}. Correct or move the reference, or deliberately change allowed_paths.`);
|
|
51
|
+
return path;
|
|
52
|
+
}
|