zcode-agent 0.0.0-stage → 1.0.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/lib/store.js ADDED
@@ -0,0 +1,340 @@
1
+ 'use strict';
2
+ // Session store: one directory per zcode session under <root>/sessions/<id>.
3
+ //
4
+ // session.json lifecycle record (atomic tmp+rename writes; the owning
5
+ // process is the only writer while it is alive)
6
+ // events.ndjson bounded activity log (phases, tools, checks — no deltas)
7
+ // result.json the final handback of the latest invocation
8
+ // home/ the session's own engine HOME (engine DB, subagent dirs)
9
+ // pending.json a detached invocation waiting for its worker
10
+ // stdout.ndjson / stderr.log output of detached workers
11
+ //
12
+ // Lifecycle: queued → running → finished (status: completed | unverified |
13
+ // partial | blocked | failed | cancelled). A record that says queued/running
14
+ // whose pid is gone reads as "interrupted" — resumable, never silently
15
+ // "running" forever.
16
+ const fs = require('node:fs');
17
+ const path = require('node:path');
18
+ const crypto = require('node:crypto');
19
+ const { rootDir } = require('./isolation.js');
20
+
21
+ const RECORD_SCHEMA = 'zcode.session/1';
22
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
23
+ const MAX_EVENTS = 2000;
24
+ const ACTIVE_STATES = new Set(['queued', 'running']);
25
+
26
+ class SessionExistsError extends Error {
27
+ constructor(id) {
28
+ super(
29
+ `session "${id}" already exists. Inspect it with "zcode-agent status ${id}" ` +
30
+ `or continue it with "zcode-agent resume ${id}".`
31
+ );
32
+ this.code = 'ZCODE_SESSION_EXISTS';
33
+ }
34
+ }
35
+
36
+ function sessionsDir(env = process.env) {
37
+ return path.join(rootDir(env), 'sessions');
38
+ }
39
+
40
+ function sessionDir(id, env = process.env) {
41
+ return path.join(sessionsDir(env), id);
42
+ }
43
+
44
+ function validId(id) {
45
+ return typeof id === 'string' && ID_RE.test(id);
46
+ }
47
+
48
+ function newId() {
49
+ return `zc-${crypto.randomBytes(4).toString('hex')}`;
50
+ }
51
+
52
+ function writeJsonAtomic(file, value) {
53
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(3).toString('hex')}.tmp`;
54
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
55
+ fs.renameSync(tmp, file);
56
+ }
57
+
58
+ function readJson(file) {
59
+ try {
60
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ // Claims the id atomically (mkdir fails if it exists) and writes the first
67
+ // record. Throws SessionExistsError on collision — an orchestrator retrying
68
+ // a start with the same --id never runs the work twice.
69
+ function createSession(id, fields, env = process.env) {
70
+ fs.mkdirSync(sessionsDir(env), { recursive: true, mode: 0o700 });
71
+ const dir = sessionDir(id, env);
72
+ try {
73
+ fs.mkdirSync(dir, { mode: 0o700 });
74
+ } catch (err) {
75
+ if (err.code === 'EEXIST') throw new SessionExistsError(id);
76
+ throw err;
77
+ }
78
+ const now = new Date().toISOString();
79
+ const record = {
80
+ schema: RECORD_SCHEMA,
81
+ id,
82
+ createdAt: now,
83
+ updatedAt: now,
84
+ state: 'queued',
85
+ status: null,
86
+ phase: 'queued',
87
+ pid: process.pid,
88
+ turns: 0,
89
+ activity: { toolCalls: 0, subagentsStarted: 0, lastTool: null, lastEventAt: now },
90
+ ...fields,
91
+ };
92
+ writeJsonAtomic(path.join(dir, 'session.json'), record);
93
+ return record;
94
+ }
95
+
96
+ function readSession(id, env = process.env) {
97
+ if (!validId(id)) return null;
98
+ return readJson(path.join(sessionDir(id, env), 'session.json'));
99
+ }
100
+
101
+ // Read-modify-write; `patch` is an object or (record) => object.
102
+ function updateSession(id, patch, env = process.env) {
103
+ const file = path.join(sessionDir(id, env), 'session.json');
104
+ const current = readJson(file);
105
+ if (!current) throw new Error(`session "${id}" has no record`);
106
+ const delta = typeof patch === 'function' ? patch(current) : patch;
107
+ const next = { ...current, ...delta, updatedAt: new Date().toISOString() };
108
+ writeJsonAtomic(file, next);
109
+ return next;
110
+ }
111
+
112
+ function deleteSession(id, env = process.env) {
113
+ if (!validId(id)) return;
114
+ fs.rmSync(sessionDir(id, env), { recursive: true, force: true });
115
+ }
116
+
117
+ function writeResult(id, result, env = process.env) {
118
+ writeJsonAtomic(path.join(sessionDir(id, env), 'result.json'), result);
119
+ }
120
+
121
+ function readResult(id, env = process.env) {
122
+ if (!validId(id)) return null;
123
+ return readJson(path.join(sessionDir(id, env), 'result.json'));
124
+ }
125
+
126
+ // Bounded append-only activity log. Counting lines once per process keeps
127
+ // appends O(1).
128
+ const eventCounts = new Map();
129
+ function appendEvent(id, event, env = process.env) {
130
+ const file = path.join(sessionDir(id, env), 'events.ndjson');
131
+ let count = eventCounts.get(file);
132
+ if (count === undefined) {
133
+ try {
134
+ count = fs.readFileSync(file, 'utf8').split('\n').length - 1;
135
+ } catch {
136
+ count = 0;
137
+ }
138
+ }
139
+ if (count >= MAX_EVENTS && event.type !== 'phase' && event.type !== 'result') return;
140
+ fs.appendFileSync(file, JSON.stringify({ t: new Date().toISOString(), ...event }) + '\n', {
141
+ mode: 0o600,
142
+ });
143
+ eventCounts.set(file, count + 1);
144
+ }
145
+
146
+ function readEvents(id, { tail = 20 } = {}, env = process.env) {
147
+ try {
148
+ const lines = fs
149
+ .readFileSync(path.join(sessionDir(id, env), 'events.ndjson'), 'utf8')
150
+ .split('\n')
151
+ .filter(Boolean);
152
+ return lines.slice(-tail).map((l) => JSON.parse(l));
153
+ } catch {
154
+ return [];
155
+ }
156
+ }
157
+
158
+ function pidAlive(pid) {
159
+ if (!Number.isInteger(pid) || pid <= 0) return false;
160
+ try {
161
+ process.kill(pid, 0);
162
+ return true;
163
+ } catch (err) {
164
+ return err.code === 'EPERM';
165
+ }
166
+ }
167
+
168
+ // The record as callers should see it: an active state whose owner process
169
+ // is gone is reported as "interrupted".
170
+ function viewSession(record) {
171
+ if (!record) return null;
172
+ if (ACTIVE_STATES.has(record.state) && !pidAlive(record.pid)) {
173
+ return { ...record, state: 'interrupted', live: false };
174
+ }
175
+ return { ...record, live: ACTIVE_STATES.has(record.state) };
176
+ }
177
+
178
+ // How long a running session has gone without any engine event
179
+ // ({idleMs, stalled?}); null unless it is running. Informational only: zcode
180
+ // never acts on it. The same rule everywhere (status, wait, watch).
181
+ const STALL_MIN = 8;
182
+ function idleInfo(view, { stallMin = STALL_MIN, now = Date.now() } = {}) {
183
+ if (!view || view.state !== 'running') return null;
184
+ const t = Date.parse((view.activity && view.activity.lastEventAt) || view.updatedAt);
185
+ if (!Number.isFinite(t)) return null;
186
+ const idleMs = Math.max(0, now - t);
187
+ return idleMs >= stallMin * 60000 ? { idleMs, stalled: true } : { idleMs };
188
+ }
189
+
190
+ function listSessions(env = process.env) {
191
+ let names = [];
192
+ try {
193
+ names = fs.readdirSync(sessionsDir(env));
194
+ } catch {
195
+ return [];
196
+ }
197
+ const out = [];
198
+ for (const name of names) {
199
+ const record = readSession(name, env);
200
+ if (record) out.push(viewSession(record));
201
+ }
202
+ return out.sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)));
203
+ }
204
+
205
+ // Accepts a zcode id or an engine session id (sess_…, as printed by 0.3.x
206
+ // and still reported as result.sessionId). Returns the zcode id or null.
207
+ function resolveSessionId(ref, env = process.env) {
208
+ if (validId(ref) && readSession(ref, env)) return ref;
209
+ for (const record of listSessions(env)) {
210
+ if (record.engineSessionId === ref) return record.id;
211
+ }
212
+ return null;
213
+ }
214
+
215
+ // Exclusive pid lock (O_EXCL create). A lock whose pid is dead is stale and
216
+ // reclaimed; the content is re-read just before removal so a fresh lock
217
+ // taken by a racing reclaimer is not deleted. Returns release() or null.
218
+ function claimLockFile(file) {
219
+ for (let attempt = 0; attempt < 3; attempt++) {
220
+ try {
221
+ fs.writeFileSync(file, String(process.pid), { flag: 'wx', mode: 0o600 });
222
+ return () => {
223
+ try {
224
+ if (fs.readFileSync(file, 'utf8') === String(process.pid)) fs.rmSync(file, { force: true });
225
+ } catch {
226
+ /* already gone */
227
+ }
228
+ };
229
+ } catch (err) {
230
+ if (err.code !== 'EEXIST') throw err;
231
+ }
232
+ let holder;
233
+ try {
234
+ holder = fs.readFileSync(file, 'utf8');
235
+ } catch {
236
+ continue; // released in between: retry the create
237
+ }
238
+ if (pidAlive(Number(holder))) return null;
239
+ try {
240
+ if (fs.readFileSync(file, 'utf8') === holder) fs.rmSync(file, { force: true });
241
+ } catch {
242
+ /* someone else reclaimed it */
243
+ }
244
+ }
245
+ return null;
246
+ }
247
+
248
+ // One live process drives a session at a time (two racing `resume`s, or a
249
+ // resume racing a detached worker, cannot both run it).
250
+ function claimSession(id, env = process.env) {
251
+ return claimLockFile(path.join(sessionDir(id, env), 'owner.lock'));
252
+ }
253
+
254
+ // --- plans (zcode plan) -------------------------------------------------------
255
+ // <root>/plans/<name>.json: the supervisor's bookkeeping for a plan file. The
256
+ // source of truth for a plan's progress is its sessions; this only remembers
257
+ // which file, which supervisor and which launches failed.
258
+
259
+ function plansDir(env = process.env) {
260
+ return path.join(rootDir(env), 'plans');
261
+ }
262
+
263
+ const planFile = (name, env = process.env) => path.join(plansDir(env), `${name}.json`);
264
+
265
+ function readPlanState(name, env = process.env) {
266
+ return validId(name) ? readJson(planFile(name, env)) : null;
267
+ }
268
+
269
+ // Exclusive create: a second `plan run` under the same name is refused.
270
+ // Returns false when the plan already exists.
271
+ function createPlanState(name, state, env = process.env) {
272
+ fs.mkdirSync(plansDir(env), { recursive: true, mode: 0o700 });
273
+ const now = new Date().toISOString();
274
+ try {
275
+ fs.writeFileSync(planFile(name, env), JSON.stringify({ schema: 'zcode.plan-state/1', name, createdAt: now, updatedAt: now, ...state }, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
276
+ return true;
277
+ } catch (err) {
278
+ if (err.code === 'EEXIST') return false;
279
+ throw err;
280
+ }
281
+ }
282
+
283
+ function updatePlanState(name, patch, env = process.env) {
284
+ const current = readPlanState(name, env);
285
+ if (!current) throw new Error(`plan "${name}" has no state`);
286
+ const delta = typeof patch === 'function' ? patch(current) : patch;
287
+ const next = { ...current, ...delta, updatedAt: new Date().toISOString() };
288
+ writeJsonAtomic(planFile(name, env), next);
289
+ return next;
290
+ }
291
+
292
+ // One supervisor per plan: a pid lock next to the state.
293
+ function claimPlan(name, env = process.env) {
294
+ fs.mkdirSync(plansDir(env), { recursive: true, mode: 0o700 });
295
+ return claimLockFile(path.join(plansDir(env), `${name}.lock`));
296
+ }
297
+
298
+ // Machine-wide soft cap on running sessions (ZAI_CODE_MAX_ACTIVE): N slot
299
+ // lock files; a session holds one while it runs.
300
+ function claimSlot(max, env = process.env) {
301
+ const dir = path.join(rootDir(env), 'slots');
302
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
303
+ for (let n = 0; n < max; n++) {
304
+ const release = claimLockFile(path.join(dir, `${n}.lock`));
305
+ if (release) return release;
306
+ }
307
+ return null;
308
+ }
309
+
310
+ module.exports = {
311
+ RECORD_SCHEMA,
312
+ SessionExistsError,
313
+ sessionsDir,
314
+ sessionDir,
315
+ validId,
316
+ newId,
317
+ createSession,
318
+ readSession,
319
+ updateSession,
320
+ deleteSession,
321
+ writeResult,
322
+ readResult,
323
+ appendEvent,
324
+ readEvents,
325
+ pidAlive,
326
+ viewSession,
327
+ idleInfo,
328
+ STALL_MIN,
329
+ listSessions,
330
+ resolveSessionId,
331
+ claimSession,
332
+ plansDir,
333
+ readPlanState,
334
+ createPlanState,
335
+ updatePlanState,
336
+ claimPlan,
337
+ claimSlot,
338
+ claimLockFile,
339
+ writeJsonAtomic,
340
+ };
@@ -0,0 +1,114 @@
1
+ 'use strict';
2
+ // Task contract from its sources: a base object (JSON contract / markdown
3
+ // brief) plus CLI-style additions. Wraps normalizeContract with what needs
4
+ // the filesystem: inlining "@file" entries, dropping a --file that is also
5
+ // inlined as context, and validating unit ownership against the session's.
6
+ // Shared by `zcode task` and anything else that builds contracts (plan files).
7
+ //
8
+ // Throws ContractError for every problem, before any engine spawn.
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const { normalizeContract, ContractError } = require('./contract.js');
12
+ const { workspaceRoot, normalizeOwns, isOwned, ownsOverlap, OwnershipError } = require('./workspace.js');
13
+
14
+ const FILE_REF = /^@(\S+)$/;
15
+
16
+ const canon = (p) => {
17
+ try {
18
+ return fs.realpathSync(p);
19
+ } catch {
20
+ return p;
21
+ }
22
+ };
23
+
24
+ const toArray = (v) => (v === undefined || v === null ? [] : Array.isArray(v) ? v : [v]);
25
+
26
+ // Units must stay inside the session's owns and must not overlap each other.
27
+ function validateUnits(contract, cwd) {
28
+ const units = contract.units || [];
29
+ if (!units.length) return;
30
+ let root;
31
+ const norm = (patterns, flag) => {
32
+ root = root || workspaceRoot(cwd);
33
+ try {
34
+ return normalizeOwns(patterns, cwd, root, flag);
35
+ } catch (err) {
36
+ if (err instanceof OwnershipError) throw new ContractError(err.message);
37
+ throw err;
38
+ }
39
+ };
40
+ const sessionOwns = norm(contract.owns || [], '--owns');
41
+ const owned = units
42
+ .filter((u) => u.owns && u.owns.length)
43
+ .map((u) => ({ unit: u, patterns: norm(u.owns, `unit "${u.name}" owns`) }));
44
+ for (const { unit, patterns } of owned) {
45
+ const at = patterns.findIndex((p) => !isOwned(p, sessionOwns));
46
+ if (at >= 0) {
47
+ throw new ContractError(
48
+ `unit "${unit.name}" owns "${unit.owns[at]}", which is outside the session's owns (${(contract.owns || []).join(', ') || 'whole workspace'})`
49
+ );
50
+ }
51
+ }
52
+ for (let i = 0; i < owned.length; i++) {
53
+ for (let j = i + 1; j < owned.length; j++) {
54
+ if (ownsOverlap(owned[i].patterns, owned[j].patterns)) {
55
+ throw new ContractError(
56
+ `units "${owned[i].unit.name}" and "${owned[j].unit.name}" have overlapping owns (${owned[i].unit.owns.join(', ')} / ${owned[j].unit.owns.join(', ')}); units must be disjoint`
57
+ );
58
+ }
59
+ }
60
+ }
61
+ }
62
+
63
+ // base: parsed contract object; baseDir: where its "@file" entries resolve
64
+ // (the contract file's directory, else cwd), then `cwd` when not found there. additions: the CLI flags
65
+ // (strings; "@file" resolves against the process cwd). cwd: --cwd.
66
+ function buildContract({ base = {}, baseDir = process.cwd(), objective = '', additions = {}, cwd = process.cwd() }) {
67
+ const inlined = new Set();
68
+ // dirs are tried in order; the error names every path tried.
69
+ const inline = (list, dirs, label) =>
70
+ toArray(list).map((item) => {
71
+ const text = String(item).trim();
72
+ const m = FILE_REF.exec(text);
73
+ if (!m) return text;
74
+ const tried = [];
75
+ for (const dir of dirs) {
76
+ const file = path.resolve(dir, m[1]);
77
+ if (tried.includes(file)) continue;
78
+ tried.push(file);
79
+ try {
80
+ const body = fs.readFileSync(file, 'utf8');
81
+ inlined.add(canon(file));
82
+ return body;
83
+ } catch {
84
+ /* try the next directory */
85
+ }
86
+ }
87
+ throw new ContractError(`${label} file "${m[1]}" could not be read (tried ${tried.join(', ')}).`);
88
+ });
89
+
90
+ let b = base;
91
+ if (b && typeof b === 'object' && !Array.isArray(b)) {
92
+ b = { ...b };
93
+ for (const key of ['context', 'decisions']) {
94
+ if (b[key] !== undefined) b[key] = inline(b[key], [baseDir, cwd], `contract ${key}`);
95
+ }
96
+ }
97
+ const flagDir = process.cwd();
98
+ const contract = normalizeContract(b, {
99
+ ...additions,
100
+ objective,
101
+ context: inline(additions.context, [flagDir], '--context'),
102
+ decisions: inline(additions.decisions, [flagDir], '--decisions'),
103
+ });
104
+ // A file the executor already gets inlined is not also listed to read.
105
+ if (inlined.size) {
106
+ contract.files = contract.files.filter(
107
+ (f) => ![cwd, baseDir, flagDir].some((dir) => inlined.has(canon(path.resolve(dir, f))))
108
+ );
109
+ }
110
+ validateUnits(contract, cwd);
111
+ return contract;
112
+ }
113
+
114
+ module.exports = { buildContract, validateUnits };