aegiscode 7.0.26 → 7.0.28

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 (118) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  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 -2957
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3023
  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 -4089
  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/filepreview.js +1 -153
  28. package/src/fingerprint.js +1 -592
  29. package/src/format.js +1 -259
  30. package/src/fuzzy.js +1 -119
  31. package/src/history.js +1 -423
  32. package/src/init.js +1 -175
  33. package/src/input.js +1 -139
  34. package/src/keys.js +1 -183
  35. package/src/markdown.js +1 -306
  36. package/src/models.js +1 -507
  37. package/src/naming.js +1 -57
  38. package/src/overlays.js +1 -462
  39. package/src/panels.js +1 -1418
  40. package/src/ping.js +1 -226
  41. package/src/presence.js +1 -238
  42. package/src/render.js +1 -516
  43. package/src/screen.js +1 -518
  44. package/src/screens.js +1 -896
  45. package/src/secret.js +1 -59
  46. package/src/securefs.js +1 -359
  47. package/src/settings.js +1 -155
  48. package/src/shared.js +1 -52
  49. package/src/sharedpaths.js +1 -53
  50. package/src/signup.js +1 -156
  51. package/src/summarize.js +1 -95
  52. package/src/sysdiag.js +1 -585
  53. package/src/system.js +1 -40
  54. package/src/theme.js +1 -570
  55. package/src/title.js +1 -220
  56. package/src/todos.js +1 -115
  57. package/src/tokens.js +1 -263
  58. package/src/topup.js +1 -210
  59. package/src/update.js +1 -191
  60. package/vendor/client/aegis.js +1 -2441
  61. package/vendor/client/attest.js +1 -518
  62. package/vendor/client/authorship-key.js +1 -410
  63. package/vendor/client/auto-provision.js +1 -134
  64. package/vendor/client/brain-catalog.js +1 -268
  65. package/vendor/client/byok-catalog.js +1 -199
  66. package/vendor/client/catalog-client.js +1 -487
  67. package/vendor/client/conversation-export.js +1 -177
  68. package/vendor/client/credentials.js +1 -494
  69. package/vendor/client/device-fingerprint.js +1 -141
  70. package/vendor/client/drive-connect.js +1 -110
  71. package/vendor/client/drive-upload.js +1 -234
  72. package/vendor/client/env-file.js +1 -1273
  73. package/vendor/client/fingerprint.js +1 -1064
  74. package/vendor/client/foreign-memory.js +1 -669
  75. package/vendor/client/google-signin.js +1 -133
  76. package/vendor/client/hooks.js +1 -430
  77. package/vendor/client/model-discovery.js +1 -373
  78. package/vendor/client/naming.js +1 -283
  79. package/vendor/client/platform.js +1 -937
  80. package/vendor/client/prefs.js +1 -351
  81. package/vendor/client/presence-constants.js +1 -107
  82. package/vendor/client/presence.js +1 -438
  83. package/vendor/client/record-vault.js +3 -1055
  84. package/vendor/client/session-store.js +1 -575
  85. package/vendor/client/topup.js +1 -297
  86. package/vendor/client/touch.js +1 -458
  87. package/vendor/client/update.js +1 -763
  88. package/vendor/client/user-models.js +1 -381
  89. package/vendor/desktop/lib/local/agents.js +1 -105
  90. package/vendor/desktop/lib/local/attachments.js +1 -276
  91. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  92. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  93. package/vendor/desktop/lib/local/context.js +1 -125
  94. package/vendor/desktop/lib/local/engine.js +1 -3666
  95. package/vendor/desktop/lib/local/entitlement.js +1 -660
  96. package/vendor/desktop/lib/local/exec-plan.js +1 -269
  97. package/vendor/desktop/lib/local/git-scope.js +1 -228
  98. package/vendor/desktop/lib/local/integrity.js +1 -163
  99. package/vendor/desktop/lib/local/local.js +1 -2145
  100. package/vendor/desktop/lib/local/prompt.js +1 -280
  101. package/vendor/desktop/lib/local/queue.js +1 -560
  102. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  103. package/vendor/desktop/lib/local/shell.js +1 -712
  104. package/vendor/desktop/lib/local/spill.js +1 -75
  105. package/vendor/desktop/lib/local/tools.js +1 -1328
  106. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  107. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  108. package/vendor/desktop/lib/settings.js +1 -890
  109. package/vendor/desktop/main.js +1 -4890
  110. package/vendor/desktop/renderer/usage.js +1 -1239
  111. package/vendor/hosts/install.js +1 -638
  112. package/vendor/hosts/openai-shim.js +1 -515
  113. package/vendor/hosts/spec.js +1 -164
  114. package/vendor/hosts/targets.js +1 -346
  115. package/vendor/mcp/server.js +1 -221
  116. package/vendor/mcp/tools.js +1 -408
  117. package/vendor/one/src/child.js +1 -285
  118. package/vendor/one/src/permissions.js +1 -383
@@ -1,271 +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
- /**
7
- * Which `exec` calls are safe to run WITHOUT the turn's persistent shell.
8
- *
9
- * WHY THIS EXISTS. `engine.js` batches the read-only calls in a round into one
10
- * `Promise.all`, but `exec` was excluded from that batching because it is in
11
- * `MUTATING_TOOLS` — one persistent shell per turn means two concurrent
12
- * commands would interleave their streams and the `__AEGIS_SH_…EXIT` sentinel
13
- * each one parses would resolve the wrong call. That exclusion is correct, but
14
- * it is also where the wall-clock went: across the measured SWE-bench runs
15
- * 81.7% of tool calls are `exec` (438/536) and only 10.4% are readFile/grep/
16
- * listDir/glob, so the parallel window covered a tenth of the work. Total time
17
- * was 2223s against another harness's 1322s for the SAME patches while the
18
- * medians matched (120s vs 126s) — a serial dispatch shows up as tail, not as
19
- * median.
20
- *
21
- * THE OPENING. Most of those exec calls are not mutations at all. They are
22
- * reads dressed as shell — `grep`, `sed -n`, `git log`, `ls`, `cat` — and
23
- * 378 of 438 chain an absolute `cd` first, which is the habit the `exec` schema
24
- * teaches ("state does not persist"? — it does, but the model writes `cd` anyway
25
- * because every one-shot example it has seen does). A leading `cd <abs> &&` is
26
- * therefore not state TO the command, it is an address the command carries with
27
- * it: run that command with `cwd` set to that directory and the shell it does
28
- * not touch is irrelevant.
29
- *
30
- * SO THE TEST IS: could this exact command run in a FRESH process, with `cwd`
31
- * set as the lead-in says, and produce the same output? Everything below is an
32
- * attempt to answer that conservatively. The bias is deliberate and one-way —
33
- * a false negative costs a round of serial execution, a false positive corrupts
34
- * a user's repository, so every uncertainty resolves to "keep it sequential".
35
- *
36
- * WHAT IS REJECTED, and why each one is not merely cautious:
37
- * - a write verb anywhere in the command (`rm`, `mv`, `tee`, `>`, `>>`, `sed -i`,
38
- * `pip install`, `patch`, `git commit`, …) — obviously not read-only;
39
- * - `cd` that is NOT the sole leading `cd <path> &&` — a mid-command `cd`
40
- * changes what a LATER command in the same string sees;
41
- * - shell variables (`$FOO`, `${FOO}`), bare `export`, `source`, `.` — these
42
- * only mean anything if session state exists, and with a fresh process they
43
- * would expand to empty strings and silently produce a DIFFERENT result
44
- * rather than an error;
45
- * - job control / backgrounding (`&`, `nohup`), pipelines into a pager;
46
- * - here-docs and multi-line commands — the exit sentinel logic is per-line
47
- * and a multi-line body is the shape most likely to hide a write;
48
- * - any command whose leading `cd` target is relative or `~`-relative beyond
49
- * the first segment, because it would resolve against the SESSION's cwd,
50
- * not this process's.
51
- */
52
-
53
- // Read-shaped verbs that are safe as the FIRST word of a pipeline segment.
54
- // Deliberately a small allow-list rather than a deny-list of write verbs: a
55
- // deny-list fails open the moment someone invents a write verb we did not
56
- // imagine, and the cost of failing open here is a corrupted tree.
57
- //
58
- // NOT in this set, on purpose: `python`, `python3`, `node`, `sh`, `bash`.
59
- // They are arbitrary programs, and the contract this classifier has to prove is
60
- // not "the command is a read the USER would call a read" but "the command cannot
61
- // produce a filesystem mutation a CONCURRENT peer could observe". No text scan
62
- // can prove that about an interpreter — `python -c "open(p,'w')"` is one line,
63
- // and chasing every spelling of a write (`write`, `os.remove`, `shutil`,
64
- // `subprocess`, `-m pip`) is an unbounded guess. So interpreter invocations stay
65
- // on the sequential path. That is a real limit on how much of the measured
66
- // exec traffic this opens up (most SWE-bench commands are `python -c`), and it
67
- // is the reason the wall-clock gain here is bounded rather than dramatic.
68
- const READ_VERBS = new Set([
69
- 'cat', 'head', 'tail', 'less', 'more', 'wc', 'grep', 'egrep', 'fgrep', 'rg',
70
- 'sed', 'awk', 'cut', 'sort', 'uniq', 'tr', 'diff', 'comm', 'join', 'nl',
71
- 'ls', 'dir', 'tree', 'stat', 'file', 'du', 'df', 'pwd', 'which', 'type',
72
- 'basename', 'dirname', 'realpath', 'readlink', 'find', 'locate',
73
- 'echo', 'printf', 'date', 'uname', 'whoami', 'id', 'env', 'printenv',
74
- 'true', 'test',
75
- ]);
76
-
77
- // `git` subcommands that only read. `git diff/status/log/show/blame/grep` are
78
- // the ones that actually appear in agent transcripts; anything else (`git
79
- // checkout`, `git apply`, `git stash`, `git reset`) is not on this list on
80
- // purpose.
81
- const GIT_READ_SUBCOMMANDS = new Set([
82
- 'diff', 'status', 'log', 'show', 'blame', 'grep', 'ls-files', 'rev-parse',
83
- 'describe', 'cat-file', 'shortlog', 'whatchanged', 'reflog', 'show-ref',
84
- 'ls-tree', 'diff-tree', 'diff-files', 'diff-index', 'merge-base',
85
- ]);
86
-
87
- // Absolute-write shapes. Any hit anywhere (not just at a segment start) makes
88
- // the whole command sequential — `find . -delete`, `sed -i`, `python -c
89
- // "open(p,'w')"` all hide their write behind a read-shaped verb.
90
- const WRITE_PATTERNS = [
91
- /(^|[\s;&|(])rm(\s|$)/,
92
- /(^|[\s;&|(])rmdir(\s|$)/,
93
- /(^|[\s;&|(])mv(\s|$)/,
94
- /(^|[\s;&|(])cp(\s|$)/,
95
- /(^|[\s;&|(])ln(\s|$)/,
96
- /(^|[\s;&|(])mkdir(\s|$)/,
97
- /(^|[\s;&|(])touch(\s|$)/,
98
- /(^|[\s;&|(])chmod(\s|$)/,
99
- /(^|[\s;&|(])chown(\s|$)/,
100
- /(^|[\s;&|(])truncate(\s|$)/,
101
- /(^|[\s;&|(])dd(\s|$)/,
102
- /(^|[\s;&|(])tee(\s|$)/,
103
- /(^|[\s;&|(])install(\s|$)/,
104
- /(^|[\s;&|(])patch(\s|$)/,
105
- /(^|[\s;&|(])git\s+(commit|add|rm|mv|checkout|switch|reset|apply|revert|merge|rebase|stash|clean|init|clone|pull|push|fetch|tag|branch|config)\b/,
106
- /(^|[\s;&|(])sed\s+(-[a-zA-Z]*i|--in-place)/,
107
- // `sort -o f`, `uniq -o`? — only a few read verbs take a write flag, and it
108
- // is easy to miss because the verb is allow-listed. `grep -o` is NOT this
109
- // (it only changes the OUTPUT shape), so the match is verb-qualified.
110
- /(^|[\s;&|(])sort\b[^|;]*\s-o(\s|$)/,
111
- /(^|[\s;&|(])sort\b[^|;]*--output=/,
112
- /(^|[\s;&|(])dd\b[^|;]*\bof=/,
113
- /(^|[\s;&|(])find\b[^|;]*\s-(fprint|fprint0|fls)\b/,
114
- /(^|[\s;&|(])find\b[^|]*\s-(delete|exec|execdir|ok|okdir)\b/,
115
- /(^|[\s;&|(])(pip|pip3)\s+(install|uninstall|download)\b/,
116
- /(^|[\s;&|(])npm\s+(install|i|ci|uninstall|publish|run)\b/,
117
- /(^|[\s;&|(])yarn\s+(add|install|remove)\b/,
118
- /(^|[\s;&|(])apt(-get)?\s+(install|remove|purge|update|upgrade)\b/,
119
- /(^|[\s;&|(])(python|python3)\s+-m\s+pip\s+install\b/,
120
- /(^|[\s;&|(])pytest\b[^|]*--(cov|junitxml)/,
121
- // Shell-level writes. `>` redirect is matched conservatively: `2>&1` and
122
- // `>&-` are not writes, so the digit/`&` cases are excluded explicitly.
123
- /(?<![0-9&])>>?(?![&-])/,
124
- /\bexport\s+[A-Za-z_]/,
125
- /(^|[\s;&|(])source(\s|$)/,
126
- ];
127
-
128
- // Commands that only make sense against session state.
129
- const STATEFUL_PATTERNS = [
130
- /\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/,
131
- /(^|[\s;&|(])pushd(\s|$)/,
132
- /(^|[\s;&|(])popd(\s|$)/,
133
- /(^|[\s;&|(])nohup(\s|$)/,
134
- /(^|[\s;&|(])disown(\s|$)/,
135
- /<<-?\s*['"]?[A-Za-z_]/,
136
- /(^|[\s;&|(])\&$/,
137
- /(^|[\s;&|(])exec(\s|$)/,
138
- /(^|[\s;&|(])history(\s|$)/,
139
- /(^|[\s;&|(])jobs(\s|$)/,
140
- ];
141
-
142
- /**
143
- * Strip leading wrapper programs (`timeout 300`, `time`, `command`, `env -i`)
144
- * down to the verb that actually runs. A wrapper must NOT be trusted on its
145
- * own: `timeout 550 python x.py` starts with `timeout`, but the thing being
146
- * run is an interpreter, and the allow-list has to judge THAT.
147
- * Returns null when the wrapper chain hides something we cannot name.
148
- */
149
- function effectiveVerb(words) {
150
- let i = 0;
151
- // Bound the walk: a pathological chain of wrappers is not worth reasoning
152
- // about, and stopping early only costs a miss (stays sequential).
153
- for (let guard = 0; guard < 4 && i < words.length; guard++) {
154
- const w = words[i];
155
- if (w === 'time' || w === 'command') { i += 1; continue; }
156
- if (w === 'env') {
157
- i += 1;
158
- // `env -i`, `env -u X`, and `env FOO=1` prefixes are all local to this
159
- // invocation (they are not session state), so skip them.
160
- while (i < words.length && (words[i].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]))) i += 1;
161
- continue;
162
- }
163
- if (w === 'timeout') {
164
- i += 1;
165
- while (i < words.length && words[i].startsWith('-')) i += 1;
166
- // the duration argument
167
- if (i < words.length && /^[0-9]+(\.[0-9]+)?[smhd]?$/.test(words[i])) i += 1;
168
- continue;
169
- }
170
- if (w === 'nice') {
171
- i += 1;
172
- if (i < words.length && words[i] === '-n') i += 2;
173
- else if (i < words.length && /^-?\d+$/.test(words[i])) i += 1;
174
- continue;
175
- }
176
- break;
177
- }
178
- return i < words.length ? { verb: words[i], rest: words.slice(i) } : null;
179
- }
180
-
181
- /** Split on `;`/`&&`/`||`/`|` into [ {sep, text} ] keeping the separators. */
182
- function segments(command) {
183
- const out = [];
184
- const re = /(\|\||&&|[;|])/g;
185
- let last = 0;
186
- let m;
187
- while ((m = re.exec(command))) {
188
- out.push({ sep: null, text: command.slice(last, m.index) });
189
- out.push({ sep: m[1] });
190
- last = m.index + m[1].length;
191
- }
192
- out.push({ sep: null, text: command.slice(last) });
193
- return out;
194
- }
195
-
196
- /**
197
- * Pull a single leading `cd <absolute path> &&` off the front.
198
- * Returns { cwd, rest } — `cwd` is null when there is no such lead-in.
199
- * Only an ABSOLUTE path qualifies: a relative one would resolve against the
200
- * session's directory, which a one-shot process does not share.
201
- */
202
- function leadingCd(command) {
203
- const m = /^\s*cd\s+(?:--\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*([\s\S]+)$/.exec(command);
204
- if (!m) return { cwd: null, rest: command };
205
- const target = (m[1] || m[2] || m[3] || '').trim();
206
- if (!target.startsWith('/')) return { cwd: null, rest: command };
207
- // `cd /a && cd /b && …` — the second cd is not the lead-in, so the rest must
208
- // be judged on its own (it will then be rejected as a non-leading cd).
209
- return { cwd: target, rest: m[4] };
210
- }
211
-
212
- /**
213
- * Decide whether `command` may run as a one-shot process with an explicit cwd.
214
- *
215
- * @param {string} command raw command the model asked `exec` to run
216
- * @param {object} [opts]
217
- * @param {string} [opts.baseCwd] the turn's cwd, used when there is no lead-in
218
- * @returns {{ oneShot: boolean, cwd: string|null, reason: string }}
219
- * `reason` is for tests and diagnostics; it is never shown to the model.
220
- */
221
- function planExec(command, opts = {}) {
222
- const baseCwd = opts.baseCwd || null;
223
- const raw = typeof command === 'string' ? command : '';
224
- const no = (reason) => ({ oneShot: false, cwd: null, reason });
225
-
226
- if (!raw.trim()) return no('empty command');
227
- // A newline means a multi-command body. The session's exit sentinel is
228
- // appended per command and a multi-line body is where a write hides; not
229
- // worth the risk for the handful of these a turn contains.
230
- if (raw.includes('\n')) return no('multi-line command');
231
-
232
- for (const re of STATEFUL_PATTERNS) {
233
- if (re.test(raw)) return no('depends on session state');
234
- }
235
- for (const re of WRITE_PATTERNS) {
236
- if (re.test(raw)) return no('contains a write');
237
- }
238
-
239
- const { cwd, rest } = leadingCd(raw);
240
- const restText = rest.trim();
241
- if (!restText) return no('nothing after the cd');
242
-
243
- // Every segment must start with a read-shaped verb. `git` is special-cased
244
- // on its subcommand; a bare `git` with no subcommand reads the status, which
245
- // is read-only, and `git --version` likewise.
246
- const segs = segments(restText).filter((s) => !s.sep);
247
- if (!segs.length) return no('no command');
248
- for (const seg of segs) {
249
- const words = seg.text.trim().replace(/^\(+\s*/, '').split(/\s+/).filter(Boolean);
250
- if (!words.length) continue;
251
- const eff = effectiveVerb(words);
252
- if (!eff) return no('empty command after wrappers');
253
- const verb = eff.verb;
254
- if (verb === 'git') {
255
- const sub = eff.rest[1];
256
- if (!sub || sub.startsWith('-')) continue; // `git`, `git --version`
257
- if (!GIT_READ_SUBCOMMANDS.has(sub)) return no(`git ${sub} is not read-only`);
258
- continue;
259
- }
260
- if (!READ_VERBS.has(verb)) return no(`${verb} is not a known read verb`);
261
- // `sed -i` is already caught by WRITE_PATTERNS above, but `sed … -w file`
262
- // and `awk … > file` write without an `-i`.
263
- if ((verb === 'sed' || verb === 'awk') && /(^|\s)-[a-zA-Z]*w\s/.test(eff.rest.join(' '))) {
264
- return no(`${verb} writes a file`);
265
- }
266
- }
267
-
268
- return { oneShot: true, cwd: cwd || baseCwd, reason: 'read-only' };
269
- }
270
-
271
- module.exports = { planExec, READ_VERBS, GIT_READ_SUBCOMMANDS, WRITE_PATTERNS, STATEFUL_PATTERNS };
3
+ const s=new Set(["cat","head","tail","less","more","wc","grep","egrep","fgrep","rg","sed","awk","cut","sort","uniq","tr","diff","comm","join","nl","ls","dir","tree","stat","file","du","df","pwd","which","type","basename","dirname","realpath","readlink","find","locate","echo","printf","date","uname","whoami","id","env","printenv","true","test"]),e=new Set(["diff","status","log","show","blame","grep","ls-files","rev-parse","describe","cat-file","shortlog","whatchanged","reflog","show-ref","ls-tree","diff-tree","diff-files","diff-index","merge-base"]),t=[/(^|[\s;&|(])rm(\s|$)/,/(^|[\s;&|(])rmdir(\s|$)/,/(^|[\s;&|(])mv(\s|$)/,/(^|[\s;&|(])cp(\s|$)/,/(^|[\s;&|(])ln(\s|$)/,/(^|[\s;&|(])mkdir(\s|$)/,/(^|[\s;&|(])touch(\s|$)/,/(^|[\s;&|(])chmod(\s|$)/,/(^|[\s;&|(])chown(\s|$)/,/(^|[\s;&|(])truncate(\s|$)/,/(^|[\s;&|(])dd(\s|$)/,/(^|[\s;&|(])tee(\s|$)/,/(^|[\s;&|(])install(\s|$)/,/(^|[\s;&|(])patch(\s|$)/,/(^|[\s;&|(])git\s+(commit|add|rm|mv|checkout|switch|reset|apply|revert|merge|rebase|stash|clean|init|clone|pull|push|fetch|tag|branch|config)\b/,/(^|[\s;&|(])sed\s+(-[a-zA-Z]*i|--in-place)/,/(^|[\s;&|(])sort\b[^|;]*\s-o(\s|$)/,/(^|[\s;&|(])sort\b[^|;]*--output=/,/(^|[\s;&|(])dd\b[^|;]*\bof=/,/(^|[\s;&|(])find\b[^|;]*\s-(fprint|fprint0|fls)\b/,/(^|[\s;&|(])find\b[^|]*\s-(delete|exec|execdir|ok|okdir)\b/,/(^|[\s;&|(])(pip|pip3)\s+(install|uninstall|download)\b/,/(^|[\s;&|(])npm\s+(install|i|ci|uninstall|publish|run)\b/,/(^|[\s;&|(])yarn\s+(add|install|remove)\b/,/(^|[\s;&|(])apt(-get)?\s+(install|remove|purge|update|upgrade)\b/,/(^|[\s;&|(])(python|python3)\s+-m\s+pip\s+install\b/,/(^|[\s;&|(])pytest\b[^|]*--(cov|junitxml)/,/(?<![0-9&])>>?(?![&-])/,/\bexport\s+[A-Za-z_]/,/(^|[\s;&|(])source(\s|$)/],n=[/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/,/(^|[\s;&|(])pushd(\s|$)/,/(^|[\s;&|(])popd(\s|$)/,/(^|[\s;&|(])nohup(\s|$)/,/(^|[\s;&|(])disown(\s|$)/,/<<-?\s*['"]?[A-Za-z_]/,/(^|[\s;&|(])\&$/,/(^|[\s;&|(])exec(\s|$)/,/(^|[\s;&|(])history(\s|$)/,/(^|[\s;&|(])jobs(\s|$)/];function r(s){let e=0;for(let t=0;t<4&&e<s.length;t++){const t=s[e];if("time"!==t&&"command"!==t)if("env"!==t)if("timeout"!==t){if("nice"!==t)break;e+=1,e<s.length&&"-n"===s[e]?e+=2:e<s.length&&/^-?\d+$/.test(s[e])&&(e+=1)}else{for(e+=1;e<s.length&&s[e].startsWith("-");)e+=1;e<s.length&&/^[0-9]+(\.[0-9]+)?[smhd]?$/.test(s[e])&&(e+=1)}else for(e+=1;e<s.length&&(s[e].startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(s[e]));)e+=1;else e+=1}return e<s.length?{verb:s[e],rest:s.slice(e)}:null}module.exports={planExec:function(i,o={}){const l=o.baseCwd||null,a="string"==typeof i?i:"",c=s=>({oneShot:!1,cwd:null,reason:s});if(!a.trim())return c("empty command");if(a.includes("\n"))return c("multi-line command");for(const s of n)if(s.test(a))return c("depends on session state");for(const s of t)if(s.test(a))return c("contains a write");const{cwd:d,rest:f}=function(s){const e=/^\s*cd\s+(?:--\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*([\s\S]+)$/.exec(s);if(!e)return{cwd:null,rest:s};const t=(e[1]||e[2]||e[3]||"").trim();return t.startsWith("/")?{cwd:t,rest:e[4]}:{cwd:null,rest:s}}(a),u=f.trim();if(!u)return c("nothing after the cd");const p=function(s){const e=[],t=/(\|\||&&|[;|])/g;let n,r=0;for(;n=t.exec(s);)e.push({sep:null,text:s.slice(r,n.index)}),e.push({sep:n[1]}),r=n.index+n[1].length;return e.push({sep:null,text:s.slice(r)}),e}(u).filter((s=>!s.sep));if(!p.length)return c("no command");for(const t of p){const n=t.text.trim().replace(/^\(+\s*/,"").split(/\s+/).filter(Boolean);if(!n.length)continue;const i=r(n);if(!i)return c("empty command after wrappers");const o=i.verb;if("git"!==o){if(!s.has(o))return c(`${o} is not a known read verb`);if(("sed"===o||"awk"===o)&&/(^|\s)-[a-zA-Z]*w\s/.test(i.rest.join(" ")))return c(`${o} writes a file`)}else{const s=i.rest[1];if(!s||s.startsWith("-"))continue;if(!e.has(s))return c(`git ${s} is not read-only`)}}return{oneShot:!0,cwd:d||l,reason:"read-only"}},READ_VERBS:s,GIT_READ_SUBCOMMANDS:e,WRITE_PATTERNS:t,STATEFUL_PATTERNS:n};
@@ -1,230 +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
- * Minimal git worktree introspection: where the repo root is, and what is
10
- * dirty right now with a content hash per path.
11
- *
12
- * Ported from the upstream engine reference (ESM → CommonJS). `turn-guard.js`
13
- * uses `gitRoot` and `gitStatusSnapshot`; the queue now hosts the commit path
14
- * too, so `foreignChanges` and `scopedCommit` are carried over as well — they
15
- * were deliberately absent while nothing here queued work, because a copy of
16
- * code nothing calls is a copy that drifts unnoticed.
17
- *
18
- * ATTRIBUTION IS TWO CONDITIONS, NOT ONE. "Dirty before AND byte-identical
19
- * now" only excludes work that nobody touched — it cannot see a concurrent
20
- * writer who edits a file *during* the task window, because that file is no
21
- * longer byte-identical and so looks like ours. Commit 96fb64f swept exactly
22
- * such a file (desktop/electron-builder.yml, edited by another live session)
23
- * into an unrelated commit that way. So `scopedCommit` also requires positive
24
- * attribution: a path is staged only if the caller reports that THIS task's own
25
- * tool layer wrote it (`written`). Everything else dirty — foreign, or merely
26
- * unattributed — is left alone and reported.
27
- */
28
-
29
- const fs = require('node:fs');
30
- const path = require('node:path');
31
- const crypto = require('node:crypto');
32
- const { spawnSync } = require('node:child_process');
33
-
34
- /** The repo root for `cwd`, or null if it isn't inside a git work tree. */
35
- function gitRoot(cwd) {
36
- const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' });
37
- return r.status === 0 ? r.stdout.trim() : null;
38
- }
39
-
40
- /**
41
- * Hash a path's worktree content, so "already dirty before the task ran" can
42
- * be told apart from "this task changed it". `absent` covers deletions;
43
- * non-files (a submodule, a directory) compare by kind.
44
- */
45
- function contentHash(cwd, rel) {
46
- try {
47
- const st = fs.lstatSync(path.join(cwd, rel));
48
- if (!st.isFile()) return st.isDirectory() ? 'nonfile:dir' : 'nonfile:other';
49
- return crypto.createHash('sha1').update(fs.readFileSync(path.join(cwd, rel))).digest('hex');
50
- } catch {
51
- return 'absent';
52
- }
53
- }
54
-
55
- /**
56
- * Every path git reports as dirty right now, mapped to its content hash.
57
- * `--no-renames` matters: in `-z` porcelain a rename emits the old name as a
58
- * second NUL-terminated token, which we would otherwise hash as a change.
59
- * Untracked files are included, since that is exactly how concurrent work
60
- * usually arrives. Returns null if `cwd` is not a usable git repo.
61
- */
62
- function gitStatusSnapshot(cwd) {
63
- // Run from the repo root: porcelain reports paths root-relative, so hashing
64
- // must resolve them against the same directory.
65
- const root = gitRoot(cwd);
66
- if (!root) return null;
67
- const r = spawnSync(
68
- 'git',
69
- ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames'],
70
- { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
71
- );
72
- if (r.status !== 0) return null;
73
- const snap = new Map();
74
- for (const rec of r.stdout.split('\0')) {
75
- if (rec.length < 4) continue;
76
- const p = rec.slice(3);
77
- snap.set(p, contentHash(root, p));
78
- }
79
- return snap;
80
- }
81
-
82
- /**
83
- * Paths that were dirty *before* and are byte-identical now: another agent's
84
- * in-flight work, not ours. These must never be committed.
85
- *
86
- * Byte-identical is the test, not "was dirty": a path that was dirty before and
87
- * that this task then EDITED has a different hash, so it is ours to commit. Only
88
- * untouched foreign work is excluded.
89
- */
90
- function foreignChanges(cwd, before) {
91
- if (!before) return [];
92
- const now = gitStatusSnapshot(cwd);
93
- if (!now) return [];
94
- const out = [];
95
- for (const [p, hash] of now) {
96
- if (before.has(p) && before.get(p) === hash) out.push(p);
97
- }
98
- return out;
99
- }
100
-
101
- /**
102
- * A path the caller reported writing, as repo-root-relative POSIX text.
103
- *
104
- * The tool layer reports what the MODEL asked for (`file_path` as typed), which
105
- * may be absolute or relative to the task's own working directory — not
106
- * necessarily this process's `cwd`. Returns '' for anything outside the repo:
107
- * a write that cannot be attributed to a path git reports is not something this
108
- * function may guess about.
109
- */
110
- function toRepoRelative(root, base, p) {
111
- const raw = String(p == null ? '' : p).trim();
112
- if (!raw) return '';
113
- const abs = path.isAbsolute(raw) ? raw : path.resolve(base || root, raw);
114
- const rel = path.relative(root, abs);
115
- if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return '';
116
- return rel.split(path.sep).join('/');
117
- }
118
-
119
- /** The repo-relative set of paths the task's own tool layer reported writing. */
120
- function writtenSet(root, base, written) {
121
- const out = new Set();
122
- for (const p of written || []) {
123
- const rel = toRepoRelative(root, base, p);
124
- if (rel) out.add(rel);
125
- }
126
- return out;
127
- }
128
-
129
- /**
130
- * Split the current dirty set by attribution. `ours` is what this task wrote
131
- * and changed; `left` is everything else git reports as dirty — a peer's
132
- * in-flight work, plus our own changes we cannot positively attribute (a file a
133
- * shell command created names no path in the tool call, so it is reported, not
134
- * assumed).
135
- *
136
- * @returns {null|{root:string, ours:string[], left:string[], written:Set<string>}}
137
- */
138
- function attributedChanges(cwd, { before, written } = {}) {
139
- const root = gitRoot(cwd);
140
- if (!root) return null;
141
- const now = gitStatusSnapshot(cwd);
142
- if (!now) return null;
143
- const mine = writtenSet(root, cwd, written);
144
- const ours = [];
145
- const left = [];
146
- for (const [p, hash] of now) {
147
- // "Differs from the pre-task snapshot": new since then, or the bytes moved.
148
- const changed = !(before && before.has(p) && before.get(p) === hash);
149
- if (changed && mine.has(p)) ours.push(p);
150
- else left.push(p);
151
- }
152
- return { root, ours, left, written: mine };
153
- }
154
-
155
- /**
156
- * Commit only the changes this task is known to have made.
157
- *
158
- * The rule, in one line: stage a dirty path only if it DIFFERS from the
159
- * pre-task snapshot AND this task's tool layer reports writing it. Two
160
- * conditions, because either alone is unsafe: "changed since the snapshot"
161
- * sweeps a concurrent writer who edits mid-run, and "was dirty before and is
162
- * byte-identical now" cannot be the only exclusion because it sees only the
163
- * writer who stopped.
164
- *
165
- * `before` is the `gitStatusSnapshot(cwd)` taken immediately before the task
166
- * ran and `written` the paths the caller's tool layer wrote during it; without
167
- * either there is no basis for attribution, and the only safe move is to refuse
168
- * (or stage nothing) — `git add -A` here would commit a concurrent agent's
169
- * half-finished edit under this task's message.
170
- *
171
- * @returns {{ok?:boolean,skipped?:boolean,reason?:string,error?:string,
172
- * message?:string,staged?:number,paths?:string[],foreign?:string[],
173
- * identicalForeign?:string[]}}
174
- */
175
- function scopedCommit(cwd, { message, before, written } = {}) {
176
- if (!gitRoot(cwd)) return { skipped: true, reason: 'not a git repo' };
177
-
178
- // No basis for attribution — refuse rather than sweep.
179
- if (!before) {
180
- return { ok: false, error: 'no pre-task snapshot; refusing to sweep the working tree' };
181
- }
182
-
183
- const attributed = attributedChanges(cwd, { before, written });
184
- if (!attributed) return { skipped: true, reason: 'not a git repo' };
185
- const { root, ours, left } = attributed;
186
-
187
- if (!ours.length) {
188
- const untouched = foreignChanges(cwd, before);
189
- return {
190
- ok: true,
191
- skipped: true,
192
- foreign: left,
193
- identicalForeign: untouched,
194
- reason: left.length
195
- ? `no changes of our own (left ${left.length} change(s) this task did not write)`
196
- : 'no changes',
197
- };
198
- }
199
-
200
- // pathspec-from-file keeps an arbitrarily long (or space/NUL-bearing) list
201
- // safe — a 400-file commit is fine, a path with a newline in it is not.
202
- const add = spawnSync('git', ['add', '-A', '--pathspec-from-file=-', '--pathspec-file-nul'], {
203
- cwd: root,
204
- encoding: 'utf8',
205
- input: ours.join('\0'),
206
- });
207
- if (add.status !== 0) return { ok: false, error: add.stderr || 'git add failed' };
208
-
209
- const commit = spawnSync('git', ['commit', '-m', message], { cwd: root, encoding: 'utf8' });
210
- if (commit.status !== 0) {
211
- // "nothing to commit" is a success for our purposes: the changes we staged
212
- // were already committed by somebody else, and the task's work is done.
213
- if (/nothing to commit|no changes added/i.test(commit.stdout + commit.stderr)) {
214
- return { ok: true, skipped: true, foreign: left, reason: 'no changes' };
215
- }
216
- return { ok: false, error: commit.stderr || commit.stdout };
217
- }
218
- return { ok: true, message, foreign: left, paths: ours, staged: ours.length };
219
- }
220
-
221
- module.exports = {
222
- gitRoot,
223
- contentHash,
224
- gitStatusSnapshot,
225
- foreignChanges,
226
- toRepoRelative,
227
- writtenSet,
228
- attributedChanges,
229
- scopedCommit,
230
- };
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),crypto=require("node:crypto"),{spawnSync:spawnSync}=require("node:child_process");function gitRoot(t){const e=spawnSync("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8"});return 0===e.status?e.stdout.trim():null}function contentHash(t,e){try{const n=fs.lstatSync(path.join(t,e));return n.isFile()?crypto.createHash("sha1").update(fs.readFileSync(path.join(t,e))).digest("hex"):n.isDirectory()?"nonfile:dir":"nonfile:other"}catch{return"absent"}}function gitStatusSnapshot(t){const e=gitRoot(t);if(!e)return null;const n=spawnSync("git",["status","--porcelain=v1","-z","--untracked-files=all","--no-renames"],{cwd:e,encoding:"utf8",maxBuffer:67108864});if(0!==n.status)return null;const o=new Map;for(const t of n.stdout.split("\0")){if(t.length<4)continue;const n=t.slice(3);o.set(n,contentHash(e,n))}return o}function foreignChanges(t,e){if(!e)return[];const n=gitStatusSnapshot(t);if(!n)return[];const o=[];for(const[t,s]of n)e.has(t)&&e.get(t)===s&&o.push(t);return o}function toRepoRelative(t,e,n){const o=String(null==n?"":n).trim();if(!o)return"";const s=path.isAbsolute(o)?o:path.resolve(e||t,o),r=path.relative(t,s);return!r||r.startsWith("..")||path.isAbsolute(r)?"":r.split(path.sep).join("/")}function writtenSet(t,e,n){const o=new Set;for(const s of n||[]){const n=toRepoRelative(t,e,s);n&&o.add(n)}return o}function attributedChanges(t,{before:e,written:n}={}){const o=gitRoot(t);if(!o)return null;const s=gitStatusSnapshot(t);if(!s)return null;const r=writtenSet(o,t,n),i=[],a=[];for(const[t,n]of s)e&&e.has(t)&&e.get(t)===n||!r.has(t)?a.push(t):i.push(t);return{root:o,ours:i,left:a,written:r}}function scopedCommit(t,{message:e,before:n,written:o}={}){if(!gitRoot(t))return{skipped:!0,reason:"not a git repo"};if(!n)return{ok:!1,error:"no pre-task snapshot; refusing to sweep the working tree"};const s=attributedChanges(t,{before:n,written:o});if(!s)return{skipped:!0,reason:"not a git repo"};const{root:r,ours:i,left:a}=s;if(!i.length)return{ok:!0,skipped:!0,foreign:a,identicalForeign:foreignChanges(t,n),reason:a.length?`no changes of our own (left ${a.length} change(s) this task did not write)`:"no changes"};const c=spawnSync("git",["add","-A","--pathspec-from-file=-","--pathspec-file-nul"],{cwd:r,encoding:"utf8",input:i.join("\0")});if(0!==c.status)return{ok:!1,error:c.stderr||"git add failed"};const u=spawnSync("git",["commit","-m",e],{cwd:r,encoding:"utf8"});return 0!==u.status?/nothing to commit|no changes added/i.test(u.stdout+u.stderr)?{ok:!0,skipped:!0,foreign:a,reason:"no changes"}:{ok:!1,error:u.stderr||u.stdout}:{ok:!0,message:e,foreign:a,paths:i,staged:i.length}}module.exports={gitRoot:gitRoot,contentHash:contentHash,gitStatusSnapshot:gitStatusSnapshot,foreignChanges:foreignChanges,toRepoRelative:toRepoRelative,writtenSet:writtenSet,attributedChanges:attributedChanges,scopedCommit:scopedCommit};