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,417 @@
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"),holders=require("./holders.js"),identity=require("./identity.js"),mirror=require("./mirror.js"),personaModule=require("./persona.js"),profileModule=require("./profile.js"),EXPORT_FILE="aegis-persona.json",EXPORT_KIND="aegis-persona",EXPORT_SCHEMA=1,PERSONA_PARTS=Object.freeze(["schema","identity","presentation","expressions","voice","register","appearance"]),MIN_LEAK_CHARS=8;function mintId(e){const r="string"==typeof e&&e?e:crypto.randomBytes(16).toString("hex");return identity.mintHolderId((e=>crypto.createHash("sha1").update(e).digest()),r)||`h_${crypto.createHash("sha1").update(r).digest("hex").slice(0,identity.FINGERPRINT_LENGTH)}`}function stringsIn(e,r=[],t=0){if(t>8||null==e)return r;if("string"==typeof e)return r.push(e),r;if("object"!=typeof e)return r;for(const n of Array.isArray(e)?e:Object.values(e))stringsIn(n,r,t+1);return r}function assertNoMemory(e,r={}){const t=JSON.stringify(null==e?null:e),n=[],o=[];for(const e of Array.isArray(r.entries)?r.entries:[]){const r=e&&null!=e.id?String(e.id):"";r.length>=MIN_LEAK_CHARS&&o.push({what:"entry id",value:r});const t=e&&(null!=e.content?e.content:e.text);"string"==typeof t&&t.trim().length>=MIN_LEAK_CHARS&&o.push({what:"entry text",value:t.trim()})}for(const e of Array.isArray(r.entryIds)?r.entryIds:[])String(e).length>=MIN_LEAK_CHARS&&o.push({what:"entry id",value:String(e)});r.fingerprint&&o.push({what:"fingerprint",value:String(r.fingerprint)});for(const e of Array.isArray(r.keys)?r.keys:[])String(e).length>=MIN_LEAK_CHARS&&o.push({what:"key material",value:String(e)});for(const e of o)t.includes(e.value)&&n.push(`${e.what} leaked: ${e.value.slice(0,24)}…`);if(r.fingerprint&&r.fingerprint.length>=MIN_LEAK_CHARS){const e=String(r.fingerprint).slice(0,MIN_LEAK_CHARS);t.includes(e)&&!n.some((e=>e.includes("fingerprint")))&&n.push("fingerprint prefix leaked")}return{ok:0===n.length,leaks:n}}function exportPersona(e,r={}){const t=e&&e.holderId?String(e.holderId):null;if(!t||!identity.HOLDER_ID_RE.test(t))return{ok:!1,reason:"exportPersona: expected a loaded holder state",doc:null};const n=personaModule.validate(e.persona),o={};for(const e of PERSONA_PARTS)void 0!==n.persona[e]&&(o[e]=n.persona[e]);o.identity=Object.assign({},o.identity,{holderId:t});const s=Array.isArray(e.ledger)?e.ledger:[],i={};let a=null,d=null;for(const e of s){if(!e||"object"!=typeof e)continue;const r=String(e.kind||"unknown");i[r]=(i[r]||0)+1;const t=Number(e.t);Number.isFinite(t)&&(a=null===a?t:Math.min(a,t),d=null===d?t:Math.max(d,t))}const l=e.profile&&"object"==typeof e.profile?e.profile:{},c=Array.isArray(l.facets)?l.facets:[],u={schema:EXPORT_SCHEMA,kind:EXPORT_KIND,exportedAt:"number"==typeof r.now?r.now:0,attribution:{holderId:t,displayName:e.displayName||null},persona:o,ledger:{rows:s.length,level:Number.isFinite(Number(e.level))?Number(e.level):1,byKind:i,firstAt:a,lastAt:d},profile:{coldStart:Boolean(l.coldStart)||0===c.length,facetCount:c.length,budget:{tokens:profileModule.BUDGET_TOKENS,used:l.budget&&l.budget.used||0},facets:c.map((e=>({id:e.id,key:e.key,confidence:e.confidence,tokens:e.tokens,firstSeen:e.firstSeen,lastSeen:e.lastSeen})))}},p=assertNoMemory(u,{entries:r.entries,entryIds:c.flatMap((e=>Array.isArray(e.sources)?e.sources:[])),fingerprint:r.fingerprint||null,keys:r.keys});return p.ok?{ok:!0,doc:u,leaks:[],warnings:n.warnings||[]}:{ok:!1,reason:p.leaks.join("; "),leaks:p.leaks,doc:null}}function writeExport(e,r,t={}){const n=t.state||holders.loadState(e,r),o=(()=>{const r=holders.holderRow(holders.readRegistry(e),n.holderId);return r&&r.fingerprint?r.fingerprint:null})(),s=exportPersona(n,Object.assign({fingerprint:o},t));if(!s.ok)return{ok:!1,reason:s.reason,leaks:s.leaks||[],file:null,doc:null};const i=t.dest||path.join(String(e),EXPORT_FILE);fs.mkdirSync(path.dirname(i),{recursive:!0,mode:448});const a=`${i}.tmp-${process.pid}`;fs.writeFileSync(a,`${JSON.stringify(s.doc,null,2)}\n`,{mode:384}),fs.renameSync(a,i);try{fs.chmodSync(i,384)}catch{}return{ok:!0,file:i,doc:s.doc,leaks:[],warnings:s.warnings}}function readDoc(e){if("string"==typeof e)try{return JSON.parse(fs.readFileSync(e,"utf8"))}catch(e){return null}return e&&"object"==typeof e?e:null}function importPersona(e,r,t={}){const n="number"==typeof t.now?t.now:0,o=readDoc(r);if(!o||"object"!=typeof o)return{ok:!1,reason:"importPersona: expected a persona document"};const s=String(o.kind||"");if(s&&s!==EXPORT_KIND)return{ok:!1,reason:`importPersona: not an ${EXPORT_KIND} document (kind "${s}")`};if(!o.persona||"object"!=typeof o.persona)return{ok:!1,reason:"importPersona: document carries no persona"};const i="rebind"===t.mode?"rebind":"new",a=t.registry||holders.readRegistry(e);if("rebind"===i){const r=String(t.holderId||o.attribution&&o.attribution.holderId||"").trim().toLowerCase();if(!identity.HOLDER_ID_RE.test(r)||!holders.holderRow(a,r))return{ok:!1,reason:"importPersona: rebind needs an existing holder id"};if(!0!==t.confirm)return{ok:!1,reason:"importPersona: rebind requires an explicit confirm",requiresConfirm:!0};const n=holders.loadState(e,r,{registry:a}),s=personaModule.validate(Object.assign({},o.persona,{identity:Object.assign({},o.persona.identity,{holderId:r})}));!1!==t.persist&&holders.writePersona(e,r,s.persona);const d=holders.loadState(e,r,{registry:a});return{ok:!0,mode:i,holderId:r,created:!1,persona:s.persona,warnings:s.warnings||[],ledger:{before:n.ledger.length,after:d.ledger.length,imported:!1},level:d.level,xpImported:!1}}const d=(t.holderId&&identity.HOLDER_ID_RE.test(String(t.holderId))?String(t.holderId):null)||mintId(t.seed),l=holders.ensureHolder(e,{id:d,displayName:t.displayName||o.attribution&&o.attribution.displayName||void 0,now:n,registry:a,persist:!1!==t.persist}),c=l.row?l.row.id:d,u=personaModule.validate(Object.assign({},o.persona,{identity:Object.assign({},o.persona.identity,{holderId:c})}));!1!==t.persist&&holders.writePersona(e,c,u.persona);const p=holders.loadState(e,c,{registry:l.registry});return{ok:!0,mode:i,holderId:c,created:l.created,persona:u.persona,warnings:u.warnings||[],ledger:{before:0,after:p.ledger.length,imported:!1},level:p.level,xpImported:!1}}function listFiles(e){try{return fs.readdirSync(e).sort()}catch(e){return[]}}function forgetHolder(e,r,t={}){const n=String(null==r?"":r).trim().toLowerCase();if(!identity.HOLDER_ID_RE.test(n))return{ok:!1,reason:"forgetHolder: expected a holder id (h_ + 8-16 hex)",holderId:null};const o=t.registry||holders.readRegistry(e);if(!holders.holderRow(o,n)&&!0!==t.force)return{ok:!1,reason:`unknown holder ${n}`,holderId:n};const s="number"==typeof t.now?t.now:0,i=mirror.queueDelete(e,n,{t:s,reason:"holder-forgotten"}),a=holders.holderDir(e,n),d=listFiles(a);try{fs.rmSync(a,{recursive:!0,force:!0})}catch(e){return{ok:!1,reason:`could not remove ${a}: ${e&&e.message||"error"}`,holderId:n,queued:i}}const l=identity.removeHolder(o,n),c=(l.holders||[]).map((e=>e.id));let u=l.active;!u&&c.length&&(u=t.active&&c.includes(t.active)?t.active:c[0]);const p=holders.writeRegistry(e,Object.assign({},l,{active:u||null}));return{ok:!0,holderId:n,removed:{dir:a,files:d},queued:{sessions:i.sessions||mirror.scopeFor(n).sessions,duplicate:Boolean(i.duplicate)},active:p.active,registry:p,remaining:c}}module.exports={EXPORT_FILE:EXPORT_FILE,EXPORT_KIND:EXPORT_KIND,EXPORT_SCHEMA:EXPORT_SCHEMA,PERSONA_PARTS:PERSONA_PARTS,MIN_LEAK_CHARS:MIN_LEAK_CHARS,mintId:mintId,stringsIn:stringsIn,assertNoMemory:assertNoMemory,exportPersona:exportPersona,writeExport:writeExport,importPersona:importPersona,forgetHolder:forgetHolder};
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
+ * transfer.js — persona export, persona import and per-holder forget.
10
+ *
11
+ * A persona is taste. Memory is not. This file exists to keep those two apart
12
+ * across the one boundary where they would otherwise merge — moving a persona
13
+ * between holders and machines — and to make forgetting a holder actually mean
14
+ * it. Three claims, each a leg in `desktop/test/avatar-transfer.test.mjs`:
15
+ *
16
+ * 1. **Export strips memory.** `exportPersona()` writes an allowlist document
17
+ * (`schema`, `kind`, `attribution`, `persona`, and *summaries* of the ledger
18
+ * and profile) and then runs it through `assertNoMemory()`, which fails the
19
+ * export if any source entry's text, any entry id, or the holder's
20
+ * fingerprint appears anywhere in the serialised document. Facet `value`s
21
+ * are memory-derived prose and are dropped: what travels is the facet's
22
+ * *shape* (`id`, `key`, `confidence`, times), never the sentence the fold
23
+ * wrote. §5 is explicit that the export contains `holderId`, `ledger` and
24
+ * `profile` — and that any entry text is stripped — so the summaries are
25
+ * counts and levels, not rows.
26
+ *
27
+ * 2. **Import never imports XP.** A level is not a thing you can hand someone
28
+ * (§5). `importPersona()` ignores `doc.ledger` however loudly it claims a
29
+ * level, creates a **new holder by default**, writes only the persona, and
30
+ * returns the holder's real, freshly-read level — which is 1. Rebind mode
31
+ * (`{ mode:'rebind', confirm:true }`) writes taste onto an existing holder
32
+ * and leaves that holder's ledger *untouched*: adopting someone's taste must
33
+ * not cost you your own memory, in either direction.
34
+ *
35
+ * 3. **Forget is real, and it is per holder** (§7.3). `forgetHolder()` queues a
36
+ * cloud delete scoped to that holder's two reserved sessions (via
37
+ * `mirror.js`, so the request outlives the directory it deletes), removes
38
+ * the holder's directory, and drops its registry row. Every other holder's
39
+ * directory, rows and registry entry are untouched — asserted directly, in
40
+ * both directions, because "forget A" quietly forgetting B is the failure
41
+ * that would make this feature unshippable.
42
+ *
43
+ * Pure Node (fs + path + crypto), no Electron. The registry and the directory
44
+ * layout belong to `holders.js`; this module deliberately owns none of them.
45
+ */
46
+
47
+ const fs = require('node:fs');
48
+ const path = require('node:path');
49
+ const crypto = require('node:crypto');
50
+
51
+ const holders = require('./holders.js');
52
+ const identity = require('./identity.js');
53
+ const mirror = require('./mirror.js');
54
+ const personaModule = require('./persona.js');
55
+ const profileModule = require('./profile.js');
56
+
57
+ /** The shareable document's file name (§5) and its `kind` marker. */
58
+ const EXPORT_FILE = 'aegis-persona.json';
59
+ const EXPORT_KIND = 'aegis-persona';
60
+ const EXPORT_SCHEMA = 1;
61
+
62
+ /** Fields of a persona that are taste, and therefore travel. */
63
+ const PERSONA_PARTS = Object.freeze([
64
+ 'schema',
65
+ 'identity',
66
+ 'presentation',
67
+ 'expressions',
68
+ 'voice',
69
+ 'register',
70
+ 'appearance',
71
+ ]);
72
+
73
+ /** Minimum length of a string we bother looking for in the export. */
74
+ const MIN_LEAK_CHARS = 8;
75
+
76
+ // --------------------------------------------------------------- helpers ----
77
+
78
+ function mintId(seed) {
79
+ const source = typeof seed === 'string' && seed ? seed : crypto.randomBytes(16).toString('hex');
80
+ const id = identity.mintHolderId((value) => crypto.createHash('sha1').update(value).digest(), source);
81
+ return id || `h_${crypto.createHash('sha1').update(source).digest('hex').slice(0, identity.FINGERPRINT_LENGTH)}`;
82
+ }
83
+
84
+ /** Every string inside `value`, depth-first. Used by the leak check. */
85
+ function stringsIn(value, out = [], depth = 0) {
86
+ if (depth > 8 || value == null) return out;
87
+ if (typeof value === 'string') {
88
+ out.push(value);
89
+ return out;
90
+ }
91
+ if (typeof value !== 'object') return out;
92
+ for (const item of Array.isArray(value) ? value : Object.values(value)) stringsIn(item, out, depth + 1);
93
+ return out;
94
+ }
95
+
96
+ /**
97
+ * Does the export still carry memory? Returns the leaks it found rather than
98
+ * throwing, so the caller can refuse to write the file *and* say why.
99
+ *
100
+ * `secret` is what the exporting holder actually knows: entry texts and ids, the
101
+ * registry row's fingerprint. A leak is any of those appearing in the document —
102
+ * not a similarity score, an actual substring.
103
+ */
104
+ function assertNoMemory(doc, secret = {}) {
105
+ const text = JSON.stringify(doc == null ? null : doc);
106
+ const leaks = [];
107
+ const needles = [];
108
+
109
+ for (const row of Array.isArray(secret.entries) ? secret.entries : []) {
110
+ const id = row && row.id != null ? String(row.id) : '';
111
+ if (id.length >= MIN_LEAK_CHARS) needles.push({ what: 'entry id', value: id });
112
+ const body = row && (row.content != null ? row.content : row.text);
113
+ if (typeof body === 'string' && body.trim().length >= MIN_LEAK_CHARS) {
114
+ needles.push({ what: 'entry text', value: body.trim() });
115
+ }
116
+ }
117
+ for (const id of Array.isArray(secret.entryIds) ? secret.entryIds : []) {
118
+ if (String(id).length >= MIN_LEAK_CHARS) needles.push({ what: 'entry id', value: String(id) });
119
+ }
120
+ if (secret.fingerprint) needles.push({ what: 'fingerprint', value: String(secret.fingerprint) });
121
+ for (const key of Array.isArray(secret.keys) ? secret.keys : []) {
122
+ if (String(key).length >= MIN_LEAK_CHARS) needles.push({ what: 'key material', value: String(key) });
123
+ }
124
+
125
+ for (const needle of needles) {
126
+ if (text.includes(needle.value)) leaks.push(`${needle.what} leaked: ${needle.value.slice(0, 24)}…`);
127
+ }
128
+ // Key material is checked by shape too: a fingerprint's *prefix* would leak
129
+ // even when the full string does not.
130
+ if (secret.fingerprint && secret.fingerprint.length >= MIN_LEAK_CHARS) {
131
+ const short = String(secret.fingerprint).slice(0, MIN_LEAK_CHARS);
132
+ if (text.includes(short) && !leaks.some((leak) => leak.includes('fingerprint'))) {
133
+ leaks.push('fingerprint prefix leaked');
134
+ }
135
+ }
136
+ return { ok: leaks.length === 0, leaks };
137
+ }
138
+
139
+ // ---------------------------------------------------------------- export ----
140
+
141
+ /**
142
+ * Build the shareable document from a holder's loaded state.
143
+ *
144
+ * Never throws on a malformed profile: a summary that cannot be computed is
145
+ * simply absent, because "the export is missing a count" is a smaller failure
146
+ * than "the export failed".
147
+ */
148
+ function exportPersona(state, opts = {}) {
149
+ const id = state && state.holderId ? String(state.holderId) : null;
150
+ if (!id || !identity.HOLDER_ID_RE.test(id)) {
151
+ return { ok: false, reason: 'exportPersona: expected a loaded holder state', doc: null };
152
+ }
153
+
154
+ const verified = personaModule.validate(state.persona);
155
+ const persona = {};
156
+ for (const part of PERSONA_PARTS) {
157
+ if (verified.persona[part] !== undefined) persona[part] = verified.persona[part];
158
+ }
159
+ persona.identity = Object.assign({}, persona.identity, { holderId: id });
160
+
161
+ const ledger = Array.isArray(state.ledger) ? state.ledger : [];
162
+ const byKind = {};
163
+ let firstAt = null;
164
+ let lastAt = null;
165
+ for (const row of ledger) {
166
+ if (!row || typeof row !== 'object') continue;
167
+ const kind = String(row.kind || 'unknown');
168
+ byKind[kind] = (byKind[kind] || 0) + 1;
169
+ const t = Number(row.t);
170
+ if (Number.isFinite(t)) {
171
+ firstAt = firstAt === null ? t : Math.min(firstAt, t);
172
+ lastAt = lastAt === null ? t : Math.max(lastAt, t);
173
+ }
174
+ }
175
+
176
+ const profile = state.profile && typeof state.profile === 'object' ? state.profile : {};
177
+ const facets = Array.isArray(profile.facets) ? profile.facets : [];
178
+ const doc = {
179
+ schema: EXPORT_SCHEMA,
180
+ kind: EXPORT_KIND,
181
+ exportedAt: typeof opts.now === 'number' ? opts.now : 0,
182
+ attribution: { holderId: id, displayName: state.displayName || null },
183
+ // Taste. Register, presentation, voice, names — exactly §5's list.
184
+ persona,
185
+ // Shape, not sentences: counts, level and facet keys. No facet `value`, no
186
+ // `sources`, no entry ids — a facet's prose is memory, not taste.
187
+ ledger: {
188
+ rows: ledger.length,
189
+ level: Number.isFinite(Number(state.level)) ? Number(state.level) : 1,
190
+ byKind,
191
+ firstAt,
192
+ lastAt,
193
+ },
194
+ profile: {
195
+ coldStart: Boolean(profile.coldStart) || facets.length === 0,
196
+ facetCount: facets.length,
197
+ budget: { tokens: profileModule.BUDGET_TOKENS, used: (profile.budget && profile.budget.used) || 0 },
198
+ facets: facets.map((facet) => ({
199
+ id: facet.id,
200
+ key: facet.key,
201
+ confidence: facet.confidence,
202
+ tokens: facet.tokens,
203
+ firstSeen: facet.firstSeen,
204
+ lastSeen: facet.lastSeen,
205
+ })),
206
+ },
207
+ };
208
+
209
+ const secret = {
210
+ entries: opts.entries,
211
+ entryIds: facets.flatMap((facet) => (Array.isArray(facet.sources) ? facet.sources : [])),
212
+ fingerprint: opts.fingerprint || null,
213
+ keys: opts.keys,
214
+ };
215
+ const check = assertNoMemory(doc, secret);
216
+ if (!check.ok) return { ok: false, reason: check.leaks.join('; '), leaks: check.leaks, doc: null };
217
+ return { ok: true, doc, leaks: [], warnings: verified.warnings || [] };
218
+ }
219
+
220
+ /**
221
+ * Load the holder, export it, verify it, and only then write
222
+ * `aegis-persona.json` (0600, tmp + rename). A document that failed the leak
223
+ * check is never written: the file is the thing that gets shared.
224
+ */
225
+ function writeExport(dir, holderId, opts = {}) {
226
+ const state = opts.state || holders.loadState(dir, holderId);
227
+ const fingerprint = (() => {
228
+ const row = holders.holderRow(holders.readRegistry(dir), state.holderId);
229
+ return row && row.fingerprint ? row.fingerprint : null;
230
+ })();
231
+ const built = exportPersona(state, Object.assign({ fingerprint }, opts));
232
+ if (!built.ok) return { ok: false, reason: built.reason, leaks: built.leaks || [], file: null, doc: null };
233
+
234
+ const file = opts.dest || path.join(String(dir), EXPORT_FILE);
235
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
236
+ const tmp = `${file}.tmp-${process.pid}`;
237
+ fs.writeFileSync(tmp, `${JSON.stringify(built.doc, null, 2)}\n`, { mode: 0o600 });
238
+ fs.renameSync(tmp, file);
239
+ try { fs.chmodSync(file, 0o600); } catch {}
240
+ return { ok: true, file, doc: built.doc, leaks: [], warnings: built.warnings };
241
+ }
242
+
243
+ // ---------------------------------------------------------------- import ----
244
+
245
+ function readDoc(input) {
246
+ if (typeof input === 'string') {
247
+ try {
248
+ return JSON.parse(fs.readFileSync(input, 'utf8'));
249
+ } catch (err) {
250
+ return null;
251
+ }
252
+ }
253
+ return input && typeof input === 'object' ? input : null;
254
+ }
255
+
256
+ /**
257
+ * Import a persona document.
258
+ *
259
+ * `mode: 'new'` (the default) mints a fresh holder and gives it *this* persona;
260
+ * the export's ledger is ignored entirely, so a shared persona confers taste and
261
+ * nothing else. `mode: 'rebind'` requires `confirm: true` — the same explicit
262
+ * confirm the conflict card demands — and writes the persona onto an existing
263
+ * holder without touching its ledger, because the memory is that holder's.
264
+ */
265
+ function importPersona(dir, input, opts = {}) {
266
+ const now = typeof opts.now === 'number' ? opts.now : 0;
267
+ const doc = readDoc(input);
268
+ if (!doc || typeof doc !== 'object') return { ok: false, reason: 'importPersona: expected a persona document' };
269
+ const kind = String(doc.kind || '');
270
+ if (kind && kind !== EXPORT_KIND) {
271
+ return { ok: false, reason: `importPersona: not an ${EXPORT_KIND} document (kind "${kind}")` };
272
+ }
273
+ if (!doc.persona || typeof doc.persona !== 'object') {
274
+ return { ok: false, reason: 'importPersona: document carries no persona' };
275
+ }
276
+
277
+ const mode = opts.mode === 'rebind' ? 'rebind' : 'new';
278
+ const registry = opts.registry || holders.readRegistry(dir);
279
+
280
+ if (mode === 'rebind') {
281
+ const wanted = String(opts.holderId || (doc.attribution && doc.attribution.holderId) || '')
282
+ .trim()
283
+ .toLowerCase();
284
+ if (!identity.HOLDER_ID_RE.test(wanted) || !holders.holderRow(registry, wanted)) {
285
+ return { ok: false, reason: 'importPersona: rebind needs an existing holder id' };
286
+ }
287
+ if (opts.confirm !== true) {
288
+ return { ok: false, reason: 'importPersona: rebind requires an explicit confirm', requiresConfirm: true };
289
+ }
290
+ const before = holders.loadState(dir, wanted, { registry });
291
+ const next = personaModule.validate(Object.assign({}, doc.persona, {
292
+ identity: Object.assign({}, doc.persona.identity, { holderId: wanted }),
293
+ }));
294
+ if (opts.persist !== false) holders.writePersona(dir, wanted, next.persona);
295
+ const after = holders.loadState(dir, wanted, { registry });
296
+ return {
297
+ ok: true,
298
+ mode,
299
+ holderId: wanted,
300
+ created: false,
301
+ persona: next.persona,
302
+ warnings: next.warnings || [],
303
+ // Untouched by construction, and reported so a caller can assert it.
304
+ ledger: { before: before.ledger.length, after: after.ledger.length, imported: false },
305
+ level: after.level,
306
+ xpImported: false,
307
+ };
308
+ }
309
+
310
+ const minted = opts.holderId ? identity.HOLDER_ID_RE.test(String(opts.holderId)) ? String(opts.holderId) : null : null;
311
+ const id = minted || mintId(opts.seed);
312
+ const created = holders.ensureHolder(dir, {
313
+ id,
314
+ displayName: opts.displayName || (doc.attribution && doc.attribution.displayName) || undefined,
315
+ now,
316
+ registry,
317
+ persist: opts.persist !== false,
318
+ });
319
+ const holderId = created.row ? created.row.id : id;
320
+ const next = personaModule.validate(Object.assign({}, doc.persona, {
321
+ identity: Object.assign({}, doc.persona.identity, { holderId }),
322
+ }));
323
+ if (opts.persist !== false) holders.writePersona(dir, holderId, next.persona);
324
+
325
+ // A new holder starts at L1 with an empty ledger. `doc.ledger` is read for
326
+ // nothing: importing XP would make a level something you can hand someone.
327
+ const after = holders.loadState(dir, holderId, { registry: created.registry });
328
+ return {
329
+ ok: true,
330
+ mode,
331
+ holderId,
332
+ created: created.created,
333
+ persona: next.persona,
334
+ warnings: next.warnings || [],
335
+ ledger: { before: 0, after: after.ledger.length, imported: false },
336
+ level: after.level,
337
+ xpImported: false,
338
+ };
339
+ }
340
+
341
+ // ---------------------------------------------------------------- forget ----
342
+
343
+ function listFiles(dir) {
344
+ try {
345
+ return fs.readdirSync(dir).sort();
346
+ } catch (err) {
347
+ return [];
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Forget one holder, for real (§7.3).
353
+ *
354
+ * Order matters and is deliberate: the cloud-delete request is queued *first*,
355
+ * then the directory is removed, then the registry row is dropped. If the
356
+ * process dies between any two steps the result is a request for a holder that
357
+ * still exists (harmless, resumable) rather than a deleted holder whose cloud
358
+ * copy nobody remembers to delete.
359
+ */
360
+ function forgetHolder(dir, holderId, opts = {}) {
361
+ const id = String(holderId == null ? '' : holderId).trim().toLowerCase();
362
+ if (!identity.HOLDER_ID_RE.test(id)) {
363
+ return { ok: false, reason: 'forgetHolder: expected a holder id (h_ + 8-16 hex)', holderId: null };
364
+ }
365
+ const registry = opts.registry || holders.readRegistry(dir);
366
+ const row = holders.holderRow(registry, id);
367
+ if (!row && opts.force !== true) {
368
+ return { ok: false, reason: `unknown holder ${id}`, holderId: id };
369
+ }
370
+
371
+ const now = typeof opts.now === 'number' ? opts.now : 0;
372
+ const queued = mirror.queueDelete(dir, id, { t: now, reason: 'holder-forgotten' });
373
+
374
+ const home = holders.holderDir(dir, id);
375
+ const files = listFiles(home);
376
+ try {
377
+ fs.rmSync(home, { recursive: true, force: true });
378
+ } catch (err) {
379
+ return {
380
+ ok: false,
381
+ reason: `could not remove ${home}: ${(err && err.message) || 'error'}`,
382
+ holderId: id,
383
+ queued,
384
+ };
385
+ }
386
+
387
+ const without = identity.removeHolder(registry, id);
388
+ const remaining = (without.holders || []).map((entry) => entry.id);
389
+ let active = without.active;
390
+ if (!active && remaining.length) active = opts.active && remaining.includes(opts.active) ? opts.active : remaining[0];
391
+ const next = holders.writeRegistry(dir, Object.assign({}, without, { active: active || null }));
392
+
393
+ return {
394
+ ok: true,
395
+ holderId: id,
396
+ removed: { dir: home, files },
397
+ queued: { sessions: queued.sessions || mirror.scopeFor(id).sessions, duplicate: Boolean(queued.duplicate) },
398
+ active: next.active,
399
+ registry: next,
400
+ remaining,
401
+ };
402
+ }
403
+
404
+ module.exports = {
405
+ EXPORT_FILE,
406
+ EXPORT_KIND,
407
+ EXPORT_SCHEMA,
408
+ PERSONA_PARTS,
409
+ MIN_LEAK_CHARS,
410
+ mintId,
411
+ stringsIn,
412
+ assertNoMemory,
413
+ exportPersona,
414
+ writeExport,
415
+ importPersona,
416
+ forgetHolder,
417
+ };
@@ -1,3 +1,218 @@
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 register=require("./register.js"),MAX_RECALL_ENTRIES=40,MAX_RECALL_TOKENS=12e3,MIN_RECALL_ENTRIES=4,MIN_RECALL_TOKENS=1500;function clampInt(e,o,r,l){const t=Number(e);return Number.isFinite(t)?Math.min(r,Math.max(o,Math.floor(t))):l}function recallPolicy(e,o={}){const r=e&&"object"==typeof e?e:{},l=clampInt(r.recallEntries,MIN_RECALL_ENTRIES,MAX_RECALL_ENTRIES,MIN_RECALL_ENTRIES),t=clampInt(r.recallTokens,MIN_RECALL_TOKENS,MAX_RECALL_TOKENS,MIN_RECALL_TOKENS),n=!0===o.deep;return Object.freeze({entries:l,tokens:t,deep:n,modelFloor:"string"==typeof r.modelFloor&&r.modelFloor?r.modelFloor:null,flags:Object.freeze({aegis_recall:!0,...n?{aegis_recall_deep:!0}:{}}),approvalFields:0})}const REASONING_MODEL_RE=/^(?:deepseek-(?:v4(?:\.\d+)?-(?:flash|pro)|flash|pro|reasoner)|(?:nexus|aegis)-brain(?:-(?:smart|neo))?)$/,REASONING_SIBLINGS=Object.freeze({deepseek:"deepseek-reasoner"});function splitModelId(e){const o=String(null==e?"":e),r=o.indexOf(":");return r<=0?{provider:"",model:o}:{provider:o.slice(0,r),model:o.slice(r+1)}}function reasoningModel(e){return REASONING_MODEL_RE.test(splitModelId(e).model)}function applyModelFloor(e,o){const r=String(null==e?"":e),l=o&&"string"==typeof o.modelFloor?o.modelFloor:null;if("reasoning"!==l)return{model:r,floor:{requested:null,met:!0,applied:!1,from:r,to:r,reason:""}};if(reasoningModel(r))return{model:r,floor:{requested:l,met:!0,applied:!1,from:r,to:r,reason:""}};const{provider:t}=splitModelId(r),n=REASONING_SIBLINGS[t];if(n){const e=`${t}:${n}`;return{model:e,floor:{requested:l,met:!0,applied:!0,from:r,to:e,reason:""}}}return{model:r,floor:{requested:l,met:!1,applied:!1,from:r,to:r,reason:`no reasoning model this build can route ${r} to`}}}function composeSystemPrompt(e,o={}){const r=recallPolicy(o.capabilities,{deep:o.deep}),l=register.fragment({persona:o.persona,capabilities:o.capabilities,maxTokens:o.maxTokens});return{system:register.append(e,l.text),fragment:l.text,fragmentTokens:l.tokens,dropped:l.dropped,neutralizations:l.neutralizations,policy:r}}module.exports={MAX_RECALL_ENTRIES:MAX_RECALL_ENTRIES,MAX_RECALL_TOKENS:MAX_RECALL_TOKENS,MIN_RECALL_ENTRIES:MIN_RECALL_ENTRIES,MIN_RECALL_TOKENS:MIN_RECALL_TOKENS,REASONING_MODEL_RE:REASONING_MODEL_RE,REASONING_SIBLINGS:REASONING_SIBLINGS,splitModelId:splitModelId,reasoningModel:reasoningModel,applyModelFloor:applyModelFloor,recallPolicy:recallPolicy,composeSystemPrompt:composeSystemPrompt};
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.js — the ONE seam where a level reaches turn assembly and
10
+ * where the persona's register fragment is attached to the engine's system
11
+ * prompt.
12
+ *
13
+ * `level.js` says what a level buys and `register.js` says what the persona's
14
+ * tone is; neither of them knows what a turn is. This file is the only place
15
+ * that combines the two — deliberately small, pure and dependency-light, so
16
+ * the claim "a level changes behaviour, and only in the knobs the engine
17
+ * already takes" is a thing a test can hold.
18
+ *
19
+ * The shape of the claim:
20
+ *
21
+ * - `recallPolicy(caps)` turns a capabilities object into the recall budget
22
+ * for one turn: how many memory entries may be injected and how many tokens
23
+ * they may take. Both GROW with level, both are clamped, and neither can
24
+ * ever exceed its hard ceiling no matter what a capabilities object says —
25
+ * so a hand-edited ledger cannot buy an unbounded context.
26
+ * - The DEEP recall tier (`aegis_recall_deep`) is a paid server-side embedding.
27
+ * Level never buys it: it stays an explicit per-session opt-in, because a
28
+ * level that silently starts spending per turn is a billing surprise.
29
+ * - No approval, grant or tool field is produced here. Turn assembly reads a
30
+ * recall policy; it is structurally incapable of reading a widened
31
+ * permission out of it, which is what makes the carve-out test a
32
+ * statement about the code rather than a promise about the developers.
33
+ * - `applyModelFloor(model, policy)` turns the L20 floor into the model this
34
+ * turn actually travels on. It is a ROUTING constraint and nothing more: it
35
+ * substitutes the reasoning sibling of the model the user picked where this
36
+ * build can route one (same provider, same key, an id the engine already
37
+ * pattern-matches), and where it cannot — a local daemon, a provider with no
38
+ * reasoning sibling — it leaves the pick alone and says so in `met:false`.
39
+ * A floor that quietly ran a different provider would be a bonus that
40
+ * invented a code path, which is exactly what §2's rule zero forbids.
41
+ * - `composeSystemPrompt(base, ctx)` appends the register fragment AFTER
42
+ * `base` (the engine's own safety/tool rules), via `register.append`, and
43
+ * returns the fragment so a caller can log exactly what was added.
44
+ *
45
+ * The app-readable shape of this file: `recallPolicy()` is what turn assembly
46
+ * reads for breadth, and `applyModelFloor()` is what it reads for the floor.
47
+ * Neither returns an approval, and `approvalFields` is kept at zero so "a
48
+ * level cannot widen blast radius" is a property of the value, not a promise.
49
+ *
50
+ * Pure Node: no Electron, no fs, no clock.
51
+ */
52
+
53
+ const register = require('./register.js');
54
+
55
+ /** Hard ceilings regardless of what a capabilities object claims. */
56
+ const MAX_RECALL_ENTRIES = 40;
57
+ const MAX_RECALL_TOKENS = 12000;
58
+
59
+ /** The floor: what an unreadable/absent capabilities object still reads. */
60
+ const MIN_RECALL_ENTRIES = 4;
61
+ const MIN_RECALL_TOKENS = 1500;
62
+
63
+ function clampInt(value, min, max, fallback) {
64
+ const n = Number(value);
65
+ if (!Number.isFinite(n)) return fallback;
66
+ return Math.min(max, Math.max(min, Math.floor(n)));
67
+ }
68
+
69
+ /**
70
+ * Recall breadth for one turn.
71
+ *
72
+ * @param {object} caps `level.capabilities(n)` (or anything shaped like it).
73
+ * @param {object} [opts]
74
+ * @param {boolean} [opts.deep] the session's explicit deep-recall opt-in.
75
+ * @returns {Readonly<{entries:number, tokens:number, deep:boolean,
76
+ * modelFloor:(string|null), flags:object, approvalFields:number}>}
77
+ */
78
+ function recallPolicy(caps, opts = {}) {
79
+ const c = caps && typeof caps === 'object' ? caps : {};
80
+ const entries = clampInt(c.recallEntries, MIN_RECALL_ENTRIES, MAX_RECALL_ENTRIES, MIN_RECALL_ENTRIES);
81
+ const tokens = clampInt(c.recallTokens, MIN_RECALL_TOKENS, MAX_RECALL_TOKENS, MIN_RECALL_TOKENS);
82
+ const deep = opts.deep === true;
83
+ return Object.freeze({
84
+ entries,
85
+ tokens,
86
+ // Never bought by level — see the header.
87
+ deep,
88
+ modelFloor: typeof c.modelFloor === 'string' && c.modelFloor ? c.modelFloor : null,
89
+ // Exactly the flags `lib/local/engine.js` already sends; nothing new is
90
+ // invented here, which is `level.js`'s rule zero.
91
+ flags: Object.freeze({
92
+ aegis_recall: true,
93
+ ...(deep ? { aegis_recall_deep: true } : {}),
94
+ }),
95
+ // Kept at zero on purpose: turn assembly reads no approval class from a
96
+ // capabilities object, so levelling can never widen blast radius.
97
+ approvalFields: 0,
98
+ });
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // the model floor (L20+)
103
+ // ---------------------------------------------------------------------------
104
+
105
+ /**
106
+ * Ids that reason on their own, as this build can tell without a round trip:
107
+ *
108
+ * - DeepSeek's reasoning family — the same anchored set `engine.js` sizes its
109
+ * budget from (DEEPSEEK_REASONING_MODEL_RE, mirrored from the upstream engine),
110
+ * because a model whose hidden chain-of-thought bills against its own output
111
+ * budget is by definition a model that reasons.
112
+ * - the pooled brain tier (`nexus-brain` and the `-smart`/`-neo` spellings the
113
+ * server serves as aliases), which is not one model at all: the server fans
114
+ * the turn out to reasoning workers plus a synthesis pass. That is the one
115
+ * id the Aegis Cloud class offers (engine.js offerableCatalog), so an
116
+ * Aegis Cloud turn satisfies the floor by construction.
117
+ */
118
+ const REASONING_MODEL_RE = /^(?:deepseek-(?:v4(?:\.\d+)?-(?:flash|pro)|flash|pro|reasoner)|(?:nexus|aegis)-brain(?:-(?:smart|neo))?)$/;
119
+
120
+ /**
121
+ * The same-provider reasoning sibling a floor may substitute, keyed by the
122
+ * provider half of a `provider:model` id. Deliberately tiny and explicit: a
123
+ * substitution is only honest when the sibling runs on the SAME credential the
124
+ * user already configured, so this table names one vendor's own sibling rather
125
+ * than guessing a mapping for the rest. `deepseek-reasoner` is in the regex
126
+ * above for exactly this reason.
127
+ */
128
+ const REASONING_SIBLINGS = Object.freeze({ deepseek: 'deepseek-reasoner' });
129
+
130
+ /** Split a `<provider>:<model>` id; ids without a colon have no provider. */
131
+ function splitModelId(model) {
132
+ const id = String(model == null ? '' : model);
133
+ const at = id.indexOf(':');
134
+ if (at <= 0) return { provider: '', model: id };
135
+ return { provider: id.slice(0, at), model: id.slice(at + 1) };
136
+ }
137
+
138
+ /** True when this model reasons on its own, ignoring any provider prefix. */
139
+ function reasoningModel(model) {
140
+ return REASONING_MODEL_RE.test(splitModelId(model).model);
141
+ }
142
+
143
+ /**
144
+ * Apply the level's model floor to the model a turn will actually run on.
145
+ *
146
+ * @param {string} model the caller's pick (`provider:model` for byok)
147
+ * @param {object} policy `recallPolicy()` output — `modelFloor` is the only
148
+ * field read, and it comes from `level.js`'s GATES.reasoningFloor.
149
+ * @returns {{model:string, floor:{requested:(string|null), met:boolean,
150
+ * applied:boolean, from:string, to:string, reason:string}}}
151
+ */
152
+ function applyModelFloor(model, policy) {
153
+ const from = String(model == null ? '' : model);
154
+ const requested = policy && typeof policy.modelFloor === 'string' ? policy.modelFloor : null;
155
+ if (requested !== 'reasoning') {
156
+ return { model: from, floor: { requested: null, met: true, applied: false, from, to: from, reason: '' } };
157
+ }
158
+ if (reasoningModel(from)) {
159
+ return { model: from, floor: { requested, met: true, applied: false, from, to: from, reason: '' } };
160
+ }
161
+ const { provider } = splitModelId(from);
162
+ const sibling = REASONING_SIBLINGS[provider];
163
+ if (sibling) {
164
+ const to = `${provider}:${sibling}`;
165
+ return { model: to, floor: { requested, met: true, applied: true, from, to, reason: '' } };
166
+ }
167
+ return {
168
+ model: from,
169
+ floor: {
170
+ requested,
171
+ met: false,
172
+ applied: false,
173
+ from,
174
+ to: from,
175
+ reason: `no reasoning model this build can route ${from} to`,
176
+ },
177
+ };
178
+ }
179
+
180
+ /**
181
+ * Compose the system prompt for one turn: the engine's own prompt, unchanged,
182
+ * with the persona's bounded register fragment appended below it.
183
+ *
184
+ * @param {string} base the engine's system prompt (safety + tool rules).
185
+ * @param {object} [ctx] `{ capabilities, persona, maxTokens }`.
186
+ * @returns {{system:string, fragment:string, fragmentTokens:number,
187
+ * dropped:string[], neutralizations:number, policy:object}}
188
+ */
189
+ function composeSystemPrompt(base, ctx = {}) {
190
+ const policy = recallPolicy(ctx.capabilities, { deep: ctx.deep });
191
+ const frag = register.fragment({
192
+ persona: ctx.persona,
193
+ capabilities: ctx.capabilities,
194
+ maxTokens: ctx.maxTokens,
195
+ });
196
+ return {
197
+ system: register.append(base, frag.text),
198
+ fragment: frag.text,
199
+ fragmentTokens: frag.tokens,
200
+ dropped: frag.dropped,
201
+ neutralizations: frag.neutralizations,
202
+ policy,
203
+ };
204
+ }
205
+
206
+ module.exports = {
207
+ MAX_RECALL_ENTRIES,
208
+ MAX_RECALL_TOKENS,
209
+ MIN_RECALL_ENTRIES,
210
+ MIN_RECALL_TOKENS,
211
+ REASONING_MODEL_RE,
212
+ REASONING_SIBLINGS,
213
+ splitModelId,
214
+ reasoningModel,
215
+ applyModelFloor,
216
+ recallPolicy,
217
+ composeSystemPrompt,
218
+ };