aegisone 1.0.32 → 1.0.34

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/README.md +1 -1
  2. package/bin/aegis.js +322 -1
  3. package/package.json +5 -4
  4. package/scripts/bump.mjs +211 -1
  5. package/scripts/bundle.js +129 -1
  6. package/scripts/predist.mjs +976 -1
  7. package/src/child.js +285 -1
  8. package/src/dispatch.js +269 -1
  9. package/src/doctor.js +639 -1
  10. package/src/host.js +111 -1
  11. package/src/permissions.js +383 -1
  12. package/src/probes.js +159 -1
  13. package/src/release.js +409 -1
  14. package/vendor/cli/package.json +7 -3
  15. package/vendor/cli/scripts/check.mjs +52 -1
  16. package/vendor/cli/scripts/demo.mjs +94 -1
  17. package/vendor/cli/scripts/predist.mjs +75 -1
  18. package/vendor/cli/scripts/runtests.mjs +56 -1
  19. package/vendor/cli/scripts/seal-gate.mjs +74 -1
  20. package/vendor/cli/src/agents.js +139 -1
  21. package/vendor/cli/src/app.js +2957 -1
  22. package/vendor/cli/src/art.js +289 -1
  23. package/vendor/cli/src/chatflow.js +3023 -1
  24. package/vendor/cli/src/checkpoint.js +90 -1
  25. package/vendor/cli/src/clipboard.js +424 -1
  26. package/vendor/cli/src/cloudsync.js +528 -1
  27. package/vendor/cli/src/commands.js +4089 -1
  28. package/vendor/cli/src/config.js +581 -1
  29. package/vendor/cli/src/connect.js +349 -1
  30. package/vendor/cli/src/credentials.js +33 -1
  31. package/vendor/cli/src/deps.js +232 -1
  32. package/vendor/cli/src/devrun.js +187 -1
  33. package/vendor/cli/src/diff.js +333 -1
  34. package/vendor/cli/src/diffview.js +296 -1
  35. package/vendor/cli/src/engine.js +297 -1
  36. package/vendor/cli/src/entitlement.js +355 -1
  37. package/vendor/cli/src/events.js +707 -1
  38. package/vendor/cli/src/export.js +67 -1
  39. package/vendor/cli/src/filepreview.js +153 -1
  40. package/vendor/cli/src/fingerprint.js +592 -1
  41. package/vendor/cli/src/format.js +259 -1
  42. package/vendor/cli/src/fuzzy.js +119 -1
  43. package/vendor/cli/src/history.js +423 -1
  44. package/vendor/cli/src/init.js +175 -1
  45. package/vendor/cli/src/input.js +139 -1
  46. package/vendor/cli/src/keys.js +183 -1
  47. package/vendor/cli/src/markdown.js +306 -1
  48. package/vendor/cli/src/models.js +507 -1
  49. package/vendor/cli/src/naming.js +57 -1
  50. package/vendor/cli/src/overlays.js +462 -1
  51. package/vendor/cli/src/panels.js +1418 -1
  52. package/vendor/cli/src/ping.js +226 -1
  53. package/vendor/cli/src/presence.js +238 -1
  54. package/vendor/cli/src/render.js +516 -1
  55. package/vendor/cli/src/screen.js +518 -1
  56. package/vendor/cli/src/screens.js +896 -1
  57. package/vendor/cli/src/secret.js +59 -1
  58. package/vendor/cli/src/securefs.js +359 -1
  59. package/vendor/cli/src/settings.js +155 -1
  60. package/vendor/cli/src/shared.js +52 -1
  61. package/vendor/cli/src/sharedpaths.js +53 -1
  62. package/vendor/cli/src/signup.js +156 -1
  63. package/vendor/cli/src/summarize.js +95 -1
  64. package/vendor/cli/src/sysdiag.js +585 -1
  65. package/vendor/cli/src/system.js +40 -1
  66. package/vendor/cli/src/theme.js +570 -1
  67. package/vendor/cli/src/title.js +220 -1
  68. package/vendor/cli/src/todos.js +115 -1
  69. package/vendor/cli/src/tokens.js +263 -1
  70. package/vendor/cli/src/topup.js +210 -1
  71. package/vendor/cli/src/update.js +191 -1
  72. package/vendor/cli/vendor/client/aegis.js +2441 -1
  73. package/vendor/cli/vendor/client/attest.js +518 -1
  74. package/vendor/cli/vendor/client/authorship-key.js +410 -1
  75. package/vendor/cli/vendor/client/auto-provision.js +134 -1
  76. package/vendor/cli/vendor/client/brain-catalog.js +268 -1
  77. package/vendor/cli/vendor/client/byok-catalog.js +199 -1
  78. package/vendor/cli/vendor/client/catalog-client.js +487 -1
  79. package/vendor/cli/vendor/client/conversation-export.js +177 -1
  80. package/vendor/cli/vendor/client/credentials.js +494 -1
  81. package/vendor/cli/vendor/client/device-fingerprint.js +141 -1
  82. package/vendor/cli/vendor/client/drive-connect.js +110 -1
  83. package/vendor/cli/vendor/client/drive-upload.js +234 -1
  84. package/vendor/cli/vendor/client/env-file.js +1273 -1
  85. package/vendor/cli/vendor/client/fingerprint.js +1064 -1
  86. package/vendor/cli/vendor/client/foreign-memory.js +669 -1
  87. package/vendor/cli/vendor/client/google-signin.js +133 -1
  88. package/vendor/cli/vendor/client/hooks.js +430 -1
  89. package/vendor/cli/vendor/client/model-discovery.js +373 -1
  90. package/vendor/cli/vendor/client/naming.js +283 -1
  91. package/vendor/cli/vendor/client/platform.js +937 -1
  92. package/vendor/cli/vendor/client/prefs.js +351 -1
  93. package/vendor/cli/vendor/client/presence-constants.js +107 -1
  94. package/vendor/cli/vendor/client/presence.js +438 -1
  95. package/vendor/cli/vendor/client/record-vault.js +1055 -3
  96. package/vendor/cli/vendor/client/session-store.js +575 -1
  97. package/vendor/cli/vendor/client/topup.js +297 -1
  98. package/vendor/cli/vendor/client/touch.js +458 -1
  99. package/vendor/cli/vendor/client/update.js +763 -1
  100. package/vendor/cli/vendor/client/user-models.js +381 -1
  101. package/vendor/cli/vendor/desktop/lib/local/agents.js +105 -1
  102. package/vendor/cli/vendor/desktop/lib/local/attachments.js +276 -1
  103. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1045 -1
  104. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1028 -1
  105. package/vendor/cli/vendor/desktop/lib/local/context.js +125 -1
  106. package/vendor/cli/vendor/desktop/lib/local/engine.js +3666 -1
  107. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +660 -1
  108. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +228 -1
  109. package/vendor/cli/vendor/desktop/lib/local/local.js +2145 -1
  110. package/vendor/cli/vendor/desktop/lib/local/prompt.js +280 -1
  111. package/vendor/cli/vendor/desktop/lib/local/queue.js +560 -1
  112. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +238 -1
  113. package/vendor/cli/vendor/desktop/lib/local/spill.js +75 -1
  114. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +300 -1
  115. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +235 -1
  116. package/vendor/cli/vendor/desktop/lib/settings.js +890 -1
  117. package/vendor/cli/vendor/desktop/renderer/usage.js +1239 -1
  118. package/vendor/cli/vendor/hosts/install.js +638 -1
  119. package/vendor/cli/vendor/hosts/openai-shim.js +515 -1
  120. package/vendor/cli/vendor/hosts/spec.js +164 -1
  121. package/vendor/cli/vendor/hosts/targets.js +346 -1
  122. package/vendor/cli/vendor/mcp/server.js +221 -1
  123. package/vendor/cli/vendor/mcp/tools.js +408 -1
  124. package/vendor/cli/vendor/one/src/child.js +285 -1
  125. package/vendor/cli/vendor/one/src/permissions.js +383 -1
  126. package/vendor/desktop/bin/aegis.js +32 -1
  127. package/vendor/desktop/lib/account-key.js +56 -1
  128. package/vendor/desktop/lib/auto.js +461 -1
  129. package/vendor/desktop/lib/avatar/companion.js +698 -1
  130. package/vendor/desktop/lib/avatar/cosmetics.js +532 -1
  131. package/vendor/desktop/lib/avatar/events.js +344 -1
  132. package/vendor/desktop/lib/avatar/holder-turn.js +350 -1
  133. package/vendor/desktop/lib/avatar/holders.js +612 -1
  134. package/vendor/desktop/lib/avatar/identity.js +641 -1
  135. package/vendor/desktop/lib/avatar/level.js +368 -1
  136. package/vendor/desktop/lib/avatar/mirror.js +524 -1
  137. package/vendor/desktop/lib/avatar/persona.js +388 -1
  138. package/vendor/desktop/lib/avatar/profile.js +977 -1
  139. package/vendor/desktop/lib/avatar/register.js +307 -1
  140. package/vendor/desktop/lib/avatar/store.js +472 -1
  141. package/vendor/desktop/lib/avatar/tiers.js +38 -1
  142. package/vendor/desktop/lib/avatar/transfer.js +415 -1
  143. package/vendor/desktop/lib/avatar/turn.js +216 -1
  144. package/vendor/desktop/lib/avatar/voice.js +328 -1
  145. package/vendor/desktop/lib/avatar/xp.js +404 -1
  146. package/vendor/desktop/lib/deep-link.js +120 -1
  147. package/vendor/desktop/lib/fingerprint.js +347 -2
  148. package/vendor/desktop/lib/google-connect.js +323 -1
  149. package/vendor/desktop/lib/local/agents.js +105 -1
  150. package/vendor/desktop/lib/local/attachments.js +276 -1
  151. package/vendor/desktop/lib/local/autonomous.js +1045 -1
  152. package/vendor/desktop/lib/local/claude-pro.js +1028 -1
  153. package/vendor/desktop/lib/local/context.js +125 -1
  154. package/vendor/desktop/lib/local/engine.js +3666 -1
  155. package/vendor/desktop/lib/local/entitlement.js +660 -1
  156. package/vendor/desktop/lib/local/git-scope.js +228 -1
  157. package/vendor/desktop/lib/local/local.js +2145 -1
  158. package/vendor/desktop/lib/local/prompt.js +280 -1
  159. package/vendor/desktop/lib/local/queue.js +560 -1
  160. package/vendor/desktop/lib/local/session-rounds.js +238 -1
  161. package/vendor/desktop/lib/local/spill.js +75 -1
  162. package/vendor/desktop/lib/local/telemetry.js +470 -1
  163. package/vendor/desktop/lib/local/turn-guard.js +300 -1
  164. package/vendor/desktop/lib/local/worktree-lock.js +235 -1
  165. package/vendor/desktop/lib/provider-key-mirror.js +252 -1
  166. package/vendor/desktop/lib/quick-launcher.js +84 -1
  167. package/vendor/desktop/lib/settings.js +890 -1
  168. package/vendor/desktop/lib/sync/memory-queue.js +60 -1
  169. package/vendor/desktop/lib/sync/persist-gate.js +148 -1
  170. package/vendor/desktop/lib/sync/sessions.js +106 -1
  171. package/vendor/desktop/lib/window-state.js +66 -1
  172. package/vendor/desktop/package.json +5 -3
  173. package/vendor/desktop/preload.js +679 -1
  174. package/vendor/desktop/renderer/app.js +7250 -1
  175. package/vendor/desktop/renderer/avatar/assemble.js +335 -1
  176. package/vendor/desktop/renderer/avatar/avatar.js +380 -1
  177. package/vendor/desktop/renderer/avatar/cards.js +141 -1
  178. package/vendor/desktop/renderer/avatar/hud.js +206 -1
  179. package/vendor/desktop/renderer/avatar/machine.js +213 -1
  180. package/vendor/desktop/renderer/avatar/pane.js +439 -1
  181. package/vendor/desktop/renderer/avatar/parts.js +437 -1
  182. package/vendor/desktop/renderer/budget.js +172 -1
  183. package/vendor/desktop/renderer/companion.js +223 -1
  184. package/vendor/desktop/renderer/diff.js +359 -1
  185. package/vendor/desktop/renderer/diffview.js +336 -1
  186. package/vendor/desktop/renderer/filepreview.js +211 -1
  187. package/vendor/desktop/renderer/fingerprint.js +789 -3
  188. package/vendor/desktop/renderer/markdown.js +168 -1
  189. package/vendor/desktop/renderer/provider-mark.js +311 -1
  190. package/vendor/desktop/renderer/provider-toolbar.js +134 -1
  191. package/vendor/desktop/renderer/providers.js +259 -1
  192. package/vendor/desktop/renderer/quick.js +285 -1
  193. package/vendor/desktop/renderer/stream-policy.js +387 -1
  194. package/vendor/desktop/renderer/transcript-view.js +323 -1
  195. package/vendor/desktop/renderer/usage.js +1239 -1
  196. package/vendor/desktop/vendor/aegis.js +2441 -1
  197. package/vendor/desktop/vendor/attest.js +518 -1
  198. package/vendor/desktop/vendor/authorship-key.js +410 -1
  199. package/vendor/desktop/vendor/auto-provision.js +134 -1
  200. package/vendor/desktop/vendor/brain-catalog.js +268 -1
  201. package/vendor/desktop/vendor/byok-catalog.js +199 -1
  202. package/vendor/desktop/vendor/catalog-client.js +487 -1
  203. package/vendor/desktop/vendor/conversation-export.js +177 -1
  204. package/vendor/desktop/vendor/credentials.js +494 -1
  205. package/vendor/desktop/vendor/device-fingerprint.js +141 -1
  206. package/vendor/desktop/vendor/drive-connect.js +110 -1
  207. package/vendor/desktop/vendor/drive-upload.js +234 -1
  208. package/vendor/desktop/vendor/env-file.js +1273 -1
  209. package/vendor/desktop/vendor/fingerprint.js +1064 -1
  210. package/vendor/desktop/vendor/foreign-memory.js +669 -1
  211. package/vendor/desktop/vendor/google-signin.js +133 -1
  212. package/vendor/desktop/vendor/hooks.js +430 -1
  213. package/vendor/desktop/vendor/model-discovery.js +373 -1
  214. package/vendor/desktop/vendor/naming.js +283 -1
  215. package/vendor/desktop/vendor/platform.js +937 -1
  216. package/vendor/desktop/vendor/prefs.js +351 -1
  217. package/vendor/desktop/vendor/presence-constants.js +107 -1
  218. package/vendor/desktop/vendor/presence.js +438 -1
  219. package/vendor/desktop/vendor/record-vault.js +1055 -3
  220. package/vendor/desktop/vendor/session-store.js +575 -1
  221. package/vendor/desktop/vendor/topup.js +297 -1
  222. package/vendor/desktop/vendor/touch.js +458 -1
  223. package/vendor/desktop/vendor/update.js +763 -1
  224. package/vendor/desktop/vendor/user-models.js +381 -1
  225. package/LICENSE +0 -661
  226. package/SOURCE-OFFER.txt +0 -9
@@ -1,3 +1,474 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
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};
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
+ };
@@ -1,3 +1,40 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
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};
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 };