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,474 +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
- * store.js — the main process's half of level authority.
10
- *
11
- * The avatar core shipped as five pure modules with no IO at all:
12
- * `xp.js` knows what an event is worth and how a ledger replays into a level,
13
- * `level.js` knows what a level buys, but neither can read a file or a clock.
14
- * This file is the missing half and it deliberately owns *only* the two things
15
- * the pure modules refuse to: the filesystem and the process's own memory of
16
- * what it has seen.
17
- *
18
- * Three rules shape everything below.
19
- *
20
- * 1. THE LEDGER IS THE ONLY STATE. There is no counter, no cached level, no
21
- * "xp so far" anywhere in this file. `append()` writes one line; `state()`
22
- * replays the whole file through `xp.evaluate()`. A hand-edited line — or a
23
- * bug in this file — cannot inflate a level, because nothing here is
24
- * trusted on the way out. The `xp` field written into each line is
25
- * advisory (a convenience for `jq`), exactly as `xp.js` documents.
26
- *
27
- * 2. WRITES ARE APPEND-ONLY AND SINGLE-SYSCALL. `fs.appendFileSync` with the
28
- * default O_APPEND is one write(2) per line, so a second process (the app
29
- * launched twice is refused a second instance lock, but the CLI and the MCP
30
- * plugin read the same home) can never rewrite a line under us, and a
31
- * process killed mid-append loses at most the last line — which
32
- * `xp.parseLedger()` is explicitly tolerant of.
33
- *
34
- * 3. LEVEL NEVER GATES A WRITE. The hook helpers below (`awardSave`,
35
- * `awardQueued`, `awardRecalls`, `awardImports`) only ever *observe* the
36
- * memory path; none of them can refuse it. `memoryWriteback` is not even
37
- * consulted here, because memory is the source of XP and gating it would be
38
- * the feedback deadlock `level.js` documents. The same goes for the
39
- * approval classes: nothing in this file is reachable from the tool gate,
40
- * which is what makes `test/avatar-approval-carveout.test.mjs` a statement
41
- * about the design rather than a promise.
42
- *
43
- * Node-only (fs + path + crypto), no Electron import, injectable `dir`/`now`/
44
- * `env` — so the whole phase is testable in plain `node --test`, the same way
45
- * `lib/sync/*` and `lib/local/*` are.
46
- */
47
-
48
- const fs = require('node:fs');
49
- const path = require('node:path');
50
- const crypto = require('node:crypto');
51
- const xp = require('./xp.js');
52
- const level = require('./level.js');
53
- const personaModule = require('./persona.js');
54
-
55
- /** `<userData>/avatar/ledger.jsonl` — the one path this module owns. */
56
- const LEDGER_DIR = 'avatar';
57
- const LEDGER_FILE = 'ledger.jsonl';
58
- /**
59
- * `<userData>/avatar/persona.json` — the persona DOCUMENT.
60
- *
61
- * It lives here, next to the ledger and not in settings.json, because a persona
62
- * is a document rather than a preference: it is imported, exported, hand-edited
63
- * and eventually synced per holder, and every one of those paths
64
- * wants validation on the way in. The `__avatar` settings namespace holds only
65
- * the three switches (lib/settings.js), so a renderer can never write a persona
66
- * through the settings surface.
67
- */
68
- const PERSONA_FILE = 'persona.json';
69
- /** Hex chars of the content fingerprint kept per observed ref. */
70
- const DIGEST_CHARS = 16;
71
-
72
- function avatarHome(dir) {
73
- return path.join(dir, LEDGER_DIR);
74
- }
75
-
76
- function ledgerPath(dir) {
77
- return path.join(avatarHome(dir), LEDGER_FILE);
78
- }
79
-
80
- function personaPath(dir) {
81
- return path.join(avatarHome(dir), PERSONA_FILE);
82
- }
83
-
84
- /** Content fingerprint for upsert/correction detection — never stored. */
85
- function fingerprint(text) {
86
- return crypto
87
- .createHash('sha1')
88
- .update(String(text == null ? '' : text))
89
- .digest('hex')
90
- .slice(0, DIGEST_CHARS);
91
- }
92
-
93
- /**
94
- * A stable, content-addressed id for a memory entry that arrived without one.
95
- *
96
- * This is not decoration. aegis1's `/api/memory/save` upserts on
97
- * `(user_id, id)` and drops any entry carrying no `id`/`content`, so a caller
98
- * that sends a bare `{text}` (the renderer's "remember" box does exactly that)
99
- * has its write silently discarded — and a renderer-side counter would then be
100
- * paying XP for memory that does not exist. Deriving the id from the normalised
101
- * text makes that save real *and* idempotent: re-remembering the same fact
102
- * upserts one row instead of duplicating it, which is precisely the
103
- * "same fact re-observed" event `xp.js` pays `memory.reinforced` for.
104
- */
105
- function memoryEntryId(entry) {
106
- const source = (entry && entry.source) || 'aegis-desktop';
107
- const text = String((entry && (entry.content != null ? entry.content : entry.text)) || '');
108
- return `note-${fingerprint(`${source}|${text.trim().toLowerCase()}`)}`;
109
- }
110
-
111
- /**
112
- * Give a plain memory entry the identity the memory path requires (id +
113
- * content + the metadata aegis1 keys rows on), leaving an entry that already
114
- * has them untouched. Fields the caller set always win.
115
- */
116
- function normalizeMemoryEntry(entry) {
117
- if (!entry || typeof entry !== 'object') return entry;
118
- const text =
119
- typeof entry.content === 'string' && entry.content
120
- ? entry.content
121
- : typeof entry.text === 'string'
122
- ? entry.text
123
- : '';
124
- if (!text) return entry;
125
- const out = Object.assign({}, entry);
126
- if (!out.content) out.content = text;
127
- if (!out.role) out.role = 'user';
128
- if (!out.source) out.source = 'aegis-desktop';
129
- if (!out.id) out.id = memoryEntryId(out);
130
- return out;
131
- }
132
-
133
- /**
134
- * Create the store for one user-data directory.
135
- *
136
- * @param {object} opts
137
- * @param {string} opts.dir `<userData>` — the ledger's parent.
138
- * @param {() => number} [opts.now] injectable clock (tests).
139
- * @param {object} [opts.env] `AEGIS_*` overrides source.
140
- * @param {(msg: string) => void} [opts.log]
141
- */
142
- function createAvatarStore({ dir, now = () => Date.now(), env = process.env, log = () => {} } = {}) {
143
- if (!dir || typeof dir !== 'string') {
144
- throw new Error('createAvatarStore: a user-data directory is required');
145
- }
146
-
147
- const file = ledgerPath(dir);
148
- /** Parsed-ledger cache, invalidated by size+mtime (another process may write). */
149
- let cache = null;
150
- /** sessionId -> level, for §1.4 "a level never regresses while you watch". */
151
- const held = new Map();
152
- /** Memory refs this process has observed to exist (reads, saves, recalls). */
153
- const live = new Set();
154
- /** ref -> fingerprint of the content last seen under it (upsert detection). */
155
- const digests = new Map();
156
- /** Refs observed to be gone; the only thing that can drop recall credit (§1.4). */
157
- const gone = new Set();
158
-
159
- function readParsed() {
160
- try {
161
- const st = fs.statSync(file);
162
- if (cache && cache.size === st.size && cache.mtimeMs === st.mtimeMs) return cache.parsed;
163
- const parsed = xp.parseLedger(fs.readFileSync(file, 'utf8'));
164
- cache = { size: st.size, mtimeMs: st.mtimeMs, parsed };
165
- return parsed;
166
- } catch (err) {
167
- if (err && err.code === 'ENOENT') return { entries: [], corrupt: 0 };
168
- // A ledger we cannot read is not a reason to take the app down: report it
169
- // and replay what we have (nothing), which reads as L1 — the honest
170
- // answer, and the one that gates no behaviour.
171
- log(`aegis: could not read ${file}: ${err && err.message}`);
172
- return { entries: [], corrupt: 0, error: (err && err.message) || 'unreadable' };
173
- }
174
- }
175
-
176
- /**
177
- * Append one ledger line. One syscall, O_APPEND, `mkdir -p` first: a ledger
178
- * line is a few dozen bytes, far below any pipe buffer, so this cannot tear.
179
- */
180
- function appendLine(entry) {
181
- const line = `${JSON.stringify(entry)}\n`;
182
- try {
183
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
184
- fs.appendFileSync(file, line);
185
- if (cache) {
186
- cache = {
187
- size: cache.size + Buffer.byteLength(line),
188
- mtimeMs: 0, // unknown after our own write; force one stat on the next read
189
- parsed: { entries: cache.parsed.entries.concat([entry]), corrupt: cache.parsed.corrupt },
190
- };
191
- }
192
- return entry;
193
- } catch (err) {
194
- // Losing a ledger line costs XP, never memory: always reported, never
195
- // thrown at a caller whose real work (the save) already succeeded.
196
- log(`aegis: could not append to ${file}: ${err && err.message}`);
197
- cache = null;
198
- return entry;
199
- }
200
- }
201
-
202
- /** Append one event. `kind` must be one `xp.js` pays for, or it pays zero. */
203
- function award(kind, fields = {}) {
204
- const t = typeof fields.t === 'number' && fields.t ? fields.t : now();
205
- const entry = xp.makeEntry(kind, Object.assign({}, fields, { t }), { t });
206
- return appendLine(entry);
207
- }
208
-
209
- /**
210
- * Award one event BY NAME, refusing anything `xp.js` does not pay for.
211
- *
212
- * `award()` above is the internal path: its callers are hooks that already
213
- * know which kind they are recording. This is the externally reachable one
214
- * (`aegis:avatarAward`), so it is the one that must not be a
215
- * generic "write a line into the ledger" bridge: an unknown kind is refused
216
- * with a reason rather than written as a zero-XP line, which keeps the ledger
217
- * a record of priced events only. `xp` is never accepted from the caller —
218
- * it is derived by replay at read time (`state()`), so a renderer cannot
219
- * propose a level.
220
- */
221
- function awardEvent(kind, fields = {}) {
222
- const name = typeof kind === 'string' ? kind : '';
223
- if (!Object.prototype.hasOwnProperty.call(xp.XP_TABLE, name)) {
224
- return { ok: false, reason: `unknown avatar event "${name}"` };
225
- }
226
- const safe = {};
227
- for (const key of ['ref', 'source', 'session', 'turn']) {
228
- if (fields && fields[key] != null) safe[key] = String(fields[key]);
229
- }
230
- const entry = award(name, safe);
231
- return { ok: true, kind: name, xp: xp.xpFor(name), entry };
232
- }
233
-
234
- // --- persona document ----------------------------------------
235
- // The persona is read and written ONLY here, by main. Both directions run
236
- // through persona.js validation, so a hand-edited or imported file is
237
- // repaired with warnings rather than trusted, and the identity/register text
238
- // it carries is re-sanitized on the way in (the storage boundary) AND on the
239
- // way out into a prompt (register.js, the use boundary).
240
-
241
- /**
242
- * Read `<userData>/avatar/persona.json`, validated. Never throws: a missing
243
- * file is the default persona, an unreadable/corrupt one is the default
244
- * persona plus a reported reason — the companion cannot be taken down by a
245
- * bad document, the same way a corrupt ledger line cannot.
246
- */
247
- function readPersona() {
248
- let raw = null;
249
- let exists = false;
250
- let error = null;
251
- try {
252
- raw = JSON.parse(fs.readFileSync(pFile, 'utf8'));
253
- exists = true;
254
- } catch (err) {
255
- if (err && err.code !== 'ENOENT') {
256
- error = (err && err.message) || 'unreadable';
257
- log(`aegis: could not read ${pFile}: ${error}`);
258
- }
259
- }
260
- const validated = personaModule.validate(raw);
261
- return {
262
- persona: validated.persona,
263
- warnings: validated.warnings ? validated.warnings.slice() : [],
264
- exists,
265
- error,
266
- file: pFile,
267
- };
268
- }
269
-
270
- /**
271
- * Merge a partial persona onto the one on disk and persist it atomically
272
- * (tmp + rename, 0600, `mkdir -p`). Returns the same shape as readPersona().
273
- *
274
- * Write-then-revalidate, in that order: `update()` validates the merge BEFORE
275
- * anything touches the filesystem, so a patch that cannot be repaired is
276
- * never written over a persona the user already had.
277
- */
278
- function writePersona(patch) {
279
- const current = readPersona();
280
- const next = personaModule.update(current.persona, patch);
281
- const record = { ...next.persona, schema: personaModule.SCHEMA_VERSION };
282
- fs.mkdirSync(path.dirname(pFile), { recursive: true, mode: 0o700 });
283
- const tmp = `${pFile}.tmp-${process.pid}`;
284
- fs.writeFileSync(tmp, JSON.stringify(record, null, 2), { mode: 0o600 });
285
- fs.renameSync(tmp, pFile);
286
- try { fs.chmodSync(pFile, 0o600); } catch {}
287
- return {
288
- ...readPersona(),
289
- warnings: (next.warnings || []).slice(),
290
- saved: true,
291
- };
292
- }
293
-
294
- /**
295
- * Record that a memory ref exists in the cloud, with the content currently
296
- * under it. Returns what the *save* was, in the vocabulary `xp.js` prices:
297
- *
298
- * 'new' — an id we have never seen: a durable save (`memory.saved`)
299
- * 'same' — the same id AND the same content: an upsert, the fact
300
- * re-observed (`memory.reinforced`)
301
- * 'changed' — the same id carrying different text: we replaced an entry
302
- * (`memory.corrected`)
303
- *
304
- * Ids are aegis1's identity (`ON CONFLICT (user_id, id)`), so this is the
305
- * server's own notion of "the same entry", not a heuristic over prose.
306
- */
307
- function observe(ref, text) {
308
- if (ref == null || ref === '') return 'new';
309
- const id = String(ref);
310
- const digest = fingerprint(text);
311
- const prior = digests.get(id);
312
- const known = live.has(id);
313
- digests.set(id, digest);
314
- live.add(id);
315
- if (prior === undefined) return known ? 'same' : 'new';
316
- return prior === digest ? 'same' : 'changed';
317
- }
318
-
319
- /** Refs that currently exist, as far as this process knows. Null = never looked. */
320
- function liveRefs() {
321
- if (!live.size) return null;
322
- const set = new Set(live);
323
- for (const ref of gone) set.delete(ref);
324
- return set;
325
- }
326
-
327
- /**
328
- * Derive the current state: replay → level → capabilities, with the `AEGIS_*`
329
- * env overrides applied (they win, so a headless run's breadth is not decided
330
- * by someone's XP).
331
- */
332
- function state(opts = {}) {
333
- const session = opts.session == null ? null : opts.session;
334
- const parsed = readParsed();
335
- const heldRec = session != null ? held.get(session) || null : null;
336
- const derived = xp.evaluate(parsed.entries, {
337
- liveRefs: liveRefs(),
338
- held: heldRec,
339
- session,
340
- });
341
- const overridden = level.applyEnvOverrides(level.capabilities(derived.level), opts.env || env);
342
- // Remember what the user was shown, so a later reconcile cannot make the
343
- // level tick downwards mid-session (§1.4).
344
- if (session != null) held.set(session, xp.nextHeld(derived, session));
345
- return Object.assign({}, derived, {
346
- capabilities: overridden.caps,
347
- envIgnored: overridden.ignored,
348
- ledger: { file, entries: parsed.entries.length, corrupt: parsed.corrupt || 0 },
349
- });
350
- }
351
-
352
- /** Just the caps object — the ONE thing turn assembly reads (§2). */
353
- function capabilities(opts = {}) {
354
- return state(opts).capabilities;
355
- }
356
-
357
- /** Award a durable cloud save, classified by the observation index. */
358
- function awardSave(entry = {}, fields = {}) {
359
- const ref = entry && entry.id != null ? String(entry.id) : null;
360
- const text = entry && (entry.content != null ? entry.content : entry.text);
361
- const klass = observe(ref, text);
362
- const kind =
363
- klass === 'new' ? 'memory.saved' : klass === 'changed' ? 'memory.corrected' : 'memory.reinforced';
364
- const written = award(
365
- kind,
366
- Object.assign({ ref, source: entry && entry.source }, fields)
367
- );
368
- return { kind, ref: ref, class: klass, entry: written };
369
- }
370
-
371
- /** Award an offline save that landed in the local queue instead of the cloud. */
372
- function awardQueued(entry = {}, fields = {}) {
373
- const ref = entry && entry.id != null ? String(entry.id) : null;
374
- observe(ref, entry && (entry.content != null ? entry.content : entry.text));
375
- const written = award('memory.queued', Object.assign({ ref, source: entry && entry.source }, fields));
376
- return { kind: 'memory.queued', ref, entry: written };
377
- }
378
-
379
- /**
380
- * Award the recalls a turn actually injected. Capped at
381
- * `xp.RECALL_PER_TURN_CAP` *lines*, so the ledger never carries a burst of
382
- * unpaid events: breadth is what a level buys, XP is not. The returned count
383
- * is "how many paid", not "how many were injected".
384
- */
385
- function awardRecalls(entries, opts = {}) {
386
- const list = Array.isArray(entries) ? entries : [];
387
- const capped = list.slice(0, xp.RECALL_PER_TURN_CAP);
388
- for (const entry of capped) {
389
- observe(entry && entry.id, entry && (entry.content != null ? entry.content : entry.text));
390
- award('memory.recalled', {
391
- ref: entry && entry.id != null ? String(entry.id) : null,
392
- session: opts.session,
393
- turn: opts.turn,
394
- });
395
- }
396
- return { awarded: capped.length, injected: list.length };
397
- }
398
-
399
- /**
400
- * Award an import batch. Capped per source per call at
401
- * `xp.IMPORT_PER_SOURCE_CAP` — the same ceiling the replay applies ledger-wide,
402
- * enforced here too so a ten-tool import cannot write 100k lines.
403
- */
404
- function awardImports(entries, opts = {}) {
405
- const list = Array.isArray(entries) ? entries : [];
406
- const capped = list.slice(0, xp.IMPORT_PER_SOURCE_CAP);
407
- for (const entry of capped) {
408
- observe(entry && entry.id, entry && (entry.content != null ? entry.content : entry.text));
409
- award('memory.imported', {
410
- ref: entry && entry.id != null ? String(entry.id) : null,
411
- source: opts.source,
412
- session: opts.session,
413
- });
414
- }
415
- return { awarded: capped.length, injected: list.length };
416
- }
417
-
418
- /**
419
- * The only way recall credit is ever dropped (§1.4): an entry the caller knows
420
- * is gone. Nothing in the desktop deletes memory yet — the per-holder forget
421
- * surface arrives with Phases 26–29 — so this is the seam, exercised by tests
422
- * today and by that surface later. Savings deliberately survive: you did that
423
- * work, and it stays done.
424
- */
425
- function markGone(refs) {
426
- const list = Array.isArray(refs) ? refs : [refs];
427
- for (const ref of list) {
428
- if (ref != null && ref !== '') gone.add(String(ref));
429
- }
430
- return gone.size;
431
- }
432
-
433
- /**
434
- * Boot check: sweep the whole level range through `level.js`'s own invariant
435
- * checker. main() calls this before it hands the caps to anything, and drops
436
- * the avatar entirely if it throws — a capabilities object that weakens the
437
- * write/shell/network gate must not be used for anything, least of all as an
438
- * excuse to keep running with it.
439
- */
440
- function verifyAtBoot() {
441
- const violations = level.verifyInvariants();
442
- level.assertCarveOuts(level.capabilities(1));
443
- return { ok: violations.length === 0, violations };
444
- }
445
-
446
- return {
447
- dir,
448
- file,
449
- read: readParsed,
450
- append: award,
451
- award,
452
- observe,
453
- awardSave,
454
- awardQueued,
455
- awardRecalls,
456
- awardImports,
457
- markGone,
458
- liveRefs,
459
- state,
460
- capabilities,
461
- verifyAtBoot,
462
- };
463
- }
464
-
465
- module.exports = {
466
- LEDGER_DIR,
467
- LEDGER_FILE,
468
- avatarHome,
469
- ledgerPath,
470
- fingerprint,
471
- memoryEntryId,
472
- normalizeMemoryEntry,
473
- createAvatarStore,
474
- };
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),crypto=require("node:crypto"),xp=require("./xp.js"),level=require("./level.js"),personaModule=require("./persona.js"),LEDGER_DIR="avatar",LEDGER_FILE="ledger.jsonl",PERSONA_FILE="persona.json",DIGEST_CHARS=16;function avatarHome(e){return path.join(e,LEDGER_DIR)}function ledgerPath(e){return path.join(avatarHome(e),LEDGER_FILE)}function personaPath(e){return path.join(avatarHome(e),PERSONA_FILE)}function fingerprint(e){return crypto.createHash("sha1").update(String(null==e?"":e)).digest("hex").slice(0,DIGEST_CHARS)}function memoryEntryId(e){return`note-${fingerprint(`${e&&e.source||"aegis-desktop"}|${String(e&&(null!=e.content?e.content:e.text)||"").trim().toLowerCase()}`)}`}function normalizeMemoryEntry(e){if(!e||"object"!=typeof e)return e;const t="string"==typeof e.content&&e.content?e.content:"string"==typeof e.text?e.text:"";if(!t)return e;const r=Object.assign({},e);return r.content||(r.content=t),r.role||(r.role="user"),r.source||(r.source="aegis-desktop"),r.id||(r.id=memoryEntryId(r)),r}function createAvatarStore({dir:e,now:t=(()=>Date.now()),env:r=process.env,log:n=(()=>{})}={}){if(!e||"string"!=typeof e)throw new Error("createAvatarStore: a user-data directory is required");const o=ledgerPath(e);let s=null;const i=new Map,a=new Set,c=new Map,u=new Set;function l(){try{const e=fs.statSync(o);if(s&&s.size===e.size&&s.mtimeMs===e.mtimeMs)return s.parsed;const t=xp.parseLedger(fs.readFileSync(o,"utf8"));return s={size:e.size,mtimeMs:e.mtimeMs,parsed:t},t}catch(e){return e&&"ENOENT"===e.code?{entries:[],corrupt:0}:(n(`aegis: could not read ${o}: ${e&&e.message}`),{entries:[],corrupt:0,error:e&&e.message||"unreadable"})}}function d(e,r={}){const i="number"==typeof r.t&&r.t?r.t:t();return function(e){const t=`${JSON.stringify(e)}\n`;try{return fs.mkdirSync(path.dirname(o),{recursive:!0,mode:448}),fs.appendFileSync(o,t),s&&(s={size:s.size+Buffer.byteLength(t),mtimeMs:0,parsed:{entries:s.parsed.entries.concat([e]),corrupt:s.parsed.corrupt}}),e}catch(t){return n(`aegis: could not append to ${o}: ${t&&t.message}`),s=null,e}}(xp.makeEntry(e,Object.assign({},r,{t:i}),{t:i}))}function f(e,t){if(null==e||""===e)return"new";const r=String(e),n=fingerprint(t),o=c.get(r),s=a.has(r);return c.set(r,n),a.add(r),void 0===o?s?"same":"new":o===n?"same":"changed"}function p(){if(!a.size)return null;const e=new Set(a);for(const t of u)e.delete(t);return e}function m(e={}){const t=null==e.session?null:e.session,n=l(),s=null!=t&&i.get(t)||null,a=xp.evaluate(n.entries,{liveRefs:p(),held:s,session:t}),c=level.applyEnvOverrides(level.capabilities(a.level),e.env||r);return null!=t&&i.set(t,xp.nextHeld(a,t)),Object.assign({},a,{capabilities:c.caps,envIgnored:c.ignored,ledger:{file:o,entries:n.entries.length,corrupt:n.corrupt||0}})}return{dir:e,file:o,read:l,append:d,award:d,observe:f,awardSave:function(e={},t={}){const r=e&&null!=e.id?String(e.id):null,n=f(r,e&&(null!=e.content?e.content:e.text)),o="new"===n?"memory.saved":"changed"===n?"memory.corrected":"memory.reinforced";return{kind:o,ref:r,class:n,entry:d(o,Object.assign({ref:r,source:e&&e.source},t))}},awardQueued:function(e={},t={}){const r=e&&null!=e.id?String(e.id):null;return f(r,e&&(null!=e.content?e.content:e.text)),{kind:"memory.queued",ref:r,entry:d("memory.queued",Object.assign({ref:r,source:e&&e.source},t))}},awardRecalls:function(e,t={}){const r=Array.isArray(e)?e:[],n=r.slice(0,xp.RECALL_PER_TURN_CAP);for(const e of n)f(e&&e.id,e&&(null!=e.content?e.content:e.text)),d("memory.recalled",{ref:e&&null!=e.id?String(e.id):null,session:t.session,turn:t.turn});return{awarded:n.length,injected:r.length}},awardImports:function(e,t={}){const r=Array.isArray(e)?e:[],n=r.slice(0,xp.IMPORT_PER_SOURCE_CAP);for(const e of n)f(e&&e.id,e&&(null!=e.content?e.content:e.text)),d("memory.imported",{ref:e&&null!=e.id?String(e.id):null,source:t.source,session:t.session});return{awarded:n.length,injected:r.length}},markGone:function(e){const t=Array.isArray(e)?e:[e];for(const e of t)null!=e&&""!==e&&u.add(String(e));return u.size},liveRefs:p,state:m,capabilities:function(e={}){return m(e).capabilities},verifyAtBoot:function(){const e=level.verifyInvariants();return level.assertCarveOuts(level.capabilities(1)),{ok:0===e.length,violations:e}}}}module.exports={LEDGER_DIR:LEDGER_DIR,LEDGER_FILE:LEDGER_FILE,avatarHome:avatarHome,ledgerPath:ledgerPath,fingerprint:fingerprint,memoryEntryId:memoryEntryId,normalizeMemoryEntry:normalizeMemoryEntry,createAvatarStore:createAvatarStore};
@@ -1,40 +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
- * tiers.js — the tier bands, alone in their own module on purpose.
10
- *
11
- * Both `xp.js` (which needs the tier name for a projection) and `level.js`
12
- * (which needs the band to decide unlocks) depend on this table. Putting it in
13
- * either one would make the other require it and create a cycle the moment
14
- * either grew a second import — so the shared vocabulary lives by itself and
15
- * both read it. Nothing here imports anything.
16
- */
17
-
18
- const TIERS = Object.freeze([
19
- Object.freeze({ min: 1, max: 4, name: 'Familiar', blink: 'familiar' }),
20
- Object.freeze({ min: 5, max: 9, name: 'Trusted', blink: 'trusted' }),
21
- Object.freeze({ min: 10, max: 19, name: 'Companion', blink: 'companion' }),
22
- Object.freeze({ min: 20, max: 34, name: 'Confidant', blink: 'confidant' }),
23
- Object.freeze({ min: 35, max: Number.POSITIVE_INFINITY, name: 'Archivist', blink: 'archivist' }),
24
- ]);
25
-
26
- /** The band a level falls in. Levels below 1 are clamped to the first band. */
27
- function tierFor(level) {
28
- const n = Math.max(1, Math.floor(typeof level === 'number' && Number.isFinite(level) ? level : 1));
29
- for (const band of TIERS) {
30
- if (n >= band.min && n <= band.max) return band;
31
- }
32
- return TIERS[TIERS.length - 1];
33
- }
34
-
35
- /** Index of the band (0-based) — handy for cosmetics rarity. */
36
- function tierIndex(level) {
37
- return TIERS.indexOf(tierFor(level));
38
- }
39
-
40
- module.exports = { TIERS, tierFor, tierIndex };
3
+ "use strict";const TIERS=Object.freeze([Object.freeze({min:1,max:4,name:"Familiar",blink:"familiar"}),Object.freeze({min:5,max:9,name:"Trusted",blink:"trusted"}),Object.freeze({min:10,max:19,name:"Companion",blink:"companion"}),Object.freeze({min:20,max:34,name:"Confidant",blink:"confidant"}),Object.freeze({min:35,max:Number.POSITIVE_INFINITY,name:"Archivist",blink:"archivist"})]);function tierFor(e){const n=Math.max(1,Math.floor("number"==typeof e&&Number.isFinite(e)?e:1));for(const e of TIERS)if(n>=e.min&&n<=e.max)return e;return TIERS[TIERS.length-1]}function tierIndex(e){return TIERS.indexOf(tierFor(e))}module.exports={TIERS:TIERS,tierFor:tierFor,tierIndex:tierIndex};