aegisone 1.0.21 → 1.0.23

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 (226) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -2
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -939
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/permissions.js +1 -369
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/bin/aegiscode.js +2 -914
  17. package/vendor/cli/package.json +3 -2
  18. package/vendor/cli/scripts/check.mjs +1 -52
  19. package/vendor/cli/scripts/demo.mjs +1 -94
  20. package/vendor/cli/scripts/predist.mjs +1 -75
  21. package/vendor/cli/scripts/runtests.mjs +1 -56
  22. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  23. package/vendor/cli/src/agents.js +1 -139
  24. package/vendor/cli/src/app.js +1 -2932
  25. package/vendor/cli/src/art.js +1 -289
  26. package/vendor/cli/src/autonomous.js +1 -515
  27. package/vendor/cli/src/caps.js +1 -879
  28. package/vendor/cli/src/chatflow.js +1 -3008
  29. package/vendor/cli/src/checkpoint.js +1 -90
  30. package/vendor/cli/src/clipboard.js +1 -424
  31. package/vendor/cli/src/cloudsync.js +1 -528
  32. package/vendor/cli/src/commands.js +1 -3987
  33. package/vendor/cli/src/config.js +1 -581
  34. package/vendor/cli/src/connect.js +1 -349
  35. package/vendor/cli/src/credentials.js +1 -33
  36. package/vendor/cli/src/deps.js +1 -232
  37. package/vendor/cli/src/devrun.js +1 -187
  38. package/vendor/cli/src/diff.js +1 -333
  39. package/vendor/cli/src/diffview.js +1 -296
  40. package/vendor/cli/src/engine.js +1 -297
  41. package/vendor/cli/src/entitlement.js +1 -355
  42. package/vendor/cli/src/events.js +1 -707
  43. package/vendor/cli/src/export.js +1 -67
  44. package/vendor/cli/src/fingerprint.js +1 -592
  45. package/vendor/cli/src/format.js +1 -259
  46. package/vendor/cli/src/fuzzy.js +1 -119
  47. package/vendor/cli/src/gate.js +1 -55
  48. package/vendor/cli/src/history.js +1 -401
  49. package/vendor/cli/src/init.js +1 -175
  50. package/vendor/cli/src/input.js +1 -139
  51. package/vendor/cli/src/keys.js +1 -183
  52. package/vendor/cli/src/limits.js +1 -190
  53. package/vendor/cli/src/markdown.js +1 -306
  54. package/vendor/cli/src/mcp.js +1 -694
  55. package/vendor/cli/src/models.js +1 -487
  56. package/vendor/cli/src/naming.js +1 -229
  57. package/vendor/cli/src/overlays.js +1 -461
  58. package/vendor/cli/src/panels.js +1 -1418
  59. package/vendor/cli/src/permissions.js +1 -290
  60. package/vendor/cli/src/ping.js +1 -226
  61. package/vendor/cli/src/presence.js +1 -238
  62. package/vendor/cli/src/provenance.js +2 -182
  63. package/vendor/cli/src/render.js +1 -515
  64. package/vendor/cli/src/screen.js +1 -518
  65. package/vendor/cli/src/screens.js +1 -896
  66. package/vendor/cli/src/secret.js +1 -59
  67. package/vendor/cli/src/securefs.js +1 -359
  68. package/vendor/cli/src/settings.js +1 -155
  69. package/vendor/cli/src/shared.js +1 -52
  70. package/vendor/cli/src/sharedpaths.js +1 -53
  71. package/vendor/cli/src/signup.js +1 -156
  72. package/vendor/cli/src/summarize.js +1 -95
  73. package/vendor/cli/src/sysdiag.js +1 -585
  74. package/vendor/cli/src/system.js +1 -40
  75. package/vendor/cli/src/theme.js +1 -570
  76. package/vendor/cli/src/title.js +1 -220
  77. package/vendor/cli/src/todos.js +1 -115
  78. package/vendor/cli/src/tokens.js +1 -263
  79. package/vendor/cli/src/topup.js +1 -210
  80. package/vendor/cli/src/update.js +1 -181
  81. package/vendor/cli/vendor/client/aegis.js +1 -2054
  82. package/vendor/cli/vendor/client/attest.js +1 -442
  83. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  84. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  85. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  86. package/vendor/cli/vendor/client/byok-catalog.js +1 -230
  87. package/vendor/cli/vendor/client/credentials.js +1 -494
  88. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  89. package/vendor/cli/vendor/client/drive-connect.js +1 -85
  90. package/vendor/cli/vendor/client/drive-upload.js +1 -174
  91. package/vendor/cli/vendor/client/env-file.js +1 -1273
  92. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  93. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  94. package/vendor/cli/vendor/client/google-signin.js +1 -125
  95. package/vendor/cli/vendor/client/hooks.js +1 -430
  96. package/vendor/cli/vendor/client/model-discovery.js +1 -330
  97. package/vendor/cli/vendor/client/platform.js +1 -937
  98. package/vendor/cli/vendor/client/prefs.js +1 -351
  99. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  100. package/vendor/cli/vendor/client/presence.js +1 -438
  101. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  102. package/vendor/cli/vendor/client/session-store.js +1 -548
  103. package/vendor/cli/vendor/client/topup.js +1 -297
  104. package/vendor/cli/vendor/client/touch.js +1 -458
  105. package/vendor/cli/vendor/client/update.js +1 -704
  106. package/vendor/cli/vendor/client/user-models.js +1 -381
  107. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  108. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  109. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -993
  110. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -95
  111. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3228
  112. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -654
  113. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  114. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2135
  115. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -275
  116. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  117. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -208
  118. package/vendor/cli/vendor/desktop/lib/local/shell.js +1 -680
  119. package/vendor/cli/vendor/desktop/lib/local/tools.js +1 -1238
  120. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  121. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  122. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  123. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  124. package/vendor/cli/vendor/hosts/install.js +1 -638
  125. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  126. package/vendor/cli/vendor/hosts/spec.js +1 -164
  127. package/vendor/cli/vendor/hosts/targets.js +1 -346
  128. package/vendor/cli/vendor/mcp/server.js +1 -221
  129. package/vendor/cli/vendor/mcp/tools.js +1 -408
  130. package/vendor/cli/vendor/one/src/child.js +1 -285
  131. package/vendor/cli/vendor/one/src/permissions.js +1 -369
  132. package/vendor/desktop/bin/aegis.js +1 -32
  133. package/vendor/desktop/lib/account-key.js +1 -56
  134. package/vendor/desktop/lib/auto.js +1 -430
  135. package/vendor/desktop/lib/avatar/companion.js +1 -698
  136. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  137. package/vendor/desktop/lib/avatar/events.js +1 -344
  138. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  139. package/vendor/desktop/lib/avatar/holders.js +1 -612
  140. package/vendor/desktop/lib/avatar/identity.js +1 -641
  141. package/vendor/desktop/lib/avatar/level.js +1 -368
  142. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  143. package/vendor/desktop/lib/avatar/persona.js +1 -388
  144. package/vendor/desktop/lib/avatar/profile.js +1 -977
  145. package/vendor/desktop/lib/avatar/register.js +1 -307
  146. package/vendor/desktop/lib/avatar/store.js +1 -472
  147. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  148. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  149. package/vendor/desktop/lib/avatar/turn.js +1 -216
  150. package/vendor/desktop/lib/avatar/voice.js +1 -328
  151. package/vendor/desktop/lib/avatar/xp.js +1 -404
  152. package/vendor/desktop/lib/deep-link.js +1 -120
  153. package/vendor/desktop/lib/fingerprint.js +2 -347
  154. package/vendor/desktop/lib/google-connect.js +1 -169
  155. package/vendor/desktop/lib/local/agents.js +1 -105
  156. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  157. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  158. package/vendor/desktop/lib/local/context.js +1 -95
  159. package/vendor/desktop/lib/local/engine.js +1 -3228
  160. package/vendor/desktop/lib/local/entitlement.js +1 -654
  161. package/vendor/desktop/lib/local/git-scope.js +1 -228
  162. package/vendor/desktop/lib/local/local.js +1 -2135
  163. package/vendor/desktop/lib/local/prompt.js +1 -275
  164. package/vendor/desktop/lib/local/queue.js +1 -560
  165. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  166. package/vendor/desktop/lib/local/shell.js +1 -680
  167. package/vendor/desktop/lib/local/telemetry.js +1 -470
  168. package/vendor/desktop/lib/local/tools.js +1 -1238
  169. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  170. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  171. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  172. package/vendor/desktop/lib/quick-launcher.js +1 -84
  173. package/vendor/desktop/lib/settings.js +1 -890
  174. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  175. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  176. package/vendor/desktop/lib/sync/sessions.js +1 -106
  177. package/vendor/desktop/lib/window-state.js +1 -66
  178. package/vendor/desktop/main.js +1 -4390
  179. package/vendor/desktop/package.json +3 -5
  180. package/vendor/desktop/preload.js +1 -628
  181. package/vendor/desktop/renderer/app.js +1 -6560
  182. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  183. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  184. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  185. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  186. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  187. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  188. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  189. package/vendor/desktop/renderer/budget.js +1 -168
  190. package/vendor/desktop/renderer/companion.js +1 -223
  191. package/vendor/desktop/renderer/diff.js +1 -359
  192. package/vendor/desktop/renderer/diffview.js +1 -336
  193. package/vendor/desktop/renderer/fingerprint.js +3 -720
  194. package/vendor/desktop/renderer/markdown.js +1 -168
  195. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  196. package/vendor/desktop/renderer/providers.js +1 -259
  197. package/vendor/desktop/renderer/quick.js +1 -191
  198. package/vendor/desktop/renderer/stream-policy.js +1 -306
  199. package/vendor/desktop/renderer/transcript-view.js +1 -323
  200. package/vendor/desktop/renderer/usage.js +1 -1239
  201. package/vendor/desktop/vendor/aegis.js +1 -2054
  202. package/vendor/desktop/vendor/attest.js +1 -442
  203. package/vendor/desktop/vendor/authorship-key.js +1 -410
  204. package/vendor/desktop/vendor/auto-provision.js +1 -134
  205. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  206. package/vendor/desktop/vendor/byok-catalog.js +1 -230
  207. package/vendor/desktop/vendor/credentials.js +1 -494
  208. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  209. package/vendor/desktop/vendor/drive-connect.js +1 -85
  210. package/vendor/desktop/vendor/drive-upload.js +1 -174
  211. package/vendor/desktop/vendor/env-file.js +1 -1273
  212. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  213. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  214. package/vendor/desktop/vendor/google-signin.js +1 -125
  215. package/vendor/desktop/vendor/hooks.js +1 -430
  216. package/vendor/desktop/vendor/model-discovery.js +1 -330
  217. package/vendor/desktop/vendor/platform.js +1 -937
  218. package/vendor/desktop/vendor/prefs.js +1 -351
  219. package/vendor/desktop/vendor/presence-constants.js +1 -107
  220. package/vendor/desktop/vendor/presence.js +1 -438
  221. package/vendor/desktop/vendor/record-vault.js +3 -1055
  222. package/vendor/desktop/vendor/session-store.js +1 -548
  223. package/vendor/desktop/vendor/topup.js +1 -297
  224. package/vendor/desktop/vendor/touch.js +1 -458
  225. package/vendor/desktop/vendor/update.js +1 -704
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -1,302 +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
- * Turn-start foreign-write detection.
10
- *
11
- * Ported from the upstream engine reference (ESM → CommonJS).
12
- *
13
- * Bug this exists for: the commit-time scope check already knew how to tell
14
- * "my changes" from "somebody else's in-flight work" — but only *after* a
15
- * task had finished. The dangerous window is the opposite end: a session
16
- * reads a file, time passes, a second agent edits that file, and the first
17
- * session then acts on a stale mental model. That is how a live session
18
- * destroyed a peer's work — the content it reverted was real and correct,
19
- * just not the content it had read.
20
- *
21
- * `git checkout HEAD -- <file>`, `git reset --hard`, `git stash` and
22
- * `git clean` are the destructive operations, and their default scope is the
23
- * whole tree. Running any of them while a peer has uncommitted work is the
24
- * entire incident.
25
- *
26
- * Fix: snapshot the dirty set at turn start, record the paths this session
27
- * actually writes, then answer two questions on demand —
28
- * `foreignSince()` / `concurrentSince()` whose work is in the tree
29
- * `blocksDestructive()` would a given command clobber it
30
- * The second is load-bearing: it turns "revert someone else's file" into a
31
- * refusal, which is the cheapest place to stop it.
32
- *
33
- * This is detection, not prevention — it cannot stop a writer outside the
34
- * host. Paired with worktree-lock.js it covers our own sessions.
35
- */
36
-
37
- const { gitRoot, gitStatusSnapshot } = require('./git-scope.js');
38
-
39
- /** Git's own flags that consume the *next* argv entry, so that token is not
40
- * the subcommand. Without this, `git -C /repo reset --hard` parses `reset`
41
- * as a flag argument and the whole command reads as harmless. */
42
- const GIT_FLAGS_WITH_ARG = new Set([
43
- '-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path',
44
- ]);
45
-
46
- /** Split a command line into shell segments and then argv, stripping quotes.
47
- * Segmenting on `&&`/`;`/`|` means `ls && git checkout -- a` is still caught,
48
- * while `git stash list` is judged on its own segment. */
49
- function tokenize(command) {
50
- const out = [];
51
- for (const segment of String(command || '').split(/[|;&\n]+/)) {
52
- const argv = [];
53
- const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
54
- let m;
55
- while ((m = re.exec(segment))) argv.push(m[1] ?? m[2] ?? m[3]);
56
- if (argv.length) out.push(argv);
57
- }
58
- return out;
59
- }
60
-
61
- /** The git subcommand and its arguments in one argv, or null if this argv
62
- * isn't a git invocation that has a subcommand. */
63
- function gitInvocation(argv) {
64
- const i = argv.findIndex((t) => t === 'git' || t.endsWith('/git'));
65
- if (i === -1) return null;
66
- let j = i + 1;
67
- while (j < argv.length && argv[j].startsWith('-')) {
68
- j += GIT_FLAGS_WITH_ARG.has(argv[j]) ? 2 : 1;
69
- }
70
- if (j >= argv.length) return null;
71
- return { sub: argv[j], args: argv.slice(j + 1) };
72
- }
73
-
74
- /** Positional arguments (the paths a command names), dropping flags. Values
75
- * after `--` are always paths; before it, anything not starting with `-` is
76
- * taken as one, which is right for checkout/restore and harmlessly unused
77
- * elsewhere. */
78
- function namedPaths(args) {
79
- const sep = args.indexOf('--');
80
- if (sep !== -1) return args.slice(sep + 1).filter((a) => !a.startsWith('-'));
81
- return args.filter((a) => !a.startsWith('-'));
82
- }
83
-
84
- const isTreeMark = (p) => p === '.' || p === './' || p === '*' || p === './*';
85
- const hasForce = (args) => args.some((a) => a === '-f' || a === '--force' || /^-[a-zA-Z]*f/.test(a));
86
-
87
- /** subcommand -> { what, scope } where scope is 'tree' (discards broadly) or
88
- * 'paths' (discards only the paths it names). Returns null when harmless. */
89
- function judge(sub, args) {
90
- const paths = namedPaths(args);
91
- const treeWide = paths.length === 0 || paths.some(isTreeMark);
92
- switch (sub) {
93
- case 'checkout':
94
- if (args.includes('--') || hasForce(args)) {
95
- return { what: 'checkout of uncommitted changes', scope: treeWide ? 'tree' : 'paths', paths };
96
- }
97
- // `git checkout .` restores the whole tree; a bare branch switch is safe.
98
- if (treeWide && paths.length) return { what: 'checkout . (tree-wide restore)', scope: 'tree', paths };
99
- return null;
100
- case 'restore':
101
- return { what: 'restore (discards uncommitted changes)', scope: treeWide ? 'tree' : 'paths', paths };
102
- case 'reset':
103
- return args.includes('--hard') ? { what: 'reset --hard', scope: 'tree', paths: [] } : null;
104
- case 'clean':
105
- return hasForce(args) ? { what: 'clean -f (deletes untracked files)', scope: 'tree', paths: [] } : null;
106
- case 'stash': {
107
- const first = args.find((a) => !a.startsWith('-'));
108
- if (first === 'list' || first === 'show') return null;
109
- // pop/apply can conflict with, and push parks, every path in the tree.
110
- return { what: `stash ${first || 'push'} (uncommitted changes across the tree)`, scope: 'tree', paths: [] };
111
- }
112
- case 'worktree': {
113
- const first = args.find((a) => !a.startsWith('-'));
114
- return first === 'remove' || first === 'prune'
115
- ? { what: `worktree ${first}`, scope: 'tree', paths: [] }
116
- : null;
117
- }
118
- default:
119
- return null;
120
- }
121
- }
122
-
123
- /**
124
- * Classify a shell command line. Returns
125
- * `{destructive:false}` or `{destructive:true, what, scope:'tree'|'paths', paths}`.
126
- *
127
- * Parsed as argv rather than matched as text, because a message *about* a
128
- * destructive command is not one: `git commit -m "fix stash handling"` must
129
- * not read as a stash. Quoting is handled, so the two are actually different.
130
- */
131
- function classifyDestructive(command) {
132
- for (const argv of tokenize(command)) {
133
- const inv = gitInvocation(argv);
134
- if (!inv) continue;
135
- const verdict = judge(inv.sub, inv.args);
136
- if (verdict) return { destructive: true, ...verdict };
137
- }
138
- return { destructive: false };
139
- }
140
-
141
- /**
142
- * Begin guarding a turn in `cwd`. Costs one `git status`; a non-repo (or a
143
- * git failure) yields a guard that reports nothing, so callers never have to
144
- * branch on whether the guard is armed.
145
- */
146
- function beginTurnGuard(cwd) {
147
- const root = gitRoot(cwd);
148
- const before = root ? gitStatusSnapshot(cwd) : null;
149
- return {
150
- root,
151
- cwd,
152
- before,
153
- startedAt: Date.now(),
154
- written: new Set(),
155
- active: Boolean(root && before),
156
- };
157
- }
158
-
159
- /** Normalise a written path to root-relative, so it can be compared against
160
- * porcelain output. Accepts absolute or relative paths. */
161
- function toRel(guard, p) {
162
- let s = String(p || '');
163
- if (!s) return null;
164
- if (guard.root && s.startsWith(guard.root)) {
165
- s = s.slice(guard.root.length).replace(/^[/\\]/, '');
166
- }
167
- return s.split('\\').join('/');
168
- }
169
-
170
- /**
171
- * Record a path this session itself wrote. A recorded path is never reported
172
- * as foreign — this is what keeps the guard from crying wolf about the
173
- * caller's own edits, and it is why the host's file tools must call it.
174
- */
175
- function recordWrite(guard, p) {
176
- if (!guard || !guard.active) return;
177
- const rel = toRel(guard, p);
178
- if (rel) guard.written.add(rel);
179
- }
180
-
181
- /**
182
- * Paths that are *unambiguously* a peer's in-flight work: dirty when the turn
183
- * started, byte-identical now, and never written by this session.
184
- *
185
- * "Dirty before and still identical" is what makes this confident — a path
186
- * nobody touched is dirty *because* it belongs to someone else. It is
187
- * git-scope's own definition, which is why the two modules agree.
188
- */
189
- function foreignSince(guard) {
190
- if (!guard || !guard.active) return [];
191
- const now = gitStatusSnapshot(guard.cwd);
192
- if (!now) return [];
193
- const out = [];
194
- for (const [p, hash] of now) {
195
- if (guard.written.has(p)) continue;
196
- if (guard.before.has(p) && guard.before.get(p) === hash) out.push(p);
197
- }
198
- return out.sort();
199
- }
200
-
201
- /**
202
- * Paths clean at turn start and dirty now, excluding any this session
203
- * recorded writing.
204
- *
205
- * Weaker than `foreignSince` because attribution is incomplete: the host's
206
- * file tools call `recordWrite`, but a path a shell command creates
207
- * (`> out.txt`, `npm install`) is invisible here and can be mistaken for a
208
- * peer's. Still reported, and still consulted by `blocksDestructive` — see
209
- * the asymmetry note there.
210
- */
211
- function concurrentSince(guard) {
212
- if (!guard || !guard.active) return [];
213
- const now = gitStatusSnapshot(guard.cwd);
214
- if (!now) return [];
215
- const out = [];
216
- for (const [p] of now) {
217
- if (guard.written.has(p)) continue;
218
- if (!guard.before.has(p)) out.push(p);
219
- }
220
- return out.sort();
221
- }
222
-
223
- /**
224
- * Would running `command` be unsafe right now? Returns `{ok:true}` or
225
- * `{ok:false, what, scope, reason, foreign, unattributed}`.
226
- *
227
- * Scope decides what has to be at risk:
228
- * - a *tree-wide* op (`git reset --hard`, `git stash`, `git checkout .`) is
229
- * refused whenever any peer work is present, because it cannot help but
230
- * touch it;
231
- * - a *path-scoped* op is refused only when one of the paths it names is
232
- * actually foreign, so reverting your own file still works while a peer
233
- * happens to be editing a different one.
234
- *
235
- * Both signals count, because the risk is asymmetric: a refusal costs the
236
- * caller one step (name the paths, or take the lock), while a miss destroys
237
- * work that may exist nowhere else. In the incident this module exists for,
238
- * the peer's files appeared *during* the turn, so the confident signal was
239
- * empty — blocking on it alone would have missed the exact case that
240
- * motivated the guard.
241
- *
242
- * A tree with nothing foreign is never blocked, so a solo session is never
243
- * wedged: the module is inert unless somebody else's work is present.
244
- */
245
- function blocksDestructive(guard, command) {
246
- const verdict = classifyDestructive(command);
247
- if (!verdict.destructive) return { ok: true };
248
- if (!guard || !guard.active) return { ok: true };
249
-
250
- let foreign = foreignSince(guard);
251
- let unattributed = concurrentSince(guard).filter((p) => !foreign.includes(p));
252
-
253
- let atRisk = [];
254
- if (verdict.scope === 'tree') {
255
- atRisk = [...foreign, ...unattributed];
256
- } else {
257
- const named = new Set(verdict.paths.map((p) => p.replace(/^\.\//, '')));
258
- const hits = (list) => list.filter((p) => named.has(p) || named.has('./' + p));
259
- foreign = hits(foreign);
260
- unattributed = hits(unattributed);
261
- atRisk = [...foreign, ...unattributed];
262
- }
263
- if (!atRisk.length) return { ok: true, what: verdict.what };
264
-
265
- const parts = [];
266
- if (foreign.length) {
267
- parts.push(
268
- `${foreign.length} hold another agent's uncommitted work: `
269
- + foreign.slice(0, 8).join(', ') + (foreign.length > 8 ? ` (+${foreign.length - 8} more)` : ''),
270
- );
271
- }
272
- if (unattributed.length) {
273
- parts.push(
274
- `${unattributed.length} changed since this turn began and were not written by `
275
- + `this session: ${unattributed.slice(0, 8).join(', ')}`
276
- + (unattributed.length > 8 ? ` (+${unattributed.length - 8} more)` : ''),
277
- );
278
- }
279
- return {
280
- ok: false,
281
- what: verdict.what,
282
- scope: verdict.scope,
283
- foreign,
284
- unattributed,
285
- reason:
286
- `refusing \`${verdict.what}\` in ${guard.root}: `
287
- + (verdict.scope === 'tree'
288
- ? 'it is tree-scoped and would discard work it did not create — '
289
- : 'it targets a path that is not yours to discard — ')
290
- + parts.join('; ')
291
- + '. Name only the paths you mean, or take the worktree lock first.',
292
- };
293
- }
294
-
295
- module.exports = {
296
- classifyDestructive,
297
- beginTurnGuard,
298
- recordWrite,
299
- foreignSince,
300
- concurrentSince,
301
- blocksDestructive,
302
- };
3
+ "use strict";const{gitRoot:gitRoot,gitStatusSnapshot:gitStatusSnapshot}=require("./git-scope.js"),GIT_FLAGS_WITH_ARG=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path"]);function tokenize(t){const e=[];for(const n of String(t||"").split(/[|;&\n]+/)){const t=[],r=/"([^"]*)"|'([^']*)'|(\S+)/g;let s;for(;s=r.exec(n);)t.push(s[1]??s[2]??s[3]);t.length&&e.push(t)}return e}function gitInvocation(t){const e=t.findIndex((t=>"git"===t||t.endsWith("/git")));if(-1===e)return null;let n=e+1;for(;n<t.length&&t[n].startsWith("-");)n+=GIT_FLAGS_WITH_ARG.has(t[n])?2:1;return n>=t.length?null:{sub:t[n],args:t.slice(n+1)}}function namedPaths(t){const e=t.indexOf("--");return-1!==e?t.slice(e+1).filter((t=>!t.startsWith("-"))):t.filter((t=>!t.startsWith("-")))}const isTreeMark=t=>"."===t||"./"===t||"*"===t||"./*"===t,hasForce=t=>t.some((t=>"-f"===t||"--force"===t||/^-[a-zA-Z]*f/.test(t)));function judge(t,e){const n=namedPaths(e),r=0===n.length||n.some(isTreeMark);switch(t){case"checkout":return e.includes("--")||hasForce(e)?{what:"checkout of uncommitted changes",scope:r?"tree":"paths",paths:n}:r&&n.length?{what:"checkout . (tree-wide restore)",scope:"tree",paths:n}:null;case"restore":return{what:"restore (discards uncommitted changes)",scope:r?"tree":"paths",paths:n};case"reset":return e.includes("--hard")?{what:"reset --hard",scope:"tree",paths:[]}:null;case"clean":return hasForce(e)?{what:"clean -f (deletes untracked files)",scope:"tree",paths:[]}:null;case"stash":{const t=e.find((t=>!t.startsWith("-")));return"list"===t||"show"===t?null:{what:`stash ${t||"push"} (uncommitted changes across the tree)`,scope:"tree",paths:[]}}case"worktree":{const t=e.find((t=>!t.startsWith("-")));return"remove"===t||"prune"===t?{what:`worktree ${t}`,scope:"tree",paths:[]}:null}default:return null}}function classifyDestructive(t){for(const e of tokenize(t)){const t=gitInvocation(e);if(!t)continue;const n=judge(t.sub,t.args);if(n)return{destructive:!0,...n}}return{destructive:!1}}function beginTurnGuard(t){const e=gitRoot(t),n=e?gitStatusSnapshot(t):null;return{root:e,cwd:t,before:n,startedAt:Date.now(),written:new Set,active:Boolean(e&&n)}}function toRel(t,e){let n=String(e||"");return n?(t.root&&n.startsWith(t.root)&&(n=n.slice(t.root.length).replace(/^[/\\]/,"")),n.split("\\").join("/")):null}function recordWrite(t,e){if(!t||!t.active)return;const n=toRel(t,e);n&&t.written.add(n)}function foreignSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r,s]of e)t.written.has(r)||t.before.has(r)&&t.before.get(r)===s&&n.push(r);return n.sort()}function concurrentSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r]of e)t.written.has(r)||t.before.has(r)||n.push(r);return n.sort()}function blocksDestructive(t,e){const n=classifyDestructive(e);if(!n.destructive)return{ok:!0};if(!t||!t.active)return{ok:!0};let r=foreignSince(t),s=concurrentSince(t).filter((t=>!r.includes(t))),o=[];if("tree"===n.scope)o=[...r,...s];else{const t=new Set(n.paths.map((t=>t.replace(/^\.\//,"")))),e=e=>e.filter((e=>t.has(e)||t.has("./"+e)));r=e(r),s=e(s),o=[...r,...s]}if(!o.length)return{ok:!0,what:n.what};const i=[];return r.length&&i.push(`${r.length} hold another agent's uncommitted work: `+r.slice(0,8).join(", ")+(r.length>8?` (+${r.length-8} more)`:"")),s.length&&i.push(`${s.length} changed since this turn began and were not written by this session: ${s.slice(0,8).join(", ")}`+(s.length>8?` (+${s.length-8} more)`:"")),{ok:!1,what:n.what,scope:n.scope,foreign:r,unattributed:s,reason:`refusing \`${n.what}\` in ${t.root}: `+("tree"===n.scope?"it is tree-scoped and would discard work it did not create — ":"it targets a path that is not yours to discard — ")+i.join("; ")+". Name only the paths you mean, or take the worktree lock first."}}module.exports={classifyDestructive:classifyDestructive,beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,foreignSince:foreignSince,concurrentSince:concurrentSince,blocksDestructive:blocksDestructive};
@@ -1,237 +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
- * Cross-process lock on a git working tree.
10
- *
11
- * Ported from the upstream engine reference (ESM → CommonJS).
12
- *
13
- * Bug this exists for: nothing keyed on *the working tree*. A session-scoped
14
- * lock only stops two processes resuming the SAME transcript, so three
15
- * different sessions in one checkout are three different ids and therefore
16
- * all legal. A queue-worker lock only serialises queue drains. An interactive
17
- * session took no lock at all.
18
- *
19
- * So N agents editing one checkout was, by every existing lock, correct
20
- * behaviour — and it is destructive. It happened for real: one session ran
21
- * `git checkout HEAD --` against a file a second session was mid-edit on
22
- * (destroying it), a third ran `git stash` and parked everybody's tree, and a
23
- * test run on that shared tree reported failures belonging to a half-built
24
- * feature that was not the caller's. Git has no advisory locking, so none of
25
- * it produced an error — just unexplained file changes, which is exactly the
26
- * kind of evidence that gets misread as "my tool lied to me".
27
- *
28
- * Fix: a lock keyed on the repository root — the resource actually contended
29
- * — taken by every host that runs a turn (the desktop app and the CLI both
30
- * reach this file through desktop/lib/local/engine.js). Same atomic-marker +
31
- * PID-liveness pattern as the session lock, so a crashed holder is reclaimed
32
- * with no staleness window to tune and no manual cleanup.
33
- *
34
- * This lock is advisory and cooperative: it cannot stop a writer that does
35
- * not take it (a plain `git` in a terminal, another harness, an editor). Its
36
- * value is that our own hosts stop racing each other, and that a caller
37
- * receiving `null` knows to back off instead of writing blind.
38
- *
39
- * The stronger fix is one worktree per agent (`git worktree add`), which
40
- * removes the shared mutable tree entirely. This lock is what makes the
41
- * single-tree case safe when that is not available.
42
- */
43
-
44
- const fs = require('node:fs');
45
- const path = require('node:path');
46
- const os = require('node:os');
47
- const crypto = require('node:crypto');
48
-
49
- /**
50
- * Where lock files live.
51
- *
52
- * The plugin's data dir is ~/.aegiscode ($AEGISCODE_HOME), per config.js's
53
- * `aegisDir()` convention — but the dev engine's ~/.aegiscodex is honoured
54
- * too, and either `*_WORKTREE_LOCK_DIR` override points every host at ONE
55
- * directory. That override is the interlock: two separate tools disagreeing
56
- * about where the lock file goes is the same as having no lock, so operators
57
- * running the GUI, the CLI and the dev engine against one checkout should set
58
- * AEGISCODE_WORKTREE_LOCK_DIR (or AEGISCODEX_WORKTREE_LOCK_DIR) to a shared
59
- * path. Within this repo the desktop and CLI hosts always agree, because both
60
- * resolve this same helper.
61
- */
62
- function worktreeLockDir() {
63
- if (process.env.AEGISCODE_WORKTREE_LOCK_DIR) return process.env.AEGISCODE_WORKTREE_LOCK_DIR;
64
- if (process.env.AEGISCODEX_WORKTREE_LOCK_DIR) return process.env.AEGISCODEX_WORKTREE_LOCK_DIR;
65
- const home = process.env.AEGISCODE_HOME
66
- || process.env.AEGISCODEX_HOME
67
- || path.join(os.homedir(), '.aegiscode');
68
- return path.join(home, 'worktree-locks');
69
- }
70
-
71
- /** Default wait: a live holder is bounded by its own turn watchdog, so
72
- * waiting slightly past that lets a legitimate queued turn run once the
73
- * holder's deadline fires, rather than failing right as the tree is about to
74
- * free up. */
75
- const DEFAULT_WORKTREE_WAIT_MS = 11 * 60 * 1000;
76
-
77
- /** Sentinel token for the "not in a repo" no-op path — always truthy, never
78
- * matches a real acquisition, so a stray release() can't release anything. */
79
- const NOOP_TOKEN = '(no-worktree)';
80
-
81
- /**
82
- * Canonicalise the root so two paths to one repo — a symlink, a trailing
83
- * slash, a relative path, `/tmp/../repo` — agree on a single lock file.
84
- * Falls back to the resolved path when realpath fails.
85
- */
86
- function canonical(root) {
87
- if (!root) return null;
88
- const abs = path.resolve(String(root));
89
- try { return fs.realpathSync(abs); } catch { return abs; }
90
- }
91
-
92
- /** The lock file for `root`. The path is hashed so an arbitrarily long or
93
- * awkward root maps to one flat, safe filename; the root itself is written
94
- * inside the file for humans reading the lock dir. */
95
- function worktreeLockPath(root) {
96
- if (!root) return null;
97
- const key = crypto.createHash('sha1').update(canonical(root)).digest('hex').slice(0, 16);
98
- return path.join(worktreeLockDir(), key + '.lock');
99
- }
100
-
101
- function pidAlive(pid) {
102
- try { process.kill(pid, 0); return true; } catch { return false; }
103
- }
104
-
105
- function readHolder(root) {
106
- try { return JSON.parse(fs.readFileSync(worktreeLockPath(root), 'utf8')); } catch { return null; }
107
- }
108
-
109
- /**
110
- * The current holder of `root`'s lock, or null. Never throws and never
111
- * clears a stale lock — use `isWorktreeLocked` for the reclaiming check.
112
- */
113
- function worktreeLockHolder(root) {
114
- if (!root) return null;
115
- const h = readHolder(root);
116
- if (!h) return null;
117
- return {
118
- pid: h.pid, token: h.token, since: h.since,
119
- root: h.root || canonical(root), session: h.session || null,
120
- };
121
- }
122
-
123
- /**
124
- * True if `root` is held by a live process (any process, including this one
125
- * — two concurrent callers inside one process must still queue behind each
126
- * other). A lock file whose PID is dead or unparsable is stale and cleared as
127
- * a side effect, so callers never special-case it.
128
- */
129
- function isWorktreeLocked(root) {
130
- if (!root) return false;
131
- const holder = readHolder(root);
132
- // `Number(null)` is 0 and `process.kill(0, 0)` targets the caller's process
133
- // GROUP, so it succeeds — a missing lock file would otherwise read as a live
134
- // holder forever. Require a real pid. (The session lock has the same latent
135
- // trap; it never surfaced there only because it is called after EEXIST.)
136
- const pid = Number(holder && holder.pid);
137
- if (!Number.isInteger(pid) || pid <= 0 || !pidAlive(pid)) {
138
- try { fs.unlinkSync(worktreeLockPath(root)); } catch {}
139
- return false;
140
- }
141
- return true;
142
- }
143
-
144
- /** Exclusive-create the lock file for `token`. Returns true on success.
145
- * Best-effort: a data-dir failure other than "already exists" fails OPEN so a
146
- * broken filesystem can never block a turn that would otherwise run fine. */
147
- function tryAcquire(root, token, meta) {
148
- try {
149
- fs.mkdirSync(worktreeLockDir(), { recursive: true });
150
- const fd = fs.openSync(worktreeLockPath(root), 'wx');
151
- fs.writeFileSync(fd, JSON.stringify({
152
- pid: process.pid,
153
- token,
154
- since: Date.now(),
155
- root: canonical(root),
156
- session: (meta && meta.session) || null,
157
- }));
158
- fs.closeSync(fd);
159
- return true;
160
- } catch (e) {
161
- if (e && e.code === 'EEXIST') return false;
162
- return true;
163
- }
164
- }
165
-
166
- /** Release `root`'s lock — only if `token` matches the current holder, so
167
- * releasing a lock you don't (or no longer) own can never clobber whoever
168
- * holds it now. No-op on a falsy root/token or any filesystem error
169
- * (best-effort, like the rest of this repo's persistence helpers). */
170
- function releaseWorktreeLock(root, token) {
171
- if (!root || !token || token === NOOP_TOKEN) return;
172
- const holder = readHolder(root);
173
- if (holder && holder.token === token) {
174
- try { fs.unlinkSync(worktreeLockPath(root)); } catch {}
175
- }
176
- }
177
-
178
- /**
179
- * Acquire `root`'s lock, waiting out a live holder instead of racing it.
180
- * Resolves a truthy opaque token once acquired — pass it back to
181
- * `releaseWorktreeLock` — or `null` if `waitMs` elapses or `signal` aborts
182
- * first; either way the caller must not write. A falsy `root` (not inside a
183
- * git work tree — nothing shared to collide over) resolves the sentinel
184
- * immediately with no file touched.
185
- */
186
- async function acquireWorktreeLock(root, {
187
- waitMs = DEFAULT_WORKTREE_WAIT_MS, pollMs = 200, signal, session = null,
188
- } = {}) {
189
- if (!root) return NOOP_TOKEN;
190
- const token = crypto.randomUUID();
191
- const deadline = Date.now() + waitMs;
192
- for (;;) {
193
- if (signal && signal.aborted) return null;
194
- if (tryAcquire(root, token, { session })) return token;
195
- // Was stale, just reclaimed by clearing — retry now.
196
- if (!isWorktreeLocked(root)) continue;
197
- if (Date.now() >= deadline) return null;
198
- await new Promise((r) => setTimeout(r, pollMs));
199
- }
200
- }
201
-
202
- /**
203
- * Run `fn` holding `root`'s lock, releasing it on every exit path. Throws
204
- * `WorktreeBusyError` (rather than running unprotected) if the lock can't be
205
- * taken, because proceeding without it is the bug this module exists to
206
- * prevent.
207
- */
208
- class WorktreeBusyError extends Error {
209
- constructor(root, holder) {
210
- super(`working tree ${root} is locked by pid ${holder ? holder.pid : '?'}`);
211
- this.name = 'WorktreeBusyError';
212
- this.root = root;
213
- this.holder = holder || null;
214
- }
215
- }
216
-
217
- async function withWorktreeLock(root, opts, fn) {
218
- const token = await acquireWorktreeLock(root, opts);
219
- if (!token) throw new WorktreeBusyError(root, worktreeLockHolder(root));
220
- try {
221
- return await fn();
222
- } finally {
223
- releaseWorktreeLock(root, token);
224
- }
225
- }
226
-
227
- module.exports = {
228
- DEFAULT_WORKTREE_WAIT_MS,
229
- worktreeLockDir,
230
- worktreeLockPath,
231
- worktreeLockHolder,
232
- isWorktreeLocked,
233
- releaseWorktreeLock,
234
- acquireWorktreeLock,
235
- WorktreeBusyError,
236
- withWorktreeLock,
237
- };
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto");function worktreeLockDir(){if(process.env.AEGISCODE_WORKTREE_LOCK_DIR)return process.env.AEGISCODE_WORKTREE_LOCK_DIR;if(process.env.AEGISCODEX_WORKTREE_LOCK_DIR)return process.env.AEGISCODEX_WORKTREE_LOCK_DIR;const r=process.env.AEGISCODE_HOME||process.env.AEGISCODEX_HOME||path.join(os.homedir(),".aegiscode");return path.join(r,"worktree-locks")}const DEFAULT_WORKTREE_WAIT_MS=66e4,NOOP_TOKEN="(no-worktree)";function canonical(r){if(!r)return null;const e=path.resolve(String(r));try{return fs.realpathSync(e)}catch{return e}}function worktreeLockPath(r){if(!r)return null;const e=crypto.createHash("sha1").update(canonical(r)).digest("hex").slice(0,16);return path.join(worktreeLockDir(),e+".lock")}function pidAlive(r){try{return process.kill(r,0),!0}catch{return!1}}function readHolder(r){try{return JSON.parse(fs.readFileSync(worktreeLockPath(r),"utf8"))}catch{return null}}function worktreeLockHolder(r){if(!r)return null;const e=readHolder(r);return e?{pid:e.pid,token:e.token,since:e.since,root:e.root||canonical(r),session:e.session||null}:null}function isWorktreeLocked(r){if(!r)return!1;const e=readHolder(r),o=Number(e&&e.pid);if(!Number.isInteger(o)||o<=0||!pidAlive(o)){try{fs.unlinkSync(worktreeLockPath(r))}catch{}return!1}return!0}function tryAcquire(r,e,o){try{fs.mkdirSync(worktreeLockDir(),{recursive:!0});const t=fs.openSync(worktreeLockPath(r),"wx");return fs.writeFileSync(t,JSON.stringify({pid:process.pid,token:e,since:Date.now(),root:canonical(r),session:o&&o.session||null})),fs.closeSync(t),!0}catch(r){return!r||"EEXIST"!==r.code}}function releaseWorktreeLock(r,e){if(!r||!e||e===NOOP_TOKEN)return;const o=readHolder(r);if(o&&o.token===e)try{fs.unlinkSync(worktreeLockPath(r))}catch{}}async function acquireWorktreeLock(r,{waitMs:e=DEFAULT_WORKTREE_WAIT_MS,pollMs:o=200,signal:t,session:n=null}={}){if(!r)return NOOP_TOKEN;const c=crypto.randomUUID(),i=Date.now()+e;for(;;){if(t&&t.aborted)return null;if(tryAcquire(r,c,{session:n}))return c;if(isWorktreeLocked(r)){if(Date.now()>=i)return null;await new Promise((r=>setTimeout(r,o)))}}}class WorktreeBusyError extends Error{constructor(r,e){super(`working tree ${r} is locked by pid ${e?e.pid:"?"}`),this.name="WorktreeBusyError",this.root=r,this.holder=e||null}}async function withWorktreeLock(r,e,o){const t=await acquireWorktreeLock(r,e);if(!t)throw new WorktreeBusyError(r,worktreeLockHolder(r));try{return await o()}finally{releaseWorktreeLock(r,t)}}module.exports={DEFAULT_WORKTREE_WAIT_MS:DEFAULT_WORKTREE_WAIT_MS,worktreeLockDir:worktreeLockDir,worktreeLockPath:worktreeLockPath,worktreeLockHolder:worktreeLockHolder,isWorktreeLocked:isWorktreeLocked,releaseWorktreeLock:releaseWorktreeLock,acquireWorktreeLock:acquireWorktreeLock,WorktreeBusyError:WorktreeBusyError,withWorktreeLock:withWorktreeLock};