aegiscode 6.5.6 → 6.5.7

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.5.6",
4
+ "version": "6.5.7",
5
5
  "description": "aegiscode \u2014 the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -55,6 +55,13 @@ const FILES = [
55
55
  'desktop/lib/local/shell.js',
56
56
  'desktop/lib/local/agents.js',
57
57
  'desktop/lib/local/prompt.js',
58
+ // engine.js requires all three at load time (turn-guard -> git-scope, and
59
+ // worktree-lock), so leaving them out stages a vendor tree whose engine
60
+ // throws MODULE_NOT_FOUND before it can answer anything — which is what
61
+ // test/cli-package.test.mjs caught in the published 6.5.6 tarball.
62
+ 'desktop/lib/local/turn-guard.js',
63
+ 'desktop/lib/local/worktree-lock.js',
64
+ 'desktop/lib/local/git-scope.js',
58
65
  ];
59
66
 
60
67
  function main() {
package/src/chatflow.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * ─────────────────────────────
13
13
  * ❯ what should I fix? input line, with history + completion
14
14
  * ─────────────────────────────
15
- * ⏸ manual mode on · ? for shortcuts status line
15
+ * ⏸ manual mode on · ? for shortcuts status line (→ switches the mode)
16
16
  *
17
17
  * driven by a raw key stream, with the turn lifecycle of the reference: a user
18
18
  * row, a live assistant row that grows as the model streams, tool rows that
@@ -258,20 +258,30 @@ function spinnerLine(state, ctx) {
258
258
  return [span(t.coral, glyph), ...tinted, span(t.white, '… '), tail];
259
259
  }
260
260
 
261
- /** The idle/modifier status line at the bottom of the frame. */
261
+ /**
262
+ * The idle/modifier status line at the bottom of the frame.
263
+ *
264
+ * The idle form advertises `→`, the chord that switches the approval mode
265
+ * (manual ⇄ auto) — see the RIGHT branch in `handleKey`. It replaces the
266
+ * reference's "← for agents" hint, which this host printed on every idle frame
267
+ * while binding nothing to it: LEFT was wired only to `editor.left()`, so the
268
+ * one chord the status line offered did nothing. A hint for a key with no
269
+ * handler is worse than no hint, and the agents panel is reachable by the
270
+ * `/agents` command it was really standing in for.
271
+ */
262
272
  function statusLine(state, cols, ctx) {
263
273
  const t = themeOf(ctx);
264
274
  let left;
265
275
  if (state.inputPrompt) {
266
276
  left = [span(t.gray, 'enter to confirm · esc to cancel')];
267
277
  } else if (state.working) {
268
- left = [span(t.gray, ` ${GLYPH.bullet} esc to interrupt ${GLYPH.bullet} ${GLYPH.leftarrow} for agents`)];
278
+ left = [span(t.gray, ` ${GLYPH.bullet} esc to interrupt`)];
269
279
  } else if (state.streamJob) {
270
- left = [span(t.gray, `${GLYPH.bullet} esc to stop ${GLYPH.bullet} ${GLYPH.leftarrow} for agents`)];
280
+ left = [span(t.gray, `${GLYPH.bullet} esc to stop`)];
271
281
  } else if (state.yolo) {
272
- left = [span(t.gray, `${GLYPH.bullet} YOLO mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.leftarrow} for agents`)];
282
+ left = [span(t.gray, `${GLYPH.bullet} YOLO mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for auto mode`)];
273
283
  } else {
274
- left = [span(t.gray, `${GLYPH.pause} manual mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.leftarrow} for agents`)];
284
+ left = [span(t.gray, `${GLYPH.pause} manual mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for auto mode`)];
275
285
  }
276
286
  return padLine(left, cols);
277
287
  }
@@ -1515,6 +1525,14 @@ async function runSession(host) {
1515
1525
  render();
1516
1526
  return;
1517
1527
  }
1528
+ // → on an empty line switches the approval mode (manual ⇄ auto) — the chord
1529
+ // the status line advertises. With an empty buffer the cursor already sits
1530
+ // at column 0, so `editor.right()` was a no-op there: the binding costs no
1531
+ // editing behaviour, and a line with text keeps plain cursor movement.
1532
+ if (key.name === KEY.RIGHT && !editor.buf) {
1533
+ await dispatch(!(host.isYolo && host.isYolo()) ? '/yolo on' : '/yolo off');
1534
+ return;
1535
+ }
1518
1536
  if (key.name === KEY.RIGHT || key.name === KEY.CTRL_RIGHT) {
1519
1537
  editor.right();
1520
1538
  render();
package/src/theme.js CHANGED
@@ -89,7 +89,7 @@ function glyphsFor(platform = process.platform) {
89
89
  hint: '❯', // "Try ..." suggestion marker
90
90
  pause: '⏸', // bottom status line (manual mode)
91
91
  star: stencilGlyph(STAR, platform), // own-session marker, decorations
92
- leftarrow: '←', // hints on the status line
92
+ rightarrow: '→', // the manual ⇄ auto mode switch, advertised on the status line
93
93
  pointer: '▸', // tips list bullets
94
94
  hook: '⎿', // inline command / tip rows (tool commands, usage hints)
95
95
  block: '●', // streaming cursor / assistant answer marker
package/src/tokens.js CHANGED
@@ -9,13 +9,59 @@
9
9
  */
10
10
 
11
11
  // Per-million-token USD rates. Cache-read/write matter for long sessions.
12
+ //
13
+ // These are the PROVIDER's rates, for the fallback path where a turn has no
14
+ // server-settled charge (a direct provider, ollama, a custom endpoint). A
15
+ // pooled turn reports the ledger figure instead — see accountingFromUsage's
16
+ // `costUsd` — because the pool's bill carries a margin and a prompt-cache
17
+ // discount this table cannot see.
18
+ //
19
+ // Keys are matched by exact id first, then by prefix (ratesFor below), so a
20
+ // family row covers every dated variant of it.
12
21
  const RATES = {
13
22
  sonnet: { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
14
23
  default: { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
15
24
  fable: { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
16
25
  opus: { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
26
+ // DeepSeek V4 — the provider's published rate, independently corroborated by
27
+ // aegis1 services/nexus_provider/catalog.py (cost_per_1k_input=0.00014,
28
+ // cost_per_1k_output=0.00028) and referenced in services/pricing.py.
29
+ //
30
+ // This row was MISSING, and usageCost fell through to RATES.sonnet for every
31
+ // DeepSeek turn: $3.00/$15.00 per M against a real $0.14/$0.28 — 21x the
32
+ // input rate and 54x the output rate, on every direct DeepSeek call. That is
33
+ // the number that made a local turn look like it cost a fraction of the
34
+ // cloud's, when most of the reported gap was the meter itself.
35
+ //
36
+ // cacheRead is 0.1x input (aegis1 services/pricing.py
37
+ // CACHE_READ_FRACTION_BY_COMPANY["deepseek"] = 0.1 -> $0.014/M).
38
+ // cacheWrite is the input rate: DeepSeek bills a cache write as ordinary
39
+ // input tokens and charges no separate write premium, unlike Anthropic's
40
+ // 1.25x. A zero here would understate a session that writes cache.
41
+ deepseek: { input: 0.14, output: 0.28, cacheRead: 0.014, cacheWrite: 0.14 },
17
42
  };
18
43
 
44
+ /**
45
+ * The rate row for a model id, provider, or alias. Exact id wins, then the
46
+ * longest matching prefix, then the Sonnet-class default — the same resolution
47
+ * order contextWindowFor uses, so the cost meter and the context meter cannot
48
+ * disagree about which family a model belongs to.
49
+ */
50
+ function ratesFor(model) {
51
+ const id = String(model || '').toLowerCase();
52
+ if (!id) return RATES.default;
53
+ if (RATES[id]) return RATES[id];
54
+ let best = null;
55
+ let bestLen = 0;
56
+ for (const [prefix, rates] of Object.entries(RATES)) {
57
+ if (id.startsWith(prefix) && prefix.length > bestLen) {
58
+ best = rates;
59
+ bestLen = prefix.length;
60
+ }
61
+ }
62
+ return best || RATES.default;
63
+ }
64
+
19
65
  // System prompt + tool definitions overhead, roughly, in tokens.
20
66
  const SYSTEM_TOKENS = 18000;
21
67
  const TOOL_TOKENS = 12000;
@@ -86,7 +132,7 @@ function transcriptUsage(transcript, model = 'sonnet') {
86
132
 
87
133
  /** Dollar cost of a usage record at the given model's rates. */
88
134
  function usageCost(usage, model = 'sonnet') {
89
- const r = RATES[model] || RATES.sonnet;
135
+ const r = ratesFor(model);
90
136
  const toD = (n, rate) => (n / 1_000_000) * rate;
91
137
  return toD(usage.input, r.input)
92
138
  + toD(usage.output, r.output)
@@ -156,6 +202,7 @@ module.exports = {
156
202
  CONTEXT_WINDOW,
157
203
  CONTEXT_WINDOWS,
158
204
  contextWindowFor,
205
+ ratesFor,
159
206
  estimateTokens,
160
207
  transcriptUsage,
161
208
  usageCost,
@@ -47,6 +47,28 @@ const toolsModule = require('./tools.js');
47
47
  const promptModule = require('./prompt.js');
48
48
  const { ShellSession } = require('./shell.js');
49
49
  const { agentSystemPrompt, agentRoleLabel } = require('./agents.js');
50
+ // Cooperative working-tree sharing (see each module's header). The lock
51
+ // serialises two hosts that start a turn on one checkout close together; the
52
+ // guard is the load-bearing half — it refuses a tree-wide git operation while
53
+ // another session's uncommitted work is present, which is the operation that
54
+ // destroyed a peer's file for real. Both live beside the engine because the
55
+ // CLI vendors this directory wholesale (cli/scripts/predist.mjs), so the GUI
56
+ // and the terminal get one implementation rather than two that drift.
57
+ const { beginTurnGuard, recordWrite, blocksDestructive } = require('./turn-guard.js');
58
+ const { acquireWorktreeLock, releaseWorktreeLock } = require('./worktree-lock.js');
59
+
60
+ /**
61
+ * How long a turn waits for the working-tree lock before running anyway.
62
+ *
63
+ * Short on purpose. This engine serves interactive hosts — a desktop window
64
+ * and a terminal — where stalling for the lock's own 11-minute default would
65
+ * be a worse failure than contending: the user is watching a spinner. So the
66
+ * lock is best-effort mutual exclusion for turns that start near-simultaneously
67
+ * (the common overlap), and the turn guard covers everything after that. A
68
+ * non-interactive caller that can afford to queue should pass
69
+ * `payload.worktreeWaitMs` with the long DEFAULT_WORKTREE_WAIT_MS instead.
70
+ */
71
+ const WORKTREE_LOCK_WAIT_MS = 1500;
50
72
 
51
73
  /** Classes whose transport is a user-supplied endpoint + credential. */
52
74
  const CUSTOM_CLASSES = Object.freeze(['openai-compat', 'anthropic']);
@@ -70,22 +92,30 @@ const CLASSES = [
70
92
  /**
71
93
  * Mirrors aegiscodex-dev's src/backend.js DEEPSEEK_REASONING_MODEL_RE +
72
94
  * EFFORT_TOKEN_BUDGET verbatim. DeepSeek's reasoning models (deepseek-flash,
73
- * deepseek-v4-pro, the deprecated deepseek-reasoner, and the legacy
74
- * v4-flash/v4.1-flash aliases some configs still carry) spend part of
75
- * max_tokens on hidden chain-of-thought before ever emitting visible
76
- * content — DeepSeek counts reasoning tokens against the same budget as
77
- * content. At the renderer's 4k default (index.html's max-tokens select),
78
- * any non-trivial question can burn the whole budget reasoning and finish
79
- * with empty content: no error, no tool calls, just a turn that "completes"
80
- * with nothing to show for it (the empty-response bug). A user pointing the
81
- * Custom OpenAI-compatible class straight at DeepSeek's API hits exactly
82
- * this, so the request floors to the same effort budget aegiscodex-dev uses
83
- * for its own direct DeepSeek calls instead of shipping whatever the
84
- * dropdown happens to have selected.
95
+ * i.e. "Flash 4.1", deepseek-v4-pro, the deprecated deepseek-reasoner, and the
96
+ * legacy v4-flash/v4.1-flash aliases some configs still carry) spend part of
97
+ * the budget on hidden chain-of-thought before ever emitting visible content —
98
+ * DeepSeek counts reasoning tokens against the same budget as content. Under
99
+ * the renderer's removed 4k dropdown default, any non-trivial question could
100
+ * burn the whole budget reasoning and finish with empty content: no error, no
101
+ * tool calls, just a turn that "completes" with nothing to show for it (the
102
+ * empty-response bug). A user pointing the Custom OpenAI-compatible class
103
+ * straight at DeepSeek's API hits exactly this, so the request is sized by the
104
+ * same effort budget aegiscodex-dev uses for its own direct DeepSeek calls.
105
+ *
106
+ * desktop/renderer/budget.js carries the renderer's copy of these two
107
+ * constants plus budgetFor() below; test/budget.test.mjs requires both and
108
+ * asserts they agree, so the mirror cannot drift silently.
85
109
  */
86
110
  const DEEPSEEK_REASONING_MODEL_RE = /^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/;
87
111
  const EFFORT_TOKEN_BUDGET = { low: 8192, medium: 16384, high: 32768 };
88
112
 
113
+ /** The one class whose wire format REQUIRES a stated `max_tokens`: Anthropic's
114
+ * Messages API 400s without it, so that field is derived from the effort rung
115
+ * rather than invented by the transport (which is what a blanket
116
+ * `max_tokens: maxTokens || 4096` did — see providers.anthropicMessages). */
117
+ const REQUIRES_STATED_BUDGET = new Set(['anthropic']);
118
+
89
119
  /**
90
120
  * Idle-stream budget for a pooled brain call ("work autonomously"). The
91
121
  * generic watchdog in vendor/aegis.js kills a stream that goes 60s without a
@@ -109,38 +139,38 @@ const EFFORT_TOKEN_BUDGET = { low: 8192, medium: 16384, high: 32768 };
109
139
  const AUTONOMOUS_IDLE_TIMEOUT_MS = 15 * 60_000;
110
140
 
111
141
  /**
112
- * The budget a DeepSeek reasoning model runs on, resolved from EXACTLY ONE
113
- * authority per call.
114
- *
115
- * A caller-stated number IS the budget, and is returned verbatim. For the
116
- * non-pooled classes the renderer's max-tokens dropdown is the only budget
117
- * control on offer — updateBudgetControls hides the effort row for them — so
118
- * silently raising that number to an effort rung is precisely what made the
119
- * figure beside the dropdown untrustworthy. The old form was
120
- * `Math.max(stated, EFFORT_TOKEN_BUDGET[eff])`, which could only ever raise a
121
- * deliberate cap: a caller asking for 1024 ran on 32768, and the number the
122
- * UI displayed was never the number the call used.
142
+ * The budget a request travels with, resolved from EXACTLY ONE authority per
143
+ * call — the engine-side half of the rule desktop/renderer/budget.js mirrors
144
+ * and test/budget.test.mjs compares the two halves of, so neither can drift.
123
145
  *
124
- * The effort rung is the DEFAULT, consulted only when no number was stated at
125
- * all (the pooled class, which the renderer sends `effort` for and which the
126
- * server sizes itself). This is the same rule doubledBudget() follows for its
127
- * truncation retry: a stated cap is never overridden, by a rung or an order of
128
- * magnitude.
146
+ * 1. a caller-stated number IS the budget and is returned verbatim. It is a
147
+ * deliberate liability ceiling (aegis1 pass_budgets honours it downward:
148
+ * total = min(ladder, max_tokens x passes)) and no rung may raise it — the
149
+ * old `Math.max(stated, EFFORT_TOKEN_BUDGET[eff])` form did exactly that,
150
+ * so a caller asking for 1024 silently ran on 32768.
151
+ * 2. with nothing stated, a model that reasons against its own output budget
152
+ * (DeepSeek bills hidden chain-of-thought against the SAME budget as the
153
+ * answer) or a class whose wire format REQUIRES the field (Anthropic's
154
+ * Messages API) gets the Effort rung. This is why the renderer's
155
+ * max-tokens dropdown was removed rather than fixed: at its 4k default a
156
+ * reasoning model spent the entire budget thinking and finished empty —
157
+ * no error, no tool call, just a "completed" turn with nothing in it.
158
+ * 3. otherwise `undefined` — no `max_tokens` goes on the wire and the
159
+ * provider's own output limit governs. The transport used to fill this
160
+ * gap with an invented 4096 default, which is the defect in (2).
129
161
  *
130
- * Truncated and empty turns are handled where they belong — the doubled-budget
131
- * retry plus emptyTurnError — rather than by inflating the caller's ceiling up
132
- * front. Escalating on a demonstrated empty turn is strictly cheaper than
133
- * pre-emptively granting the top rung to every reasoning call.
134
- *
135
- * Everything else (non-DeepSeek models, non-reasoning DeepSeek ids like
136
- * deepseek-chat) passes through untouched.
162
+ * Truncated and empty turns are still handled where they belong — the
163
+ * doubled-budget retry plus emptyTurnError — rather than by inflating the
164
+ * caller's ceiling up front.
137
165
  */
138
- function reasoningBudget(model, maxTokens, effort) {
139
- if (!DEEPSEEK_REASONING_MODEL_RE.test(String(model || ''))) return maxTokens;
166
+ function reasoningBudget(cls, model, maxTokens, effort) {
140
167
  const stated = Number(maxTokens);
141
168
  if (Number.isFinite(stated) && stated > 0) return stated;
142
- const eff = effort === 'low' || effort === 'medium' ? effort : 'high';
143
- return EFFORT_TOKEN_BUDGET[eff];
169
+ if (DEEPSEEK_REASONING_MODEL_RE.test(String(model || '')) || REQUIRES_STATED_BUDGET.has(cls)) {
170
+ const eff = effort === 'low' || effort === 'medium' ? effort : 'high';
171
+ return EFFORT_TOKEN_BUDGET[eff];
172
+ }
173
+ return undefined;
144
174
  }
145
175
 
146
176
  /** Relay model entries arrive as ids or objects; keep only real model ids. */
@@ -279,6 +309,33 @@ function doubledBudget(maxTokens) {
279
309
  return n > 0 ? n * 2 : 8192;
280
310
  }
281
311
 
312
+ /**
313
+ * The cap the CALLER stated, or `undefined` meaning "none was stated".
314
+ *
315
+ * The two branches resolve one question — whose number is this? — and the
316
+ * first is the fix. An internal re-entry (runSubagent's nested chat()) passes
317
+ * `statedMaxTokens` explicitly, because the `maxTokens` it holds is the rung
318
+ * reasoningBudget() derived from `effort`: a number the server is about to
319
+ * derive for itself. Re-reading that value as the caller's own is what put a
320
+ * guessed 32768 on the wire as a *ceiling over* aegis1's ladder
321
+ * (pass_budgets: total = min(ladder, max_tokens x passes)) — so a
322
+ * high-effort subagent silently ran at 8192 and the ladder the UI advertised
323
+ * was not the budget the call used.
324
+ *
325
+ * A non-numeric or non-positive value means "nothing stated" — never a 0- or
326
+ * NaN-token ceiling.
327
+ */
328
+ function statedCapOf(payload) {
329
+ const asCap = (v) => {
330
+ const n = Number(v);
331
+ return Number.isFinite(n) && n > 0 ? n : undefined;
332
+ };
333
+ if (payload && Object.prototype.hasOwnProperty.call(payload, 'statedMaxTokens')) {
334
+ return asCap(payload.statedMaxTokens);
335
+ }
336
+ return asCap(payload && payload.maxTokens);
337
+ }
338
+
282
339
  /**
283
340
  * The follow-up shown to a model that ended its turn with neither text nor a
284
341
  * tool call. Sent as a plain user message (never as a tool result — there is
@@ -305,9 +362,9 @@ const EMPTY_TURN_NUDGE =
305
362
  function emptyTurnError({ cls, model, maxTokens, finishReason }) {
306
363
  const err = new Error(
307
364
  `The model returned no answer after ${cls}/${model} was asked to summarise its results ` +
308
- `(stop reason: ${finishReason || 'none'}, max_tokens: ${maxTokens}). The token budget ` +
309
- 'was most likely consumed before any visible text — raise the max-tokens setting, ' +
310
- 'or lower effort.'
365
+ `(stop reason: ${finishReason || 'none'}, max_tokens: ${maxTokens || 'unstated'}). The token budget ` +
366
+ 'was most likely consumed before any visible text — raise the Effort rung, which is ' +
367
+ 'what sizes this call, or ask for a smaller piece of work.'
311
368
  );
312
369
  err.status = 502;
313
370
  return err;
@@ -484,11 +541,44 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
484
541
  * runs straight through exactly like a session-allowed one, so "don't ask"
485
542
  * is one switch rather than a per-tool blanket allow in every conversation.
486
543
  */
544
+ /**
545
+ * The single place a tool executor is called from the chat loop, so the
546
+ * turn guard cannot be bypassed by reaching a different branch (there are
547
+ * four `return`s in gatedExecuteTool below; all of them come through here).
548
+ *
549
+ * exec is *checked* before running and writeFile/editFile are *recorded*
550
+ * after, and the asymmetry is the point: a refusal has to happen before the
551
+ * command runs, while "this path is mine" is only true once the write
552
+ * actually happened — recording a denied or preview-failed write would hide
553
+ * a genuinely foreign file behind a claim of ownership.
554
+ *
555
+ * A refusal is returned as an ordinary tool error, so the model reads it and
556
+ * adapts (name the paths, or don't do it) with no new IPC or renderer
557
+ * channel — the same reason it works identically in the GUI and the CLI.
558
+ */
559
+ async function guardedExecute(name, args, toolCtx) {
560
+ const guard = toolCtx && toolCtx.guard;
561
+ if (guard && name === 'exec') {
562
+ const verdict = blocksDestructive(guard, args && args.command);
563
+ if (!verdict.ok) return { ok: false, error: verdict.reason };
564
+ }
565
+ // Awaited, not merely returned: "this path is mine" is only true once the
566
+ // write actually landed, and `executeTool` is async — inspecting `.ok` on
567
+ // an un-awaited promise would read undefined and record every write,
568
+ // including the ones that failed. Ownership is load-bearing in the other
569
+ // direction too: a path wrongly claimed stops being reported as foreign.
570
+ const result = await T.executeTool(name, args, toolCtx);
571
+ if (guard && (name === 'writeFile' || name === 'editFile') && result && result.ok !== false) {
572
+ recordWrite(guard, args && args.path);
573
+ }
574
+ return result;
575
+ }
576
+
487
577
  async function gatedExecuteTool(call, { toolCtx, rootSessionId, rootOnDelta, signal }) {
488
578
  const { name, args } = call;
489
- if (!T.MUTATING_TOOLS.has(name)) return T.executeTool(name, args, toolCtx);
490
- if (!confirmModeEnabled()) return T.executeTool(name, args, toolCtx);
491
- if (sessionAllows(rootSessionId, name)) return T.executeTool(name, args, toolCtx);
579
+ if (!T.MUTATING_TOOLS.has(name)) return guardedExecute(name, args, toolCtx);
580
+ if (!confirmModeEnabled()) return guardedExecute(name, args, toolCtx);
581
+ if (sessionAllows(rootSessionId, name)) return guardedExecute(name, args, toolCtx);
492
582
  // Already refused in this conversation: refuse again WITHOUT raising a
493
583
  // second card. Before this, the model's retry after a denial re-prompted
494
584
  // the user for the same tool — one "no" produced a card per round for up
@@ -521,8 +611,18 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
521
611
  }
522
612
  if (decision === 'session') allowForSession(rootSessionId, name);
523
613
 
524
- if (preview) return T.applyChecked(name, args, preview);
525
- return T.executeTool(name, args, toolCtx);
614
+ if (preview) {
615
+ const res = T.applyChecked(name, args, preview);
616
+ // Recorded on the same condition as guardedExecute's path: only a write
617
+ // that landed is this session's. (The previous form returned here
618
+ // unconditionally, making every line below it unreachable — the
619
+ // approved-write path recorded nothing at all.)
620
+ if (res && res.ok !== false && toolCtx && toolCtx.guard) {
621
+ recordWrite(toolCtx.guard, args && args.path);
622
+ }
623
+ return res;
624
+ }
625
+ return guardedExecute(name, args, toolCtx);
526
626
  }
527
627
 
528
628
  /**
@@ -634,8 +734,9 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
634
734
  // derived number states one decision twice — and the copies had already
635
735
  // drifted: 974adc5 doubled aegis1's ladder while this side stood still,
636
736
  // leaving the client capping below the budget it displayed. The cap was
637
- // never the one the renderer showed either (updateBudgetControls hides
638
- // the max-tokens dropdown for the pooled class). Omitting the field is
737
+ // never the one the renderer showed either (the Max tokens dropdown
738
+ // that used to claim a figure for the pooled class is gone — see
739
+ // desktop/renderer/budget.js). Omitting the field is
639
740
  // what tells aegis1 "no cap stated — let effort decide", the same
640
741
  // contract aegiscodex-dev sends.
641
742
  //
@@ -779,7 +880,7 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
779
880
  async function chat(payload, onDelta) {
780
881
  const cls = payload && payload.class;
781
882
  const model = payload && payload.model;
782
- const maxTokens = reasoningBudget(model, payload && payload.maxTokens, payload && payload.effort);
883
+ const maxTokens = reasoningBudget(cls, model, payload && payload.maxTokens, payload && payload.effort);
783
884
  // The caller's OWN number, kept apart from `maxTokens` above. That one
784
885
  // collapses two different facts into a single value — "the caller stated
785
886
  // 4096" and "effort implies 32768" — and the pooled path must treat them
@@ -788,7 +889,10 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
788
889
  // an effort-derived one is the server's own arithmetic stated twice, and
789
890
  // sending it is how the two copies came to disagree. So the pooled call
790
891
  // forwards only what the caller actually asked for.
791
- const statedMaxTokens = Number(payload && payload.maxTokens) > 0 ? Number(payload.maxTokens) : undefined;
892
+ // ...and it is read through statedCapOf(), so a nested chat() that states
893
+ // the key overrides its own derived `maxTokens` instead of being mistaken
894
+ // for a caller who asked for that number (see statedCapOf).
895
+ const statedMaxTokens = statedCapOf(payload);
792
896
  // "Work autonomously" — routes this call through aegis1's pool_brain
793
897
  // worker fan-out (services/pool_brain.py: N reasoning workers + a
794
898
  // synthesis pass) instead of a single provider call. UI-gated to the
@@ -1105,7 +1209,8 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1105
1209
  for (const call of calls) {
1106
1210
  const result = call.name === T.SUBAGENT_TOOL
1107
1211
  ? await runSubagent(call.args, {
1108
- cls, model, maxTokens, mode: payload && payload.mode, parentSignal: signal, depth, rootSessionId, rootOnDelta,
1212
+ cls, model, statedMaxTokens, effort: payload && payload.effort,
1213
+ mode: payload && payload.mode, parentSignal: signal, depth, rootSessionId, rootOnDelta,
1109
1214
  })
1110
1215
  : await gatedExecuteTool(call, { toolCtx, rootSessionId, rootOnDelta, signal });
1111
1216
  // A subagent's spend rides back on its tool result (see runSubagent).
@@ -1135,7 +1240,7 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1135
1240
  */
1136
1241
  async function runSubagent(
1137
1242
  { description, subagent_type, prompt: subPrompt } = {},
1138
- { cls, model, maxTokens, mode, parentSignal, depth, rootSessionId, rootOnDelta } = {}
1243
+ { cls, model, statedMaxTokens, effort, mode, parentSignal, depth, rootSessionId, rootOnDelta } = {}
1139
1244
  ) {
1140
1245
  const task = String(subPrompt || description || '').trim();
1141
1246
  if (!task) return { ok: false, error: 'task requires a prompt' };
@@ -1159,8 +1264,17 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1159
1264
  // silently hanging behind this call's no-op onDelta below.
1160
1265
  const res = await chat(
1161
1266
  {
1162
- class: cls, model, maxTokens, mode, system, prompt: task, sessionId: subSessionId, depth: (depth || 0) + 1,
1267
+ class: cls, model, mode, system, prompt: task, sessionId: subSessionId, depth: (depth || 0) + 1,
1163
1268
  rootSessionId, rootOnDelta,
1269
+ // The parent's budget AUTHORITY is forwarded, not the number it
1270
+ // implies. `maxTokens` is deliberately absent: it is the rung this
1271
+ // turn derived from `effort`, and a re-entry that hands it back gets
1272
+ // read as the caller's own cap (statedCapOf). The rung itself rides
1273
+ // along as `effort`, which is what aegis1 sizes the fan-out and its
1274
+ // ladder from — so a subagent now runs at the effort the user chose
1275
+ // instead of at a number that only meant anything for this model id.
1276
+ statedMaxTokens,
1277
+ effort,
1164
1278
  },
1165
1279
  () => {}
1166
1280
  );
@@ -1199,4 +1313,4 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1199
1313
  };
1200
1314
  }
1201
1315
 
1202
- module.exports = { CLASSES, createLocalEngine, extractToolCalls, parseArgs };
1316
+ module.exports = { CLASSES, createLocalEngine, extractToolCalls, parseArgs, reasoningBudget };
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Minimal git worktree introspection: where the repo root is, and what is
5
+ * dirty right now with a content hash per path.
6
+ *
7
+ * Ported from aegiscodex-dev/src/git-scope.js (ESM → CommonJS). Only the two
8
+ * functions `turn-guard.js` needs are carried over — `gitRoot` and
9
+ * `gitStatusSnapshot` (plus their `contentHash` helper). The source file's
10
+ * `foreignChanges` and `scopedCommit` belong to the autonomous queue's
11
+ * commit path, which the plugin does not host, so they are deliberately not
12
+ * vendored: a copy of code nothing calls is a copy that drifts unnoticed.
13
+ *
14
+ * The "dirty before AND byte-identical now" definition lives in
15
+ * `gitStatusSnapshot`'s hashes; `turn-guard.js` is the only consumer.
16
+ */
17
+
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+ const crypto = require('node:crypto');
21
+ const { spawnSync } = require('node:child_process');
22
+
23
+ /** The repo root for `cwd`, or null if it isn't inside a git work tree. */
24
+ function gitRoot(cwd) {
25
+ const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' });
26
+ return r.status === 0 ? r.stdout.trim() : null;
27
+ }
28
+
29
+ /**
30
+ * Hash a path's worktree content, so "already dirty before the task ran" can
31
+ * be told apart from "this task changed it". `absent` covers deletions;
32
+ * non-files (a submodule, a directory) compare by kind.
33
+ */
34
+ function contentHash(cwd, rel) {
35
+ try {
36
+ const st = fs.lstatSync(path.join(cwd, rel));
37
+ if (!st.isFile()) return st.isDirectory() ? 'nonfile:dir' : 'nonfile:other';
38
+ return crypto.createHash('sha1').update(fs.readFileSync(path.join(cwd, rel))).digest('hex');
39
+ } catch {
40
+ return 'absent';
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Every path git reports as dirty right now, mapped to its content hash.
46
+ * `--no-renames` matters: in `-z` porcelain a rename emits the old name as a
47
+ * second NUL-terminated token, which we would otherwise hash as a change.
48
+ * Untracked files are included, since that is exactly how concurrent work
49
+ * usually arrives. Returns null if `cwd` is not a usable git repo.
50
+ */
51
+ function gitStatusSnapshot(cwd) {
52
+ // Run from the repo root: porcelain reports paths root-relative, so hashing
53
+ // must resolve them against the same directory.
54
+ const root = gitRoot(cwd);
55
+ if (!root) return null;
56
+ const r = spawnSync(
57
+ 'git',
58
+ ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames'],
59
+ { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
60
+ );
61
+ if (r.status !== 0) return null;
62
+ const snap = new Map();
63
+ for (const rec of r.stdout.split('\0')) {
64
+ if (rec.length < 4) continue;
65
+ const p = rec.slice(3);
66
+ snap.set(p, contentHash(root, p));
67
+ }
68
+ return snap;
69
+ }
70
+
71
+ module.exports = { gitRoot, contentHash, gitStatusSnapshot };
@@ -0,0 +1,297 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Turn-start foreign-write detection.
5
+ *
6
+ * Ported from aegiscodex-dev/src/turn-guard.js (ESM → CommonJS).
7
+ *
8
+ * Bug this exists for: the commit-time scope check already knew how to tell
9
+ * "my changes" from "somebody else's in-flight work" — but only *after* a
10
+ * task had finished. The dangerous window is the opposite end: a session
11
+ * reads a file, time passes, a second agent edits that file, and the first
12
+ * session then acts on a stale mental model. That is how a live session
13
+ * destroyed a peer's work — the content it reverted was real and correct,
14
+ * just not the content it had read.
15
+ *
16
+ * `git checkout HEAD -- <file>`, `git reset --hard`, `git stash` and
17
+ * `git clean` are the destructive operations, and their default scope is the
18
+ * whole tree. Running any of them while a peer has uncommitted work is the
19
+ * entire incident.
20
+ *
21
+ * Fix: snapshot the dirty set at turn start, record the paths this session
22
+ * actually writes, then answer two questions on demand —
23
+ * `foreignSince()` / `concurrentSince()` whose work is in the tree
24
+ * `blocksDestructive()` would a given command clobber it
25
+ * The second is load-bearing: it turns "revert someone else's file" into a
26
+ * refusal, which is the cheapest place to stop it.
27
+ *
28
+ * This is detection, not prevention — it cannot stop a writer outside the
29
+ * host. Paired with worktree-lock.js it covers our own sessions.
30
+ */
31
+
32
+ const { gitRoot, gitStatusSnapshot } = require('./git-scope.js');
33
+
34
+ /** Git's own flags that consume the *next* argv entry, so that token is not
35
+ * the subcommand. Without this, `git -C /repo reset --hard` parses `reset`
36
+ * as a flag argument and the whole command reads as harmless. */
37
+ const GIT_FLAGS_WITH_ARG = new Set([
38
+ '-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path',
39
+ ]);
40
+
41
+ /** Split a command line into shell segments and then argv, stripping quotes.
42
+ * Segmenting on `&&`/`;`/`|` means `ls && git checkout -- a` is still caught,
43
+ * while `git stash list` is judged on its own segment. */
44
+ function tokenize(command) {
45
+ const out = [];
46
+ for (const segment of String(command || '').split(/[|;&\n]+/)) {
47
+ const argv = [];
48
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
49
+ let m;
50
+ while ((m = re.exec(segment))) argv.push(m[1] ?? m[2] ?? m[3]);
51
+ if (argv.length) out.push(argv);
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /** The git subcommand and its arguments in one argv, or null if this argv
57
+ * isn't a git invocation that has a subcommand. */
58
+ function gitInvocation(argv) {
59
+ const i = argv.findIndex((t) => t === 'git' || t.endsWith('/git'));
60
+ if (i === -1) return null;
61
+ let j = i + 1;
62
+ while (j < argv.length && argv[j].startsWith('-')) {
63
+ j += GIT_FLAGS_WITH_ARG.has(argv[j]) ? 2 : 1;
64
+ }
65
+ if (j >= argv.length) return null;
66
+ return { sub: argv[j], args: argv.slice(j + 1) };
67
+ }
68
+
69
+ /** Positional arguments (the paths a command names), dropping flags. Values
70
+ * after `--` are always paths; before it, anything not starting with `-` is
71
+ * taken as one, which is right for checkout/restore and harmlessly unused
72
+ * elsewhere. */
73
+ function namedPaths(args) {
74
+ const sep = args.indexOf('--');
75
+ if (sep !== -1) return args.slice(sep + 1).filter((a) => !a.startsWith('-'));
76
+ return args.filter((a) => !a.startsWith('-'));
77
+ }
78
+
79
+ const isTreeMark = (p) => p === '.' || p === './' || p === '*' || p === './*';
80
+ const hasForce = (args) => args.some((a) => a === '-f' || a === '--force' || /^-[a-zA-Z]*f/.test(a));
81
+
82
+ /** subcommand -> { what, scope } where scope is 'tree' (discards broadly) or
83
+ * 'paths' (discards only the paths it names). Returns null when harmless. */
84
+ function judge(sub, args) {
85
+ const paths = namedPaths(args);
86
+ const treeWide = paths.length === 0 || paths.some(isTreeMark);
87
+ switch (sub) {
88
+ case 'checkout':
89
+ if (args.includes('--') || hasForce(args)) {
90
+ return { what: 'checkout of uncommitted changes', scope: treeWide ? 'tree' : 'paths', paths };
91
+ }
92
+ // `git checkout .` restores the whole tree; a bare branch switch is safe.
93
+ if (treeWide && paths.length) return { what: 'checkout . (tree-wide restore)', scope: 'tree', paths };
94
+ return null;
95
+ case 'restore':
96
+ return { what: 'restore (discards uncommitted changes)', scope: treeWide ? 'tree' : 'paths', paths };
97
+ case 'reset':
98
+ return args.includes('--hard') ? { what: 'reset --hard', scope: 'tree', paths: [] } : null;
99
+ case 'clean':
100
+ return hasForce(args) ? { what: 'clean -f (deletes untracked files)', scope: 'tree', paths: [] } : null;
101
+ case 'stash': {
102
+ const first = args.find((a) => !a.startsWith('-'));
103
+ if (first === 'list' || first === 'show') return null;
104
+ // pop/apply can conflict with, and push parks, every path in the tree.
105
+ return { what: `stash ${first || 'push'} (uncommitted changes across the tree)`, scope: 'tree', paths: [] };
106
+ }
107
+ case 'worktree': {
108
+ const first = args.find((a) => !a.startsWith('-'));
109
+ return first === 'remove' || first === 'prune'
110
+ ? { what: `worktree ${first}`, scope: 'tree', paths: [] }
111
+ : null;
112
+ }
113
+ default:
114
+ return null;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Classify a shell command line. Returns
120
+ * `{destructive:false}` or `{destructive:true, what, scope:'tree'|'paths', paths}`.
121
+ *
122
+ * Parsed as argv rather than matched as text, because a message *about* a
123
+ * destructive command is not one: `git commit -m "fix stash handling"` must
124
+ * not read as a stash. Quoting is handled, so the two are actually different.
125
+ */
126
+ function classifyDestructive(command) {
127
+ for (const argv of tokenize(command)) {
128
+ const inv = gitInvocation(argv);
129
+ if (!inv) continue;
130
+ const verdict = judge(inv.sub, inv.args);
131
+ if (verdict) return { destructive: true, ...verdict };
132
+ }
133
+ return { destructive: false };
134
+ }
135
+
136
+ /**
137
+ * Begin guarding a turn in `cwd`. Costs one `git status`; a non-repo (or a
138
+ * git failure) yields a guard that reports nothing, so callers never have to
139
+ * branch on whether the guard is armed.
140
+ */
141
+ function beginTurnGuard(cwd) {
142
+ const root = gitRoot(cwd);
143
+ const before = root ? gitStatusSnapshot(cwd) : null;
144
+ return {
145
+ root,
146
+ cwd,
147
+ before,
148
+ startedAt: Date.now(),
149
+ written: new Set(),
150
+ active: Boolean(root && before),
151
+ };
152
+ }
153
+
154
+ /** Normalise a written path to root-relative, so it can be compared against
155
+ * porcelain output. Accepts absolute or relative paths. */
156
+ function toRel(guard, p) {
157
+ let s = String(p || '');
158
+ if (!s) return null;
159
+ if (guard.root && s.startsWith(guard.root)) {
160
+ s = s.slice(guard.root.length).replace(/^[/\\]/, '');
161
+ }
162
+ return s.split('\\').join('/');
163
+ }
164
+
165
+ /**
166
+ * Record a path this session itself wrote. A recorded path is never reported
167
+ * as foreign — this is what keeps the guard from crying wolf about the
168
+ * caller's own edits, and it is why the host's file tools must call it.
169
+ */
170
+ function recordWrite(guard, p) {
171
+ if (!guard || !guard.active) return;
172
+ const rel = toRel(guard, p);
173
+ if (rel) guard.written.add(rel);
174
+ }
175
+
176
+ /**
177
+ * Paths that are *unambiguously* a peer's in-flight work: dirty when the turn
178
+ * started, byte-identical now, and never written by this session.
179
+ *
180
+ * "Dirty before and still identical" is what makes this confident — a path
181
+ * nobody touched is dirty *because* it belongs to someone else. It is
182
+ * git-scope's own definition, which is why the two modules agree.
183
+ */
184
+ function foreignSince(guard) {
185
+ if (!guard || !guard.active) return [];
186
+ const now = gitStatusSnapshot(guard.cwd);
187
+ if (!now) return [];
188
+ const out = [];
189
+ for (const [p, hash] of now) {
190
+ if (guard.written.has(p)) continue;
191
+ if (guard.before.has(p) && guard.before.get(p) === hash) out.push(p);
192
+ }
193
+ return out.sort();
194
+ }
195
+
196
+ /**
197
+ * Paths clean at turn start and dirty now, excluding any this session
198
+ * recorded writing.
199
+ *
200
+ * Weaker than `foreignSince` because attribution is incomplete: the host's
201
+ * file tools call `recordWrite`, but a path a shell command creates
202
+ * (`> out.txt`, `npm install`) is invisible here and can be mistaken for a
203
+ * peer's. Still reported, and still consulted by `blocksDestructive` — see
204
+ * the asymmetry note there.
205
+ */
206
+ function concurrentSince(guard) {
207
+ if (!guard || !guard.active) return [];
208
+ const now = gitStatusSnapshot(guard.cwd);
209
+ if (!now) return [];
210
+ const out = [];
211
+ for (const [p] of now) {
212
+ if (guard.written.has(p)) continue;
213
+ if (!guard.before.has(p)) out.push(p);
214
+ }
215
+ return out.sort();
216
+ }
217
+
218
+ /**
219
+ * Would running `command` be unsafe right now? Returns `{ok:true}` or
220
+ * `{ok:false, what, scope, reason, foreign, unattributed}`.
221
+ *
222
+ * Scope decides what has to be at risk:
223
+ * - a *tree-wide* op (`git reset --hard`, `git stash`, `git checkout .`) is
224
+ * refused whenever any peer work is present, because it cannot help but
225
+ * touch it;
226
+ * - a *path-scoped* op is refused only when one of the paths it names is
227
+ * actually foreign, so reverting your own file still works while a peer
228
+ * happens to be editing a different one.
229
+ *
230
+ * Both signals count, because the risk is asymmetric: a refusal costs the
231
+ * caller one step (name the paths, or take the lock), while a miss destroys
232
+ * work that may exist nowhere else. In the incident this module exists for,
233
+ * the peer's files appeared *during* the turn, so the confident signal was
234
+ * empty — blocking on it alone would have missed the exact case that
235
+ * motivated the guard.
236
+ *
237
+ * A tree with nothing foreign is never blocked, so a solo session is never
238
+ * wedged: the module is inert unless somebody else's work is present.
239
+ */
240
+ function blocksDestructive(guard, command) {
241
+ const verdict = classifyDestructive(command);
242
+ if (!verdict.destructive) return { ok: true };
243
+ if (!guard || !guard.active) return { ok: true };
244
+
245
+ let foreign = foreignSince(guard);
246
+ let unattributed = concurrentSince(guard).filter((p) => !foreign.includes(p));
247
+
248
+ let atRisk = [];
249
+ if (verdict.scope === 'tree') {
250
+ atRisk = [...foreign, ...unattributed];
251
+ } else {
252
+ const named = new Set(verdict.paths.map((p) => p.replace(/^\.\//, '')));
253
+ const hits = (list) => list.filter((p) => named.has(p) || named.has('./' + p));
254
+ foreign = hits(foreign);
255
+ unattributed = hits(unattributed);
256
+ atRisk = [...foreign, ...unattributed];
257
+ }
258
+ if (!atRisk.length) return { ok: true, what: verdict.what };
259
+
260
+ const parts = [];
261
+ if (foreign.length) {
262
+ parts.push(
263
+ `${foreign.length} hold another agent's uncommitted work: `
264
+ + foreign.slice(0, 8).join(', ') + (foreign.length > 8 ? ` (+${foreign.length - 8} more)` : ''),
265
+ );
266
+ }
267
+ if (unattributed.length) {
268
+ parts.push(
269
+ `${unattributed.length} changed since this turn began and were not written by `
270
+ + `this session: ${unattributed.slice(0, 8).join(', ')}`
271
+ + (unattributed.length > 8 ? ` (+${unattributed.length - 8} more)` : ''),
272
+ );
273
+ }
274
+ return {
275
+ ok: false,
276
+ what: verdict.what,
277
+ scope: verdict.scope,
278
+ foreign,
279
+ unattributed,
280
+ reason:
281
+ `refusing \`${verdict.what}\` in ${guard.root}: `
282
+ + (verdict.scope === 'tree'
283
+ ? 'it is tree-scoped and would discard work it did not create — '
284
+ : 'it targets a path that is not yours to discard — ')
285
+ + parts.join('; ')
286
+ + '. Name only the paths you mean, or take the worktree lock first.',
287
+ };
288
+ }
289
+
290
+ module.exports = {
291
+ classifyDestructive,
292
+ beginTurnGuard,
293
+ recordWrite,
294
+ foreignSince,
295
+ concurrentSince,
296
+ blocksDestructive,
297
+ };
@@ -0,0 +1,232 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Cross-process lock on a git working tree.
5
+ *
6
+ * Ported from aegiscodex-dev/src/worktree-lock.js (ESM → CommonJS).
7
+ *
8
+ * Bug this exists for: nothing keyed on *the working tree*. A session-scoped
9
+ * lock only stops two processes resuming the SAME transcript, so three
10
+ * different sessions in one checkout are three different ids and therefore
11
+ * all legal. A queue-worker lock only serialises queue drains. An interactive
12
+ * session took no lock at all.
13
+ *
14
+ * So N agents editing one checkout was, by every existing lock, correct
15
+ * behaviour — and it is destructive. It happened for real: one session ran
16
+ * `git checkout HEAD --` against a file a second session was mid-edit on
17
+ * (destroying it), a third ran `git stash` and parked everybody's tree, and a
18
+ * test run on that shared tree reported failures belonging to a half-built
19
+ * feature that was not the caller's. Git has no advisory locking, so none of
20
+ * it produced an error — just unexplained file changes, which is exactly the
21
+ * kind of evidence that gets misread as "my tool lied to me".
22
+ *
23
+ * Fix: a lock keyed on the repository root — the resource actually contended
24
+ * — taken by every host that runs a turn (the desktop app and the CLI both
25
+ * reach this file through desktop/lib/local/engine.js). Same atomic-marker +
26
+ * PID-liveness pattern as the session lock, so a crashed holder is reclaimed
27
+ * with no staleness window to tune and no manual cleanup.
28
+ *
29
+ * This lock is advisory and cooperative: it cannot stop a writer that does
30
+ * not take it (a plain `git` in a terminal, another harness, an editor). Its
31
+ * value is that our own hosts stop racing each other, and that a caller
32
+ * receiving `null` knows to back off instead of writing blind.
33
+ *
34
+ * The stronger fix is one worktree per agent (`git worktree add`), which
35
+ * removes the shared mutable tree entirely. This lock is what makes the
36
+ * single-tree case safe when that is not available.
37
+ */
38
+
39
+ const fs = require('node:fs');
40
+ const path = require('node:path');
41
+ const os = require('node:os');
42
+ const crypto = require('node:crypto');
43
+
44
+ /**
45
+ * Where lock files live.
46
+ *
47
+ * The plugin's data dir is ~/.aegiscode ($AEGISCODE_HOME), per config.js's
48
+ * `aegisDir()` convention — but the dev engine's ~/.aegiscodex is honoured
49
+ * too, and either `*_WORKTREE_LOCK_DIR` override points every host at ONE
50
+ * directory. That override is the interlock: two separate tools disagreeing
51
+ * about where the lock file goes is the same as having no lock, so operators
52
+ * running the GUI, the CLI and the dev engine against one checkout should set
53
+ * AEGISCODE_WORKTREE_LOCK_DIR (or AEGISCODEX_WORKTREE_LOCK_DIR) to a shared
54
+ * path. Within this repo the desktop and CLI hosts always agree, because both
55
+ * resolve this same helper.
56
+ */
57
+ function worktreeLockDir() {
58
+ if (process.env.AEGISCODE_WORKTREE_LOCK_DIR) return process.env.AEGISCODE_WORKTREE_LOCK_DIR;
59
+ if (process.env.AEGISCODEX_WORKTREE_LOCK_DIR) return process.env.AEGISCODEX_WORKTREE_LOCK_DIR;
60
+ const home = process.env.AEGISCODE_HOME
61
+ || process.env.AEGISCODEX_HOME
62
+ || path.join(os.homedir(), '.aegiscode');
63
+ return path.join(home, 'worktree-locks');
64
+ }
65
+
66
+ /** Default wait: a live holder is bounded by its own turn watchdog, so
67
+ * waiting slightly past that lets a legitimate queued turn run once the
68
+ * holder's deadline fires, rather than failing right as the tree is about to
69
+ * free up. */
70
+ const DEFAULT_WORKTREE_WAIT_MS = 11 * 60 * 1000;
71
+
72
+ /** Sentinel token for the "not in a repo" no-op path — always truthy, never
73
+ * matches a real acquisition, so a stray release() can't release anything. */
74
+ const NOOP_TOKEN = '(no-worktree)';
75
+
76
+ /**
77
+ * Canonicalise the root so two paths to one repo — a symlink, a trailing
78
+ * slash, a relative path, `/tmp/../repo` — agree on a single lock file.
79
+ * Falls back to the resolved path when realpath fails.
80
+ */
81
+ function canonical(root) {
82
+ if (!root) return null;
83
+ const abs = path.resolve(String(root));
84
+ try { return fs.realpathSync(abs); } catch { return abs; }
85
+ }
86
+
87
+ /** The lock file for `root`. The path is hashed so an arbitrarily long or
88
+ * awkward root maps to one flat, safe filename; the root itself is written
89
+ * inside the file for humans reading the lock dir. */
90
+ function worktreeLockPath(root) {
91
+ if (!root) return null;
92
+ const key = crypto.createHash('sha1').update(canonical(root)).digest('hex').slice(0, 16);
93
+ return path.join(worktreeLockDir(), key + '.lock');
94
+ }
95
+
96
+ function pidAlive(pid) {
97
+ try { process.kill(pid, 0); return true; } catch { return false; }
98
+ }
99
+
100
+ function readHolder(root) {
101
+ try { return JSON.parse(fs.readFileSync(worktreeLockPath(root), 'utf8')); } catch { return null; }
102
+ }
103
+
104
+ /**
105
+ * The current holder of `root`'s lock, or null. Never throws and never
106
+ * clears a stale lock — use `isWorktreeLocked` for the reclaiming check.
107
+ */
108
+ function worktreeLockHolder(root) {
109
+ if (!root) return null;
110
+ const h = readHolder(root);
111
+ if (!h) return null;
112
+ return {
113
+ pid: h.pid, token: h.token, since: h.since,
114
+ root: h.root || canonical(root), session: h.session || null,
115
+ };
116
+ }
117
+
118
+ /**
119
+ * True if `root` is held by a live process (any process, including this one
120
+ * — two concurrent callers inside one process must still queue behind each
121
+ * other). A lock file whose PID is dead or unparsable is stale and cleared as
122
+ * a side effect, so callers never special-case it.
123
+ */
124
+ function isWorktreeLocked(root) {
125
+ if (!root) return false;
126
+ const holder = readHolder(root);
127
+ // `Number(null)` is 0 and `process.kill(0, 0)` targets the caller's process
128
+ // GROUP, so it succeeds — a missing lock file would otherwise read as a live
129
+ // holder forever. Require a real pid. (The session lock has the same latent
130
+ // trap; it never surfaced there only because it is called after EEXIST.)
131
+ const pid = Number(holder && holder.pid);
132
+ if (!Number.isInteger(pid) || pid <= 0 || !pidAlive(pid)) {
133
+ try { fs.unlinkSync(worktreeLockPath(root)); } catch {}
134
+ return false;
135
+ }
136
+ return true;
137
+ }
138
+
139
+ /** Exclusive-create the lock file for `token`. Returns true on success.
140
+ * Best-effort: a data-dir failure other than "already exists" fails OPEN so a
141
+ * broken filesystem can never block a turn that would otherwise run fine. */
142
+ function tryAcquire(root, token, meta) {
143
+ try {
144
+ fs.mkdirSync(worktreeLockDir(), { recursive: true });
145
+ const fd = fs.openSync(worktreeLockPath(root), 'wx');
146
+ fs.writeFileSync(fd, JSON.stringify({
147
+ pid: process.pid,
148
+ token,
149
+ since: Date.now(),
150
+ root: canonical(root),
151
+ session: (meta && meta.session) || null,
152
+ }));
153
+ fs.closeSync(fd);
154
+ return true;
155
+ } catch (e) {
156
+ if (e && e.code === 'EEXIST') return false;
157
+ return true;
158
+ }
159
+ }
160
+
161
+ /** Release `root`'s lock — only if `token` matches the current holder, so
162
+ * releasing a lock you don't (or no longer) own can never clobber whoever
163
+ * holds it now. No-op on a falsy root/token or any filesystem error
164
+ * (best-effort, like the rest of this repo's persistence helpers). */
165
+ function releaseWorktreeLock(root, token) {
166
+ if (!root || !token || token === NOOP_TOKEN) return;
167
+ const holder = readHolder(root);
168
+ if (holder && holder.token === token) {
169
+ try { fs.unlinkSync(worktreeLockPath(root)); } catch {}
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Acquire `root`'s lock, waiting out a live holder instead of racing it.
175
+ * Resolves a truthy opaque token once acquired — pass it back to
176
+ * `releaseWorktreeLock` — or `null` if `waitMs` elapses or `signal` aborts
177
+ * first; either way the caller must not write. A falsy `root` (not inside a
178
+ * git work tree — nothing shared to collide over) resolves the sentinel
179
+ * immediately with no file touched.
180
+ */
181
+ async function acquireWorktreeLock(root, {
182
+ waitMs = DEFAULT_WORKTREE_WAIT_MS, pollMs = 200, signal, session = null,
183
+ } = {}) {
184
+ if (!root) return NOOP_TOKEN;
185
+ const token = crypto.randomUUID();
186
+ const deadline = Date.now() + waitMs;
187
+ for (;;) {
188
+ if (signal && signal.aborted) return null;
189
+ if (tryAcquire(root, token, { session })) return token;
190
+ // Was stale, just reclaimed by clearing — retry now.
191
+ if (!isWorktreeLocked(root)) continue;
192
+ if (Date.now() >= deadline) return null;
193
+ await new Promise((r) => setTimeout(r, pollMs));
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Run `fn` holding `root`'s lock, releasing it on every exit path. Throws
199
+ * `WorktreeBusyError` (rather than running unprotected) if the lock can't be
200
+ * taken, because proceeding without it is the bug this module exists to
201
+ * prevent.
202
+ */
203
+ class WorktreeBusyError extends Error {
204
+ constructor(root, holder) {
205
+ super(`working tree ${root} is locked by pid ${holder ? holder.pid : '?'}`);
206
+ this.name = 'WorktreeBusyError';
207
+ this.root = root;
208
+ this.holder = holder || null;
209
+ }
210
+ }
211
+
212
+ async function withWorktreeLock(root, opts, fn) {
213
+ const token = await acquireWorktreeLock(root, opts);
214
+ if (!token) throw new WorktreeBusyError(root, worktreeLockHolder(root));
215
+ try {
216
+ return await fn();
217
+ } finally {
218
+ releaseWorktreeLock(root, token);
219
+ }
220
+ }
221
+
222
+ module.exports = {
223
+ DEFAULT_WORKTREE_WAIT_MS,
224
+ worktreeLockDir,
225
+ worktreeLockPath,
226
+ worktreeLockHolder,
227
+ isWorktreeLocked,
228
+ releaseWorktreeLock,
229
+ acquireWorktreeLock,
230
+ WorktreeBusyError,
231
+ withWorktreeLock,
232
+ };
@@ -3,7 +3,7 @@
3
3
  /**
4
4
  * Pure token-usage → display-number mapping.
5
5
  *
6
- * Standalone from app.js (same reason as max-tokens.js/stream-policy.js): it is
6
+ * Standalone from app.js (same reason as budget.js/stream-policy.js): it is
7
7
  * requireable from a plain Node test without window.aegis. app.js only calls
8
8
  * into it.
9
9
  *