aegiscode 6.8.11 → 6.8.12

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.
@@ -0,0 +1,455 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * VENDORED — do not edit. Generated by tools/vendor-fingerprint.mjs.
5
+ *
6
+ * source: aegiscodex 079f445 — src/touch.js
7
+ * rewrite: ESM -> CJS, module syntax only. No constant, purpose string,
8
+ * attested field list or digest differs from the engine's.
9
+ * verify: node --test test/fingerprint-interop.test.mjs
10
+ * refresh: node tools/vendor-fingerprint.mjs
11
+ */
12
+ /**
13
+ * touch.js — the thumb axis of φ(α): gesture dynamics from the trackpad.
14
+ *
15
+ * ## What this is, and what it is not
16
+ *
17
+ * It is NOT a fingerprint. This machine has no fingerprint sensor: `fprintd-list`
18
+ * reports "No devices available", `lsusb` shows no imaging device, and the
19
+ * trackpad (Apple `05ac:0253`, bcm5974) has no imager. A trackpad cannot image a
20
+ * ridge pattern, so nothing here should ever be labelled `fingerprint`.
21
+ *
22
+ * It is also not the trackpad's *touch* data. The kernel does expose contact size
23
+ * and force for this device (`ABS_MT_TOUCH_MAJOR`, pressure), but only through
24
+ * `/dev/input/eventN`, which is `root:input` and this user is not in `input`.
25
+ * Reachable without privilege through X, the trackpad exposes exactly four
26
+ * valuators — `Rel X`, `Rel Y`, `Rel Horiz Scroll`, `Rel Vert Scroll`. There is
27
+ * no absolute contact geometry in that list, and there is no `Touch` class, so
28
+ * the pad cannot say where a finger is, how big it is, or how hard it presses.
29
+ *
30
+ * What is left — and it is real — is *how the thumb moves*: the timing, shape and
31
+ * smoothness of a stroke. That is a behavioural biometric, the same family as
32
+ * keystroke dynamics. It is stable enough to distinguish habitual users on one
33
+ * device, and it is a much weaker claim than a fingerprint: it varies with
34
+ * fatigue, moisture, posture and what else is on the pad, and it is *learned*,
35
+ * not measured. `compareTouch` therefore returns a graded score, never a
36
+ * boolean identity, and `THRESHOLD` is documented as a default rather than a
37
+ * truth.
38
+ *
39
+ * ## Why the deltas are raw
40
+ *
41
+ * `Rel X`/`Rel Y` in a `Motion` event have already been through the X pointer
42
+ * acceleration curve, which multiplies fast movement more than slow movement.
43
+ * Speed is one of the features below, so acceleration would make the feature
44
+ * partly a function of the acceleration profile rather than of the thumb.
45
+ * `RawMotion` valuators are the device's own deltas, before acceleration, and
46
+ * that is what `parseXi2` prefers when both are present.
47
+ *
48
+ * ## Why nothing here is a timestamp from X
49
+ *
50
+ * `xinput test-xi2` prints no event time, so the sampler stamps arrival time at
51
+ * read. That makes every duration a *lower bound* with reader jitter on top.
52
+ * Features are therefore built to survive tens of milliseconds of noise: they
53
+ * are binned with explicit tolerances, and the median across strokes is what
54
+ * gets hashed, so one mistimed stroke cannot swing the result.
55
+ *
56
+ * Pure: node:crypto only, no I/O, no spawn. The capture tool
57
+ * (`tools/aegis-touchpad.mjs`) owns the process side and is the only file in
58
+ * this axis allowed to touch it.
59
+ */
60
+
61
+ const crypto = require('node:crypto');
62
+
63
+ /** Enough strokes for a median to mean something, few enough to ask of a thumb. */
64
+ const MIN_STROKES = 3;
65
+ const MAX_STROKES = 64;
66
+ const MAX_SAMPLES = 20000;
67
+
68
+ /** A gap this long with no motion ends a stroke. Motion bursts are all X gives us. */
69
+ const DEFAULT_IDLE_GAP_MS = 140;
70
+
71
+ /** Bump when the axis set or a tolerance changes: signatures are not portable across it. */
72
+ const TOUCH_VERSION = 1;
73
+
74
+ const SIG_LENGTH = 16;
75
+
76
+ /**
77
+ * One axis per habitual trait. `mode` decides how a value is binned:
78
+ * 'linear' — absolute tolerance in the axis's own units
79
+ * 'log' — multiplicative tolerance, for axes whose *scale* is device-specific
80
+ * `tol` is the half-bin width; a value is quantised to `round(v / tol)`.
81
+ */
82
+ const AXES = Object.freeze([
83
+ { name: 'samples', mode: 'linear', tol: 3 }, // how many events the stroke took
84
+ { name: 'durationMs', mode: 'linear', tol: 150 }, // how long the thumb was moving
85
+ { name: 'straightness', mode: 'linear', tol: 0.15 }, // net / path; 1 = dead straight
86
+ { name: 'verticalBias', mode: 'linear', tol: 0.15 }, // |dy| / path
87
+ { name: 'pauseRatio', mode: 'linear', tol: 0.15 }, // fraction of zero-delta samples
88
+ { name: 'dtCv', mode: 'linear', tol: 0.15 }, // jitter of the sampling interval
89
+ { name: 'turnMean', mode: 'linear', tol: 0.12 }, // mean turn per sample, radians
90
+ { name: 'speedSkew', mode: 'linear', tol: 0.5 }, // peak / mean - 1
91
+ { name: 'reversalRate', mode: 'linear', tol: 0.1 }, // direction changes per sample
92
+ { name: 'pathPerSample', mode: 'log', tol: 1.25 }, // device-scale, so multiplicative
93
+ ]);
94
+
95
+ /**
96
+ * Mean bin distance at or below which two profiles are called a match. One whole
97
+ * bin of slop on every axis on average is a deliberately loose default: this is a
98
+ * behavioural axis, and a tight threshold would report "different thumb" for the
99
+ * same thumb on a cold hand. Tune per device; do not read it as an identity test.
100
+ */
101
+ const THRESHOLD = 1.0;
102
+
103
+ const AXIS_NAMES = Object.freeze(AXES.map((a) => a.name));
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // parsing
107
+ // ---------------------------------------------------------------------------
108
+
109
+ /**
110
+ * Parse `xinput test-xi2 --root` output into motion samples.
111
+ *
112
+ * Two shapes are accepted. The block form is what XI2 prints:
113
+ *
114
+ * EVENT type 17 (RawMotion)
115
+ * device: 9 (9)
116
+ * valuators:
117
+ * 0: -1.00 (0.00)
118
+ * 1: 6.00 (0.00)
119
+ *
120
+ * and the flat form is what the older `xinput test <id>` prints:
121
+ *
122
+ * motion id 9 [9, 3] 0: -1 1: 0
123
+ *
124
+ * The leading device table that `test-xi2` prints at startup is skipped. Events
125
+ * are stamped with arrival time: `now` is injectable so tests are deterministic.
126
+ */
127
+ function parseXi2(text, { now = () => Date.now(), device = null } = {}) {
128
+ const samples = [];
129
+ let current = null;
130
+
131
+ const flush = () => {
132
+ if (!current) return;
133
+ const dv = current.valuators;
134
+ if (dv[0] !== undefined || dv[1] !== undefined) {
135
+ samples.push({
136
+ type: current.type,
137
+ device: current.device,
138
+ dx: Number(dv[0] || 0),
139
+ dy: Number(dv[1] || 0),
140
+ t: current.t,
141
+ });
142
+ }
143
+ current = null;
144
+ };
145
+
146
+ for (const rawLine of String(text).split('\n')) {
147
+ const line = rawLine.replace(/\u001b\[[0-9;]*m/g, '');
148
+
149
+ const ev = /^\s*EVENT\s+type\s+(\d+)\s*(?:\(([^)]*)\))?/.exec(line);
150
+ if (ev) {
151
+ flush();
152
+ current = { type: Number(ev[1]), name: ev[2] || '', device: null, valuators: {}, t: now() };
153
+ continue;
154
+ }
155
+
156
+ const dev = /^\s*device:\s*(\d+)/.exec(line);
157
+ if (dev && current) {
158
+ current.device = Number(dev[1]);
159
+ continue;
160
+ }
161
+
162
+ if (current) {
163
+ // " 0: -1.00 (0.00)" — index: value (raw value)
164
+ const v = /^\s*(\d+):\s*(-?[\d.]+)\s*(?:\((-?[\d.]+)\))?\s*$/.exec(line);
165
+ if (v) {
166
+ current.valuators[Number(v[1])] = Number(v[2]);
167
+ continue;
168
+ }
169
+ continue;
170
+ }
171
+
172
+ // flat form
173
+ const flat = /^\s*(?:motion|raw motion)\s+id\s+(\d+)\s+\[[^\]]*\]\s*(.*)$/.exec(line);
174
+ if (flat) {
175
+ const dv = {};
176
+ for (const pair of flat[2].matchAll(/(\d+):\s*(-?\d+)/g)) dv[Number(pair[1])] = Number(pair[2]);
177
+ if (dv[0] !== undefined || dv[1] !== undefined) {
178
+ samples.push({ type: 0, device: Number(flat[1]), dx: Number(dv[0] || 0), dy: Number(dv[1] || 0), t: now() });
179
+ }
180
+ }
181
+ }
182
+ flush();
183
+
184
+ const filtered = device === null ? samples : samples.filter((s) => s.device === device);
185
+ return filtered.slice(0, MAX_SAMPLES);
186
+ }
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // segmentation
190
+ // ---------------------------------------------------------------------------
191
+
192
+ /**
193
+ * Split samples into strokes: a stroke is a run of samples with no gap longer
194
+ * than `idleGapMs`. X gives us no finger-down/finger-up through the relative
195
+ * pointer path, so a silence gap is the only boundary available — which is why
196
+ * `aegis-touchpad.mjs` asks for *separate, deliberate* strokes with the thumb
197
+ * lifted in between rather than one continuous scribble.
198
+ */
199
+ function segmentStrokes(samples, { idleGapMs = DEFAULT_IDLE_GAP_MS } = {}) {
200
+ const strokes = [];
201
+ let current = [];
202
+ for (const s of samples) {
203
+ if (current.length) {
204
+ const gap = s.t - current[current.length - 1].t;
205
+ if (gap > idleGapMs) {
206
+ strokes.push(current);
207
+ current = [];
208
+ }
209
+ }
210
+ current.push(s);
211
+ }
212
+ if (current.length) strokes.push(current);
213
+ return strokes.filter((s) => s.length > 1).slice(0, MAX_STROKES);
214
+ }
215
+
216
+ // ---------------------------------------------------------------------------
217
+ // features
218
+ // ---------------------------------------------------------------------------
219
+
220
+ const mean = (xs) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0);
221
+
222
+ /**
223
+ * Ten traits from one stroke. Every ratio is guarded against a zero denominator
224
+ * and returns 0 rather than NaN: a NaN would poison canonicalisation downstream,
225
+ * and a stroke that moved nowhere is better described as "no trait" than as a
226
+ * crash.
227
+ */
228
+ function strokeFeatures(stroke) {
229
+ const n = stroke.length;
230
+ let path = 0;
231
+ let dx = 0;
232
+ let dy = 0;
233
+ let pauses = 0;
234
+ let turns = 0;
235
+ let reversals = 0;
236
+
237
+ const speeds = [];
238
+ const dts = [];
239
+
240
+ let prevSignX = 0;
241
+ let prevSignY = 0;
242
+ let prevAngle = null;
243
+
244
+ for (let i = 0; i < n; i++) {
245
+ const s = stroke[i];
246
+ const mag = Math.hypot(s.dx, s.dy);
247
+ path += mag;
248
+ dx += s.dx;
249
+ dy += s.dy;
250
+ if (mag === 0) pauses++;
251
+
252
+ if (i > 0) {
253
+ const dt = Math.max(1, stroke[i].t - stroke[i - 1].t);
254
+ dts.push(dt);
255
+ speeds.push(mag / dt);
256
+ const angle = Math.atan2(s.dy, s.dx);
257
+ if (prevAngle !== null) {
258
+ let d = angle - prevAngle;
259
+ while (d > Math.PI) d -= 2 * Math.PI;
260
+ while (d < -Math.PI) d += 2 * Math.PI;
261
+ turns += Math.abs(d);
262
+ }
263
+ prevAngle = angle;
264
+ }
265
+
266
+ const sx = Math.sign(s.dx);
267
+ const sy = Math.sign(s.dy);
268
+ if (sx && prevSignX && sx !== prevSignX) reversals++;
269
+ if (sy && prevSignY && sy !== prevSignY) reversals++;
270
+ if (sx) prevSignX = sx;
271
+ if (sy) prevSignY = sy;
272
+ }
273
+
274
+ const net = Math.hypot(dx, dy);
275
+ const duration = Math.max(1, stroke[n - 1].t - stroke[0].t);
276
+ const meanSpeed = mean(speeds);
277
+ const dtMean = mean(dts);
278
+ const dtVar = mean(dts.map((d) => (d - dtMean) ** 2));
279
+
280
+ return {
281
+ samples: n,
282
+ durationMs: duration,
283
+ straightness: path ? net / path : 0,
284
+ verticalBias: path ? Math.abs(dy) / path : 0,
285
+ pauseRatio: pauses / n,
286
+ dtCv: dtMean ? Math.sqrt(dtVar) / dtMean : 0,
287
+ turnMean: n > 1 ? turns / (n - 1) : 0,
288
+ speedSkew: meanSpeed ? Math.max(...speeds) / meanSpeed - 1 : 0,
289
+ reversalRate: reversals / n,
290
+ pathPerSample: path / n,
291
+ };
292
+ }
293
+
294
+ // ---------------------------------------------------------------------------
295
+ // quantisation
296
+ // ---------------------------------------------------------------------------
297
+
298
+ /** Bin one value. `log` mode is symmetric in ratio, so 2x and 0.5x are equidistant. */
299
+ function binValue(axis, value) {
300
+ const v = Number.isFinite(value) ? value : 0;
301
+ if (axis.mode === 'log') {
302
+ if (v <= 0) return 0;
303
+ return Math.round(Math.log(v) / Math.log(axis.tol));
304
+ }
305
+ return Math.round(v / axis.tol);
306
+ }
307
+
308
+ /** Distance between two bins, in bin units, on one axis. */
309
+ function binDistance(axis, a, b) {
310
+ if (axis.mode === 'log') {
311
+ const ratio = Math.log(axis.tol);
312
+ const ra = a * ratio;
313
+ const rb = b * ratio;
314
+ return Math.abs(ra - rb);
315
+ }
316
+ return Math.abs(a - b);
317
+ }
318
+
319
+ /** Quantise a feature object to integers, axis by axis. Unknown axes are ignored. */
320
+ function quantise(features) {
321
+ const out = {};
322
+ for (const axis of AXES) out[axis.name] = binValue(axis, features[axis.name]);
323
+ return out;
324
+ }
325
+
326
+ /** Median across strokes per axis: order-independent, and robust to one bad stroke. */
327
+ function medians(featureList) {
328
+ const out = {};
329
+ for (const axis of AXES) {
330
+ const xs = featureList.map((f) => Number(f[axis.name]) || 0).sort((a, b) => a - b);
331
+ const mid = Math.floor(xs.length / 2);
332
+ const med = xs.length % 2 ? xs[mid] : (xs[mid - 1] + xs[mid]) / 2;
333
+ out[axis.name] = Number.isFinite(med) ? med : 0;
334
+ }
335
+ return out;
336
+ }
337
+
338
+ /**
339
+ * The signature body: versioned, one `axis=bin` line per trait, fixed order.
340
+ * Exported shape is a hash, but this is the thing hashed, and it is what a
341
+ * verifier recomputes.
342
+ */
343
+ function signatureBody(med) {
344
+ const bins = quantise(med);
345
+ return TOUCH_VERSION + '\n' + AXIS_NAMES.map((k) => `${k}=${bins[k]}`).join('\n');
346
+ }
347
+
348
+ /**
349
+ * 16 hex over the median-binned trait vector, recomputed from the medians.
350
+ *
351
+ * This is the function `src/fingerprint.js` calls, and it takes medians rather
352
+ * than a stored hash on purpose: a profile file's own `signature` field is then
353
+ * never trusted, only recomputed. Editing `medians` in that file changes the
354
+ * signature and the record's attestation breaks, which is the same property the
355
+ * rest of φ(α) has.
356
+ *
357
+ * `strokeCount` is what makes absence honest — see rule 3.
358
+ *
359
+ * @returns {string|null} null below `MIN_STROKES`: the median of one stroke is
360
+ * just that stroke, and one gesture is not evidence of a habit.
361
+ */
362
+ function signatureFromMedians(med, strokeCount) {
363
+ if (!med || Number(strokeCount) < MIN_STROKES) return null;
364
+ return crypto.createHash('sha256').update(signatureBody(med), 'utf8').digest('hex').slice(0, SIG_LENGTH);
365
+ }
366
+
367
+ /**
368
+ * The thumb signature over a list of stroke features.
369
+ *
370
+ * Median across strokes makes this order-independent — the same thumb producing
371
+ * the same habits in a different order fingerprints identically, matching the
372
+ * rule the behavioural axis already follows.
373
+ */
374
+ function touchSignature(featureList) {
375
+ const usable = (Array.isArray(featureList) ? featureList : [])
376
+ .filter((f) => f && Number.isFinite(Number(f.samples)) && Number(f.samples) > 1)
377
+ .slice(0, MAX_STROKES);
378
+ if (usable.length < MIN_STROKES) return null;
379
+ return signatureFromMedians(medians(usable), usable.length);
380
+ }
381
+
382
+ // ---------------------------------------------------------------------------
383
+ // profile + comparison
384
+ // ---------------------------------------------------------------------------
385
+
386
+ /**
387
+ * A full touch profile: the signature, the medians it came from, and the axis
388
+ * table with tolerances — so a verifier can recompute rather than trust, and a
389
+ * reader can see which axes were even in play.
390
+ */
391
+ function profile(samples, opts = {}) {
392
+ const strokes = segmentStrokes(samples, opts);
393
+ const featureList = strokes.map(strokeFeatures);
394
+ const signature = touchSignature(featureList);
395
+ const med = featureList.length ? medians(featureList) : null;
396
+
397
+ return Object.freeze({
398
+ version: TOUCH_VERSION,
399
+ kind: 'gesture-dynamics',
400
+ notice:
401
+ 'not a fingerprint: this machine has no fingerprint sensor, and the trackpad ' +
402
+ 'exposes no contact geometry through X. These are habits of motion, learned not measured.',
403
+ signature,
404
+ samples: featureList.length,
405
+ strokes: strokes.length,
406
+ medians: med ? Object.freeze({ ...med }) : null,
407
+ bins: med ? Object.freeze(quantise(med)) : null,
408
+ axes: AXES,
409
+ });
410
+ }
411
+
412
+ /**
413
+ * Graded comparison, never a bare boolean.
414
+ *
415
+ * @returns {{score:number, withinTolerance:boolean, distance:number, worst:Array, comparable:boolean}}
416
+ * `comparable` is false when either side has no signature — two absences are
417
+ * not a match, and saying so is the point.
418
+ */
419
+ function compareTouch(a, b, { threshold = THRESHOLD } = {}) {
420
+ const empty = { score: 0, withinTolerance: false, distance: Infinity, worst: [], comparable: false };
421
+ if (!a || !b) return empty;
422
+ const ba = a.bins || (a.medians ? quantise(a.medians) : null);
423
+ const bb = b.bins || (b.medians ? quantise(b.medians) : null);
424
+ if (!ba || !bb) return empty;
425
+
426
+ const worst = [];
427
+ let total = 0;
428
+ let count = 0;
429
+ for (const axis of AXES) {
430
+ if (ba[axis.name] === undefined || bb[axis.name] === undefined) continue;
431
+ const d = binDistance(axis, ba[axis.name], bb[axis.name]);
432
+ total += d;
433
+ count++;
434
+ worst.push({ axis: axis.name, bins: d, a: ba[axis.name], b: bb[axis.name] });
435
+ }
436
+ if (!count) return empty;
437
+ const distance = total / count;
438
+ worst.sort((x, y) => y.bins - x.bins);
439
+ return {
440
+ score: Number((1 / (1 + distance)).toFixed(4)),
441
+ withinTolerance: distance <= threshold,
442
+ distance: Number(distance.toFixed(4)),
443
+ worst: worst.slice(0, 3),
444
+ comparable: true,
445
+ };
446
+ }
447
+
448
+
449
+
450
+ module.exports = {
451
+ parseXi2, segmentStrokes, strokeFeatures, quantise, medians, touchSignature,
452
+ signatureBody, signatureFromMedians, profile, compareTouch, binValue, binDistance,
453
+ AXES, AXIS_NAMES, TOUCH_VERSION, SIG_LENGTH, MIN_STROKES, MAX_STROKES,
454
+ DEFAULT_IDLE_GAP_MS, THRESHOLD,
455
+ };
@@ -322,6 +322,7 @@ function autonomousDirective(rounds = DEFAULT_ROUNDS) {
322
322
  'Work the task end to end:',
323
323
  '1. Plan in one line, then start acting in the same turn — never end a turn on a plan.',
324
324
  '2. Read only what you need to make the change (no fishing through the repo).',
325
+ '2b. If this demand has been made before, establish whether it was met: check recalled memory, the queue file, PLAN.md, and git history for the earlier attempt. When it was fixed and the problem is back, state how it was fixed then and why it regressed, and fix that cause — a blind re-fix is a regression, not a resolution.',
325
326
  '3. Make the change with Write/Edit/Bash, then VERIFY it: re-read the result and run the relevant test/command.',
326
327
  '4. If verification fails, fix it and verify again — loop until it passes or you are genuinely blocked.',
327
328
  '5. Do not ask for permission, do not hand the work back, do not stop at "let me check…".',
@@ -31,6 +31,12 @@ const MAIN_CHAT_PROMPT =
31
31
  `- Use tools silently. A one-line reason is enough; do not narrate your plan as a story. ` +
32
32
  `- Never claim what a tool found or what a command returned before the tool actually runs. ` +
33
33
  ` Report only the results you really received. ` +
34
+ `- Before you start a fix or feature the user asks for, check whether they have asked for ` +
35
+ ` it before and whether it was already delivered: look in recalled memory, ` +
36
+ ` ~/.aegiscode/queue.jsonl, PLAN.md/notes, and \`git log\` for the same demand. If it was ` +
37
+ ` resolved before and the problem is back, report how it was resolved (the commit, file, or ` +
38
+ ` mechanism that fixed it) and why it regressed, then fix the cause — never re-fix blind as ` +
39
+ ` if the request were new. If it was never met, say so plainly before starting. ` +
34
40
  `- Match the response to the request. A greeting, a question about something you already ` +
35
41
  ` know, or a request for an opinion is answered in plain words with NO tools. Only reach ` +
36
42
  ` for a tool when the answer genuinely depends on something in this repo or on this ` +
@@ -92,7 +92,59 @@ const AVATAR_NAMESPACE = '__avatar';
92
92
  * main.js telemetryEnabled() through getTelemetryOptIn(). */
93
93
  const TELEMETRY_NAMESPACE = '__telemetry';
94
94
 
95
- /** Namespaces the provider-config surface must never see or mutate. */
95
+ /** Reserved namespace for the auto-drain opt-in:
96
+ * `{ enabled, intervalMs }` — app-level, not a provider.
97
+ *
98
+ * DEFAULT OFF, and unlike every preference above that default is the design
99
+ * rather than a convention: this is the one setting in the app that causes a
100
+ * full tool loop to run on a real model in the user's checkout with nobody
101
+ * watching. desktop/main.js and desktop/preload.js both used to state the
102
+ * absolute rule — "there is no interval, no drain at startup, and no
103
+ * drain-on-idle anywhere" — and that rule is still what an install that never
104
+ * touches this namespace gets. What changed (user request, phase A of the
105
+ * automation work) is that the rule became a DEFAULT instead of an absolute:
106
+ * an explicit `enabled: true` here is the only thing that arms a timer, the
107
+ * toggle that writes it is in the queue card, and `lib/auto.js` refuses to
108
+ * run a tick when the queue is empty or another host already holds the drain
109
+ * lock. Nothing secret lives here, so no encryption — same shape as
110
+ * `__confirmMode`/`__memoryPersist` above. */
111
+ const AUTO_DRAIN_NAMESPACE = '__autoDrain';
112
+
113
+ /** Reserved namespace for the auto-mint (seal-on-quiet) opt-in:
114
+ * `{ enabled, publish }` — app-level, not a provider.
115
+ *
116
+ * DEFAULT OFF for the same reason as auto-drain, and `publish` is a second,
117
+ * independent opt-in: sealing writes a local record, whereas publishing sends
118
+ * those bytes to the vault over `rclone` and writes an anchor beside them. An
119
+ * automatic network copy is never implied by an automatic seal.
120
+ *
121
+ * The AI half of the record resolves through the shared rungs in
122
+ * client/attest.js (`$AEGIS_AI_SECRET`/`$AEGIS_AI_MODEL` in the app scope) —
123
+ * this namespace deliberately does NOT hold a credential, because a settings
124
+ * file that can carry a provider key is a second place to leak one. */
125
+ const AUTO_MINT_NAMESPACE = '__autoMint';
126
+
127
+ /** How often an armed auto-drain looks at the queue. One minute is the
128
+ * compromise the two failure modes set: a shorter interval makes the desktop
129
+ * a busy-waiter over a file several hosts write (each tick stats the queue and
130
+ * the lock), and a longer one means a task queued in the card sits visibly
131
+ * idle. The worker does the rest of the waiting itself. */
132
+ const AUTO_DRAIN_INTERVAL_DEFAULT_MS = 60_000;
133
+
134
+ /** Floor for `intervalMs`. Below this the timer is a poll loop, not a drain
135
+ * cadence: nothing about a queue whose tasks take minutes to run changes
136
+ * fifteen times a second, and the tick does file I/O. */
137
+ const AUTO_DRAIN_INTERVAL_MIN_MS = 15_000;
138
+
139
+ /** Ceiling for `intervalMs` — half an hour. A hand-edited settings file asking
140
+ * for a day is a typo, not a preference. */
141
+ const AUTO_DRAIN_INTERVAL_MAX_MS = 30 * 60_000;
142
+
143
+ /** Reserved namespaces: the provider-config surface must never see or mutate
144
+ * any of these. The two automation switches are here for the SAME reason the
145
+ * others are — `set()`/`remove()`/`list()` operate on provider rows, and a
146
+ * preference parked in that namespace would be listed as a provider and
147
+ * deletable with "Remove". */
96
148
  const RESERVED_NAMESPACES = Object.freeze([
97
149
  AEGIS_KEY_NAMESPACE,
98
150
  LEGACY_AEGIS_NAMESPACE,
@@ -101,6 +153,8 @@ const RESERVED_NAMESPACES = Object.freeze([
101
153
  MEMORY_PERSIST_NAMESPACE,
102
154
  AVATAR_NAMESPACE,
103
155
  TELEMETRY_NAMESPACE,
156
+ AUTO_DRAIN_NAMESPACE,
157
+ AUTO_MINT_NAMESPACE,
104
158
  ]);
105
159
 
106
160
  /** Motion modes the renderer understands (`system` = follow the OS). */
@@ -451,6 +505,93 @@ function createSettingsStore({ dir, safeStorage } = {}) {
451
505
  return avatarState();
452
506
  }
453
507
 
508
+ // --- Auto-drain / auto-mint: reserved namespaces, DEFAULT OFF ------------
509
+ // The two opt-in automations (lib/auto.js). Both live in their own top-level
510
+ // namespace, both are booted OFF, and both keep the "off" and "never set"
511
+ // cases distinguishable through a `source` field — the same shape
512
+ // memoryPersistState()/avatarState() use above, for the same reason: a UI
513
+ // that cannot tell "you turned it off" from "this build never had it" shows
514
+ // the wrong sentence after an upgrade.
515
+ //
516
+ // `intervalMs` is clamped rather than trusted: it comes back through IPC from
517
+ // a renderer and off disk from a hand-edited file, and a timer is the one
518
+ // place where a hostile or fat-fingered number costs real CPU.
519
+
520
+ /** A usable tick interval, or the default. Out-of-range reads as unset. */
521
+ function clampAutoDrainInterval(value) {
522
+ const n = Number(value);
523
+ if (!Number.isFinite(n)) return AUTO_DRAIN_INTERVAL_DEFAULT_MS;
524
+ const ms = Math.round(n);
525
+ if (ms < AUTO_DRAIN_INTERVAL_MIN_MS || ms > AUTO_DRAIN_INTERVAL_MAX_MS) {
526
+ return AUTO_DRAIN_INTERVAL_DEFAULT_MS;
527
+ }
528
+ return ms;
529
+ }
530
+
531
+ function getAutoDrain() {
532
+ const cfg = load()[AUTO_DRAIN_NAMESPACE] || {};
533
+ return {
534
+ // Unset === false. This is the opposite of confirm mode/memory persist,
535
+ // and it is the whole point of the feature: nothing drains itself until
536
+ // someone says so in as many words.
537
+ enabled: cfg.enabled === true,
538
+ intervalMs: clampAutoDrainInterval(cfg.intervalMs),
539
+ };
540
+ }
541
+
542
+ function autoDrainState() {
543
+ const cfg = load()[AUTO_DRAIN_NAMESPACE] || {};
544
+ return {
545
+ ...getAutoDrain(),
546
+ source: cfg.enabled === undefined ? 'default' : 'config',
547
+ };
548
+ }
549
+
550
+ function setAutoDrain(patch = {}) {
551
+ const current = getAutoDrain();
552
+ const p = patch && typeof patch === 'object' ? patch : {};
553
+ const data = load();
554
+ data[AUTO_DRAIN_NAMESPACE] = {
555
+ enabled: p.enabled === undefined ? current.enabled : Boolean(p.enabled),
556
+ intervalMs:
557
+ p.intervalMs === undefined
558
+ ? current.intervalMs
559
+ : clampAutoDrainInterval(p.intervalMs),
560
+ };
561
+ save(data);
562
+ return autoDrainState();
563
+ }
564
+
565
+ function getAutoMint() {
566
+ const cfg = load()[AUTO_MINT_NAMESPACE] || {};
567
+ return {
568
+ enabled: cfg.enabled === true,
569
+ // Independent of `enabled` on purpose: an automatic seal must not drag
570
+ // an automatic upload along with it.
571
+ publish: cfg.publish === true,
572
+ };
573
+ }
574
+
575
+ function autoMintState() {
576
+ const cfg = load()[AUTO_MINT_NAMESPACE] || {};
577
+ return {
578
+ ...getAutoMint(),
579
+ source: cfg.enabled === undefined ? 'default' : 'config',
580
+ };
581
+ }
582
+
583
+ function setAutoMint(patch = {}) {
584
+ const current = getAutoMint();
585
+ const p = patch && typeof patch === 'object' ? patch : {};
586
+ const data = load();
587
+ data[AUTO_MINT_NAMESPACE] = {
588
+ enabled: p.enabled === undefined ? current.enabled : Boolean(p.enabled),
589
+ publish: p.publish === undefined ? current.publish : Boolean(p.publish),
590
+ };
591
+ save(data);
592
+ return autoMintState();
593
+ }
594
+
454
595
  return {
455
596
  file,
456
597
  get,
@@ -476,6 +617,13 @@ function createSettingsStore({ dir, safeStorage } = {}) {
476
617
  getAvatar,
477
618
  avatarState,
478
619
  setAvatar,
620
+ getAutoDrain,
621
+ autoDrainState,
622
+ setAutoDrain,
623
+ getAutoMint,
624
+ autoMintState,
625
+ setAutoMint,
626
+ clampAutoDrainInterval,
479
627
  };
480
628
  }
481
629
 
@@ -488,6 +636,11 @@ module.exports = {
488
636
  MEMORY_PERSIST_NAMESPACE,
489
637
  AVATAR_NAMESPACE,
490
638
  TELEMETRY_NAMESPACE,
639
+ AUTO_DRAIN_NAMESPACE,
640
+ AUTO_MINT_NAMESPACE,
641
+ AUTO_DRAIN_INTERVAL_DEFAULT_MS,
642
+ AUTO_DRAIN_INTERVAL_MIN_MS,
643
+ AUTO_DRAIN_INTERVAL_MAX_MS,
491
644
  AVATAR_MOTION_MODES,
492
645
  DEFAULT_QUICK_LAUNCHER_SHORTCUT,
493
646
  RESERVED_NAMESPACES,