aegiscode 7.0.14 → 7.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +3 -2
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2932
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3020
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4003
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/fingerprint.js +1 -592
  28. package/src/format.js +1 -259
  29. package/src/fuzzy.js +1 -119
  30. package/src/history.js +1 -401
  31. package/src/init.js +1 -175
  32. package/src/input.js +1 -139
  33. package/src/keys.js +1 -183
  34. package/src/markdown.js +1 -306
  35. package/src/models.js +1 -487
  36. package/src/naming.js +1 -229
  37. package/src/overlays.js +1 -461
  38. package/src/panels.js +1 -1418
  39. package/src/ping.js +1 -226
  40. package/src/presence.js +1 -238
  41. package/src/render.js +1 -515
  42. package/src/screen.js +1 -518
  43. package/src/screens.js +1 -896
  44. package/src/secret.js +1 -59
  45. package/src/securefs.js +1 -359
  46. package/src/settings.js +1 -155
  47. package/src/shared.js +1 -52
  48. package/src/sharedpaths.js +1 -53
  49. package/src/signup.js +1 -156
  50. package/src/summarize.js +1 -95
  51. package/src/sysdiag.js +1 -585
  52. package/src/system.js +1 -40
  53. package/src/theme.js +1 -570
  54. package/src/title.js +1 -220
  55. package/src/todos.js +1 -115
  56. package/src/tokens.js +1 -263
  57. package/src/topup.js +1 -210
  58. package/src/update.js +1 -181
  59. package/vendor/client/aegis.js +1 -2179
  60. package/vendor/client/attest.js +1 -442
  61. package/vendor/client/authorship-key.js +1 -410
  62. package/vendor/client/auto-provision.js +1 -134
  63. package/vendor/client/brain-catalog.js +1 -268
  64. package/vendor/client/byok-catalog.js +1 -230
  65. package/vendor/client/credentials.js +1 -494
  66. package/vendor/client/device-fingerprint.js +1 -141
  67. package/vendor/client/drive-connect.js +1 -110
  68. package/vendor/client/drive-upload.js +1 -174
  69. package/vendor/client/env-file.js +1 -1273
  70. package/vendor/client/fingerprint.js +1 -1064
  71. package/vendor/client/foreign-memory.js +1 -669
  72. package/vendor/client/google-signin.js +1 -133
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -373
  75. package/vendor/client/platform.js +1 -937
  76. package/vendor/client/prefs.js +1 -351
  77. package/vendor/client/presence-constants.js +1 -107
  78. package/vendor/client/presence.js +1 -438
  79. package/vendor/client/record-vault.js +3 -1055
  80. package/vendor/client/session-store.js +1 -548
  81. package/vendor/client/topup.js +1 -297
  82. package/vendor/client/touch.js +1 -458
  83. package/vendor/client/update.js +1 -704
  84. package/vendor/client/user-models.js +1 -381
  85. package/vendor/desktop/lib/local/agents.js +1 -105
  86. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  87. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  88. package/vendor/desktop/lib/local/context.js +1 -95
  89. package/vendor/desktop/lib/local/engine.js +1 -3301
  90. package/vendor/desktop/lib/local/entitlement.js +1 -660
  91. package/vendor/desktop/lib/local/git-scope.js +1 -228
  92. package/vendor/desktop/lib/local/local.js +1 -2135
  93. package/vendor/desktop/lib/local/prompt.js +1 -275
  94. package/vendor/desktop/lib/local/queue.js +1 -560
  95. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  96. package/vendor/desktop/lib/local/shell.js +1 -680
  97. package/vendor/desktop/lib/local/tools.js +1 -1238
  98. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  99. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  100. package/vendor/desktop/lib/settings.js +1 -890
  101. package/vendor/desktop/renderer/usage.js +1 -1239
  102. package/vendor/hosts/install.js +1 -638
  103. package/vendor/hosts/openai-shim.js +1 -515
  104. package/vendor/hosts/spec.js +1 -164
  105. package/vendor/hosts/targets.js +1 -346
  106. package/vendor/mcp/server.js +1 -221
  107. package/vendor/mcp/tools.js +1 -408
  108. package/vendor/one/src/child.js +1 -285
  109. package/vendor/one/src/permissions.js +1 -369
@@ -1,562 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * queue.js — the autonomous work queue.
10
- *
11
- * "Do X autonomously" means: nobody is at the keyboard, so the task has to
12
- * survive the conversation that produced it. This module is that survival: a
13
- * durable, crash-safe list of tasks in
14
- * `~/.aegiscode/queue.jsonl` (`$AEGISCODE_HOME`/`$AEGIS_HOME` override the dir,
15
- * `$AEGIS_QUEUE_FILE` the file) that any host — the desktop app, the
16
- * `aegiscode` CLI, a systemd timer — can add to, and that a worker drains one
17
- * task at a time.
18
- *
19
- * Why a FILE and not the renderer's in-memory state: the same reason the
20
- * session store exists. The desktop app owns the queue while it is open, but a
21
- * task queued at 18:00 has to still be there at 08:00 after a reboot, and the
22
- * CLI has to see the tasks the GUI queued. A process-local list answers
23
- * neither, so the queue is the file and every host is just a reader/writer of
24
- * it.
25
- *
26
- * Three properties are load-bearing, and each one exists because its absence
27
- * was a real failure:
28
- *
29
- * 1. WRITES ARE ATOMIC (temp file + rename). A queue that is rewritten in
30
- * place loses everything on a crash mid-write — the same defect the session
31
- * store was fixed for. Rename is atomic within a filesystem, so a reader
32
- * sees either the old queue or the new one, never half of each.
33
- *
34
- * 2. WRITES ARE AN UPSERT keyed on id, never a blind overwrite of the whole
35
- * file. A drain holds the queue in memory for minutes at a time, and
36
- * anything added during that window (another host, another window, the
37
- * queue's own `reconcile`) would be silently erased by the stale copy the
38
- * drain saves back. The drain only ever writes back *its own* item's status
39
- * (`settle`), and `upsert` merges instead of replacing, so a mid-drain add
40
- * survives.
41
- *
42
- * 3. A `running` ITEM WHOSE PROCESS IS GONE IS `pending` AGAIN. A task is
43
- * marked running with the pid holding it; when a worker is killed
44
- * (SIGKILL, a reboot, a closed laptop) nothing gets to clear that flag, and
45
- * a queue that trusts the flag is a queue that never runs that task again.
46
- * `recoverStale` re-reads liveness instead of trusting the file, the same
47
- * no-staleness-window pattern the worktree and session locks use.
48
- *
49
- * Pure-ish on purpose: every function takes its paths/clock/env from the
50
- * caller (or a `process.env` default), so the whole module is testable against
51
- * a temp dir with no Electron, no network, and no home directory.
52
- */
53
-
54
- const fs = require('node:fs');
55
- const os = require('node:os');
56
- const path = require('node:path');
57
-
58
- /** The only legal statuses. `error` (not "failed") matches the runs log's. */
59
- const STATUSES = Object.freeze(['pending', 'running', 'done', 'error']);
60
-
61
- /**
62
- * The per-user data dir the whole repo already agrees on: `$AEGISCODE_HOME`
63
- * (this plugin's convention — see worktree-lock.js's worktreeLockDir and
64
- * config.js's aegisDir) or `~/.aegiscode`. `$AEGIS_HOME` is honoured as well so
65
- * a host that already exports it (the generic spelling) points at the same
66
- * place rather than quietly queueing into a second directory — two hosts
67
- * disagreeing about where the queue file goes is indistinguishable from having
68
- * no queue.
69
- */
70
- function dataDir(env = process.env) {
71
- const e = env || {};
72
- const home = e.AEGISCODE_HOME || e.AEGIS_HOME;
73
- return home ? path.resolve(home) : path.join(os.homedir(), '.aegiscode');
74
- }
75
-
76
- /** The queue file for this environment (tests point AEGIS_QUEUE_FILE at a temp dir). */
77
- function queuePath(env = process.env) {
78
- return (env && env.AEGIS_QUEUE_FILE) || path.join(dataDir(env), 'queue.jsonl');
79
- }
80
-
81
- /** Append-only accounting: one line per finished task, never rewritten. */
82
- function runsPath(env = process.env) {
83
- return (env && env.AEGIS_RUNS_FILE) || path.join(dataDir(env), 'runs.jsonl');
84
- }
85
-
86
- /** The single-worker lock. One drain at a time; a second worker backs off. */
87
- function lockPath(env = process.env) {
88
- return (env && env.AEGIS_QUEUE_LOCK) || path.join(dataDir(env), 'queue.lock');
89
- }
90
-
91
- function ensureDir(dir) {
92
- fs.mkdirSync(dir, { recursive: true });
93
- return dir;
94
- }
95
-
96
- // ── reading and writing ─────────────────────────────────────────────────────
97
-
98
- /**
99
- * Parse a queue file. A line that does not parse is skipped rather than
100
- * thrown on: an interrupted append (power loss between `write` and `fsync`)
101
- * can leave a torn final line, and losing the whole queue to one bad byte is
102
- * a worse outcome than losing the one item that was mid-write.
103
- */
104
- function readQueue(file) {
105
- let raw = '';
106
- try {
107
- raw = fs.readFileSync(file, 'utf8');
108
- } catch {
109
- return []; // no queue yet is the normal first-run state, not an error
110
- }
111
- const out = [];
112
- for (const line of raw.split('\n')) {
113
- const text = line.trim();
114
- if (!text) continue;
115
- try {
116
- const item = JSON.parse(text);
117
- if (item && typeof item === 'object' && item.id != null) out.push(item);
118
- } catch {
119
- /* torn or hand-edited line — skip it, keep the rest */
120
- }
121
- }
122
- return out;
123
- }
124
-
125
- /** Write the whole queue atomically (temp file + rename), mode 0600. */
126
- function writeQueue(file, items) {
127
- ensureDir(path.dirname(file));
128
- const body = items.map((i) => JSON.stringify(i)).join('\n') + (items.length ? '\n' : '');
129
- const tmp = `${file}.${process.pid}.tmp`;
130
- fs.writeFileSync(tmp, body, { mode: 0o600 });
131
- fs.renameSync(tmp, file);
132
- return items;
133
- }
134
-
135
- function loadQueue(env = process.env) {
136
- return readQueue(queuePath(env));
137
- }
138
-
139
- function saveQueue(env, items) {
140
- return writeQueue(queuePath(env), items);
141
- }
142
-
143
- /**
144
- * Highest id in the queue, +1. Ids increase for as long as the queue file has
145
- * any history to count, so they are never reused while anything remains. They
146
- * are NOT globally unique across generations: `clear --all` empties the file and
147
- * the next `add` starts again at #1. The runs log therefore records each task's
148
- * text and time alongside its id — a `#7` is unique within one queue generation,
149
- * and the text is what makes it identifiable across a `clear --all`.
150
- */
151
- function nextId(items) {
152
- let max = 0;
153
- for (const i of items) {
154
- const n = Number(i && i.id);
155
- if (Number.isFinite(n) && n > max) max = n;
156
- }
157
- return max + 1;
158
- }
159
-
160
- /**
161
- * Insert or replace by id, leaving every other item in the list untouched.
162
- *
163
- * This is the ONLY way a drain writes back — `saveQueue(env, upsert(loadQueue(env),
164
- * myItem))` — and the load has to be FRESH, taken immediately before the write.
165
- * upsert can only preserve what the caller actually passed it: hand it a stale
166
- * snapshot and anything added since is erased, because `saveQueue` rewrites the
167
- * whole file. The worker re-reads before each of its two writes for exactly this
168
- * reason (autonomous.js: claim and settle). The remaining window is the instant
169
- * between that read and the write, which is why `add` never takes the drain lock
170
- * and a queue is a work list, not a ledger.
171
- */
172
- function upsert(items, entry) {
173
- const list = Array.isArray(items) ? items : [];
174
- const idx = list.findIndex((i) => i && i.id === entry.id);
175
- if (idx === -1) list.push(entry);
176
- else list[idx] = { ...list[idx], ...entry };
177
- return list;
178
- }
179
-
180
- // ── the queue's own vocabulary ──────────────────────────────────────────────
181
-
182
- /**
183
- * Queue a task. `cwd` is where the work happens (the worker runs the turn
184
- * with it as the tool loop's working directory), `class` + `model` are the
185
- * same pair engine.js's interactive turns use ('aegis'/'byok'/'local' and the
186
- * model id that class expects), and `commit` asks the worker to commit what
187
- * the task changed (scoped — see autonomous.js).
188
- *
189
- * REFUSED AT THE DOOR, not three stages into a drain. `class` defaults to
190
- * 'aegis' (every task queued before this field existed), and the (model,
191
- * class) pair has to pass autonomous.js's own accept-list — the CLI
192
- * (`aegiscode autonomous add --model`), the desktop card and a hand-written
193
- * queue file are all held to the same rule, so a bad row fails here with a
194
- * reason instead of coming back as an opaque server error after being picked
195
- * up. `model: null` stays legal for the 'aegis' class only: that is "no
196
- * pick", and autonomous.resolveModel fills in the pooled brain. 'byok' and
197
- * 'local' have no such default and are refused if blank — see
198
- * autonomous.modelRefusal. Required lazily: queue.js is a dependency of
199
- * autonomous.js, and this check must not turn that into a load-order cycle.
200
- */
201
- function addTask(env, opts = {}) {
202
- const task = String(opts.task == null ? '' : opts.task).trim();
203
- if (!task) throw new Error('queue: a task needs text');
204
- const autonomousMod = require('./autonomous.js');
205
- const cls = autonomousMod.normalizeClass(opts.class);
206
- const statedModel = String(opts.model == null ? '' : opts.model).trim();
207
- const refusal = autonomousMod.modelRefusal(statedModel, cls);
208
- if (refusal) throw new Error(`queue: ${refusal}`);
209
- const items = loadQueue(env);
210
- const now = opts.now || Date.now();
211
- const entry = {
212
- id: nextId(items),
213
- task,
214
- cwd: opts.cwd || process.cwd(),
215
- class: cls,
216
- model: statedModel || null,
217
- effort: opts.effort || null,
218
- workers: Number.isInteger(opts.workers) ? opts.workers : null,
219
- singlePass: Boolean(opts.singlePass),
220
- commit: Boolean(opts.commit),
221
- maxRounds: Number.isInteger(opts.maxRounds) ? opts.maxRounds : null,
222
- source: opts.source || 'manual',
223
- status: 'pending',
224
- attempts: 0,
225
- created: now,
226
- updated: now,
227
- };
228
- upsert(items, entry);
229
- saveQueue(env, items);
230
- return entry;
231
- }
232
-
233
- function findTask(items, id) {
234
- const n = Number(id);
235
- return (items || []).find((i) => Number(i && i.id) === n) || null;
236
- }
237
-
238
- /** Claim a task: `pending` → `running`, stamped with the pid that owns it. */
239
- function markRunning(items, id, opts = {}) {
240
- const item = findTask(items, id);
241
- if (!item) return null;
242
- const now = opts.now || Date.now();
243
- item.status = 'running';
244
- item.pid = opts.pid || process.pid;
245
- item.startedAt = now;
246
- item.updated = now;
247
- item.attempts = (Number(item.attempts) || 0) + 1;
248
- return item;
249
- }
250
-
251
- /**
252
- * Record a finished task. `result` is whatever the worker learned (output
253
- * text, token usage, round count, the commit it made); it is kept verbatim so
254
- * the runs log and the queue never disagree about what happened.
255
- */
256
- function settle(items, id, { status, result, error, now = Date.now() } = {}) {
257
- const item = findTask(items, id);
258
- if (!item) return null;
259
- item.status = STATUSES.includes(status) ? status : 'error';
260
- item.updated = now;
261
- item.finishedAt = now;
262
- delete item.pid;
263
- if (result !== undefined) item.result = result;
264
- if (error) item.error = String(error);
265
- else delete item.error;
266
- return item;
267
- }
268
-
269
- /** Put a task back at the head of the queue, keeping its attempt count. */
270
- function retryTask(env, id, opts = {}) {
271
- const items = loadQueue(env);
272
- const item = findTask(items, id);
273
- if (!item) return null;
274
- item.status = 'pending';
275
- item.updated = opts.now || Date.now();
276
- delete item.error;
277
- delete item.pid;
278
- // A manual retry is a fresh deliberate ask, so it gets its own full run of
279
- // MAX_ROUND_STOPS chances (autonomous.js) rather than inheriting whatever
280
- // count a previous, unrelated failure left behind.
281
- delete item.roundStops;
282
- saveQueue(env, items);
283
- return item;
284
- }
285
-
286
- /**
287
- * Drop finished items. Pending and running are NEVER removed: `clear` is the
288
- * "tidy the log" command, and a user who runs it mid-drain must not lose the
289
- * task that is running or the ones waiting. `all: true` (`--all`) is the
290
- * explicit "empty it" escape hatch.
291
- */
292
- function clearQueue(env, { all = false } = {}) {
293
- const items = loadQueue(env);
294
- const kept = all ? [] : items.filter((i) => i.status === 'pending' || i.status === 'running');
295
- const removed = items.length - kept.length;
296
- saveQueue(env, kept);
297
- return { removed, kept: kept.length };
298
- }
299
-
300
- /** True if `pid` names a live process (EPERM means it exists but isn't ours). */
301
- function isAlive(pid) {
302
- const n = Number(pid);
303
- if (!Number.isInteger(n) || n <= 0) return false;
304
- try {
305
- process.kill(n, 0);
306
- return true;
307
- } catch (e) {
308
- return Boolean(e && e.code === 'EPERM');
309
- }
310
- }
311
-
312
- /**
313
- * Re-read liveness for every `running` item. A running item whose pid is gone
314
- * (or which never recorded one) goes back to `pending`; the queue's promise is
315
- * that a task is worked eventually, and "a dead process left the flag up" is
316
- * not an acceptable reason for it never to be.
317
- *
318
- * Items held by a LIVE pid are left alone — that process is the drain, and
319
- * re-pending its item would run it twice.
320
- */
321
- function recoverStale(items, { isAliveFn = isAlive, now = Date.now() } = {}) {
322
- const recovered = [];
323
- for (const item of items || []) {
324
- if (!item || item.status !== 'running') continue;
325
- if (item.pid && isAliveFn(item.pid)) continue;
326
- item.status = 'pending';
327
- item.updated = now;
328
- item.recoveredAt = now;
329
- delete item.pid;
330
- recovered.push(item.id);
331
- }
332
- return recovered;
333
- }
334
-
335
- /** Count of tasks a drain still has to work. */
336
- function pendingCount(items) {
337
- return (items || []).filter((i) => i && i.status === 'pending').length;
338
- }
339
-
340
- /** Pending tasks in queue order (the order they were added). */
341
- function pending(items) {
342
- return (items || []).filter((i) => i && i.status === 'pending');
343
- }
344
-
345
- // ── single-worker lock ──────────────────────────────────────────────────────
346
-
347
- function lockHolder(env = process.env) {
348
- try {
349
- return JSON.parse(fs.readFileSync(lockPath(env), 'utf8'));
350
- } catch {
351
- return null;
352
- }
353
- }
354
-
355
- /**
356
- * Take the drain lock, or report who holds it.
357
- *
358
- * Only ONE drain may run at a time. Two drains are not twice as fast: they
359
- * share a working tree, and the second one's `git add`/commit races the
360
- * first's — the exact multi-agent-one-checkout failure the worktree lock
361
- * exists for. The lock is a marker with a pid in it, not a timeout, so a
362
- * worker killed with SIGKILL is reclaimed by the next caller immediately
363
- * rather than after a staleness window nobody can tune correctly.
364
- */
365
- function acquireLock(env = process.env, { pid = process.pid, now = Date.now(), isAliveFn = isAlive } = {}) {
366
- const file = lockPath(env);
367
- const holder = lockHolder(env);
368
- if (holder && holder.pid && holder.pid !== pid && isAliveFn(holder.pid)) {
369
- return { ok: false, holder };
370
- }
371
- ensureDir(path.dirname(file));
372
- fs.writeFileSync(file, JSON.stringify({ pid, host: os.hostname(), startedAt: now }), { mode: 0o600 });
373
- return { ok: true, holder: { pid, startedAt: now } };
374
- }
375
-
376
- /** Release the lock, but only if we still hold it (never free another's). */
377
- function releaseLock(env = process.env, { pid = process.pid } = {}) {
378
- const holder = lockHolder(env);
379
- if (holder && holder.pid && holder.pid !== pid) return { ok: false, holder };
380
- try {
381
- fs.unlinkSync(lockPath(env));
382
- return { ok: true };
383
- } catch {
384
- return { ok: true, already: true };
385
- }
386
- }
387
-
388
- // ── run accounting ──────────────────────────────────────────────────────────
389
-
390
- /**
391
- * Append one finished run. Append-only and never rewritten: the queue is
392
- * current state (and is deliberately small), the runs log is history, and
393
- * history that can be truncated by a crash is not history.
394
- */
395
- function appendRun(env, record) {
396
- const file = runsPath(env);
397
- ensureDir(path.dirname(file));
398
- fs.appendFileSync(file, JSON.stringify(record) + '\n', { mode: 0o600 });
399
- return record;
400
- }
401
-
402
- function readRuns(env = process.env, { limit = 20 } = {}) {
403
- let raw = '';
404
- try {
405
- raw = fs.readFileSync(runsPath(env), 'utf8');
406
- } catch {
407
- return [];
408
- }
409
- const lines = raw.split('\n').filter((l) => l.trim());
410
- const slice = limit > 0 ? lines.slice(-limit) : lines;
411
- const out = [];
412
- for (const line of slice) {
413
- try {
414
- out.push(JSON.parse(line));
415
- } catch {
416
- /* same tolerance as readQueue */
417
- }
418
- }
419
- return out;
420
- }
421
-
422
- // ── reconcile: pull the next PLAN.md phase into the queue ───────────────────
423
- //
424
- // PLAN.md carries a top `Status:` checklist (`- [x] Phase N — …`) plus one
425
- // `## Phase N …` section per phase, marked done with a ✅ in the heading. The
426
- // two have drifted here before (a phase shipped with a ✅ heading and no
427
- // checklist line), so a phase counts as done if EITHER says so, and a missing
428
- // checklist line under a ✅ heading is healed from the heading rather than
429
- // silently re-queued as work.
430
-
431
- function planPath(cwd) {
432
- return path.join(cwd, 'PLAN.md');
433
- }
434
-
435
- function parsePlanStatus(text) {
436
- const statusDone = new Map(); // phase number -> checked?
437
- const headerDone = new Set(); // phase numbers whose heading carries ✅
438
- const headerNums = new Set(); // every phase number with a heading
439
- let inStatus = false;
440
- for (const line of String(text || '').split('\n')) {
441
- if (/^Status:/.test(line)) {
442
- inStatus = true;
443
- continue;
444
- }
445
- if (inStatus) {
446
- const m = line.match(/^- \[([ x])\] Phase (\d+)/);
447
- if (m) {
448
- statusDone.set(Number(m[2]), m[1] === 'x');
449
- continue;
450
- }
451
- // Blank lines and indented wraps belong to the same list item/block.
452
- if (line.trim() === '' || /^\s+\S/.test(line)) continue;
453
- inStatus = false; // anything else (e.g. '---') ends the block
454
- }
455
- // Every PLAN.md in these repos writes `## Phase N ✅ — title` (✅ right after
456
- // the number). A trailing `## Phase N — title ✅` is accepted too, because
457
- // reconcile reads plans other sessions and agents wrote, and a heading that
458
- // says it shipped means it shipped wherever the ✅ sits.
459
- const hm = line.match(/^##\s*Phase\s+(\d+)\b/);
460
- if (hm) {
461
- const num = Number(hm[1]);
462
- headerNums.add(num);
463
- if (/✅/.test(line.slice(hm[0].length))) headerDone.add(num);
464
- }
465
- }
466
- return { statusDone, headerDone, headerNums };
467
- }
468
-
469
- function extractPhaseTitle(text, num) {
470
- const m = String(text || '').match(new RegExp(`^## Phase ${num}\\b(.*)$`, 'm'));
471
- if (!m) return `Phase ${num}`;
472
- const rest = m[1]
473
- .trim()
474
- .replace(/^(✅|⚠️)\s*/, '')
475
- .replace(/\s*(✅|⚠️)$/, '')
476
- .replace(/^[—-]\s*/, '')
477
- .trim();
478
- return rest || `Phase ${num}`;
479
- }
480
-
481
- /** Append a checklist line for any ✅ heading the Status list never got. */
482
- function healPlanStatus(text, parsed) {
483
- const missing = [...parsed.headerDone].filter((n) => !parsed.statusDone.has(n)).sort((a, b) => a - b);
484
- if (!missing.length) return { text, changed: false, added: [] };
485
- const lines = String(text || '').split('\n');
486
- const statusStart = lines.findIndex((l) => /^Status:/.test(l));
487
- if (statusStart === -1) return { text, changed: false, added: [] };
488
- let lastListIdx = -1;
489
- for (let i = statusStart + 1; i < lines.length; i++) {
490
- if (/^- \[[ x]\] Phase \d+/.test(lines[i])) {
491
- lastListIdx = i;
492
- continue;
493
- }
494
- if (lines[i].trim() === '' || /^\s+\S/.test(lines[i])) continue;
495
- break;
496
- }
497
- if (lastListIdx === -1) return { text, changed: false, added: [] };
498
- const newLines = missing.map((n) => `- [x] Phase ${n} — ${extractPhaseTitle(text, n)}`);
499
- lines.splice(lastListIdx + 1, 0, ...newLines);
500
- return { text: lines.join('\n'), changed: true, added: missing };
501
- }
502
-
503
- /**
504
- * Read PLAN.md and say what the next uncompleted phase is, healing the Status
505
- * checklist on the way (when `write` is true). Returns `{ ok, text, parsed,
506
- * healed, next, title }` — the caller decides what to do with it, so the pure
507
- * read is testable and nothing here queues on its own.
508
- */
509
- function reconcilePlan(cwd, { write = false } = {}) {
510
- let text;
511
- try {
512
- text = fs.readFileSync(planPath(cwd), 'utf8');
513
- } catch {
514
- return { ok: false, reason: `no PLAN.md in ${cwd}`, next: null };
515
- }
516
- const parsed = parsePlanStatus(text);
517
- const healed = healPlanStatus(text, parsed);
518
- if (healed.changed && write) {
519
- fs.writeFileSync(planPath(cwd), healed.text);
520
- text = healed.text;
521
- }
522
- const done = new Set(parsed.headerDone);
523
- for (const [num, checked] of parsed.statusDone) if (checked) done.add(num);
524
- const next = [...parsed.headerNums].filter((n) => !done.has(n)).sort((a, b) => a - b)[0];
525
- if (next == null) return { ok: true, text, parsed, healed, next: null, title: null };
526
- return { ok: true, text, parsed, healed, next, title: extractPhaseTitle(text, next) };
527
- }
528
-
529
- module.exports = {
530
- STATUSES,
531
- dataDir,
532
- queuePath,
533
- runsPath,
534
- lockPath,
535
- ensureDir,
536
- readQueue,
537
- writeQueue,
538
- loadQueue,
539
- saveQueue,
540
- nextId,
541
- upsert,
542
- addTask,
543
- findTask,
544
- markRunning,
545
- settle,
546
- retryTask,
547
- clearQueue,
548
- isAlive,
549
- recoverStale,
550
- pendingCount,
551
- pending,
552
- lockHolder,
553
- acquireLock,
554
- releaseLock,
555
- appendRun,
556
- readRuns,
557
- planPath,
558
- parsePlanStatus,
559
- extractPhaseTitle,
560
- healPlanStatus,
561
- reconcilePlan,
562
- };
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),STATUSES=Object.freeze(["pending","running","done","error"]);function dataDir(e=process.env){const t=e||{},n=t.AEGISCODE_HOME||t.AEGIS_HOME;return n?path.resolve(n):path.join(os.homedir(),".aegiscode")}function queuePath(e=process.env){return e&&e.AEGIS_QUEUE_FILE||path.join(dataDir(e),"queue.jsonl")}function runsPath(e=process.env){return e&&e.AEGIS_RUNS_FILE||path.join(dataDir(e),"runs.jsonl")}function lockPath(e=process.env){return e&&e.AEGIS_QUEUE_LOCK||path.join(dataDir(e),"queue.lock")}function ensureDir(e){return fs.mkdirSync(e,{recursive:!0}),e}function readQueue(e){let t="";try{t=fs.readFileSync(e,"utf8")}catch{return[]}const n=[];for(const e of t.split("\n")){const t=e.trim();if(t)try{const e=JSON.parse(t);e&&"object"==typeof e&&null!=e.id&&n.push(e)}catch{}}return n}function writeQueue(e,t){ensureDir(path.dirname(e));const n=t.map((e=>JSON.stringify(e))).join("\n")+(t.length?"\n":""),r=`${e}.${process.pid}.tmp`;return fs.writeFileSync(r,n,{mode:384}),fs.renameSync(r,e),t}function loadQueue(e=process.env){return readQueue(queuePath(e))}function saveQueue(e,t){return writeQueue(queuePath(e),t)}function nextId(e){let t=0;for(const n of e){const e=Number(n&&n.id);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function upsert(e,t){const n=Array.isArray(e)?e:[],r=n.findIndex((e=>e&&e.id===t.id));return-1===r?n.push(t):n[r]={...n[r],...t},n}function addTask(e,t={}){const n=String(null==t.task?"":t.task).trim();if(!n)throw new Error("queue: a task needs text");const r=require("./autonomous.js"),s=r.normalizeClass(t.class),u=String(null==t.model?"":t.model).trim(),a=r.modelRefusal(u,s);if(a)throw new Error(`queue: ${a}`);const o=loadQueue(e),i=t.now||Date.now(),c={id:nextId(o),task:n,cwd:t.cwd||process.cwd(),class:s,model:u||null,effort:t.effort||null,workers:Number.isInteger(t.workers)?t.workers:null,singlePass:Boolean(t.singlePass),commit:Boolean(t.commit),maxRounds:Number.isInteger(t.maxRounds)?t.maxRounds:null,source:t.source||"manual",status:"pending",attempts:0,created:i,updated:i};return upsert(o,c),saveQueue(e,o),c}function findTask(e,t){const n=Number(t);return(e||[]).find((e=>Number(e&&e.id)===n))||null}function markRunning(e,t,n={}){const r=findTask(e,t);if(!r)return null;const s=n.now||Date.now();return r.status="running",r.pid=n.pid||process.pid,r.startedAt=s,r.updated=s,r.attempts=(Number(r.attempts)||0)+1,r}function settle(e,t,{status:n,result:r,error:s,now:u=Date.now()}={}){const a=findTask(e,t);return a?(a.status=STATUSES.includes(n)?n:"error",a.updated=u,a.finishedAt=u,delete a.pid,void 0!==r&&(a.result=r),s?a.error=String(s):delete a.error,a):null}function retryTask(e,t,n={}){const r=loadQueue(e),s=findTask(r,t);return s?(s.status="pending",s.updated=n.now||Date.now(),delete s.error,delete s.pid,delete s.roundStops,saveQueue(e,r),s):null}function clearQueue(e,{all:t=!1}={}){const n=loadQueue(e),r=t?[]:n.filter((e=>"pending"===e.status||"running"===e.status)),s=n.length-r.length;return saveQueue(e,r),{removed:s,kept:r.length}}function isAlive(e){const t=Number(e);if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function recoverStale(e,{isAliveFn:t=isAlive,now:n=Date.now()}={}){const r=[];for(const s of e||[])s&&"running"===s.status&&(s.pid&&t(s.pid)||(s.status="pending",s.updated=n,s.recoveredAt=n,delete s.pid,r.push(s.id)));return r}function pendingCount(e){return(e||[]).filter((e=>e&&"pending"===e.status)).length}function pending(e){return(e||[]).filter((e=>e&&"pending"===e.status))}function lockHolder(e=process.env){try{return JSON.parse(fs.readFileSync(lockPath(e),"utf8"))}catch{return null}}function acquireLock(e=process.env,{pid:t=process.pid,now:n=Date.now(),isAliveFn:r=isAlive}={}){const s=lockPath(e),u=lockHolder(e);return u&&u.pid&&u.pid!==t&&r(u.pid)?{ok:!1,holder:u}:(ensureDir(path.dirname(s)),fs.writeFileSync(s,JSON.stringify({pid:t,host:os.hostname(),startedAt:n}),{mode:384}),{ok:!0,holder:{pid:t,startedAt:n}})}function releaseLock(e=process.env,{pid:t=process.pid}={}){const n=lockHolder(e);if(n&&n.pid&&n.pid!==t)return{ok:!1,holder:n};try{return fs.unlinkSync(lockPath(e)),{ok:!0}}catch{return{ok:!0,already:!0}}}function appendRun(e,t){const n=runsPath(e);return ensureDir(path.dirname(n)),fs.appendFileSync(n,JSON.stringify(t)+"\n",{mode:384}),t}function readRuns(e=process.env,{limit:t=20}={}){let n="";try{n=fs.readFileSync(runsPath(e),"utf8")}catch{return[]}const r=n.split("\n").filter((e=>e.trim())),s=t>0?r.slice(-t):r,u=[];for(const e of s)try{u.push(JSON.parse(e))}catch{}return u}function planPath(e){return path.join(e,"PLAN.md")}function parsePlanStatus(e){const t=new Map,n=new Set,r=new Set;let s=!1;for(const u of String(e||"").split("\n")){if(/^Status:/.test(u)){s=!0;continue}if(s){const e=u.match(/^- \[([ x])\] Phase (\d+)/);if(e){t.set(Number(e[2]),"x"===e[1]);continue}if(""===u.trim()||/^\s+\S/.test(u))continue;s=!1}const e=u.match(/^##\s*Phase\s+(\d+)\b/);if(e){const t=Number(e[1]);r.add(t),/✅/.test(u.slice(e[0].length))&&n.add(t)}}return{statusDone:t,headerDone:n,headerNums:r}}function extractPhaseTitle(e,t){const n=String(e||"").match(new RegExp(`^## Phase ${t}\\b(.*)$`,"m"));return n&&n[1].trim().replace(/^(✅|⚠️)\s*/,"").replace(/\s*(✅|⚠️)$/,"").replace(/^[—-]\s*/,"").trim()||`Phase ${t}`}function healPlanStatus(e,t){const n=[...t.headerDone].filter((e=>!t.statusDone.has(e))).sort(((e,t)=>e-t));if(!n.length)return{text:e,changed:!1,added:[]};const r=String(e||"").split("\n"),s=r.findIndex((e=>/^Status:/.test(e)));if(-1===s)return{text:e,changed:!1,added:[]};let u=-1;for(let e=s+1;e<r.length;e++)if(/^- \[[ x]\] Phase \d+/.test(r[e]))u=e;else if(""!==r[e].trim()&&!/^\s+\S/.test(r[e]))break;if(-1===u)return{text:e,changed:!1,added:[]};const a=n.map((t=>`- [x] Phase ${t} — ${extractPhaseTitle(e,t)}`));return r.splice(u+1,0,...a),{text:r.join("\n"),changed:!0,added:n}}function reconcilePlan(e,{write:t=!1}={}){let n;try{n=fs.readFileSync(planPath(e),"utf8")}catch{return{ok:!1,reason:`no PLAN.md in ${e}`,next:null}}const r=parsePlanStatus(n),s=healPlanStatus(n,r);s.changed&&t&&(fs.writeFileSync(planPath(e),s.text),n=s.text);const u=new Set(r.headerDone);for(const[e,t]of r.statusDone)t&&u.add(e);const a=[...r.headerNums].filter((e=>!u.has(e))).sort(((e,t)=>e-t))[0];return null==a?{ok:!0,text:n,parsed:r,healed:s,next:null,title:null}:{ok:!0,text:n,parsed:r,healed:s,next:a,title:extractPhaseTitle(n,a)}}module.exports={STATUSES:STATUSES,dataDir:dataDir,queuePath:queuePath,runsPath:runsPath,lockPath:lockPath,ensureDir:ensureDir,readQueue:readQueue,writeQueue:writeQueue,loadQueue:loadQueue,saveQueue:saveQueue,nextId:nextId,upsert:upsert,addTask:addTask,findTask:findTask,markRunning:markRunning,settle:settle,retryTask:retryTask,clearQueue:clearQueue,isAlive:isAlive,recoverStale:recoverStale,pendingCount:pendingCount,pending:pending,lockHolder:lockHolder,acquireLock:acquireLock,releaseLock:releaseLock,appendRun:appendRun,readRuns:readRuns,planPath:planPath,parsePlanStatus:parsePlanStatus,extractPhaseTitle:extractPhaseTitle,healPlanStatus:healPlanStatus,reconcilePlan:reconcilePlan};