aegisone 1.0.34 → 1.0.35

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 -5
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -976
  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 -383
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/package.json +3 -7
  17. package/vendor/cli/scripts/check.mjs +1 -52
  18. package/vendor/cli/scripts/demo.mjs +1 -94
  19. package/vendor/cli/scripts/predist.mjs +1 -75
  20. package/vendor/cli/scripts/runtests.mjs +1 -56
  21. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  22. package/vendor/cli/src/agents.js +1 -139
  23. package/vendor/cli/src/app.js +1 -2957
  24. package/vendor/cli/src/art.js +1 -289
  25. package/vendor/cli/src/chatflow.js +1 -3023
  26. package/vendor/cli/src/checkpoint.js +1 -90
  27. package/vendor/cli/src/clipboard.js +1 -424
  28. package/vendor/cli/src/cloudsync.js +1 -528
  29. package/vendor/cli/src/commands.js +1 -4089
  30. package/vendor/cli/src/config.js +1 -581
  31. package/vendor/cli/src/connect.js +1 -349
  32. package/vendor/cli/src/credentials.js +1 -33
  33. package/vendor/cli/src/deps.js +1 -232
  34. package/vendor/cli/src/devrun.js +1 -187
  35. package/vendor/cli/src/diff.js +1 -333
  36. package/vendor/cli/src/diffview.js +1 -296
  37. package/vendor/cli/src/engine.js +1 -297
  38. package/vendor/cli/src/entitlement.js +1 -355
  39. package/vendor/cli/src/events.js +1 -707
  40. package/vendor/cli/src/export.js +1 -67
  41. package/vendor/cli/src/filepreview.js +1 -153
  42. package/vendor/cli/src/fingerprint.js +1 -592
  43. package/vendor/cli/src/format.js +1 -259
  44. package/vendor/cli/src/fuzzy.js +1 -119
  45. package/vendor/cli/src/history.js +1 -423
  46. package/vendor/cli/src/init.js +1 -175
  47. package/vendor/cli/src/input.js +1 -139
  48. package/vendor/cli/src/keys.js +1 -183
  49. package/vendor/cli/src/markdown.js +1 -306
  50. package/vendor/cli/src/models.js +1 -507
  51. package/vendor/cli/src/naming.js +1 -57
  52. package/vendor/cli/src/overlays.js +1 -462
  53. package/vendor/cli/src/panels.js +1 -1418
  54. package/vendor/cli/src/ping.js +1 -226
  55. package/vendor/cli/src/presence.js +1 -238
  56. package/vendor/cli/src/render.js +1 -516
  57. package/vendor/cli/src/screen.js +1 -518
  58. package/vendor/cli/src/screens.js +1 -896
  59. package/vendor/cli/src/secret.js +1 -59
  60. package/vendor/cli/src/securefs.js +1 -359
  61. package/vendor/cli/src/settings.js +1 -155
  62. package/vendor/cli/src/shared.js +1 -52
  63. package/vendor/cli/src/sharedpaths.js +1 -53
  64. package/vendor/cli/src/signup.js +1 -156
  65. package/vendor/cli/src/summarize.js +1 -95
  66. package/vendor/cli/src/sysdiag.js +1 -585
  67. package/vendor/cli/src/system.js +1 -40
  68. package/vendor/cli/src/theme.js +1 -570
  69. package/vendor/cli/src/title.js +1 -220
  70. package/vendor/cli/src/todos.js +1 -115
  71. package/vendor/cli/src/tokens.js +1 -263
  72. package/vendor/cli/src/topup.js +1 -210
  73. package/vendor/cli/src/update.js +1 -191
  74. package/vendor/cli/vendor/client/aegis.js +1 -2441
  75. package/vendor/cli/vendor/client/attest.js +1 -518
  76. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  77. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  78. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  79. package/vendor/cli/vendor/client/byok-catalog.js +1 -199
  80. package/vendor/cli/vendor/client/catalog-client.js +1 -487
  81. package/vendor/cli/vendor/client/conversation-export.js +1 -177
  82. package/vendor/cli/vendor/client/credentials.js +1 -494
  83. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  84. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  85. package/vendor/cli/vendor/client/drive-upload.js +1 -234
  86. package/vendor/cli/vendor/client/env-file.js +1 -1273
  87. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  88. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  89. package/vendor/cli/vendor/client/google-signin.js +1 -133
  90. package/vendor/cli/vendor/client/hooks.js +1 -430
  91. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  92. package/vendor/cli/vendor/client/naming.js +1 -283
  93. package/vendor/cli/vendor/client/platform.js +1 -937
  94. package/vendor/cli/vendor/client/prefs.js +1 -351
  95. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  96. package/vendor/cli/vendor/client/presence.js +1 -438
  97. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  98. package/vendor/cli/vendor/client/session-store.js +1 -575
  99. package/vendor/cli/vendor/client/topup.js +1 -297
  100. package/vendor/cli/vendor/client/touch.js +1 -458
  101. package/vendor/cli/vendor/client/update.js +1 -763
  102. package/vendor/cli/vendor/client/user-models.js +1 -381
  103. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  104. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -276
  105. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  106. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1028
  107. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -125
  108. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3666
  109. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  110. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  111. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2145
  112. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -280
  113. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  114. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -238
  115. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -75
  116. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  117. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  118. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  119. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  120. package/vendor/cli/vendor/hosts/install.js +1 -638
  121. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  122. package/vendor/cli/vendor/hosts/spec.js +1 -164
  123. package/vendor/cli/vendor/hosts/targets.js +1 -346
  124. package/vendor/cli/vendor/mcp/server.js +1 -221
  125. package/vendor/cli/vendor/mcp/tools.js +1 -408
  126. package/vendor/cli/vendor/one/src/child.js +1 -285
  127. package/vendor/cli/vendor/one/src/permissions.js +1 -383
  128. package/vendor/desktop/bin/aegis.js +1 -32
  129. package/vendor/desktop/lib/account-key.js +1 -56
  130. package/vendor/desktop/lib/auto.js +1 -461
  131. package/vendor/desktop/lib/avatar/companion.js +1 -698
  132. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  133. package/vendor/desktop/lib/avatar/events.js +1 -344
  134. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  135. package/vendor/desktop/lib/avatar/holders.js +1 -612
  136. package/vendor/desktop/lib/avatar/identity.js +1 -641
  137. package/vendor/desktop/lib/avatar/level.js +1 -368
  138. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  139. package/vendor/desktop/lib/avatar/persona.js +1 -388
  140. package/vendor/desktop/lib/avatar/profile.js +1 -977
  141. package/vendor/desktop/lib/avatar/register.js +1 -307
  142. package/vendor/desktop/lib/avatar/store.js +1 -472
  143. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  144. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  145. package/vendor/desktop/lib/avatar/turn.js +1 -216
  146. package/vendor/desktop/lib/avatar/voice.js +1 -328
  147. package/vendor/desktop/lib/avatar/xp.js +1 -404
  148. package/vendor/desktop/lib/deep-link.js +1 -120
  149. package/vendor/desktop/lib/fingerprint.js +2 -347
  150. package/vendor/desktop/lib/google-connect.js +1 -323
  151. package/vendor/desktop/lib/local/agents.js +1 -105
  152. package/vendor/desktop/lib/local/attachments.js +1 -276
  153. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  154. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  155. package/vendor/desktop/lib/local/context.js +1 -125
  156. package/vendor/desktop/lib/local/engine.js +1 -3666
  157. package/vendor/desktop/lib/local/entitlement.js +1 -660
  158. package/vendor/desktop/lib/local/git-scope.js +1 -228
  159. package/vendor/desktop/lib/local/local.js +1 -2145
  160. package/vendor/desktop/lib/local/prompt.js +1 -280
  161. package/vendor/desktop/lib/local/queue.js +1 -560
  162. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  163. package/vendor/desktop/lib/local/spill.js +1 -75
  164. package/vendor/desktop/lib/local/telemetry.js +1 -470
  165. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  166. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  167. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  168. package/vendor/desktop/lib/quick-launcher.js +1 -84
  169. package/vendor/desktop/lib/settings.js +1 -890
  170. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  171. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  172. package/vendor/desktop/lib/sync/sessions.js +1 -106
  173. package/vendor/desktop/lib/window-state.js +1 -66
  174. package/vendor/desktop/package.json +2 -4
  175. package/vendor/desktop/preload.js +1 -679
  176. package/vendor/desktop/renderer/app.js +1 -7250
  177. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  178. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  179. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  180. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  181. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  182. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  183. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  184. package/vendor/desktop/renderer/budget.js +1 -172
  185. package/vendor/desktop/renderer/companion.js +1 -223
  186. package/vendor/desktop/renderer/diff.js +1 -359
  187. package/vendor/desktop/renderer/diffview.js +1 -336
  188. package/vendor/desktop/renderer/filepreview.js +1 -211
  189. package/vendor/desktop/renderer/fingerprint.js +3 -789
  190. package/vendor/desktop/renderer/markdown.js +1 -168
  191. package/vendor/desktop/renderer/provider-mark.js +1 -311
  192. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  193. package/vendor/desktop/renderer/providers.js +1 -259
  194. package/vendor/desktop/renderer/quick.js +1 -285
  195. package/vendor/desktop/renderer/stream-policy.js +1 -387
  196. package/vendor/desktop/renderer/transcript-view.js +1 -323
  197. package/vendor/desktop/renderer/usage.js +1 -1239
  198. package/vendor/desktop/vendor/aegis.js +1 -2441
  199. package/vendor/desktop/vendor/attest.js +1 -518
  200. package/vendor/desktop/vendor/authorship-key.js +1 -410
  201. package/vendor/desktop/vendor/auto-provision.js +1 -134
  202. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  203. package/vendor/desktop/vendor/byok-catalog.js +1 -199
  204. package/vendor/desktop/vendor/catalog-client.js +1 -487
  205. package/vendor/desktop/vendor/conversation-export.js +1 -177
  206. package/vendor/desktop/vendor/credentials.js +1 -494
  207. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  208. package/vendor/desktop/vendor/drive-connect.js +1 -110
  209. package/vendor/desktop/vendor/drive-upload.js +1 -234
  210. package/vendor/desktop/vendor/env-file.js +1 -1273
  211. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  212. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  213. package/vendor/desktop/vendor/google-signin.js +1 -133
  214. package/vendor/desktop/vendor/hooks.js +1 -430
  215. package/vendor/desktop/vendor/model-discovery.js +1 -373
  216. package/vendor/desktop/vendor/naming.js +1 -283
  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 -575
  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 -763
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -1,1066 +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
- * VENDORED — do not edit. Generated by tools/vendor-fingerprint.mjs.
10
- *
11
- * source: aegiscodex 046ba6f — src/fingerprint.js
12
- * rewrite: ESM -> CJS, module syntax only. No constant, purpose string,
13
- * attested field list or digest differs from the engine's.
14
- * verify: node --test test/fingerprint-interop.test.mjs
15
- * refresh: node tools/vendor-fingerprint.mjs
16
- */
17
- /**
18
- * fingerprint.js — φ(α), the agent fingerprint.
19
- *
20
- * The covenant defines the thing this file mints:
21
- *
22
- * Fingerprint φ(α) cryptographically verifiable identity
23
- * carries reputation + track record + behavioural signature
24
- *
25
- * and then states the structural claim that makes it worth having: *identity and
26
- * reputation are properties of the agent, not of the platform hosting it.* φ(α)
27
- * travels. It is not a session token.
28
- *
29
- * So this module answers three separate questions, and keeps them separate:
30
- *
31
- * 1. "same credential?" `keyFingerprint(secret)` — one-way, truncated.
32
- * 2. "same behaviour?" `behaviouralSignature(observations)` — a digest
33
- * over what the agent actually did, order-independent
34
- * so a re-ordered transcript is still the same agent.
35
- * 3. "is this record intact?" `verify(record, secret)` — an HMAC attestation,
36
- * compared in constant time.
37
- *
38
- * Four rules, and each is an assertion in `tests/fingerprint.test.mjs` rather
39
- * than a sentence in a doc:
40
- *
41
- * 1. **A fingerprint is not an identity.** `keyFingerprint` says "same
42
- * credential", never "same person" — two agents on one box can legitimately
43
- * share a key. The record therefore keeps credential identity and behavioural
44
- * signature in separate fields and `same()` requires the caller to say which
45
- * one they mean.
46
- * 2. **No key material escapes.** The raw secret is never a field, never a
47
- * substring of one, and `assertNoLeak` re-checks that on every minted record:
48
- * no field other than `attestation` may carry a long hex run. `keyFingerprint`
49
- * is truncated to the same 12 hex the avatar registry already uses, so a
50
- * fingerprint minted here indexes the same way a registry row does.
51
- * 3. **A signature over nothing is not evidence.** `behaviouralSignature([])`
52
- * returns `null`, and the record records `behaviourSamples: 0`. Absence of
53
- * track record reads as absence, never as a zero-valued hash. The thumb axis
54
- * follows the same rule: fewer than `touch.MIN_STROKES` strokes gives
55
- * `touch: null`, `touchSamples: 0`.
56
- * 4. **Verification is recomputation.** `verify` re-derives the attestation
57
- * from the attested fields only (`ATTESTED_FIELDS`), so appending fields to
58
- * a record cannot invalidate it and editing any attested field must.
59
- *
60
- * The fourth axis — `touch`, the thumb's gesture dynamics — is described in
61
- * `src/touch.js`, including the part that matters most: it is **not** a
62
- * fingerprint, because this hardware has no fingerprint sensor and the trackpad
63
- * exposes no contact geometry through X. It is a behavioural biometric. Two
64
- * consequences are structural here rather than documented:
65
- *
66
- * - The thumb signature is **not keyed by the secret**. A credential says "same
67
- * key"; a habit says "same thumb". Keying one with the other would make every
68
- * agent sharing a credential look like the same hand.
69
- * - `mint` **recomputes** `touch` from the profile's medians via
70
- * `touch.signatureFromMedians`, so a `signature` field sitting in a captured
71
- * profile file is never trusted.
72
- *
73
- * The fifth axis is the **AI's own**: `aiKey` / `ai` / `aiSamples` / `aiModel`.
74
- *
75
- * Every axis above describes the *human* half of a turn — their credential, their
76
- * demands, their thumb, their tree. Until v4 the mind on the other side of the
77
- * turn was present only as `model`, a free-text label nobody attested, which is
78
- * the one thing this module refuses elsewhere: a fabricated field is not
79
- * evidence. So the record now carries both halves of a session, and they stay
80
- * separate for the same reason credential identity and behaviour stay separate:
81
- *
82
- * - `aiKey` is `keyFingerprint` of the credential the session *ran on* — the
83
- * model provider key, not the authorship key. Same derivation, same namespace,
84
- * so `same(a, b, 'ai-credential')` answers "same mind?" and `same(a, b,
85
- * 'credential')` still answers "same author?" without one reading as the
86
- * other. It is `null` when the minter nominated no AI credential: an
87
- * un-nominated key must not hash to a shared value, and the record says
88
- * "nobody said which mind this was" rather than inventing one.
89
- * - `ai` is a digest over the assistant's turns (which tools, which targets,
90
- * which outcomes, which model), under its own frozen purpose string so an AI
91
- * digest and a human-turn digest over identical text can never collide. It is
92
- * **unkeyed**, exactly like `touch`: a habit says "same mind", not "same key".
93
- * - `aiSamples` counts the AI turns that carried signal, and `ai` is `null` when
94
- * none did — rule 3 again: absence of track record reads as absence.
95
- *
96
- * `aiModel` is the attested spelling of what `model` was only claiming: the model
97
- * the session actually ran on, bounded and normalised like every other field.
98
- *
99
- * Record versions 1–3 have different attested bodies and are all kept, selected
100
- * by `record.v`: an older record still verifies under its own field list rather
101
- * than being silently unreadable.
102
- *
103
- * Pure: node:crypto only (plus the equally pure `src/touch.js`). No network, no
104
- * spawn, no Electron — testable in plain Node, and safe to call in the
105
- * autonomous queue where nothing is interactive.
106
- */
107
-
108
- const crypto = require('node:crypto');
109
- const fs = require('node:fs');
110
-
111
- const { signatureFromMedians, MIN_STROKES: TOUCH_MIN_STROKES } = require('./touch.js');
112
-
113
- /** Bump when the record shape changes; `verify` refuses versions it cannot read. */
114
- const FP_VERSION = 4;
115
-
116
- const FP_ALGO = 'sha256';
117
- const FP_PREFIX = 'φ_';
118
-
119
- /**
120
- * `sha256(secret).slice(0, 12)` — deliberately identical in shape and length to
121
- * `desktop/lib/avatar/identity.js`'s FINGERPRINT_LENGTH, because this value is
122
- * what that module's `keyFingerprint` rung resolves against. Short on purpose:
123
- * it is an index for a registry row, not an authenticator.
124
- */
125
- const KEY_FP_LENGTH = 12;
126
-
127
- /** Behavioural signatures are truncated too — they are labels for comparison. */
128
- const SIG_LENGTH = 16;
129
-
130
- /** 128-bit HMAC tag. Not the key, so the long-hex rule below exempts it. */
131
- const ATTEST_LENGTH = 32;
132
-
133
- /** Longest hex run tolerated in a non-attestation field before we call it a leak. */
134
- const LEAK_HEX_RUN = 24;
135
-
136
- const MAX_LABEL = 40;
137
- const MAX_FIELD = 64;
138
- const MAX_TOOLS = 64;
139
- const MAX_OBSERVATIONS = 4096;
140
- const MAX_DEPTH = 8;
141
-
142
- /**
143
- * The code axis. `CODE_LEN` is deliberately SIG_LENGTH: a 16-hex digest is
144
- * shorter than `LEAK_HEX_RUN`, so the aggregate can never be mistaken for key
145
- * material by `assertNoLeak`, and it is the same length as the behavioural
146
- * signature, which is the same kind of claim.
147
- */
148
- const CODE_LEN = SIG_LENGTH;
149
- const MAX_CODE_FILES = 4096;
150
- const MAX_PATH = 200;
151
-
152
- /** v1 attested body — no thumb axis. Kept so v1 records still verify. */
153
- const ATTESTED_FIELDS_V1 = Object.freeze([
154
- 'v',
155
- 'algo',
156
- 'keyFingerprint',
157
- 'label',
158
- 'account',
159
- 'model',
160
- 'tools',
161
- 'behaviour',
162
- 'behaviourSamples',
163
- 'createdAt',
164
- ]);
165
-
166
- /**
167
- * The purpose prefix of the behavioural digest is FROZEN and must not track
168
- * `FP_VERSION`.
169
- *
170
- * It used to be `aegiscode-behaviour-v${FP_VERSION}`, which quietly coupled two
171
- * unrelated things: bumping the *record shape* changed the *behavioural axis*.
172
- * Same observations, new version, different signature — so a v2 record's
173
- * `behaviour` could no longer be reproduced by re-running the tool that minted
174
- * it, which is precisely what makes the axis comparable across time. The
175
- * algorithm has not changed since v2, so the string is pinned there.
176
- */
177
- const BEHAVIOUR_PURPOSE = 'aegiscode-behaviour-v2';
178
-
179
- /**
180
- * The AI axis's purpose prefix, frozen for the same reason and separately from
181
- * `BEHAVIOUR_PURPOSE`.
182
- *
183
- * Domain separation is the whole point of the string here: the human's turns and
184
- * the assistant's turns are hashed from the same observation primer, so without a
185
- * distinct prefix a record whose two axes happened to see the same text would
186
- * carry one digest under two names — and "same author" would silently read as
187
- * "same mind". Pinned to v1 and not to `FP_VERSION`: the algorithm must not
188
- * change because the record shape did.
189
- */
190
- const AI_PURPOSE = 'aegiscode-ai-v1';
191
-
192
- /** v2 attested body — adds the thumb axis. Field order is load-bearing and frozen. */
193
- const ATTESTED_FIELDS_V2 = Object.freeze([
194
- 'v',
195
- 'algo',
196
- 'keyFingerprint',
197
- 'label',
198
- 'account',
199
- 'model',
200
- 'tools',
201
- 'behaviour',
202
- 'behaviourSamples',
203
- 'touch',
204
- 'touchSamples',
205
- 'createdAt',
206
- ]);
207
-
208
- /**
209
- * v3 attested body — adds the code axis: *which revision of which files produced
210
- * this turn*. Rule 4 still holds — appending a field to a record must not
211
- * invalidate it — so a v1 or v2 record keeps verifying under its own list.
212
- */
213
- const ATTESTED_FIELDS_V3 = Object.freeze([
214
- 'v',
215
- 'algo',
216
- 'keyFingerprint',
217
- 'label',
218
- 'account',
219
- 'model',
220
- 'tools',
221
- 'behaviour',
222
- 'behaviourSamples',
223
- 'touch',
224
- 'touchSamples',
225
- 'code',
226
- 'codeFiles',
227
- 'codeDirty',
228
- 'createdAt',
229
- ]);
230
-
231
- /**
232
- * v4 attested body — adds the AI axis: *which mind answered, and what it did*,
233
- * beside the human half the earlier versions already carried.
234
- *
235
- * The AI fields sit before `createdAt` and after the human's, so the two halves
236
- * read in the order a session happens (the demand, then the answer). Field order
237
- * is load-bearing and frozen: this list is the attestation preimage, so
238
- * reordering it would invalidate every v4 record ever minted.
239
- */
240
- const ATTESTED_FIELDS_V4 = Object.freeze([
241
- 'v',
242
- 'algo',
243
- 'keyFingerprint',
244
- 'label',
245
- 'account',
246
- 'model',
247
- 'tools',
248
- 'behaviour',
249
- 'behaviourSamples',
250
- 'touch',
251
- 'touchSamples',
252
- 'code',
253
- 'codeFiles',
254
- 'codeDirty',
255
- 'aiKey',
256
- 'aiModel',
257
- 'ai',
258
- 'aiSamples',
259
- 'createdAt',
260
- ]);
261
-
262
- /** The fields the current version attests. Exported for callers that print them. */
263
- const ATTESTED_FIELDS = ATTESTED_FIELDS_V4;
264
-
265
- const ATTESTED_FIELDS_BY_VERSION = Object.freeze({
266
- 1: ATTESTED_FIELDS_V1,
267
- 2: ATTESTED_FIELDS_V2,
268
- 3: ATTESTED_FIELDS_V3,
269
- 4: ATTESTED_FIELDS_V4,
270
- });
271
-
272
- /** null for a version this build cannot read — verification refuses rather than guesses. */
273
- function attestedFieldsFor(version) {
274
- // `v` comes from untrusted JSON on the verify path. Two coercions make a
275
- // bare property read wrong here: numeric keys are stored as strings, so
276
- // ATTESTED_FIELDS_BY_VERSION['2'] resolves and a record carrying the *string*
277
- // "2" would pin its own field list; and an inherited key ('constructor',
278
- // '__proto__') resolves to a function or object rather than a field list.
279
- // Require a real integer and an own property.
280
- if (typeof version !== 'number' || !Number.isInteger(version)) return null;
281
- return Object.prototype.hasOwnProperty.call(ATTESTED_FIELDS_BY_VERSION, version)
282
- ? ATTESTED_FIELDS_BY_VERSION[version]
283
- : null;
284
- }
285
-
286
- // ---------------------------------------------------------------------------
287
- // canonicalisation
288
- // ---------------------------------------------------------------------------
289
-
290
- /**
291
- * Collapse a value to its comparable form: trimmed, whitespace-collapsed,
292
- * lowercased. Hashing is the only consumer, so display casing is preserved only
293
- * in `label`.
294
- */
295
- function normalise(value) {
296
- if (value === null || value === undefined) return '';
297
- return String(value).trim().replace(/\s+/g, ' ').toLowerCase();
298
- }
299
-
300
- /**
301
- * Deterministic JSON: keys sorted, undefined/function/symbol dropped, numbers
302
- * non-finite -> null, strings normalised, recursion bounded. Two structurally
303
- * equal records always produce byte-identical output, which is what lets
304
- * `verify` be a recomputation rather than a stored comparison.
305
- */
306
- function canonical(value, depth = 0) {
307
- if (depth > MAX_DEPTH) return '"[depth]"';
308
- if (value === null || value === undefined) return 'null';
309
-
310
- const t = typeof value;
311
- if (t === 'number') return Number.isFinite(value) ? String(value) : 'null';
312
- if (t === 'boolean') return value ? 'true' : 'false';
313
- if (t === 'string') return JSON.stringify(normalise(value));
314
- if (t === 'function' || t === 'symbol' || t === 'bigint') return 'null';
315
-
316
- if (Array.isArray(value)) {
317
- return '[' + value.map((v) => canonical(v, depth + 1)).join(',') + ']';
318
- }
319
-
320
- if (t === 'object') {
321
- const keys = Object.keys(value)
322
- .filter((k) => value[k] !== undefined && typeof value[k] !== 'function')
323
- .sort();
324
- return (
325
- '{' +
326
- keys.map((k) => JSON.stringify(k) + ':' + canonical(value[k], depth + 1)).join(',') +
327
- '}'
328
- );
329
- }
330
-
331
- return 'null';
332
- }
333
-
334
- /** Purpose-prefixed digest, hex. The prefix keeps one purpose's digest from ever
335
- * colliding with another's over the same input. */
336
- function digest(purpose, body) {
337
- return crypto.createHash(FP_ALGO).update(purpose + '\n' + body, 'utf8').digest('hex');
338
- }
339
-
340
- // ---------------------------------------------------------------------------
341
- // redaction helpers
342
- // ---------------------------------------------------------------------------
343
-
344
- /**
345
- * A label safe to store and display: bounded length, and control characters /
346
- * newlines stripped so a value can never forge a second record line. Mirrors
347
- * `avatar/identity.js`'s `safeLabel`, including its rule that a rejected value
348
- * is never echoed back.
349
- */
350
- function safeLabel(value, max = MAX_LABEL) {
351
- if (value === null || value === undefined) return '';
352
- const cleaned = String(value)
353
- // eslint-disable-next-line no-control-regex
354
- .replace(/[\u0000-\u001f\u007f]+/g, ' ')
355
- .replace(/\s+/g, ' ')
356
- .trim();
357
- if (!cleaned) return '';
358
- return cleaned.length > max ? cleaned.slice(0, max) : cleaned;
359
- }
360
-
361
- /** Any run of >= `n` hex characters. Keys, digests and seeds all look like this. */
362
- function longHexRun(value, n = LEAK_HEX_RUN) {
363
- return new RegExp(`[0-9a-fA-F]{${n},}`).test(String(value));
364
- }
365
-
366
- const HEX_ATTESTATION = new RegExp(`^[0-9a-f]{${ATTEST_LENGTH}}$`);
367
-
368
- function isFingerprintShape(value) {
369
- return new RegExp(`^[0-9a-f]{${KEY_FP_LENGTH}}$`).test(String(value || ''));
370
- }
371
-
372
- /**
373
- * Refuse to return a record that carries the secret or anything that looks like
374
- * a key. Throws rather than redacting: a caller that reached this point has a
375
- * bug in the shape of what it passes in, and silently dropping the field would
376
- * hide it.
377
- */
378
- function assertNoLeak(record, secret, alsoSecret) {
379
- const secrets = [secret, alsoSecret]
380
- .map((v) => (v === null || v === undefined ? '' : String(v)))
381
- .filter(Boolean);
382
- for (const [key, value] of Object.entries(record)) {
383
- if (value === null || value === undefined) continue;
384
- const text = Array.isArray(value) ? value.join('\u0000') : String(value);
385
-
386
- for (const s of secrets) {
387
- if (text.includes(s)) {
388
- throw new Error(`fingerprint: field "${key}" would carry the secret verbatim`);
389
- }
390
- }
391
- if (key === 'attestation') {
392
- if (!HEX_ATTESTATION.test(text)) {
393
- throw new Error('fingerprint: attestation must be 32 lowercase hex characters');
394
- }
395
- continue;
396
- }
397
- if (longHexRun(text)) {
398
- throw new Error(`fingerprint: field "${key}" carries a long hex run (possible key leak)`);
399
- }
400
- }
401
- return true;
402
- }
403
-
404
- /**
405
- * The same rule, applied to the *raw* inputs before any bounding.
406
- *
407
- * Without this, truncation is a laundering route: `label: 'x'.repeat(12) + secret`
408
- * gets cut to MAX_LABEL, the secret no longer appears whole, and twenty hex
409
- * characters of a live key land in the record unremarked. A caller that hands a
410
- * credential to a display field has a bug, and rule 2 says a caller bug in this
411
- * shape becomes loud rather than quiet — which is exactly what `assertNoLeak`
412
- * cannot do once the value has already been trimmed to fit.
413
- */
414
- function assertInputsClean(inputs, secret, alsoSecret) {
415
- const secrets = [secret, alsoSecret]
416
- .map((v) => (v === null || v === undefined ? '' : String(v)))
417
- .filter(Boolean);
418
- if (!secrets.length) return true;
419
- for (const field of ['label', 'account', 'model', 'tools', 'aiModel']) {
420
- const value = inputs[field];
421
- if (value === null || value === undefined) continue;
422
- const text = Array.isArray(value) ? value.join('\u0000') : String(value);
423
- if (secrets.some((s) => text.includes(s))) {
424
- throw new Error(`fingerprint: input "${field}" would carry the secret verbatim`);
425
- }
426
- if (longHexRun(text)) {
427
- throw new Error(`fingerprint: input "${field}" carries a long hex run (possible key leak)`);
428
- }
429
- }
430
- return true;
431
- }
432
-
433
- // ---------------------------------------------------------------------------
434
- // 1. credential identity
435
- // ---------------------------------------------------------------------------
436
-
437
- /**
438
- * `sha256('aegiscode-agent-v1:' + secret).slice(0, 12)`, hex — or `null` when no
439
- * secret is available, because "no credential" must not hash to a shared value
440
- * that would make every keyless agent look like the same agent.
441
- *
442
- * @param {string} secret - API key, device fingerprint seed, or any stable credential.
443
- * @returns {string|null}
444
- */
445
- function keyFingerprint(secret) {
446
- if (secret === null || secret === undefined) return null;
447
- const s = String(secret).trim();
448
- if (!s) return null;
449
- return digest('aegiscode-agent-v1', s).slice(0, KEY_FP_LENGTH);
450
- }
451
-
452
- // ---------------------------------------------------------------------------
453
- // 2. behavioural signature
454
- // ---------------------------------------------------------------------------
455
-
456
- /** One observation rendered canonically, or '' if it carries nothing usable. */
457
- function observationKey(observation) {
458
- if (typeof observation === 'string' || typeof observation === 'number') {
459
- return normalise(observation);
460
- }
461
- if (!observation || typeof observation !== 'object') return '';
462
- const parts = [observation.tool, observation.target, observation.outcome, observation.model]
463
- .map((p) => normalise(p))
464
- .join('|');
465
- return parts.replace(/^\|+|\|+$/g, '') ? parts : '';
466
- }
467
-
468
- /** How many observations actually carried signal. */
469
- function countObservations(observations) {
470
- if (!Array.isArray(observations)) return 0;
471
- return observations.slice(0, MAX_OBSERVATIONS).filter((o) => observationKey(o) !== '').length;
472
- }
473
-
474
- /**
475
- * A digest over a set of observations — deduplicated and sorted, so the same set
476
- * of actions fingerprints identically however the transcript was ordered, and a
477
- * replayed action adds nothing. This is the "behavioural signature" of the
478
- * covenant, not a transcript hash: two agents that used the same tools the same
479
- * way match, and a padded log does not inflate the match.
480
- *
481
- * The purpose string is a parameter because this primer serves two axes that must
482
- * not be able to agree by accident — the human's turns and the assistant's (see
483
- * `AI_PURPOSE`). Callers outside this file get `behaviouralSignature` and
484
- * `aiSignature`, each with its purpose bound.
485
- *
486
- * @returns {string|null} null when there is no observable behaviour — see rule 3.
487
- */
488
- function signatureFromObservations(observations, purpose) {
489
- if (!Array.isArray(observations)) return null;
490
- const keys = observations
491
- .slice(0, MAX_OBSERVATIONS)
492
- .map(observationKey)
493
- .filter(Boolean);
494
- if (!keys.length) return null;
495
- const unique = Array.from(new Set(keys)).sort();
496
- return digest(purpose, unique.join('\n')).slice(0, SIG_LENGTH);
497
- }
498
-
499
- function behaviouralSignature(observations) {
500
- return signatureFromObservations(observations, BEHAVIOUR_PURPOSE);
501
- }
502
-
503
- /**
504
- * The AI axis's behavioural signature: the same primer over the assistant's own
505
- * turns, under `AI_PURPOSE`.
506
- *
507
- * `null` for no observations, for the same reason `behaviouralSignature` is: a
508
- * mind with no recorded track record has no track record, and rendering that as a
509
- * zero-valued hash would be a claim the evidence does not support.
510
- */
511
- function aiSignature(observations) {
512
- return signatureFromObservations(observations, AI_PURPOSE);
513
- }
514
-
515
- /** Bounded, deduplicated tool list in canonical order. */
516
- function normaliseTools(tools) {
517
- if (!Array.isArray(tools)) return Object.freeze([]);
518
- const seen = new Set();
519
- for (const t of tools.slice(0, MAX_TOOLS)) {
520
- const n = normalise(typeof t === 'string' ? t : (t && (t.name || t.id)) || '');
521
- if (n) seen.add(n);
522
- }
523
- return Object.freeze(Array.from(seen).sort());
524
- }
525
-
526
- // ---------------------------------------------------------------------------
527
- // 2b. the code axis — which revision of which files produced this turn
528
- // ---------------------------------------------------------------------------
529
-
530
- /**
531
- * A repo-relative path in comparable form, or `null` if unusable.
532
- *
533
- * Separators are normalised to `/` and a leading `./` is dropped so the same
534
- * file reached two ways hashes once. Absolute paths and any path containing a
535
- * `..` segment are refused rather than "cleaned": a record whose paths could
536
- * escape its own root would name files outside the tree it claims to describe,
537
- * and the whole point of the axis is that the claim is recomputable.
538
- */
539
- function normaliseCodePath(value) {
540
- if (value === null || value === undefined) return null;
541
- const raw = String(value).replace(/\\/g, '/').trim();
542
- if (!raw) return null;
543
- if (raw.startsWith('/') || /^[a-zA-Z]:\//.test(raw)) return null;
544
- const parts = [];
545
- for (const seg of raw.split('/')) {
546
- if (seg === '' || seg === '.') continue;
547
- if (seg === '..') return null;
548
- parts.push(seg);
549
- }
550
- const rel = parts.join('/');
551
- if (!rel) return null;
552
- return rel.length > MAX_PATH ? null : rel;
553
- }
554
-
555
- /**
556
- * One file's contribution: `sha256('aegiscode-code-v3' + '\0' + relpath + '\0' +
557
- * content)`.
558
- *
559
- * The path is inside the hash on purpose. Hashing contents alone would make a
560
- * rename invisible, and a tree where `auth.js` and `handler.js` swap names is
561
- * not the same tree. Length-prefixing nothing and delimiting with NUL keeps
562
- * path and content from bleeding into each other: `('ab', 'c')` and `('a',
563
- * 'bc')` cannot collide.
564
- */
565
- function codeFileDigest(relpath, content) {
566
- const rel = normaliseCodePath(relpath);
567
- if (!rel) throw new Error(`fingerprint: unusable code path ${JSON.stringify(String(relpath))}`);
568
- const buf = Buffer.isBuffer(content)
569
- ? content
570
- : Buffer.from(content === null || content === undefined ? '' : String(content), 'utf8');
571
- return crypto
572
- .createHash(FP_ALGO)
573
- .update(`aegiscode-code-v3\u0000${rel}\u0000`, 'utf8')
574
- .update(buf)
575
- .digest('hex');
576
- }
577
-
578
- /**
579
- * Fold per-file digests, in sorted path order, into one 16-hex aggregate.
580
- *
581
- * Order-independence comes from the sort, not from the caller: a directory walk
582
- * returns files in whatever order the filesystem feels like, and two walks of
583
- * one tree must agree. The fold chains each file's digest into the running
584
- * accumulator, so moving a byte from one file to another changes the result —
585
- * unlike summing or XOR-ing per-file digests, which would not.
586
- *
587
- * @param {Array<{path: string, content: string|Buffer}>} files
588
- * @returns {{code: string|null, codeFiles: number}} `null`/`0` for no files —
589
- * absence of code evidence reads as absence (rule 3), never as a
590
- * zero-valued hash that a caller might mistake for a real revision.
591
- */
592
- function codeDigest(files) {
593
- if (!Array.isArray(files)) return { code: null, codeFiles: 0 };
594
-
595
- // Sorted input, duplicates resolved last-wins: a path listed twice is the same
596
- // file twice, and folding both would make the aggregate depend on how many
597
- // times the caller mentioned it.
598
- const byPath = new Map();
599
- for (const f of files) {
600
- if (!f || typeof f !== 'object') continue;
601
- const rel = normaliseCodePath(f.path);
602
- if (!rel) continue;
603
- byPath.set(rel, { path: rel, content: f.content });
604
- }
605
- const entries = Array.from(byPath.keys()).sort();
606
- if (!entries.length) return { code: null, codeFiles: 0 };
607
- if (entries.length > MAX_CODE_FILES) {
608
- throw new Error(
609
- `fingerprint: ${entries.length} code files exceeds MAX_CODE_FILES (${MAX_CODE_FILES}); ` +
610
- 'hash a subtree rather than silently attesting a prefix of one',
611
- );
612
- }
613
-
614
- let acc = digest('aegiscode-code-v3-root', String(entries.length));
615
- for (const rel of entries) {
616
- const d = codeFileDigest(rel, byPath.get(rel).content);
617
- acc = digest('aegiscode-code-v3-fold', `${acc}\n${rel}\n${d}`);
618
- }
619
- return { code: acc.slice(0, CODE_LEN), codeFiles: entries.length };
620
- }
621
-
622
- /**
623
- * The code axis of a record, with dirtiness passed through honestly.
624
- *
625
- * `codeDirty` is `true`/`false` only when the caller actually knew; anything
626
- * else is `null`. The CLI cannot tell clean from dirty without spawning `git`,
627
- * and this module's callers are promised a module that spawns nothing — so
628
- * "unknown" is a state the record is allowed to be in, and it is stored as
629
- * unknown rather than being rendered as `false`, which would be a claim the
630
- * evidence does not support.
631
- */
632
- function codeAxisFrom(files, codeDirty) {
633
- const { code, codeFiles } = codeDigest(files);
634
- const dirty = typeof codeDirty === 'boolean' ? codeDirty : null;
635
- return { code, codeFiles, codeDirty: code ? dirty : null };
636
- }
637
-
638
- // ---------------------------------------------------------------------------
639
- // 2c. the AI axis — which mind answered, and what it did
640
- // ---------------------------------------------------------------------------
641
-
642
- /**
643
- * Fold the AI half of a record out of the caller's inputs.
644
- *
645
- * Every field degrades to `null`/`0` rather than to a stand-in value, and for the
646
- * same reason the other axes do: a record may carry only what was observed.
647
- *
648
- * - no nominated credential ⇒ `aiKey: null`. NOT a hash of the authorship
649
- * key: the authorship key says who *sealed* the record, and reusing it here
650
- * would make every record look like it ran under its author's own key, which
651
- * is a claim about the session that nobody made.
652
- * - no AI observations ⇒ `ai: null, aiSamples: 0` (rule 3).
653
- * - no model named ⇒ `aiModel: null`, never the empty string.
654
- *
655
- * @param {object} [axis]
656
- * @param {string} [axis.secret] - the credential the session ran on. Never stored.
657
- * @param {string} [axis.model] - the model that answered.
658
- * @param {Array} [axis.observations]- the assistant's turns: `{tool, target, outcome, model}`.
659
- * @returns {{aiKey: string|null, aiModel: string|null, ai: string|null, aiSamples: number}}
660
- */
661
- function aiAxisFrom(axis = {}) {
662
- const { secret, model, observations } = axis || {};
663
- const aiKey = keyFingerprint(secret);
664
- const ai = aiSignature(observations);
665
- return {
666
- aiKey,
667
- aiModel: safeLabel(model, MAX_FIELD) || null,
668
- ai,
669
- aiSamples: ai ? countObservations(observations) : 0,
670
- };
671
- }
672
-
673
- // ---------------------------------------------------------------------------
674
- // 3. mint / attest / verify
675
- // ---------------------------------------------------------------------------
676
-
677
- /**
678
- * The exact bytes the attestation covers. The field list is chosen by the
679
- * record's own `v`, so a v1 record is attested over v1's fields and keeps
680
- * verifying after the shape moved on. Unknown fields are ignored either way.
681
- */
682
- function attestationBody(record) {
683
- const fields = attestedFieldsFor(record && record.v);
684
- if (!fields) {
685
- throw new Error(`fingerprint: cannot attest version ${record && record.v}`);
686
- }
687
- const body = {};
688
- for (const field of fields) {
689
- const v = record[field];
690
- body[field] = v === undefined ? null : v;
691
- }
692
- return canonical(body);
693
- }
694
-
695
- /** HMAC-SHA256(secret, attested fields), truncated to 128 bits. */
696
- function attest(record, secret) {
697
- if (!secret) throw new Error('fingerprint: a secret is required to attest a record');
698
- return crypto
699
- .createHmac(FP_ALGO, String(secret))
700
- .update(attestationBody(record), 'utf8')
701
- .digest('hex')
702
- .slice(0, ATTEST_LENGTH);
703
- }
704
-
705
- function isoTs(value) {
706
- if (value === null || value === undefined) return new Date().toISOString();
707
- const d = value instanceof Date ? value : new Date(value);
708
- if (Number.isNaN(d.getTime())) throw new Error('fingerprint: createdAt is not a valid date');
709
- return d.toISOString();
710
- }
711
-
712
- /**
713
- * The thumb axis of a record, recomputed from a captured profile's medians.
714
- *
715
- * Deliberately ignores any `signature` field the profile carries: recomputation
716
- * is what makes the record's thumb axis trustworthy, and trusting the file's own
717
- * hash would make it the one field in φ(α) that was taken on faith. Unusable
718
- * input degrades to "no thumb axis" (`null`/`0`), never to a zero-valued hash and
719
- * never to a leaked string.
720
- *
721
- * @param {object} profile - shape as produced by `src/touch.js`'s `profile()`.
722
- * @returns {{signature: string|null, samples: number}}
723
- */
724
- function touchSignatureFrom(profile) {
725
- if (!profile || typeof profile !== 'object') return { signature: null, samples: 0 };
726
- const samples = Number(profile.samples) || 0;
727
- const signature = signatureFromMedians(profile.medians, samples);
728
- return { signature, samples: signature ? samples : 0 };
729
- }
730
-
731
- /**
732
- * Mint φ(α).
733
- *
734
- * @param {object} input
735
- * @param {string} input.secret - credential; required. Never stored.
736
- * @param {string} [input.label] - human display name.
737
- * @param {string} [input.account] - cloud account id (survives key rotation).
738
- * @param {string} [input.model] - model the agent runs on.
739
- * @param {string[]} [input.tools] - tools it can reach.
740
- * @param {Array} [input.observations] - what it did; feeds the behavioural signature.
741
- * @param {object} [input.touch] - thumb profile from `src/touch.js`; feeds the
742
- * gesture-dynamics signature. NOT keyed by the
743
- * secret: a credential is not a hand.
744
- * @param {Array<{path: string, content: string|Buffer}>} [input.code]
745
- * - the revision this turn ran against, as
746
- * repo-relative path + content pairs. The
747
- * walk that produces them lives in the caller
748
- * (a tool), so this module stays I/O-free
749
- * apart from test vectors.
750
- * @param {boolean} [input.codeDirty] - whether that tree had uncommitted changes,
751
- * when the caller could actually tell.
752
- * @param {string|Date} [input.createdAt]
753
- * @returns {object} frozen, attested record.
754
- */
755
- function mint(input = {}) {
756
- const {
757
- secret,
758
- label,
759
- account,
760
- model,
761
- tools,
762
- observations,
763
- touch,
764
- code,
765
- codeDirty,
766
- aiSecret,
767
- aiModel,
768
- aiObservations,
769
- createdAt,
770
- } = input;
771
- const kf = keyFingerprint(secret);
772
- if (!kf) {
773
- throw new Error('fingerprint: a secret (API key or device seed) is required to mint φ(α)');
774
- }
775
-
776
- // Before bounding: a key in a display field must refuse, not get truncated.
777
- // Both credentials are checked — the AI's key is a live provider key, and a
778
- // record carrying it in `aiModel` would be exactly the leak this guard exists
779
- // to catch.
780
- assertInputsClean({ label, account, model, tools, aiModel }, secret, aiSecret);
781
-
782
- const thumb = touchSignatureFrom(touch);
783
- const codeAxis = codeAxisFrom(code, codeDirty);
784
- const ai = aiAxisFrom({ secret: aiSecret, model: aiModel, observations: aiObservations });
785
-
786
- const record = {
787
- v: FP_VERSION,
788
- algo: FP_ALGO,
789
- keyFingerprint: kf,
790
- label: safeLabel(label, MAX_LABEL),
791
- account: safeLabel(account, MAX_FIELD) || null,
792
- model: safeLabel(model, MAX_FIELD) || null,
793
- tools: normaliseTools(tools),
794
- behaviour: behaviouralSignature(observations),
795
- behaviourSamples: countObservations(observations),
796
- touch: thumb.signature,
797
- touchSamples: thumb.samples,
798
- code: codeAxis.code,
799
- codeFiles: codeAxis.codeFiles,
800
- codeDirty: codeAxis.codeDirty,
801
- aiKey: ai.aiKey,
802
- aiModel: ai.aiModel,
803
- ai: ai.ai,
804
- aiSamples: ai.aiSamples,
805
- createdAt: isoTs(createdAt),
806
- };
807
-
808
- const sealed = { ...record, attestation: attest(record, secret) };
809
- assertNoLeak(sealed, secret, aiSecret);
810
- return Object.freeze(sealed);
811
- }
812
-
813
- /** `φ_<keyFingerprint><behaviour|——>`: short, stable, safe to log. */
814
- function id(record) {
815
- if (!record || !isFingerprintShape(record.keyFingerprint)) {
816
- throw new Error('fingerprint: not a fingerprinted record');
817
- }
818
- return `${FP_PREFIX}${record.keyFingerprint}-${record.behaviour || 'unobserved'}`;
819
- }
820
-
821
- function sameReason(record) {
822
- if (!record || typeof record !== 'object') return 'not a record';
823
- if (!attestedFieldsFor(record.v)) return `unsupported version ${record.v}`;
824
- if (record.algo !== FP_ALGO) return `unsupported algo ${record.algo}`;
825
- if (!isFingerprintShape(record.keyFingerprint)) return 'keyFingerprint is malformed';
826
- return null;
827
- }
828
-
829
- /**
830
- * Verify a record by recomputation, not by trusting its stored tag.
831
- *
832
- * @returns {{ok: boolean, reason: string|null, id: string|null, credentialMatch: boolean|null}}
833
- */
834
- function verify(record, secret) {
835
- const bad = sameReason(record);
836
- if (bad) return { ok: false, reason: bad, id: null, credentialMatch: null };
837
-
838
- const credentialMatch = secret ? keyFingerprint(secret) === record.keyFingerprint : null;
839
-
840
- if (!secret) {
841
- return {
842
- ok: false,
843
- reason: 'no secret supplied — attestation cannot be recomputed',
844
- id: id(record),
845
- credentialMatch: null,
846
- };
847
- }
848
-
849
- const expected = attest(record, secret);
850
- const got = String(record.attestation || '');
851
- const a = Buffer.from(expected, 'utf8');
852
- const b = Buffer.from(got.padEnd(expected.length, ' ').slice(0, expected.length), 'utf8');
853
- const tagOk = a.length === b.length && crypto.timingSafeEqual(a, b);
854
-
855
- if (!tagOk) {
856
- return { ok: false, reason: 'attestation mismatch', id: id(record), credentialMatch };
857
- }
858
- if (!credentialMatch) {
859
- return {
860
- ok: false,
861
- reason: 'attestation valid but secret does not match keyFingerprint',
862
- id: id(record),
863
- credentialMatch: false,
864
- };
865
- }
866
- return { ok: true, reason: null, id: id(record), credentialMatch: true };
867
- }
868
-
869
- /**
870
- * Compare two records on one axis. Explicit on purpose: "same credential" and
871
- * "same behaviour" are different claims (rule 1), and a caller that does not say
872
- * which one it wants gets an error rather than an answer.
873
- *
874
- * @param {'credential'|'behaviour'|'full'} axis
875
- */
876
- function same(a, b, axis = 'full') {
877
- if (!a || !b) return false;
878
- if (axis === 'credential') return a.keyFingerprint === b.keyFingerprint;
879
- if (axis === 'behaviour') {
880
- return Boolean(a.behaviour) && a.behaviour === b.behaviour;
881
- }
882
- if (axis === 'full') {
883
- return a.keyFingerprint === b.keyFingerprint && a.behaviour === b.behaviour;
884
- }
885
- if (axis === 'ai-credential') {
886
- return Boolean(a.aiKey) && a.aiKey === b.aiKey;
887
- }
888
- if (axis === 'ai') {
889
- return Boolean(a.ai) && a.ai === b.ai;
890
- }
891
- if (axis === 'mind') {
892
- return (
893
- Boolean(a.aiKey) && a.aiKey === b.aiKey && Boolean(a.ai) && a.ai === b.ai
894
- );
895
- }
896
- throw new Error(`fingerprint: unknown comparison axis "${axis}"`);
897
- }
898
-
899
- /** Display form. Carries no field a key could hide in. */
900
- function describe(record) {
901
- const bad = sameReason(record);
902
- if (bad) return `φ(?) ${bad}`;
903
- const bits = [
904
- `key ${record.keyFingerprint}`,
905
- record.behaviour ? `behaviour ${record.behaviour}` : 'behaviour unobserved',
906
- record.behaviourSamples ? `${record.behaviourSamples} samples` : null,
907
- record.touch ? `touch ${record.touch}` : 'touch unobserved',
908
- record.touchSamples ? `${record.touchSamples} strokes` : null,
909
- record.code
910
- ? `code ${record.code}${record.codeDirty === null ? '' : record.codeDirty ? ' (dirty)' : ' (clean)'}`
911
- : 'code unobserved',
912
- record.codeFiles ? `${record.codeFiles} files` : null,
913
- record.ai && record.aiKey
914
- ? `ai ${record.ai} on ${record.aiKey}`
915
- : record.ai
916
- ? `ai ${record.ai} (no key nominated)`
917
- : record.aiKey
918
- ? `ai key ${record.aiKey}, behaviour unobserved`
919
- : 'ai unobserved',
920
- record.aiSamples ? `${record.aiSamples} ai turn(s)` : null,
921
- record.aiModel ? `ran on ${record.aiModel}` : null,
922
- record.model ? `model ${record.model}` : null,
923
- record.tools && record.tools.length ? `tools ${record.tools.length}` : null,
924
- ].filter(Boolean);
925
- return `${record.label || 'agent'} · ${bits.join(' · ')}`;
926
- }
927
-
928
- // ---------------------------------------------------------------------------
929
- // CLI — `node src/fingerprint.js --label x --observations file.json`
930
- // `node src/fingerprint.js --ai-observations ai.json --ai-model gpt-5`
931
- // `node src/fingerprint.js --verify record.json`
932
- //
933
- // The secret comes from AEGIS_FINGERPRINT_SECRET or --secret-file, never from
934
- // argv: argv is visible in `ps` to every process on the box.
935
- // ---------------------------------------------------------------------------
936
-
937
- /**
938
- * The AI half's credential, from the same two rungs as the authorship secret and
939
- * never from argv (a key in `ps` is a published key).
940
- *
941
- * It is read from `AEGIS_AI_SECRET`, then `--ai-secret-file`. Deliberately a
942
- * separate variable from `AEGIS_FINGERPRINT_SECRET`: the authorship key seals the
943
- * record, the AI key names the mind that answered, and a single variable would
944
- * make "sealed by" and "ran on" the same value by default — the conflation the two
945
- * fields exist to prevent.
946
- */
947
- function readAiSecret(argv, env) {
948
- if (env.AEGIS_AI_SECRET) return String(env.AEGIS_AI_SECRET).trim();
949
- const i = argv.indexOf('--ai-secret-file');
950
- if (i !== -1 && argv[i + 1]) {
951
- return fs.readFileSync(argv[i + 1], 'utf8').trim();
952
- }
953
- return '';
954
- }
955
-
956
- function readSecret(argv, env) {
957
- if (env.AEGIS_FINGERPRINT_SECRET) return String(env.AEGIS_FINGERPRINT_SECRET).trim();
958
- const i = argv.indexOf('--secret-file');
959
- if (i !== -1 && argv[i + 1]) {
960
- return fs.readFileSync(argv[i + 1], 'utf8').trim();
961
- }
962
- return '';
963
- }
964
-
965
- function flag(argv, name, fallback = null) {
966
- const i = argv.indexOf(name);
967
- return i !== -1 && argv[i + 1] !== undefined ? argv[i + 1] : fallback;
968
- }
969
-
970
- function main(argv, env = process.env) {
971
- const secret = readSecret(argv, env);
972
-
973
- if (argv.includes('--verify')) {
974
- const file = flag(argv, '--verify');
975
- if (!file) throw new Error('fingerprint: --verify needs a record file');
976
- const record = JSON.parse(fs.readFileSync(file, 'utf8'));
977
- const result = verify(record, secret);
978
- process.stdout.write(JSON.stringify(result, null, 2) + '\n');
979
- return result.ok ? 0 : 1;
980
- }
981
-
982
- const obsFile = flag(argv, '--observations');
983
- const observations = obsFile ? JSON.parse(fs.readFileSync(obsFile, 'utf8')) : [];
984
-
985
- // The thumb profile comes from `tools/aegis-touchpad.mjs capture`. Only its
986
- // medians are used; its own `signature` field is recomputed, not believed.
987
- const touchFile = flag(argv, '--touch');
988
- const touch = touchFile ? JSON.parse(fs.readFileSync(touchFile, 'utf8')) : null;
989
-
990
- // The AI half: which mind answered, and what it did. The observations file is a
991
- // separate one because the two axes are separate claims — a session log's
992
- // `reply` text is not an AI observation, and `--ai-observations` is the caller
993
- // saying it actually has some.
994
- const aiObsFile = flag(argv, '--ai-observations');
995
- const aiObservations = aiObsFile ? JSON.parse(fs.readFileSync(aiObsFile, 'utf8')) : null;
996
-
997
- const record = mint({
998
- secret,
999
- label: flag(argv, '--label', ''),
1000
- account: flag(argv, '--account', ''),
1001
- model: flag(argv, '--model', ''),
1002
- tools: (flag(argv, '--tools', '') || '').split(',').filter(Boolean),
1003
- observations,
1004
- touch,
1005
- aiSecret: readAiSecret(argv, env),
1006
- aiModel: flag(argv, '--ai-model', ''),
1007
- aiObservations,
1008
- });
1009
- process.stdout.write(JSON.stringify(record, null, 2) + '\n');
1010
- return 0;
1011
- }
1012
-
1013
- const API = {
1014
- // identity
1015
- mint,
1016
- verify,
1017
- attest,
1018
- attestationBody,
1019
- id,
1020
- same,
1021
- describe,
1022
- // pieces
1023
- keyFingerprint,
1024
- behaviouralSignature,
1025
- aiSignature,
1026
- aiAxisFrom,
1027
- observationKey,
1028
- countObservations,
1029
- normaliseTools,
1030
- safeLabel,
1031
- touchSignatureFrom,
1032
- normaliseCodePath,
1033
- codeFileDigest,
1034
- codeDigest,
1035
- codeAxisFrom,
1036
- // guards & constants
1037
- canonical,
1038
- assertNoLeak,
1039
- assertInputsClean,
1040
- longHexRun,
1041
- isFingerprintShape,
1042
- attestedFieldsFor,
1043
- FP_VERSION,
1044
- FP_ALGO,
1045
- FP_PREFIX,
1046
- KEY_FP_LENGTH,
1047
- SIG_LENGTH,
1048
- ATTEST_LENGTH,
1049
- LEAK_HEX_RUN,
1050
- CODE_LEN,
1051
- MAX_CODE_FILES,
1052
- MAX_PATH,
1053
- BEHAVIOUR_PURPOSE,
1054
- AI_PURPOSE,
1055
- ATTESTED_FIELDS,
1056
- ATTESTED_FIELDS_V1,
1057
- ATTESTED_FIELDS_V2,
1058
- ATTESTED_FIELDS_V3,
1059
- ATTESTED_FIELDS_V4,
1060
- ATTESTED_FIELDS_BY_VERSION,
1061
- main,
1062
- };
1063
-
1064
-
1065
-
1066
- module.exports = API;
3
+ "use strict";const crypto=require("node:crypto"),fs=require("node:fs"),{signatureFromMedians:signatureFromMedians,MIN_STROKES:TOUCH_MIN_STROKES}=require("./touch.js"),FP_VERSION=4,FP_ALGO="sha256",FP_PREFIX="φ_",KEY_FP_LENGTH=12,SIG_LENGTH=16,ATTEST_LENGTH=32,LEAK_HEX_RUN=24,MAX_LABEL=40,MAX_FIELD=64,MAX_TOOLS=64,MAX_OBSERVATIONS=4096,MAX_DEPTH=8,CODE_LEN=SIG_LENGTH,MAX_CODE_FILES=4096,MAX_PATH=200,ATTESTED_FIELDS_V1=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","createdAt"]),BEHAVIOUR_PURPOSE="aegiscode-behaviour-v2",AI_PURPOSE="aegiscode-ai-v1",ATTESTED_FIELDS_V2=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","createdAt"]),ATTESTED_FIELDS_V3=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","code","codeFiles","codeDirty","createdAt"]),ATTESTED_FIELDS_V4=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","code","codeFiles","codeDirty","aiKey","aiModel","ai","aiSamples","createdAt"]),ATTESTED_FIELDS=ATTESTED_FIELDS_V4,ATTESTED_FIELDS_BY_VERSION=Object.freeze({1:ATTESTED_FIELDS_V1,2:ATTESTED_FIELDS_V2,3:ATTESTED_FIELDS_V3,4:ATTESTED_FIELDS_V4});function attestedFieldsFor(e){return"number"==typeof e&&Number.isInteger(e)&&Object.prototype.hasOwnProperty.call(ATTESTED_FIELDS_BY_VERSION,e)?ATTESTED_FIELDS_BY_VERSION[e]:null}function normalise(e){return null==e?"":String(e).trim().replace(/\s+/g," ").toLowerCase()}function canonical(e,t=0){if(t>MAX_DEPTH)return'"[depth]"';if(null==e)return"null";const r=typeof e;return"number"===r?Number.isFinite(e)?String(e):"null":"boolean"===r?e?"true":"false":"string"===r?JSON.stringify(normalise(e)):"function"===r||"symbol"===r||"bigint"===r?"null":Array.isArray(e)?"["+e.map((e=>canonical(e,t+1))).join(",")+"]":"object"===r?"{"+Object.keys(e).filter((t=>void 0!==e[t]&&"function"!=typeof e[t])).sort().map((r=>JSON.stringify(r)+":"+canonical(e[r],t+1))).join(",")+"}":"null"}function digest(e,t){return crypto.createHash(FP_ALGO).update(e+"\n"+t,"utf8").digest("hex")}function safeLabel(e,t=MAX_LABEL){if(null==e)return"";const r=String(e).replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return r?r.length>t?r.slice(0,t):r:""}function longHexRun(e,t=LEAK_HEX_RUN){return new RegExp(`[0-9a-fA-F]{${t},}`).test(String(e))}const HEX_ATTESTATION=new RegExp(`^[0-9a-f]{${ATTEST_LENGTH}}$`);function isFingerprintShape(e){return new RegExp(`^[0-9a-f]{${KEY_FP_LENGTH}}$`).test(String(e||""))}function assertNoLeak(e,t,r){const n=[t,r].map((e=>null==e?"":String(e))).filter(Boolean);for(const[t,r]of Object.entries(e)){if(null==r)continue;const e=Array.isArray(r)?r.join("\0"):String(r);for(const r of n)if(e.includes(r))throw new Error(`fingerprint: field "${t}" would carry the secret verbatim`);if("attestation"!==t){if(longHexRun(e))throw new Error(`fingerprint: field "${t}" carries a long hex run (possible key leak)`)}else if(!HEX_ATTESTATION.test(e))throw new Error("fingerprint: attestation must be 32 lowercase hex characters")}return!0}function assertInputsClean(e,t,r){const n=[t,r].map((e=>null==e?"":String(e))).filter(Boolean);if(!n.length)return!0;for(const t of["label","account","model","tools","aiModel"]){const r=e[t];if(null==r)continue;const i=Array.isArray(r)?r.join("\0"):String(r);if(n.some((e=>i.includes(e))))throw new Error(`fingerprint: input "${t}" would carry the secret verbatim`);if(longHexRun(i))throw new Error(`fingerprint: input "${t}" carries a long hex run (possible key leak)`)}return!0}function keyFingerprint(e){if(null==e)return null;const t=String(e).trim();return t?digest("aegiscode-agent-v1",t).slice(0,KEY_FP_LENGTH):null}function observationKey(e){if("string"==typeof e||"number"==typeof e)return normalise(e);if(!e||"object"!=typeof e)return"";const t=[e.tool,e.target,e.outcome,e.model].map((e=>normalise(e))).join("|");return t.replace(/^\|+|\|+$/g,"")?t:""}function countObservations(e){return Array.isArray(e)?e.slice(0,MAX_OBSERVATIONS).filter((e=>""!==observationKey(e))).length:0}function signatureFromObservations(e,t){if(!Array.isArray(e))return null;const r=e.slice(0,MAX_OBSERVATIONS).map(observationKey).filter(Boolean);return r.length?digest(t,Array.from(new Set(r)).sort().join("\n")).slice(0,SIG_LENGTH):null}function behaviouralSignature(e){return signatureFromObservations(e,BEHAVIOUR_PURPOSE)}function aiSignature(e){return signatureFromObservations(e,AI_PURPOSE)}function normaliseTools(e){if(!Array.isArray(e))return Object.freeze([]);const t=new Set;for(const r of e.slice(0,MAX_TOOLS)){const e=normalise("string"==typeof r?r:r&&(r.name||r.id)||"");e&&t.add(e)}return Object.freeze(Array.from(t).sort())}function normaliseCodePath(e){if(null==e)return null;const t=String(e).replace(/\\/g,"/").trim();if(!t)return null;if(t.startsWith("/")||/^[a-zA-Z]:\//.test(t))return null;const r=[];for(const e of t.split("/"))if(""!==e&&"."!==e){if(".."===e)return null;r.push(e)}const n=r.join("/");return n?n.length>MAX_PATH?null:n:null}function codeFileDigest(e,t){const r=normaliseCodePath(e);if(!r)throw new Error(`fingerprint: unusable code path ${JSON.stringify(String(e))}`);const n=Buffer.isBuffer(t)?t:Buffer.from(null==t?"":String(t),"utf8");return crypto.createHash(FP_ALGO).update(`aegiscode-code-v3\0${r}\0`,"utf8").update(n).digest("hex")}function codeDigest(e){if(!Array.isArray(e))return{code:null,codeFiles:0};const t=new Map;for(const r of e){if(!r||"object"!=typeof r)continue;const e=normaliseCodePath(r.path);e&&t.set(e,{path:e,content:r.content})}const r=Array.from(t.keys()).sort();if(!r.length)return{code:null,codeFiles:0};if(r.length>MAX_CODE_FILES)throw new Error(`fingerprint: ${r.length} code files exceeds MAX_CODE_FILES (${MAX_CODE_FILES}); hash a subtree rather than silently attesting a prefix of one`);let n=digest("aegiscode-code-v3-root",String(r.length));for(const e of r)n=digest("aegiscode-code-v3-fold",`${n}\n${e}\n${codeFileDigest(e,t.get(e).content)}`);return{code:n.slice(0,CODE_LEN),codeFiles:r.length}}function codeAxisFrom(e,t){const{code:r,codeFiles:n}=codeDigest(e);return{code:r,codeFiles:n,codeDirty:r&&"boolean"==typeof t?t:null}}function aiAxisFrom(e={}){const{secret:t,model:r,observations:n}=e||{},i=keyFingerprint(t),o=aiSignature(n);return{aiKey:i,aiModel:safeLabel(r,MAX_FIELD)||null,ai:o,aiSamples:o?countObservations(n):0}}function attestationBody(e){const t=attestedFieldsFor(e&&e.v);if(!t)throw new Error(`fingerprint: cannot attest version ${e&&e.v}`);const r={};for(const n of t){const t=e[n];r[n]=void 0===t?null:t}return canonical(r)}function attest(e,t){if(!t)throw new Error("fingerprint: a secret is required to attest a record");return crypto.createHmac(FP_ALGO,String(t)).update(attestationBody(e),"utf8").digest("hex").slice(0,ATTEST_LENGTH)}function isoTs(e){if(null==e)return(new Date).toISOString();const t=e instanceof Date?e:new Date(e);if(Number.isNaN(t.getTime()))throw new Error("fingerprint: createdAt is not a valid date");return t.toISOString()}function touchSignatureFrom(e){if(!e||"object"!=typeof e)return{signature:null,samples:0};const t=Number(e.samples)||0,r=signatureFromMedians(e.medians,t);return{signature:r,samples:r?t:0}}function mint(e={}){const{secret:t,label:r,account:n,model:i,tools:o,observations:a,touch:s,code:l,codeDirty:u,aiSecret:c,aiModel:f,aiObservations:d,createdAt:E}=e,S=keyFingerprint(t);if(!S)throw new Error("fingerprint: a secret (API key or device seed) is required to mint φ(α)");assertInputsClean({label:r,account:n,model:i,tools:o,aiModel:f},t,c);const g=touchSignatureFrom(s),_=codeAxisFrom(l,u),p=aiAxisFrom({secret:c,model:f,observations:d}),F={v:FP_VERSION,algo:FP_ALGO,keyFingerprint:S,label:safeLabel(r,MAX_LABEL),account:safeLabel(n,MAX_FIELD)||null,model:safeLabel(i,MAX_FIELD)||null,tools:normaliseTools(o),behaviour:behaviouralSignature(a),behaviourSamples:countObservations(a),touch:g.signature,touchSamples:g.samples,code:_.code,codeFiles:_.codeFiles,codeDirty:_.codeDirty,aiKey:p.aiKey,aiModel:p.aiModel,ai:p.ai,aiSamples:p.aiSamples,createdAt:isoTs(E)},T={...F,attestation:attest(F,t)};return assertNoLeak(T,t,c),Object.freeze(T)}function id(e){if(!e||!isFingerprintShape(e.keyFingerprint))throw new Error("fingerprint: not a fingerprinted record");return`${FP_PREFIX}${e.keyFingerprint}-${e.behaviour||"unobserved"}`}function sameReason(e){return e&&"object"==typeof e?attestedFieldsFor(e.v)?e.algo!==FP_ALGO?`unsupported algo ${e.algo}`:isFingerprintShape(e.keyFingerprint)?null:"keyFingerprint is malformed":`unsupported version ${e.v}`:"not a record"}function verify(e,t){const r=sameReason(e);if(r)return{ok:!1,reason:r,id:null,credentialMatch:null};const n=t?keyFingerprint(t)===e.keyFingerprint:null;if(!t)return{ok:!1,reason:"no secret supplied — attestation cannot be recomputed",id:id(e),credentialMatch:null};const i=attest(e,t),o=String(e.attestation||""),a=Buffer.from(i,"utf8"),s=Buffer.from(o.padEnd(i.length," ").slice(0,i.length),"utf8");return a.length===s.length&&crypto.timingSafeEqual(a,s)?n?{ok:!0,reason:null,id:id(e),credentialMatch:!0}:{ok:!1,reason:"attestation valid but secret does not match keyFingerprint",id:id(e),credentialMatch:!1}:{ok:!1,reason:"attestation mismatch",id:id(e),credentialMatch:n}}function same(e,t,r="full"){if(!e||!t)return!1;if("credential"===r)return e.keyFingerprint===t.keyFingerprint;if("behaviour"===r)return Boolean(e.behaviour)&&e.behaviour===t.behaviour;if("full"===r)return e.keyFingerprint===t.keyFingerprint&&e.behaviour===t.behaviour;if("ai-credential"===r)return Boolean(e.aiKey)&&e.aiKey===t.aiKey;if("ai"===r)return Boolean(e.ai)&&e.ai===t.ai;if("mind"===r)return Boolean(e.aiKey)&&e.aiKey===t.aiKey&&Boolean(e.ai)&&e.ai===t.ai;throw new Error(`fingerprint: unknown comparison axis "${r}"`)}function describe(e){const t=sameReason(e);if(t)return`φ(?) ${t}`;const r=[`key ${e.keyFingerprint}`,e.behaviour?`behaviour ${e.behaviour}`:"behaviour unobserved",e.behaviourSamples?`${e.behaviourSamples} samples`:null,e.touch?`touch ${e.touch}`:"touch unobserved",e.touchSamples?`${e.touchSamples} strokes`:null,e.code?`code ${e.code}${null===e.codeDirty?"":e.codeDirty?" (dirty)":" (clean)"}`:"code unobserved",e.codeFiles?`${e.codeFiles} files`:null,e.ai&&e.aiKey?`ai ${e.ai} on ${e.aiKey}`:e.ai?`ai ${e.ai} (no key nominated)`:e.aiKey?`ai key ${e.aiKey}, behaviour unobserved`:"ai unobserved",e.aiSamples?`${e.aiSamples} ai turn(s)`:null,e.aiModel?`ran on ${e.aiModel}`:null,e.model?`model ${e.model}`:null,e.tools&&e.tools.length?`tools ${e.tools.length}`:null].filter(Boolean);return`${e.label||"agent"} · ${r.join(" · ")}`}function readAiSecret(e,t){if(t.AEGIS_AI_SECRET)return String(t.AEGIS_AI_SECRET).trim();const r=e.indexOf("--ai-secret-file");return-1!==r&&e[r+1]?fs.readFileSync(e[r+1],"utf8").trim():""}function readSecret(e,t){if(t.AEGIS_FINGERPRINT_SECRET)return String(t.AEGIS_FINGERPRINT_SECRET).trim();const r=e.indexOf("--secret-file");return-1!==r&&e[r+1]?fs.readFileSync(e[r+1],"utf8").trim():""}function flag(e,t,r=null){const n=e.indexOf(t);return-1!==n&&void 0!==e[n+1]?e[n+1]:r}function main(e,t=process.env){const r=readSecret(e,t);if(e.includes("--verify")){const t=flag(e,"--verify");if(!t)throw new Error("fingerprint: --verify needs a record file");const n=verify(JSON.parse(fs.readFileSync(t,"utf8")),r);return process.stdout.write(JSON.stringify(n,null,2)+"\n"),n.ok?0:1}const n=flag(e,"--observations"),i=n?JSON.parse(fs.readFileSync(n,"utf8")):[],o=flag(e,"--touch"),a=o?JSON.parse(fs.readFileSync(o,"utf8")):null,s=flag(e,"--ai-observations"),l=s?JSON.parse(fs.readFileSync(s,"utf8")):null,u=mint({secret:r,label:flag(e,"--label",""),account:flag(e,"--account",""),model:flag(e,"--model",""),tools:(flag(e,"--tools","")||"").split(",").filter(Boolean),observations:i,touch:a,aiSecret:readAiSecret(e,t),aiModel:flag(e,"--ai-model",""),aiObservations:l});return process.stdout.write(JSON.stringify(u,null,2)+"\n"),0}const API={mint:mint,verify:verify,attest:attest,attestationBody:attestationBody,id:id,same:same,describe:describe,keyFingerprint:keyFingerprint,behaviouralSignature:behaviouralSignature,aiSignature:aiSignature,aiAxisFrom:aiAxisFrom,observationKey:observationKey,countObservations:countObservations,normaliseTools:normaliseTools,safeLabel:safeLabel,touchSignatureFrom:touchSignatureFrom,normaliseCodePath:normaliseCodePath,codeFileDigest:codeFileDigest,codeDigest:codeDigest,codeAxisFrom:codeAxisFrom,canonical:canonical,assertNoLeak:assertNoLeak,assertInputsClean:assertInputsClean,longHexRun:longHexRun,isFingerprintShape:isFingerprintShape,attestedFieldsFor:attestedFieldsFor,FP_VERSION:FP_VERSION,FP_ALGO:FP_ALGO,FP_PREFIX:FP_PREFIX,KEY_FP_LENGTH:KEY_FP_LENGTH,SIG_LENGTH:SIG_LENGTH,ATTEST_LENGTH:ATTEST_LENGTH,LEAK_HEX_RUN:LEAK_HEX_RUN,CODE_LEN:CODE_LEN,MAX_CODE_FILES:MAX_CODE_FILES,MAX_PATH:MAX_PATH,BEHAVIOUR_PURPOSE:BEHAVIOUR_PURPOSE,AI_PURPOSE:AI_PURPOSE,ATTESTED_FIELDS:ATTESTED_FIELDS,ATTESTED_FIELDS_V1:ATTESTED_FIELDS_V1,ATTESTED_FIELDS_V2:ATTESTED_FIELDS_V2,ATTESTED_FIELDS_V3:ATTESTED_FIELDS_V3,ATTESTED_FIELDS_V4:ATTESTED_FIELDS_V4,ATTESTED_FIELDS_BY_VERSION:ATTESTED_FIELDS_BY_VERSION,main:main};module.exports=API;