@akasecurity/ai-tc-codex 0.9.16 → 0.9.17-beta.1

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.
@@ -1,888 +1,8 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- try {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- } catch (e) {
11
- throw mod = 0, e;
12
- }
13
- };
14
2
  var __export = (target, all) => {
15
3
  for (var name in all)
16
4
  __defProp(target, name, { get: all[name], enumerable: true });
17
5
  };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
- // If the importer is in node compatibility mode or this is not an ESM
28
- // file that has been converted to a CommonJS file using a Babel-
29
- // compatible transform (i.e. "__esModule" has not been set), then set
30
- // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
- mod
33
- ));
34
-
35
- // ../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js
36
- var require_ignore = __commonJS({
37
- "../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js"(exports, module) {
38
- "use strict";
39
- function makeArray(subject) {
40
- return Array.isArray(subject) ? subject : [subject];
41
- }
42
- var UNDEFINED = void 0;
43
- var EMPTY = "";
44
- var SPACE = " ";
45
- var ESCAPE = "\\";
46
- var REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
47
- var REGEX_TEST_BLANK_LINE = /^\uFEFF? *$/;
48
- var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
49
- var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
50
- var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
51
- var REGEX_SPLITALL_CRLF = /\r?\n/g;
52
- var DOUBLE_SLASH = "//";
53
- var SLASH_CODE = 47;
54
- var DOT_CODE = 46;
55
- var SLASH3 = "/";
56
- var TMP_KEY_IGNORE = "node-ignore";
57
- if (typeof Symbol !== "undefined") {
58
- TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
59
- }
60
- var KEY_IGNORE = TMP_KEY_IGNORE;
61
- var define = (object2, key, value) => {
62
- Object.defineProperty(object2, key, { value });
63
- return value;
64
- };
65
- var RETURN_FALSE = () => false;
66
- var cleanRangeBackSlash = (slashes) => {
67
- const { length } = slashes;
68
- return slashes.slice(0, length - length % 2);
69
- };
70
- var POSIX_CLASSES = {
71
- alnum: "0-9A-Za-z",
72
- alpha: "A-Za-z",
73
- blank: " \\t",
74
- cntrl: "\\x00-\\x1f\\x7f",
75
- digit: "0-9",
76
- graph: "!-.0-~",
77
- lower: "a-z",
78
- print: " -.0-~",
79
- punct: "!-.:-@\\[-`{-~",
80
- // git's `sane-ctype.h` classifies \v and \f as control, not space,
81
- // unlike C's `isspace`
82
- space: " \\t\\n\\r",
83
- upper: "A-Z",
84
- xdigit: "0-9A-Fa-f"
85
- };
86
- var CLASS_MEMBERS_TO_ESCAPE = "\\]^-[";
87
- var escapeMember = (char) => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0 ? char : ESCAPE + char;
88
- var NON_SLASH = "(?!\\/)";
89
- var classSource = (negated, body) => {
90
- if (negated) {
91
- return `[^\\/${body}]`;
92
- }
93
- const source = `[${body}]`;
94
- return new RegExp(source).test("/") ? NON_SLASH + source : source;
95
- };
96
- var scanBracket = (pattern, start) => {
97
- const { length } = pattern;
98
- let index = start + 1;
99
- let negated = EMPTY;
100
- const lead = pattern[index];
101
- if (lead === "!" || lead === "^") {
102
- negated = "^";
103
- index++;
104
- }
105
- let body = EMPTY;
106
- let prev = EMPTY;
107
- for (; ; ) {
108
- const char = pattern[index];
109
- if (char === UNDEFINED) {
110
- return null;
111
- }
112
- if (char === ESCAPE) {
113
- const escaped = pattern[index + 1];
114
- if (escaped === UNDEFINED) {
115
- return null;
116
- }
117
- body += escapeMember(escaped);
118
- prev = escaped;
119
- index++;
120
- } else if (char === "-" && prev && index + 1 < length && pattern[index + 1] !== "]") {
121
- index++;
122
- let to = pattern[index];
123
- if (to === ESCAPE) {
124
- to = pattern[index += 1];
125
- }
126
- if (prev <= to) {
127
- body += `-${escapeMember(to)}`;
128
- }
129
- prev = EMPTY;
130
- } else if (char === "[" && pattern[index + 1] === ":") {
131
- const nameStart = index + 2;
132
- let end = nameStart;
133
- while (end < length && pattern[end] !== "]") {
134
- end++;
135
- }
136
- if (end === length) {
137
- return null;
138
- }
139
- if (end > nameStart && pattern[end - 1] === ":") {
140
- const expanded = POSIX_CLASSES[pattern.slice(nameStart, end - 1)];
141
- if (expanded === UNDEFINED) {
142
- return null;
143
- }
144
- body += expanded;
145
- prev = EMPTY;
146
- index = end;
147
- } else {
148
- body += escapeMember("[");
149
- prev = "[";
150
- index = nameStart - 2;
151
- }
152
- } else {
153
- body += escapeMember(char);
154
- prev = char;
155
- }
156
- index++;
157
- if (pattern[index] === "]") {
158
- return {
159
- end: index,
160
- source: classSource(negated, body)
161
- };
162
- }
163
- }
164
- };
165
- var NEVER_MATCH = "[]";
166
- var PLACEHOLDER = "\0";
167
- var REGEX_RESTORE_PLACEHOLDER = new RegExp(
168
- `${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,
169
- "g"
170
- );
171
- var TRAILING_WILDCARD = "\uE000";
172
- var TRAILING_DOUBLESTAR = "\uE001";
173
- var extractBrackets = (pattern) => {
174
- const sources = [];
175
- const hold = (source) => `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`;
176
- const { length } = pattern;
177
- let out = EMPTY;
178
- let index = 0;
179
- while (index < length) {
180
- const char = pattern[index];
181
- if (char === ESCAPE) {
182
- const escaped = pattern[index + 1];
183
- if (escaped === "*" || escaped === "[" || escaped === SPACE || escaped === ESCAPE) {
184
- out += pattern.slice(index, index + 2);
185
- } else {
186
- out += hold(
187
- REGEX_LITERAL_SPECIAL.test(escaped) ? ESCAPE + escaped : escaped
188
- );
189
- }
190
- index += 2;
191
- } else if (char === PLACEHOLDER) {
192
- out += hold(`[${PLACEHOLDER}]`);
193
- index++;
194
- } else if (char === "[") {
195
- const scanned = scanBracket(pattern, index);
196
- if (scanned === null) {
197
- out += hold(NEVER_MATCH);
198
- index = length;
199
- } else {
200
- out += hold(scanned.source);
201
- index = scanned.end + 1;
202
- }
203
- } else {
204
- out += char;
205
- index++;
206
- }
207
- }
208
- return {
209
- source: out,
210
- sources
211
- };
212
- };
213
- var DIRECT = null;
214
- var REGEX_INNER_SLASH = /\/(?!$)/;
215
- var REPLACERS = [
216
- [
217
- // Remove BOM
218
- // TODO:
219
- // Other similar zero-width characters?
220
- /^\uFEFF/,
221
- () => EMPTY,
222
- "\uFEFF"
223
- ],
224
- [
225
- // A trailing line terminator, left on when a whole file's contents are
226
- // added as one pattern rather than split into lines. git never sees one
227
- // -- it reads a `.gitignore` line by line -- so it is not part of the
228
- // pattern and is dropped here, apart from the trailing-space trimming,
229
- // which follows git in touching spaces and nothing else.
230
- /[\r\n]+$/,
231
- () => EMPTY
232
- ],
233
- // > Trailing spaces are ignored unless they are quoted with backslash ("\")
234
- [
235
- // Only spaces, never tabs or other whitespace: git trims a trailing run
236
- // of `' '` and nothing else (dir.c, `trim_trailing_spaces`, a single
237
- // `case ' '`), so a pattern ending in a tab keeps it as a literal.
238
- // (a\ ) -> (a )
239
- // (a ) -> (a)
240
- // (a ) -> (a)
241
- // (a \ ) -> (a )
242
- /((?:\\\\)*?)(\\? +)$/,
243
- (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
244
- ],
245
- // Replace (\ ) with ' '
246
- // Only a space: an escaped tab or other whitespace is already a literal by
247
- // the time it reaches here, and a bare tab must be left as one, not turned
248
- // into a space.
249
- // (\ ) -> ' '
250
- // (\\ ) -> '\\ '
251
- // (\\\ ) -> '\\ '
252
- [
253
- /(\\+?) /g,
254
- (_, m1) => {
255
- const { length } = m1;
256
- return m1.slice(0, length - length % 2) + SPACE;
257
- }
258
- ],
259
- // Escape metacharacters
260
- // which is written down by users but means special for regular expressions.
261
- // > There are 12 characters with special meanings:
262
- // > - the backslash \,
263
- // > - the caret ^,
264
- // > - the dollar sign $,
265
- // > - the period or dot .,
266
- // > - the vertical bar or pipe symbol |,
267
- // > - the question mark ?,
268
- // > - the asterisk or star *,
269
- // > - the plus sign +,
270
- // > - the opening parenthesis (,
271
- // > - the closing parenthesis ),
272
- // > - and the opening square bracket [,
273
- // > - the opening curly brace {,
274
- // > These special characters are often called "metacharacters".
275
- [
276
- /[\\$.|*+(){^]/g,
277
- (match) => `\\${match}`
278
- ],
279
- [
280
- // > a question mark (?) matches a single character
281
- /(?!\\)\?/g,
282
- () => "[^/]",
283
- "?"
284
- ],
285
- // leading slash
286
- [
287
- // > A leading slash matches the beginning of the pathname.
288
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
289
- // A leading slash matches the beginning of the pathname
290
- /^\//,
291
- () => "^",
292
- SLASH3
293
- ],
294
- // replace special metacharacter slash after the leading slash
295
- [
296
- /\//g,
297
- () => "\\/",
298
- SLASH3
299
- ],
300
- [
301
- // > A leading "**" followed by a slash means match in all directories.
302
- // > For example, "**/foo" matches file or directory "foo" anywhere,
303
- // > the same as pattern "foo".
304
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
305
- // > under directory "foo".
306
- // Notice that the '*'s have been replaced as '\\*'
307
- /^\^*(?:\\\*\\\*\\\/)+/,
308
- // '**/foo' <-> 'foo'
309
- () => "^(?:.*\\/)?",
310
- "*"
311
- ],
312
- // starting
313
- [
314
- // there will be no leading '/'
315
- // (which has been replaced by section "leading slash")
316
- // If starts with '**', adding a '^' to the regular expression also works
317
- DIRECT,
318
- (source, pattern) => {
319
- if (!source || source[0] === "^") {
320
- return source;
321
- }
322
- const anchor2 = !REGEX_INNER_SLASH.test(pattern) ? "(?:^|\\/)" : "^";
323
- return anchor2 + source;
324
- }
325
- ],
326
- // two globstars
327
- [
328
- // Use lookahead assertions so that we could match more than one `'/**'`
329
- /\\\/\\\*\\\*(?=\\\/|$)/g,
330
- // Zero, one or several directories
331
- // should not use '*', or it will be replaced by the next replacer
332
- // Check if it is not the last `'/**'`
333
- (_, index, str2) => index + 6 < str2.length ? str2.slice(index + 6) === "\\/" ? "(?:\\/[^\\/]+)+" : "(?:\\/[^\\/]+)*" : `\\/${TRAILING_DOUBLESTAR}`,
334
- "*"
335
- ],
336
- // normal intermediate wildcards
337
- [
338
- // Never replace escaped '*'
339
- // ignore rule '\*' will match the path '*'
340
- // 'abc.*/' -> go
341
- // 'abc.*' -> skip this rule,
342
- // coz trailing single wildcard will be handed by [trailing wildcard]
343
- /(^|[^\\]+)(\\\*)+(?=.+)/g,
344
- // '*.js' matches '.js'
345
- // '*.js' doesn't match 'abc'
346
- (_, p1, p2) => {
347
- const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
348
- return p1 + unescaped;
349
- },
350
- "*"
351
- ],
352
- // trailing wildcard, held apart from a literal star
353
- [
354
- // The step above leaves a trailing `*` alone, so a single `\*` is all that
355
- // can be left at the end here. Whether it is a wildcard or a literal
356
- // turns on the backslashes the user put in front of it: the escaper has
357
- // since doubled every one, so what stands here is those `2N` doubled
358
- // backslashes and then the star's own escape. An even number of the
359
- // original `N` leaves the star unescaped -- a wildcard -- and an odd
360
- // number escapes it -- a literal. This runs while the two are still
361
- // distinct, before the unescape steps below collapse the literal onto
362
- // the very `\*` a wildcard leaves behind.
363
- /(^|[^\\])((?:\\\\)*)\\\*$/,
364
- (match, p1, p2) => (
365
- // `p2` holds the doubled user backslashes; half of them is `N`.
366
- p2.length / 2 % 2 === 0 ? p1 + p2 + TRAILING_WILDCARD : match
367
- ),
368
- "*"
369
- ],
370
- [
371
- // unescape, revert step 3 except for back slash
372
- // For example, if a user escape a '\\*',
373
- // after step 3, the result will be '\\\\\\*'
374
- /\\\\\\(?=[$.|*+(){^])/g,
375
- () => ESCAPE,
376
- ESCAPE + ESCAPE
377
- ],
378
- [
379
- // '\\\\' -> '\\'
380
- /\\\\/g,
381
- () => ESCAPE,
382
- ESCAPE + ESCAPE
383
- ],
384
- [
385
- // Every real bracket expression -- POSIX classes included -- has already
386
- // been held aside by `extractBrackets`, so the only `[` left in the
387
- // pattern is an escaped, literal one.
388
- // `\` is escaped by step 3
389
- /\\\[([^\]/]*?)(\\*)($|\])/g,
390
- // '\\[bar]' -> '\\\\[bar\\]'
391
- (match, range, endEscape, close) => `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`,
392
- "["
393
- ],
394
- // ending
395
- [
396
- // 'js' will not match 'js.'
397
- // 'ab' will not match 'abc'
398
- DIRECT,
399
- // WTF!
400
- // https://git-scm.com/docs/gitignore
401
- // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
402
- // which re-fixes #24, #38
403
- // > If there is a separator at the end of the pattern then the pattern
404
- // > will only match directories, otherwise the pattern can match both
405
- // > files and directories.
406
- // 'js*' will not match 'a.js'
407
- // 'js/' will not match 'a.js'
408
- // 'js' will match 'a.js' and 'a.js/'
409
- (source) => {
410
- const last = source[source.length - 1];
411
- if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {
412
- return source;
413
- }
414
- return last === SLASH3 ? `${source}$` : `${source}(?=$|\\/$)`;
415
- }
416
- ]
417
- ];
418
- var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\uE000$/;
419
- var MODE_IGNORE = "regex";
420
- var MODE_CHECK_IGNORE = "checkRegex";
421
- var UNDERSCORE = "_";
422
- var replaceTrailingWildcard = (_, p1) => {
423
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
424
- return `${prefix}(?=$|\\/$)`;
425
- };
426
- var REGEX_REPLACE_TRAILING_DOUBLESTAR = /\uE001$/;
427
- var replaceTrailingDoublestar = () => ".+(?=$|\\/$)";
428
- var WILDCARD = "[^\\/]*";
429
- var separatorAfter = (run, at) => {
430
- let separator = EMPTY;
431
- for (let index = at + 1; index < run.length && !run[index].wildcard; index++) {
432
- separator += run[index].single;
433
- }
434
- return separator;
435
- };
436
- var pinWildcards = (source) => {
437
- if (source.indexOf(WILDCARD) < 0) {
438
- return source;
439
- }
440
- const tokens = [];
441
- const { length } = source;
442
- let index = 0;
443
- while (index < length) {
444
- const char = source[index];
445
- if (source.startsWith(WILDCARD, index)) {
446
- tokens.push({ wildcard: true });
447
- index += WILDCARD.length;
448
- } else if (char === "[") {
449
- let end = index + 1;
450
- if (source[end] === "^") {
451
- end++;
452
- }
453
- if (source[end] === "]") {
454
- end++;
455
- }
456
- while (end < length && source[end] !== "]") {
457
- end += source[end] === ESCAPE ? 2 : 1;
458
- }
459
- end++;
460
- tokens.push({ single: source.slice(index, end) });
461
- index = end;
462
- } else if (char === ESCAPE) {
463
- tokens.push({ single: source.slice(index, index + 2) });
464
- index += 2;
465
- } else if (char === "(") {
466
- let depth = 0;
467
- let end = index;
468
- do {
469
- if (source[end] === ESCAPE) {
470
- end++;
471
- } else if (source[end] === "(") {
472
- depth++;
473
- } else if (source[end] === ")") {
474
- depth--;
475
- }
476
- end++;
477
- } while (end < length && depth > 0);
478
- if ("*+?".indexOf(source[end]) >= 0) {
479
- end++;
480
- }
481
- tokens.push({ boundary: source.slice(index, end) });
482
- index = end;
483
- } else if (char === "^" || char === "$") {
484
- tokens.push({ boundary: char });
485
- index++;
486
- } else {
487
- tokens.push({ single: char });
488
- index++;
489
- }
490
- }
491
- let out = EMPTY;
492
- let run = [];
493
- const flush = () => {
494
- let lastWildcard;
495
- run.forEach((token, at) => {
496
- if (token.wildcard) {
497
- lastWildcard = at;
498
- }
499
- });
500
- run.forEach((token, at) => {
501
- if (!token.wildcard) {
502
- out += token.single;
503
- return;
504
- }
505
- out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run, at)})[^\\/])*`;
506
- });
507
- run = [];
508
- };
509
- tokens.forEach((token) => {
510
- if (token.boundary === void 0) {
511
- run.push(token);
512
- return;
513
- }
514
- flush();
515
- out += token.boundary;
516
- });
517
- flush();
518
- return out;
519
- };
520
- var makeRegexPrefix = (pattern) => {
521
- const { source, sources } = extractBrackets(pattern);
522
- const replaced = REPLACERS.reduce(
523
- // A pass whose matcher finds nothing hands back the very string it was
524
- // given, so asking first costs a search and saves a rewrite. Ten of the
525
- // fifteen passes never fire for a typical .gitignore line, and between
526
- // them they were 45% of this chain.
527
- (prev, [matcher, replacer, required2]) => {
528
- if (matcher === DIRECT) {
529
- return replacer(prev, pattern);
530
- }
531
- if (required2 !== UNDEFINED && prev.indexOf(required2) < 0) {
532
- return prev;
533
- }
534
- return matcher.test(prev) ? prev.replace(matcher, replacer.bind(pattern)) : prev;
535
- },
536
- source
537
- );
538
- return sources.length ? replaced.replace(
539
- REGEX_RESTORE_PLACEHOLDER,
540
- (match, index) => sources[index]
541
- ) : replaced;
542
- };
543
- var checkSourceOf = (body, prefix) => {
544
- if (body[body.length - 1] === SLASH3) {
545
- prefix = makeRegexPrefix(body.slice(0, -1));
546
- }
547
- const head = prefix.slice(0, -1);
548
- const last = prefix[prefix.length - 1];
549
- return last === TRAILING_WILDCARD ? `${head}$` : last === TRAILING_DOUBLESTAR ? `${head}.*$` : NEVER_MATCH;
550
- };
551
- var matchesBasename = (body) => {
552
- const index = body.indexOf(SLASH3);
553
- return index < 0 || index === body.length - 1;
554
- };
555
- var basenameOf = (path) => {
556
- const end = path.length - 1;
557
- const index = path.lastIndexOf(
558
- SLASH3,
559
- path[end] === SLASH3 ? end - 1 : end
560
- );
561
- return index < 0 ? path : path.slice(index + 1);
562
- };
563
- var parentOf = (path) => {
564
- if (path.charCodeAt(0) === SLASH_CODE || path.indexOf(DOUBLE_SLASH) >= 0) {
565
- const slices = path.split(SLASH3).filter(Boolean);
566
- slices.pop();
567
- return slices.length ? slices.join(SLASH3) + SLASH3 : EMPTY;
568
- }
569
- const end = path.length - 1;
570
- const cut = path.lastIndexOf(
571
- SLASH3,
572
- path.charCodeAt(end) === SLASH_CODE ? end - 1 : end
573
- );
574
- return cut < 0 ? EMPTY : path.slice(0, cut + 1);
575
- };
576
- var isString = (subject) => typeof subject === "string";
577
- var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
578
- var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
579
- var IgnoreRule = class {
580
- constructor(pattern, mark, body, ignoreCase, negative, prefix) {
581
- this.pattern = pattern;
582
- this.mark = mark;
583
- this.negative = negative;
584
- define(this, "body", body);
585
- define(this, "ignoreCase", ignoreCase);
586
- define(this, "regexPrefix", prefix);
587
- }
588
- // Worked out on first use and kept behind an own property, the way `regex`
589
- // caches itself in `_regex`. Deciding it in the constructor instead would
590
- // add a fourth `defineProperty` to every rule ever built, which cost 4% of
591
- // every compile -- including the compiles of rules that are never matched
592
- // against anything.
593
- get _basenameOnly() {
594
- return define(this, "_basenameOnly", matchesBasename(this.body));
595
- }
596
- get regex() {
597
- const key = UNDERSCORE + MODE_IGNORE;
598
- if (this[key]) {
599
- return this[key];
600
- }
601
- return this._make(MODE_IGNORE, key);
602
- }
603
- get checkRegex() {
604
- const key = UNDERSCORE + MODE_CHECK_IGNORE;
605
- if (this[key]) {
606
- return this[key];
607
- }
608
- return this._make(MODE_CHECK_IGNORE, key);
609
- }
610
- _make(mode, key) {
611
- const str2 = pinWildcards(
612
- mode === MODE_IGNORE ? this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard).replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar) : checkSourceOf(this.body, this.regexPrefix)
613
- );
614
- const regex = this.ignoreCase ? new RegExp(str2, "i") : new RegExp(str2);
615
- return define(this, key, regex);
616
- }
617
- };
618
- var createRule = ({
619
- pattern,
620
- mark
621
- }, ignoreCase) => {
622
- let negative = false;
623
- let body = pattern;
624
- if (body.indexOf("!") === 0) {
625
- negative = true;
626
- body = body.substr(1);
627
- }
628
- body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
629
- const regexPrefix = makeRegexPrefix(body);
630
- return new IgnoreRule(
631
- pattern,
632
- mark,
633
- body,
634
- ignoreCase,
635
- negative,
636
- regexPrefix
637
- );
638
- };
639
- var RuleManager = class {
640
- constructor(ignoreCase) {
641
- this._ignoreCase = ignoreCase;
642
- this._rules = [];
643
- this._basenameCount = 0;
644
- }
645
- _add(pattern) {
646
- if (pattern && pattern[KEY_IGNORE]) {
647
- this._rules = this._rules.concat(pattern._rules._rules);
648
- this._basenameCount += pattern._rules._basenameCount;
649
- this._added = true;
650
- return;
651
- }
652
- if (isString(pattern)) {
653
- pattern = {
654
- pattern
655
- };
656
- }
657
- if (checkPattern(pattern.pattern)) {
658
- const rule = createRule(pattern, this._ignoreCase);
659
- this._added = true;
660
- this._rules.push(rule);
661
- if (matchesBasename(rule.body)) {
662
- this._basenameCount++;
663
- }
664
- }
665
- }
666
- // @param {Array<string> | string | Ignore} pattern
667
- add(pattern) {
668
- this._added = false;
669
- makeArray(
670
- isString(pattern) ? splitPattern(pattern) : pattern
671
- ).forEach(this._add, this);
672
- if (this._added) {
673
- this._literalRules = UNDEFINED;
674
- }
675
- return this._added;
676
- }
677
- // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule
678
- // ending in a wildcard can match it (see `checkSourceOf`), so the rest
679
- // are left out once, rather than tested or compiled for every path.
680
- testLiteral(path) {
681
- const rules = this._literalRules || (this._literalRules = this._rules.filter(
682
- ({ body }) => body[body.length - (body[body.length - 1] === SLASH3 ? 2 : 1)] === "*"
683
- ));
684
- let ignored = false;
685
- let unignored = false;
686
- let matchedRule;
687
- for (let index = rules.length - 1; index >= 0; index--) {
688
- const rule = rules[index];
689
- if (rule.checkRegex.test(path)) {
690
- ignored = !rule.negative;
691
- unignored = rule.negative;
692
- matchedRule = rule.negative ? UNDEFINED : rule;
693
- break;
694
- }
695
- }
696
- const ret = {
697
- ignored,
698
- unignored
699
- };
700
- if (matchedRule) {
701
- ret.rule = matchedRule;
702
- }
703
- return ret;
704
- }
705
- // Test one single path without recursively checking parent directories
706
- //
707
- // - checkUnignored `boolean` whether should check if the path is unignored,
708
- // setting `checkUnignored` to `false` could reduce additional
709
- // path matching.
710
- // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
711
- // @returns {TestResult} true if a file is ignored
712
- test(path, checkUnignored, mode) {
713
- let ignored = false;
714
- let unignored = false;
715
- let matchedRule;
716
- const rules = this._rules;
717
- const { length } = rules;
718
- const shortcut = this._basenameCount * 2 >= length;
719
- const basename7 = shortcut ? basenameOf(path) : path;
720
- for (let index = 0; index < length; index++) {
721
- const rule = rules[index];
722
- const { negative } = rule;
723
- const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
724
- if (!skip && rule[mode].test(
725
- shortcut && rule._basenameOnly ? basename7 : path
726
- )) {
727
- ignored = !negative;
728
- unignored = negative;
729
- matchedRule = negative ? UNDEFINED : rule;
730
- }
731
- }
732
- const ret = {
733
- ignored,
734
- unignored
735
- };
736
- if (matchedRule) {
737
- ret.rule = matchedRule;
738
- }
739
- return ret;
740
- }
741
- };
742
- var throwError = (message, Ctor) => {
743
- throw new Ctor(message);
744
- };
745
- var checkPath = (path, originalPath, doThrow) => {
746
- if (!isString(path)) {
747
- return doThrow(
748
- `path must be a string, but got \`${originalPath}\``,
749
- TypeError
750
- );
751
- }
752
- if (!path) {
753
- return doThrow(`path must not be empty`, TypeError);
754
- }
755
- if (checkPath.isNotRelative(path)) {
756
- const r = "`path.relative()`d";
757
- return doThrow(
758
- `path should be a ${r} string, but got "${originalPath}"`,
759
- RangeError
760
- );
761
- }
762
- return true;
763
- };
764
- var isNotRelative = (path) => {
765
- const first = path.charCodeAt(0);
766
- if (first === SLASH_CODE) {
767
- return true;
768
- }
769
- if (first !== DOT_CODE) {
770
- return false;
771
- }
772
- if (path.length === 1) {
773
- return true;
774
- }
775
- const second = path.charCodeAt(1);
776
- if (second === SLASH_CODE) {
777
- return true;
778
- }
779
- if (second !== DOT_CODE) {
780
- return false;
781
- }
782
- return path.length === 2 || path.charCodeAt(2) === SLASH_CODE;
783
- };
784
- checkPath.isNotRelative = isNotRelative;
785
- checkPath.convert = (p) => p;
786
- var Ignore = class {
787
- constructor({
788
- ignorecase = true,
789
- ignoreCase = ignorecase,
790
- allowRelativePaths = false
791
- } = {}) {
792
- define(this, KEY_IGNORE, true);
793
- this._rules = new RuleManager(ignoreCase);
794
- this._strictPathCheck = !allowRelativePaths;
795
- this._initCache();
796
- }
797
- _initCache() {
798
- this._ignoreCache = /* @__PURE__ */ Object.create(null);
799
- this._testCache = /* @__PURE__ */ Object.create(null);
800
- }
801
- add(pattern) {
802
- if (this._rules.add(pattern)) {
803
- this._initCache();
804
- }
805
- return this;
806
- }
807
- // legacy
808
- addPattern(pattern) {
809
- return this.add(pattern);
810
- }
811
- // @returns {TestResult}
812
- _test(originalPath, cache, checkUnignored) {
813
- const path = originalPath && checkPath.convert(originalPath);
814
- checkPath(
815
- path,
816
- originalPath,
817
- this._strictPathCheck ? throwError : RETURN_FALSE
818
- );
819
- return this._t(path, cache, checkUnignored);
820
- }
821
- checkIgnore(path) {
822
- if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {
823
- return this.test(path);
824
- }
825
- const dir = this._t(path, this._testCache, true);
826
- if (dir.ignored) {
827
- return dir;
828
- }
829
- const literal2 = this._rules.testLiteral(path);
830
- return literal2.ignored || literal2.unignored ? literal2 : dir;
831
- }
832
- _t(path, cache, checkUnignored) {
833
- if (path in cache) {
834
- return cache[path];
835
- }
836
- const parentPath = parentOf(path);
837
- const parent = parentPath ? this._t(parentPath, cache, checkUnignored) : UNDEFINED;
838
- return cache[path] = parent && parent.ignored ? parent : this._rules.test(path, checkUnignored, MODE_IGNORE);
839
- }
840
- ignores(path) {
841
- return this._test(path, this._ignoreCache, false).ignored;
842
- }
843
- createFilter() {
844
- return (path) => !this.ignores(path);
845
- }
846
- filter(paths) {
847
- return makeArray(paths).filter(this.createFilter());
848
- }
849
- // @returns {TestResult}
850
- test(path) {
851
- return this._test(path, this._testCache, true);
852
- }
853
- };
854
- var factory = (options) => new Ignore(options);
855
- var isPathValid = (path) => checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
856
- var setupWindows = () => {
857
- const makePosix = (str2) => /^\\\\\?\\/.test(str2) || /["<>|\u0000-\u001F]+/u.test(str2) ? str2 : str2.replace(/\\/g, "/");
858
- checkPath.convert = makePosix;
859
- const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
860
- checkPath.isNotRelative = (path) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
861
- };
862
- if (
863
- // Detect `process` so that it can run in browsers.
864
- typeof process !== "undefined" && process.platform === "win32"
865
- ) {
866
- setupWindows();
867
- }
868
- module.exports = factory;
869
- factory.default = factory;
870
- module.exports.isPathValid = isPathValid;
871
- define(module.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows);
872
- }
873
- });
874
-
875
- // ../../packages/persistence/src/attached-derived.ts
876
- import { rmSync } from "fs";
877
- import { join } from "path";
878
- var POLICY_CACHE_FILENAME = "policy-cache.json";
879
- var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
880
- var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
881
- var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
882
-
883
- // ../../packages/persistence/src/control-plane-credential.ts
884
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
885
- import { join as join2 } from "path";
886
6
 
887
7
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
888
8
  var DEFERRED_MIGRATION_TAGS = [
@@ -1055,7 +175,7 @@ var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1055
175
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1056
176
 
1057
177
  // ../../packages/schema/src/invisible-padding.ts
1058
- var INVISIBLE_PADDING = /[\u00AD\u200B\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\u{E0001}\u{E0020}-\u{E007F}]/gu;
178
+ var INVISIBLE_PADDING = /[\u00AD\u061C\u180E\u200B\u200E\u200F\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\uFFF9-\uFFFB\u{E0001}\u{E0020}-\u{E007F}]/gu;
1059
179
  function stripInvisiblePadding(text) {
1060
180
  return text.replace(INVISIBLE_PADDING, "");
1061
181
  }
@@ -3873,9 +2993,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
3873
2993
  function stripTabAndNewline(value) {
3874
2994
  return value.replace(asciiTabOrNewline, "");
3875
2995
  }
3876
- function urlHostnameOk(url2, hostname7) {
3877
- hostname7.lastIndex = 0;
3878
- return hostname7.test(url2.hostname);
2996
+ function urlHostnameOk(url2, hostname6) {
2997
+ hostname6.lastIndex = 0;
2998
+ return hostname6.test(url2.hostname);
3879
2999
  }
3880
3000
  function urlProtocolOk(url2, protocol) {
3881
3001
  protocol.lastIndex = 0;
@@ -20795,13 +19915,16 @@ function serviceTierMultiplier(tier) {
20795
19915
  if (tier === void 0) return 1;
20796
19916
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20797
19917
  }
19918
+ function promptTokensOf(usage) {
19919
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
19920
+ }
20798
19921
  function costOf(price, usage) {
20799
19922
  const metered = [
20800
19923
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20801
19924
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20802
19925
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20803
19926
  ];
20804
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
19927
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20805
19928
  if (band !== null && (band.input === null || band.output === null)) return null;
20806
19929
  const inputRate = band?.input ?? price.input;
20807
19930
  const outputRate = band?.output ?? price.output;
@@ -20874,8 +19997,8 @@ var PLATFORM_HOSTING = /* @__PURE__ */ new Map([
20874
19997
  ["ollama", "local"],
20875
19998
  ["local", "local"]
20876
19999
  ]);
20877
- function hostingFor(platform2) {
20878
- return PLATFORM_HOSTING.get(platform2) ?? "api";
20000
+ function hostingFor(platform) {
20001
+ return PLATFORM_HOSTING.get(platform) ?? "api";
20879
20002
  }
20880
20003
  var FIRST_PARTY = /* @__PURE__ */ new Map([
20881
20004
  ["anthropic", "anthropic"],
@@ -20889,8 +20012,8 @@ var FIRST_PARTY = /* @__PURE__ */ new Map([
20889
20012
  function firstPartyPlatformFor(vendor2) {
20890
20013
  return FIRST_PARTY.get(vendor2) ?? null;
20891
20014
  }
20892
- function isFirstParty(vendor2, platform2) {
20893
- return FIRST_PARTY.get(vendor2) === platform2;
20015
+ function isFirstParty(vendor2, platform) {
20016
+ return FIRST_PARTY.get(vendor2) === platform;
20894
20017
  }
20895
20018
  var PLATFORM_NAMESPACES = Object.freeze([
20896
20019
  "anthropic",
@@ -20951,14 +20074,14 @@ var ModelVendorBuilder = class {
20951
20074
  );
20952
20075
  }
20953
20076
  for (const ref of spec.on ?? []) {
20954
- const { platform: platform2, price, retention, region } = normalizeRef(ref);
20955
- const firstParty = isFirstParty(this.vendor, platform2);
20956
- const hosting = hostingFor(platform2);
20077
+ const { platform, price, retention, region } = normalizeRef(ref);
20078
+ const firstParty = isFirstParty(this.vendor, platform);
20079
+ const hosting = hostingFor(platform);
20957
20080
  const isSelfHosted = hosting === "local";
20958
20081
  platforms.set(
20959
- platform2,
20082
+ platform,
20960
20083
  Object.freeze({
20961
- platform: platform2,
20084
+ platform,
20962
20085
  hosting,
20963
20086
  firstParty,
20964
20087
  price: price ?? (isSelfHosted ? ZERO_PRICE : firstParty ? spec.price ?? null : null),
@@ -21011,35 +20134,35 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21011
20134
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21012
20135
  var BEDROCK_REVISION_RE = /:\d+$/u;
21013
20136
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21014
- var DATED_SUFFIX_RE = /-\d{8}$/u;
20137
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21015
20138
  function stripPlatformDecorations(model) {
21016
20139
  let id = model.trim();
21017
- let platform2 = null;
20140
+ let platform = null;
21018
20141
  if (GEO_PREFIX_RE.test(id)) {
21019
20142
  id = id.replace(GEO_PREFIX_RE, "");
21020
- platform2 = "bedrock";
20143
+ platform = "bedrock";
21021
20144
  }
21022
20145
  if (NAMESPACE_DOT_RE.test(id)) {
21023
20146
  id = id.replace(NAMESPACE_DOT_RE, "");
21024
- platform2 ??= "bedrock";
20147
+ platform ??= "bedrock";
21025
20148
  }
21026
20149
  if (BEDROCK_VERSION_RE.test(id)) {
21027
20150
  id = id.replace(BEDROCK_VERSION_RE, "");
21028
- platform2 ??= "bedrock";
20151
+ platform ??= "bedrock";
21029
20152
  } else if (BEDROCK_REVISION_RE.test(id)) {
21030
20153
  id = id.replace(BEDROCK_REVISION_RE, "");
21031
- platform2 ??= "bedrock";
20154
+ platform ??= "bedrock";
21032
20155
  }
21033
20156
  if (VERTEX_VERSION_RE.test(id)) {
21034
20157
  id = id.replace(VERTEX_VERSION_RE, "");
21035
- platform2 ??= "vertex";
20158
+ platform ??= "vertex";
21036
20159
  }
21037
20160
  if (NAMESPACE_SLASH_RE.test(id)) {
21038
20161
  id = id.replace(NAMESPACE_SLASH_RE, "");
21039
20162
  } else if (GATEWAY_VENDOR_SLASH_RE.test(id)) {
21040
20163
  id = id.replace(GATEWAY_VENDOR_SLASH_RE, "");
21041
20164
  }
21042
- return { id, platform: platform2 };
20165
+ return { id, platform };
21043
20166
  }
21044
20167
  function buildModelIndex(entries) {
21045
20168
  const byId = /* @__PURE__ */ new Map();
@@ -21056,19 +20179,19 @@ function resolveModel(raw, index) {
21056
20179
  if (exact !== void 0) {
21057
20180
  return { entry: exact, canonicalId: raw, platform: null, raw };
21058
20181
  }
21059
- const { id, platform: platform2 } = stripPlatformDecorations(raw);
20182
+ const { id, platform } = stripPlatformDecorations(raw);
21060
20183
  const stripped = index.byId.get(id);
21061
20184
  if (stripped !== void 0) {
21062
- return { entry: stripped, canonicalId: id, platform: platform2, raw };
20185
+ return { entry: stripped, canonicalId: id, platform, raw };
21063
20186
  }
21064
20187
  if (DATED_SUFFIX_RE.test(id)) {
21065
20188
  const undated = id.replace(DATED_SUFFIX_RE, "");
21066
20189
  const byDate = index.byId.get(undated);
21067
20190
  if (byDate !== void 0) {
21068
- return { entry: byDate, canonicalId: undated, platform: platform2, raw };
20191
+ return { entry: byDate, canonicalId: undated, platform, raw };
21069
20192
  }
21070
20193
  }
21071
- return { entry: null, canonicalId: raw, platform: platform2, raw };
20194
+ return { entry: null, canonicalId: raw, platform, raw };
21072
20195
  }
21073
20196
 
21074
20197
  // ../../packages/schema/src/model/catalog.ts
@@ -21161,7 +20284,7 @@ anthropic.model("claude-haiku-4-5", {
21161
20284
  name: "Claude Haiku 4.5",
21162
20285
  ctx: 2e5,
21163
20286
  maxOut: 64e3,
21164
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
20287
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21165
20288
  capability: null,
21166
20289
  price: anthropicPrice(1, 5, 0.1),
21167
20290
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21292,6 +20415,11 @@ openai.model("gpt-4o", {
21292
20415
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21293
20416
  on: [...OPENAI_RESELLERS]
21294
20417
  });
20418
+ openai.model("gpt-4o-2024-05-13", {
20419
+ name: "GPT-4o (2024-05-13)",
20420
+ price: tokenPrice(5, 15),
20421
+ on: [...OPENAI_RESELLERS]
20422
+ });
21295
20423
  openai.model("gpt-4o-mini", {
21296
20424
  name: "GPT-4o mini",
21297
20425
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21311,6 +20439,24 @@ openai.model("o3", {
21311
20439
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21312
20440
  on: [...OPENAI_RESELLERS]
21313
20441
  });
20442
+ openai.model("text-embedding-3-small", {
20443
+ name: "text-embedding-3-small",
20444
+ capability: "embedding",
20445
+ price: tokenPrice(0.02, 0),
20446
+ on: [...OPENAI_RESELLERS]
20447
+ });
20448
+ openai.model("text-embedding-3-large", {
20449
+ name: "text-embedding-3-large",
20450
+ capability: "embedding",
20451
+ price: tokenPrice(0.13, 0),
20452
+ on: [...OPENAI_RESELLERS]
20453
+ });
20454
+ openai.model("text-embedding-ada-002", {
20455
+ name: "text-embedding-ada-002",
20456
+ capability: "embedding",
20457
+ price: tokenPrice(0.1, 0),
20458
+ on: [...OPENAI_RESELLERS]
20459
+ });
21314
20460
  openai.model("gpt-oss-120b", {
21315
20461
  name: "GPT-OSS 120B",
21316
20462
  openWeights: true,
@@ -21597,10 +20743,21 @@ var MODEL_ENTRIES = Object.freeze([
21597
20743
  ...alibaba.models(),
21598
20744
  ...amazon.models()
21599
20745
  ]);
20746
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
20747
+ [
20748
+ ...new Set(
20749
+ MODEL_ENTRIES.flatMap(
20750
+ (entry) => [...entry.platforms.values()].flatMap(
20751
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
20752
+ )
20753
+ )
20754
+ )
20755
+ ].sort((a, b) => a - b)
20756
+ );
21600
20757
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21601
20758
 
21602
20759
  // ../../packages/schema/src/model/governance.ts
21603
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
20760
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21604
20761
  var DataRetention = external_exports.enum([
21605
20762
  "zero_retention",
21606
20763
  "no_storage",
@@ -21696,16 +20853,16 @@ function platformForProvider(provider) {
21696
20853
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
21697
20854
  }
21698
20855
  function isLocalProvider(provider) {
21699
- const platform2 = platformForProvider(provider);
21700
- return platform2 !== null && hostingFor(platform2) === "local";
20856
+ const platform = platformForProvider(provider);
20857
+ return platform !== null && hostingFor(platform) === "local";
21701
20858
  }
21702
20859
  function priceFor(provider, model) {
21703
20860
  if (isLocalProvider(provider)) return ZERO_PRICE;
21704
20861
  const resolved = resolveModel(model, MODEL_INDEX);
21705
20862
  if (resolved.entry === null) return null;
21706
- const platform2 = resolved.platform ?? platformForProvider(provider);
21707
- if (platform2 === null) return null;
21708
- return resolved.entry.platforms.get(platform2)?.price ?? null;
20863
+ const platform = resolved.platform ?? platformForProvider(provider);
20864
+ if (platform === null) return null;
20865
+ return resolved.entry.platforms.get(platform)?.price ?? null;
21709
20866
  }
21710
20867
  var defaultCostModel = {
21711
20868
  normalizeModelId(provider, model) {
@@ -21731,7 +20888,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21731
20888
 
21732
20889
  // ../../packages/schema/src/token/token-report.ts
21733
20890
  var num = (value) => value ?? 0;
21734
- function costUsageOf(a) {
20891
+ function costUsageOf(a, promptTokens) {
21735
20892
  const usage = {
21736
20893
  inputTokens: num(a.input_tokens),
21737
20894
  outputTokens: num(a.output_tokens),
@@ -21741,11 +20898,12 @@ function costUsageOf(a) {
21741
20898
  webSearchRequests: num(a.web_search_requests)
21742
20899
  };
21743
20900
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
20901
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21744
20902
  return usage;
21745
20903
  }
21746
20904
  function buildTokenReports(leaves, costModel) {
21747
20905
  const bySession = /* @__PURE__ */ new Map();
21748
- for (const { sessionId, attributes } of leaves) {
20906
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21749
20907
  const provider = attributes.provider ?? "unknown";
21750
20908
  const model = attributes.model ?? "unknown";
21751
20909
  const key = `${provider} ${model}`;
@@ -21764,7 +20922,8 @@ function buildTokenReports(leaves, costModel) {
21764
20922
  cacheCreation: 0,
21765
20923
  cacheRead: 0,
21766
20924
  costUsd: 0,
21767
- priced: false
20925
+ priced: false,
20926
+ partial: false
21768
20927
  };
21769
20928
  rollups.set(key, acc);
21770
20929
  }
@@ -21772,8 +20931,14 @@ function buildTokenReports(leaves, costModel) {
21772
20931
  acc.output += num(attributes.output_tokens);
21773
20932
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21774
20933
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21775
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21776
- if (leafCost !== null) {
20934
+ const leafCost = costModel.costFor({
20935
+ provider,
20936
+ model,
20937
+ usage: costUsageOf(attributes, promptTokens)
20938
+ });
20939
+ if (leafCost === null) {
20940
+ acc.partial = true;
20941
+ } else {
21777
20942
  acc.costUsd += leafCost;
21778
20943
  acc.priced = true;
21779
20944
  }
@@ -21789,9 +20954,8 @@ function buildTokenReports(leaves, costModel) {
21789
20954
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21790
20955
  totalTokens += rollupTotal;
21791
20956
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21792
- if (estimatedCostUsd === null) {
21793
- anyUnpriced = true;
21794
- } else {
20957
+ if (acc.partial) anyUnpriced = true;
20958
+ if (estimatedCostUsd !== null) {
21795
20959
  anyPriced = true;
21796
20960
  costUsd += estimatedCostUsd;
21797
20961
  }
@@ -21814,7 +20978,7 @@ function buildTokenReports(leaves, costModel) {
21814
20978
  totalTokens,
21815
20979
  // Σ of the PRICED rollups; null when none had a known price.
21816
20980
  estimatedCostUsd: anyPriced ? costUsd : null,
21817
- // Any unknown (provider, model) means the total understates real spend.
20981
+ // Any call priced to null means the total understates real spend.
21818
20982
  costIsPartial: anyUnpriced
21819
20983
  });
21820
20984
  }
@@ -22693,8 +21857,9 @@ var SessionTokenReport = external_exports.object({
22693
21857
  totalTokens: external_exports.number().int().nonnegative(),
22694
21858
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22695
21859
  estimatedCostUsd: external_exports.number().nullable(),
22696
- // True whenever any rollup has a null cost (unknown provider/model), so the
22697
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
21860
+ // True whenever any call priced to null (an unknown provider/model, or a call
21861
+ // over a long-context threshold whose rate is unpublished), so the total
21862
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22698
21863
  // precise figure rather than silently dropping the unpriced calls.
22699
21864
  costIsPartial: external_exports.boolean()
22700
21865
  });
@@ -23571,7 +22736,15 @@ var StorePostureSnapshot = external_exports.object({
23571
22736
  policyCounts: StorePosturePolicyCounts,
23572
22737
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23573
22738
  // getting its 200 without a payload change.
23574
- plugin: StorePosturePlugin.optional()
22739
+ plugin: StorePosturePlugin.optional(),
22740
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22741
+ // machine attachment omits it, so its body is byte for byte the one it
22742
+ // sent before this member existed. Absent therefore means machine-wide OR
22743
+ // a reporter older than this member, never "scoped". Both values parse, so
22744
+ // a sender that one day spells `machine` breaks no receiver; any other
22745
+ // value fails the whole snapshot, which is why the reporter sends a
22746
+ // constant and never the raw mode.
22747
+ attachmentMode: AttachmentMode.optional()
23575
22748
  }).meta({ id: "StorePostureSnapshot" });
23576
22749
  var CAPTURE_VERSION_PREFIX = "capture/";
23577
22750
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -24018,7 +23191,7 @@ var Rule = external_exports.strictObject({
24018
23191
  postValidators: external_exports.array(PostValidatorRef).optional(),
24019
23192
  requiresNearby: RequiresNearby.optional(),
24020
23193
  examples: external_exports.array(external_exports.string()).optional(),
24021
- // Whether the matched text is itself sensitive. Absent means 'value'.
23194
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24022
23195
  evidence: RuleEvidence.optional()
24023
23196
  }).meta({ id: "Rule" });
24024
23197
  var Author = external_exports.object({
@@ -24110,7 +23283,13 @@ var DetectionRule = external_exports.object({
24110
23283
  // Representative matching strings the rule author shipped with the rule. The
24111
23284
  // cheapest honest answer to "show me what this rule catches" — every bundled
24112
23285
  // rule has them, and they are already in the stored snapshot.
24113
- examples: external_exports.array(external_exports.string()).optional()
23286
+ examples: external_exports.array(external_exports.string()).optional(),
23287
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23288
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23289
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23290
+ // in a value category (secret/pii/financial/phi) is always 'value',
23291
+ // whatever it declares.
23292
+ evidence: RuleEvidence.optional()
24114
23293
  }).meta({ id: "DetectionRule" });
24115
23294
  var DetectionUpdate = external_exports.object({
24116
23295
  available: external_exports.boolean(),
@@ -24178,8 +23357,10 @@ var ImportDetectionRequest = external_exports.object({
24178
23357
  }).meta({ id: "ImportDetectionRequest" });
24179
23358
 
24180
23359
  // ../../packages/schema/src/zod/detection-build.ts
24181
- function optional2(key, parsed2, raw) {
24182
- if (raw === void 0 || !parsed2.success || parsed2.data === void 0) return {};
23360
+ function optional2(key, raw, parse4) {
23361
+ if (raw === void 0) return {};
23362
+ const parsed2 = parse4(raw);
23363
+ if (!parsed2.success || parsed2.data === void 0) return {};
24183
23364
  return { [key]: parsed2.data };
24184
23365
  }
24185
23366
  function isStringArray(value) {
@@ -24214,10 +23395,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24214
23395
  category: r.category,
24215
23396
  severity: r.severity,
24216
23397
  matcher: parsed2.data,
24217
- // The rest of what decides whether this rule fires. Carried so a consumer
24218
- // re-running the rule (a preview, a tester) evaluates what the engine
24219
- // evaluates rather than a matcher stripped of its guards — half the
24220
- // bundled catalog carries at least one of these.
23398
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23399
+ // decides whether this rule fires. Carried so a consumer re-running the
23400
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23401
+ // than a matcher stripped of its guards — half the bundled catalog
23402
+ // carries at least one of these. `examples` and `evidence` describe the
23403
+ // rule and never gate a match.
24221
23404
  //
24222
23405
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24223
23406
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24227,18 +23410,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24227
23410
  // test should stay exactly what it was, namely a renderable matcher. A
24228
23411
  // field that fails validation is omitted, which reads as "not set" and is
24229
23412
  // the same thing the consumer saw before this change.
24230
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23413
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24231
23414
  ...optional2(
24232
23415
  "postValidators",
24233
- PostValidatorRef.array().safeParse(r.postValidators),
24234
- r.postValidators
23416
+ r.postValidators,
23417
+ (v) => PostValidatorRef.array().safeParse(v)
24235
23418
  ),
24236
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23419
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24237
23420
  ...optional2(
24238
23421
  "examples",
24239
- { success: isStringArray(r.examples), data: r.examples },
24240
- r.examples
24241
- )
23422
+ r.examples,
23423
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23424
+ ),
23425
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24242
23426
  }
24243
23427
  ];
24244
23428
  });
@@ -24931,11 +24115,14 @@ var PolicyBundle = external_exports.object({
24931
24115
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24932
24116
  // Model ids (the raw `model` string a harness reports, e.g.
24933
24117
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
24934
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
24935
- // one (UserPromptSubmit). Optional so an older backend — and an older
24936
- // on-disk cache — still parses; consumers read `?? []`, which is the
24937
- // unenforced behaviour that predates this field and the safe direction to
24938
- // default.
24118
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24119
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24120
+ // wherever the organization governs the event: everywhere on a
24121
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24122
+ // one (the plugin runtime's `governanceApplies`).
24123
+ // Optional so an older backend — and an older on-disk cache — still
24124
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24125
+ // predates this field and the safe direction to default.
24939
24126
  //
24940
24127
  // Ids, not display names: the governance decision is keyed on the exact
24941
24128
  // string the harness reports (`model_status_override.versionId` in the
@@ -25394,6 +24581,8 @@ var AttachmentScopeEntry = external_exports.object({
25394
24581
  });
25395
24582
  var AttachmentScope = external_exports.object({
25396
24583
  endpoint: external_exports.string().min(1),
24584
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24585
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25397
24586
  entries: external_exports.array(AttachmentScopeEntry)
25398
24587
  });
25399
24588
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25406,7 +24595,13 @@ function parseAttachmentScope(raw) {
25406
24595
  const entry = AttachmentScopeEntry.safeParse(candidate);
25407
24596
  if (entry.success) entries.push(entry.data);
25408
24597
  }
25409
- return { endpoint: envelope.data.endpoint, entries };
24598
+ const { endpoint, tenantName, userEmail } = envelope.data;
24599
+ return {
24600
+ endpoint,
24601
+ ...tenantName === void 0 ? {} : { tenantName },
24602
+ ...userEmail === void 0 ? {} : { userEmail },
24603
+ entries
24604
+ };
25410
24605
  } catch {
25411
24606
  return void 0;
25412
24607
  }
@@ -25771,6 +24966,27 @@ var ManagedSettings = external_exports.object({
25771
24966
  };
25772
24967
  }).meta({ id: "ManagedSettings" });
25773
24968
 
24969
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
24970
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
24971
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
24972
+ var ModPolicySnapshot = external_exports.object({
24973
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
24974
+ generatedAt: external_exports.iso.datetime(),
24975
+ // The complete effective ruleset, as the hook's runtime scans with it: the
24976
+ // user's enabled installed packs (user-modified and custom packs included).
24977
+ // Absent means the store holds no authoritative snapshot, and the reader
24978
+ // scans with the packs it ships — the hook's own fallback.
24979
+ rules: external_exports.array(Rule).optional(),
24980
+ // Rule-targeted actions (first enabled policy per rule wins).
24981
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
24982
+ // The resolved action per detection category.
24983
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
24984
+ // Rules with an active exception grant. Honouring a grant means matching a
24985
+ // keyed fingerprint of the value and consuming a use, which only the hook can
24986
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
24987
+ exceptionRuleIds: external_exports.array(external_exports.string())
24988
+ }).meta({ id: "ModPolicySnapshot" });
24989
+
25774
24990
  // ../../packages/schema/src/zod/project-files.ts
25775
24991
  var ProjectFileInput = external_exports.object({
25776
24992
  path: external_exports.string().min(1),
@@ -26091,7 +25307,16 @@ var AttachInput = external_exports.object({
26091
25307
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26092
25308
  // renders a longer one usefully.
26093
25309
  label: printable(200).optional(),
26094
- accessKey: external_exports.string()
25310
+ accessKey: external_exports.string(),
25311
+ // How much of this machine the attachment is for: everything, or only the
25312
+ // repositories its user enrolls. Optional, so an input without it still
25313
+ // parses; what an absent mode means is for whatever reads it to decide, not
25314
+ // this shape. This member validates the VALUE rather than leaving that to the
25315
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25316
+ // rejection names the field, so a value that is not a mode is refused as a bad
25317
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25318
+ // it as the mode to attach in.
25319
+ mode: AttachmentMode.optional()
26095
25320
  });
26096
25321
 
26097
25322
  // ../../packages/schema/src/zod/triage.ts
@@ -26377,6 +25602,18 @@ function fromCaptureStatusAttributes(bag) {
26377
25602
  return parsedStatus.success ? parsedStatus.data : null;
26378
25603
  }
26379
25604
 
25605
+ // ../../packages/persistence/src/attached-derived.ts
25606
+ import { rmSync } from "fs";
25607
+ import { join } from "path";
25608
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25609
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
25610
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
25611
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
25612
+
25613
+ // ../../packages/persistence/src/control-plane-credential.ts
25614
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25615
+ import { join as join2 } from "path";
25616
+
26380
25617
  // ../../packages/persistence/src/paths.ts
26381
25618
  import {
26382
25619
  chmodSync,
@@ -26523,6 +25760,14 @@ function repairOrRefuseMode(file2) {
26523
25760
  }
26524
25761
  return "ok";
26525
25762
  }
25763
+ function asReadableCredential(value) {
25764
+ const result = AttachedCredentialAny.safeParse(value);
25765
+ if (!result.success) return null;
25766
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
25767
+ return null;
25768
+ }
25769
+ return result.data;
25770
+ }
26526
25771
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26527
25772
  const file2 = controlPlaneCredentialPath(settingsDir2);
26528
25773
  let raw;
@@ -26541,20 +25786,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26541
25786
  } catch {
26542
25787
  return { usable: false, reason: "malformed" };
26543
25788
  }
26544
- const result = AttachedCredential.safeParse(parsed2);
26545
- if (!result.success) return { usable: false, reason: "malformed" };
26546
- if (!isSafeEndpoint(result.data.endpoint)) {
25789
+ const credential = asReadableCredential(parsed2);
25790
+ if (credential === null) return { usable: false, reason: "malformed" };
25791
+ if (!isSafeEndpoint(credential.endpoint)) {
26547
25792
  return { usable: false, reason: "unsafe-endpoint" };
26548
25793
  }
26549
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
25794
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26550
25795
  return {
26551
25796
  usable: false,
26552
25797
  reason: "endpoint-mismatch",
26553
- credentialEndpoint: result.data.endpoint,
25798
+ credentialEndpoint: credential.endpoint,
26554
25799
  settingsEndpoint: connection.endpoint
26555
25800
  };
26556
25801
  }
26557
- return { usable: true, credential: result.data };
25802
+ return { usable: true, credential };
26558
25803
  }
26559
25804
  function readControlPlaneCredential(settingsDir2, connection) {
26560
25805
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26563,7 +25808,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26563
25808
 
26564
25809
  // ../../packages/persistence/src/database.ts
26565
25810
  import { randomUUID as randomUUID11 } from "crypto";
26566
- import { dirname as dirname2, join as join7, sep } from "path";
25811
+ import { dirname as dirname2, join as join8, sep } from "path";
26567
25812
  import { DatabaseSync } from "node:sqlite";
26568
25813
 
26569
25814
  // ../../packages/persistence/src/ids.ts
@@ -26617,6 +25862,7 @@ function uuidFromDigest(digest) {
26617
25862
  function captureWireId(sessionId, contentHash, filePath = null) {
26618
25863
  return uuidFromDigest(captureId(sessionId, contentHash, filePath));
26619
25864
  }
25865
+ var DOT = ".".charCodeAt(0);
26620
25866
 
26621
25867
  // ../../packages/persistence/src/internal/snapshot.ts
26622
25868
  import { randomUUID } from "crypto";
@@ -26944,6 +26190,25 @@ function scopeKeysParam(scopeKeys) {
26944
26190
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26945
26191
  FROM audit_events AS session_root
26946
26192
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26193
+ var COUNTED_IN_SCOPE = `
26194
+ AND ${inScope("scope_key")}
26195
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
26196
+ var DRAIN_TOTALS = `SELECT
26197
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26198
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26199
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26200
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26201
+ THEN 1 ELSE 0 END) AS skipped,
26202
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26203
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26204
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26205
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26206
+ FROM audit_events
26207
+ WHERE event_type IN (${TYPE_LIST})`;
26208
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
26209
+ FROM audit_events
26210
+ WHERE synced_at = ${String(SKIPPED)}
26211
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26947
26212
  var ROW_COLUMNS = `id,
26948
26213
  parent_id AS parentId,
26949
26214
  root_session_id AS rootSessionId,
@@ -27019,7 +26284,7 @@ var SqliteHistorySyncRepository = class {
27019
26284
  );
27020
26285
  this.scopedCaptureRowsStmt = db.prepare(
27021
26286
  `SELECT ${ROW_COLUMNS}
27022
- FROM audit_events
26287
+ FROM audit_events INDEXED BY idx_audit_scope_owed
27023
26288
  WHERE synced_at IS NULL
27024
26289
  AND sync_claimed_at IS NULL
27025
26290
  AND outbox_owed = 1
@@ -27072,40 +26337,28 @@ var SqliteHistorySyncRepository = class {
27072
26337
  );
27073
26338
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27074
26339
  FROM audit_events${COUNTED_SCOPE}`);
26340
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26341
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27075
26342
  this.partitionByKindStmt = db.prepare(
27076
26343
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27077
26344
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27078
26345
  GROUP BY event_type`
27079
26346
  );
27080
- this.countsStmt = db.prepare(
27081
- `SELECT
27082
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27083
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27084
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27085
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27086
- THEN 1 ELSE 0 END) AS skipped,
27087
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27088
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27089
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27090
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27091
- FROM audit_events
27092
- WHERE event_type IN (${TYPE_LIST})`
26347
+ this.scopedPartitionByKindStmt = db.prepare(
26348
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26349
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26350
+ GROUP BY event_type`
27093
26351
  );
27094
- this.captureSkipCountStmt = db.prepare(
27095
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
27096
- // way the structural totals are. The split exists because a refusal is
27097
- // terminal only against the deployment that gave it, and the structural
27098
- // re-arm frees it on a change of deployment. The capture lane has no such
27099
- // escape: re-arming a capture would offer one deployment's undelivered
27100
- // prompts, with their text, to a deployment that never saw them, which is
27101
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
27102
- // reasons mean the same thing — this row will not be sent — and splitting
27103
- // them would put refused captures in a bucket nothing reads and nothing
27104
- // frees.
27105
- `SELECT COUNT(*) AS skipped
27106
- FROM audit_events
27107
- WHERE synced_at = ${String(SKIPPED)}
27108
- AND event_type IN (${CAPTURE_TYPE_LIST})`
26352
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26353
+ this.scopedCountsStmt = db.prepare(
26354
+ `${DRAIN_TOTALS}
26355
+ AND ${inScope("scope_key")}
26356
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26357
+ );
26358
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26359
+ this.scopedCaptureSkipCountStmt = db.prepare(
26360
+ `${CAPTURE_SKIPS}
26361
+ AND ${inScope("scope_key")}`
27109
26362
  );
27110
26363
  this.fingerprintStmt = db.prepare(
27111
26364
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27219,6 +26472,10 @@ var SqliteHistorySyncRepository = class {
27219
26472
  scopedCaptureRowsStmt;
27220
26473
  scopedCaptureBacklogOwedStmt;
27221
26474
  markScopeCapturesOwedStmt;
26475
+ scopedPartitionStmt;
26476
+ scopedPartitionByKindStmt;
26477
+ scopedCountsStmt;
26478
+ scopedCaptureSkipCountStmt;
27222
26479
  /**
27223
26480
  * The masked detections recorded against one tool call.
27224
26481
  *
@@ -27440,7 +26697,29 @@ var SqliteHistorySyncRepository = class {
27440
26697
  * in" — and a machine that has never attached has no boundary to pass, so
27441
26698
  * requiring one would force a caller to invent one and report the whole store
27442
26699
  * as queued.
26700
+ *
26701
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26702
+ * the rows that pass the drain's reachability rule for that scope
26703
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26704
+ * drain never offers), so a personal repository's rows are in none of them.
26705
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26706
+ * nothing.
27443
26707
  */
26708
+ partition(scopeKeys) {
26709
+ const row = getRow(
26710
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26711
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26712
+ );
26713
+ return {
26714
+ queued: row?.queued ?? 0,
26715
+ inProgress: row?.inProgress ?? 0,
26716
+ synced: row?.synced ?? 0,
26717
+ failed: row?.failed ?? 0,
26718
+ refused: row?.refused ?? 0,
26719
+ detached: row?.detached ?? 0,
26720
+ total: row?.total ?? 0
26721
+ };
26722
+ }
27444
26723
  /**
27445
26724
  * The same partition, one row per kind that a lane carries.
27446
26725
  *
@@ -27450,11 +26729,14 @@ var SqliteHistorySyncRepository = class {
27450
26729
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27451
26730
  * rows", never as "zero sent"; the two look identical in a bar and mean
27452
26731
  * different things.
26732
+ *
26733
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26734
+ * still sum to the scoped aggregate. An empty list returns no rows.
27453
26735
  */
27454
- partitionByKind() {
26736
+ partitionByKind(scopeKeys) {
27455
26737
  return allRows(
27456
- this.partitionByKindStmt,
27457
- {}
26738
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26739
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27458
26740
  ).map((row) => ({
27459
26741
  kind: row.kind,
27460
26742
  queued: row.queued ?? 0,
@@ -27466,22 +26748,25 @@ var SqliteHistorySyncRepository = class {
27466
26748
  total: row.total ?? 0
27467
26749
  }));
27468
26750
  }
27469
- partition() {
27470
- const row = getRow(this.partitionStmt, {});
27471
- return {
27472
- queued: row?.queued ?? 0,
27473
- inProgress: row?.inProgress ?? 0,
27474
- synced: row?.synced ?? 0,
27475
- failed: row?.failed ?? 0,
27476
- refused: row?.refused ?? 0,
27477
- detached: row?.detached ?? 0,
27478
- total: row?.total ?? 0
27479
- };
27480
- }
27481
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27482
- counts(before) {
27483
- const row = getRow(this.countsStmt, { before });
27484
- const captures = getRow(this.captureSkipCountStmt);
26751
+ /**
26752
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26753
+ * and skipped are totals.
26754
+ *
26755
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26756
+ * `capturesSkipped` included: a structural row is counted only when its own
26757
+ * key and its session root's key are among them, a capture when its own key
26758
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26759
+ * under the same keys and boundary. Omitted, this runs the machine
26760
+ * statements, unchanged; an empty list counts nothing.
26761
+ */
26762
+ counts(before, scopeKeys) {
26763
+ const row = getRow(
26764
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26765
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26766
+ );
26767
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26768
+ scopeKeys: scopeKeysParam(scopeKeys)
26769
+ });
27485
26770
  return {
27486
26771
  pending: row?.pending ?? 0,
27487
26772
  sent: row?.sent ?? 0,
@@ -27733,6 +27018,7 @@ function applyMigrations(db, file2, options = {}) {
27733
27018
  }
27734
27019
  ensureSyncedAtColumn(db, "audit_events");
27735
27020
  ensureScopeKeyColumn(db);
27021
+ ensureScopeOwedIndex(db);
27736
27022
  ensureScanLedgerTable(db);
27737
27023
  ensureHistorySyncTable(db);
27738
27024
  ensureBlockedDetectionsTable(db);
@@ -28173,14 +27459,48 @@ function ensureScopeKeyColumn(db) {
28173
27459
  function hasScopeKeyColumn(db) {
28174
27460
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28175
27461
  }
27462
+ var SCOPE_OWED_INDEX_DDL = "CREATE INDEX IF NOT EXISTS idx_audit_scope_owed ON audit_events (scope_key, event_type, started_at) WHERE outbox_owed = 1 AND synced_at IS NULL";
27463
+ function ensureScopeOwedIndex(db) {
27464
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27465
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27466
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27467
+ if (!complete) return;
27468
+ db.exec(SCOPE_OWED_INDEX_DDL);
27469
+ }
28176
27470
  function ensureScanLedgerTable(db) {
28177
27471
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28178
27472
  path TEXT PRIMARY KEY,
28179
27473
  mtime TEXT NOT NULL,
28180
27474
  content_hash TEXT NOT NULL,
28181
27475
  ruleset_hash TEXT NOT NULL,
28182
- scanned_at INTEGER NOT NULL
27476
+ scanned_at INTEGER NOT NULL,
27477
+ scope_key TEXT,
27478
+ scope_root TEXT
28183
27479
  )`);
27480
+ ensureScanLedgerScopeKeyColumn(db);
27481
+ ensureScanLedgerScopeRootColumn(db);
27482
+ }
27483
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27484
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27485
+ function ensureScanLedgerScopeKeyColumn(db) {
27486
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27487
+ }
27488
+ function ensureScanLedgerScopeRootColumn(db) {
27489
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27490
+ }
27491
+ function ensureScanLedgerColumn(db, column, ddl) {
27492
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27493
+ if (hasScanLedgerColumn(db, column)) return;
27494
+ withTransaction(
27495
+ db,
27496
+ () => {
27497
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27498
+ },
27499
+ "IMMEDIATE"
27500
+ );
27501
+ }
27502
+ function hasScanLedgerColumn(db, column) {
27503
+ return columnNames(db, "scan_ledger").includes(column);
28184
27504
  }
28185
27505
  function ensureHistorySyncTable(db) {
28186
27506
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28231,6 +27551,106 @@ function ensureRuleProbeCacheTable(db) {
28231
27551
  )`);
28232
27552
  }
28233
27553
 
27554
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27555
+ import { createHash as createHash2 } from "crypto";
27556
+ import { readFileSync as readFileSync2 } from "fs";
27557
+ import { join as join4 } from "path";
27558
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27559
+ function modPolicySnapshotPath(dataDir2) {
27560
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27561
+ }
27562
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27563
+ const byRule = /* @__PURE__ */ new Map();
27564
+ const byCategory = /* @__PURE__ */ new Map();
27565
+ for (const policy of input2.policies) {
27566
+ if (!policy.enabled) continue;
27567
+ if ("ruleId" in policy.target) {
27568
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27569
+ } else if (!byCategory.has(policy.target.category)) {
27570
+ byCategory.set(policy.target.category, policy.action);
27571
+ }
27572
+ }
27573
+ const categoryActions = {};
27574
+ for (const category of DetectionCategory.options) {
27575
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27576
+ }
27577
+ return {
27578
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27579
+ generatedAt: generatedAt.toISOString(),
27580
+ // `examples` is documentation the mod never reads, and a custom pack's are
27581
+ // whatever its author pasted in, so they stay behind.
27582
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27583
+ ruleActions: Object.fromEntries(byRule),
27584
+ categoryActions,
27585
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27586
+ };
27587
+ }
27588
+ function assignedRuleActionPolicies(installed) {
27589
+ const out = [];
27590
+ for (const [ruleId, action] of installed.ruleActions) {
27591
+ if (installed.assignedRules.has(ruleId))
27592
+ out.push({ target: { ruleId }, action, enabled: true });
27593
+ }
27594
+ return out;
27595
+ }
27596
+ function withoutExamples(rule) {
27597
+ const copy = { ...rule };
27598
+ delete copy.examples;
27599
+ return copy;
27600
+ }
27601
+ function sameContent(a, b) {
27602
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27603
+ }
27604
+ function readModPolicySnapshot(dataDir2) {
27605
+ try {
27606
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27607
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27608
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
27609
+ return parsed2.success ? parsed2.data : null;
27610
+ } catch {
27611
+ return null;
27612
+ }
27613
+ }
27614
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27615
+ const text = JSON.stringify(snapshot);
27616
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27617
+ const existing = readModPolicySnapshot(dataDir2);
27618
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27619
+ ensureDataDirSync(dataDir2);
27620
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27621
+ return true;
27622
+ }
27623
+ function regexProbeKey(matcher) {
27624
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27625
+ }
27626
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27627
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27628
+ return rules.filter((rule) => {
27629
+ if (rule.matcher.type !== "regex") return true;
27630
+ const key = regexProbeKey(rule.matcher);
27631
+ const verdict = sources.probeVerdict(key);
27632
+ if (verdict === "quarantined") return false;
27633
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27634
+ });
27635
+ }
27636
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27637
+ const policies = sources.readPolicies();
27638
+ const snapshot = sources.installedRuleset();
27639
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27640
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27641
+ return {
27642
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27643
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27644
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27645
+ };
27646
+ }
27647
+ function refreshModPolicySnapshot(dataDir2, sources) {
27648
+ try {
27649
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27650
+ } catch {
27651
+ }
27652
+ }
27653
+
28234
27654
  // ../../packages/persistence/src/internal/json.ts
28235
27655
  function safeJson(s, fallback) {
28236
27656
  if (s == null) return fallback;
@@ -28405,6 +27825,11 @@ var TIMELINE_COLUMNS = `
28405
27825
  json_extract(attributes, '$.targetId') AS target_id,
28406
27826
  json_extract(attributes, '$.internal') AS internal,
28407
27827
  json_extract(attributes, '$.flagged') AS flagged`;
27828
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27829
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27830
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27831
+ " + "
27832
+ );
28408
27833
  var LLM_USAGE_SELECT = `
28409
27834
  SELECT root_session_id AS sessionId,
28410
27835
  provider,
@@ -28416,9 +27841,10 @@ var LLM_USAGE_SELECT = `
28416
27841
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28417
27842
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28418
27843
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28419
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27844
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27845
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28420
27846
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28421
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
27847
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28422
27848
  function usageLeaves(rows) {
28423
27849
  return rows.map((row) => {
28424
27850
  const attributes = {
@@ -28433,7 +27859,7 @@ function usageLeaves(rows) {
28433
27859
  if (row.provider !== null) attributes.provider = row.provider;
28434
27860
  if (row.model !== null) attributes.model = row.model;
28435
27861
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28436
- return { sessionId: row.sessionId, attributes };
27862
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28437
27863
  });
28438
27864
  }
28439
27865
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29767,9 +29193,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29767
29193
  AND conditions IS NULL
29768
29194
  AND ${ACTIVE_PREDICATE}`;
29769
29195
  var SqliteExceptionsRepository = class {
29770
- constructor(db, now = () => Date.now()) {
29196
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29771
29197
  this.db = db;
29772
29198
  this.now = now;
29199
+ this.onChange = onChange;
29773
29200
  this.consumeStmt = db.prepare(
29774
29201
  `UPDATE exceptions
29775
29202
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29788,6 +29215,7 @@ var SqliteExceptionsRepository = class {
29788
29215
  }
29789
29216
  db;
29790
29217
  now;
29218
+ onChange;
29791
29219
  consumeStmt;
29792
29220
  insertBlockedStmt;
29793
29221
  sweepBlockedStmt;
@@ -29803,7 +29231,9 @@ var SqliteExceptionsRepository = class {
29803
29231
  */
29804
29232
  create(input2) {
29805
29233
  try {
29806
- return Promise.resolve(this.createSync(input2));
29234
+ const created = this.createSync(input2);
29235
+ this.onChange();
29236
+ return Promise.resolve(created);
29807
29237
  } catch (err) {
29808
29238
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29809
29239
  }
@@ -29934,6 +29364,7 @@ var SqliteExceptionsRepository = class {
29934
29364
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29935
29365
  WHERE id = :id AND revoked_at IS NULL`
29936
29366
  ).run({ id, revokedBy, reason: reason ?? null, now });
29367
+ if (Number(result.changes) === 1) this.onChange();
29937
29368
  return Promise.resolve(Number(result.changes) === 1);
29938
29369
  }
29939
29370
  /**
@@ -29946,6 +29377,15 @@ var SqliteExceptionsRepository = class {
29946
29377
  const result = this.consumeStmt.run({ id, now });
29947
29378
  return Promise.resolve(Number(result.changes) === 1);
29948
29379
  }
29380
+ /** The rule ids with at least one active grant, under any key version. */
29381
+ activeRuleIds(now = this.now()) {
29382
+ return allRows(
29383
+ this.db.prepare(
29384
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29385
+ ),
29386
+ { now }
29387
+ ).map((row) => row.ruleId);
29388
+ }
29949
29389
  /**
29950
29390
  * The evaluation subset of every active grant under one fingerprint key
29951
29391
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31069,31 +30509,31 @@ var SqliteInspectionFindingsRepository = class {
31069
30509
  };
31070
30510
 
31071
30511
  // ../../packages/persistence/src/repositories/installed-packs.ts
31072
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30512
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31073
30513
 
31074
30514
  // ../../packages/persistence/src/policy-floor.ts
31075
- import { readFileSync as readFileSync5 } from "fs";
31076
- import { join as join6 } from "path";
30515
+ import { readFileSync as readFileSync6 } from "fs";
30516
+ import { join as join7 } from "path";
31077
30517
 
31078
30518
  // ../../packages/persistence/src/local-layout.ts
31079
30519
  import { renameSync as renameSync3 } from "fs";
31080
30520
  import { mkdir } from "fs/promises";
31081
30521
  import { homedir } from "os";
31082
- import { join as join4 } from "path";
30522
+ import { join as join5 } from "path";
31083
30523
  function defaultDataDir() {
31084
- return join4(homedir(), ".aka");
30524
+ return join5(homedir(), ".aka");
31085
30525
  }
31086
30526
  function settingsDir(base = defaultDataDir()) {
31087
- return join4(base, "settings");
30527
+ return join5(base, "settings");
31088
30528
  }
31089
30529
  function dataDir(base = defaultDataDir()) {
31090
- return join4(base, "data");
30530
+ return join5(base, "data");
31091
30531
  }
31092
30532
  function dbPath(base = defaultDataDir()) {
31093
- return join4(dataDir(base), "aka.db");
30533
+ return join5(dataDir(base), "aka.db");
31094
30534
  }
31095
30535
  function keysDir(base = defaultDataDir()) {
31096
- return join4(base, "keys");
30536
+ return join5(base, "keys");
31097
30537
  }
31098
30538
  async function ensureDataDir(dir = defaultDataDir()) {
31099
30539
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31110,8 +30550,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31110
30550
  for (const { name, dest } of moves) {
31111
30551
  try {
31112
30552
  ensureDataDirSync(dest);
31113
- const moved = join4(dest, name);
31114
- renameSync3(join4(base, name), moved);
30553
+ const moved = join5(dest, name);
30554
+ renameSync3(join5(base, name), moved);
31115
30555
  tightenFile(moved);
31116
30556
  } catch {
31117
30557
  }
@@ -31119,8 +30559,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31119
30559
  }
31120
30560
 
31121
30561
  // ../../packages/persistence/src/settings.ts
31122
- import { readFileSync as readFileSync4 } from "fs";
31123
- import { join as join5 } from "path";
30562
+ import { readFileSync as readFileSync5 } from "fs";
30563
+ import { join as join6 } from "path";
31124
30564
 
31125
30565
  // ../../packages/persistence/src/file-lock.ts
31126
30566
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31128,7 +30568,7 @@ import {
31128
30568
  closeSync,
31129
30569
  existsSync as existsSync2,
31130
30570
  openSync,
31131
- readFileSync as readFileSync2,
30571
+ readFileSync as readFileSync3,
31132
30572
  rmSync as rmSync5,
31133
30573
  statSync as statSync3,
31134
30574
  writeFileSync as writeFileSync2
@@ -31137,16 +30577,16 @@ import { hostname as hostname3 } from "os";
31137
30577
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31138
30578
 
31139
30579
  // ../../packages/persistence/src/managed-settings.ts
31140
- import { readFileSync as readFileSync3 } from "fs";
30580
+ import { readFileSync as readFileSync4 } from "fs";
31141
30581
  import { posix, win32 } from "path";
31142
- function managedSettingsPaths(platform2 = process.platform) {
31143
- if (platform2 === "darwin") {
30582
+ function managedSettingsPaths(platform = process.platform) {
30583
+ if (platform === "darwin") {
31144
30584
  return [
31145
30585
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31146
30586
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31147
30587
  ];
31148
30588
  }
31149
- if (platform2 === "win32") {
30589
+ if (platform === "win32") {
31150
30590
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31151
30591
  }
31152
30592
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -31156,7 +30596,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31156
30596
  for (const path of paths) {
31157
30597
  let text;
31158
30598
  try {
31159
- text = readFileSync3(path, "utf8");
30599
+ text = readFileSync4(path, "utf8");
31160
30600
  } catch {
31161
30601
  continue;
31162
30602
  }
@@ -31210,7 +30650,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31210
30650
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31211
30651
  }
31212
30652
  function readUserSettings(base) {
31213
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30653
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31214
30654
  if (!record2) return defaultWorkspaceSettings();
31215
30655
  try {
31216
30656
  return WorkspaceSettings.parse(record2);
@@ -31221,7 +30661,7 @@ function readUserSettings(base) {
31221
30661
  function readJson(file2) {
31222
30662
  let text;
31223
30663
  try {
31224
- text = readFileSync4(file2, "utf8");
30664
+ text = readFileSync5(file2, "utf8");
31225
30665
  } catch {
31226
30666
  return null;
31227
30667
  }
@@ -31261,7 +30701,7 @@ var PolicyFloorError = class extends Error {
31261
30701
  };
31262
30702
  function readCachedPolicyBundle(base = defaultDataDir()) {
31263
30703
  try {
31264
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30704
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31265
30705
  const parsed2 = JSON.parse(raw);
31266
30706
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31267
30707
  return PolicyBundle.parse(parsed2.bundle);
@@ -31385,7 +30825,7 @@ function inventorySignature(packs2) {
31385
30825
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31386
30826
  }
31387
30827
  function hashRules(rulesJson) {
31388
- return createHash2("sha256").update(rulesJson).digest("hex");
30828
+ return createHash3("sha256").update(rulesJson).digest("hex");
31389
30829
  }
31390
30830
  function parseVersion(v) {
31391
30831
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31427,9 +30867,10 @@ var SqliteInstalledPacksRepository = class {
31427
30867
  * from `openLocalDatabase`, which is the single construction site that owns a
31428
30868
  * real `~/.aka`.
31429
30869
  */
31430
- constructor(db, baseDir) {
30870
+ constructor(db, baseDir, onChange = () => void 0) {
31431
30871
  this.db = db;
31432
30872
  this.baseDir = baseDir;
30873
+ this.onChange = onChange;
31433
30874
  this.insertMissingStmt = db.prepare(
31434
30875
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31435
30876
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31458,6 +30899,7 @@ var SqliteInstalledPacksRepository = class {
31458
30899
  }
31459
30900
  db;
31460
30901
  baseDir;
30902
+ onChange;
31461
30903
  insertMissingStmt;
31462
30904
  upsertAvailableStmt;
31463
30905
  signatureStmt;
@@ -31530,6 +30972,7 @@ var SqliteInstalledPacksRepository = class {
31530
30972
  },
31531
30973
  "IMMEDIATE"
31532
30974
  );
30975
+ this.onChange();
31533
30976
  } catch {
31534
30977
  }
31535
30978
  }
@@ -31604,6 +31047,7 @@ var SqliteInstalledPacksRepository = class {
31604
31047
  },
31605
31048
  "IMMEDIATE"
31606
31049
  );
31050
+ if (changed) this.onChange();
31607
31051
  return changed;
31608
31052
  }
31609
31053
  /**
@@ -31845,6 +31289,7 @@ var SqliteInstalledPacksRepository = class {
31845
31289
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31846
31290
  WHERE namespace = :namespace AND pack_id = :packId`
31847
31291
  ).run({ policyId, now: Date.now(), namespace, packId });
31292
+ if (Number(res.changes) > 0) this.onChange();
31848
31293
  return Number(res.changes) > 0;
31849
31294
  }
31850
31295
  /**
@@ -31869,6 +31314,7 @@ var SqliteInstalledPacksRepository = class {
31869
31314
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31870
31315
  WHERE namespace = :namespace AND pack_id = :packId`
31871
31316
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31317
+ if (Number(res.changes) > 0) this.onChange();
31872
31318
  return Number(res.changes) > 0;
31873
31319
  }
31874
31320
  // Fingerprint of the recorded available mirror — compared against the
@@ -32766,13 +32212,19 @@ var SqliteInventoryAssetsRepository = class {
32766
32212
  import { randomUUID as randomUUID6 } from "crypto";
32767
32213
  var SEED_BATCH_WINDOW_MS = 6e4;
32768
32214
  var SqlitePoliciesRepository = class {
32769
- constructor(db) {
32215
+ constructor(db, onChange = () => void 0) {
32770
32216
  this.db = db;
32217
+ this.onChange = onChange;
32771
32218
  }
32772
32219
  db;
32220
+ onChange;
32773
32221
  readPolicies() {
32222
+ return Promise.resolve(this.listPolicies());
32223
+ }
32224
+ /** The synchronous read behind {@link readPolicies}. */
32225
+ listPolicies() {
32774
32226
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32775
- const policies = mapRowsTolerant(rows, (row) => {
32227
+ return mapRowsTolerant(rows, (row) => {
32776
32228
  const target = JSON.parse(row.target);
32777
32229
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32778
32230
  return Policy.parse({
@@ -32784,7 +32236,6 @@ var SqlitePoliciesRepository = class {
32784
32236
  customKeywords
32785
32237
  });
32786
32238
  });
32787
- return Promise.resolve(policies);
32788
32239
  }
32789
32240
  // Seed one policy per bundled category at Monitor so the detection-type config
32790
32241
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32795,7 +32246,7 @@ var SqlitePoliciesRepository = class {
32795
32246
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32796
32247
  if (count > 0) {
32797
32248
  this.markEarlierChoices();
32798
- this.monitorUntouchedSeeds();
32249
+ if (this.monitorUntouchedSeeds()) this.onChange();
32799
32250
  return;
32800
32251
  }
32801
32252
  const stmt = this.db.prepare(
@@ -32812,6 +32263,7 @@ var SqlitePoliciesRepository = class {
32812
32263
  });
32813
32264
  }
32814
32265
  });
32266
+ this.onChange();
32815
32267
  }
32816
32268
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32817
32269
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32877,7 +32329,7 @@ var SqlitePoliciesRepository = class {
32877
32329
  ).filter(
32878
32330
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32879
32331
  );
32880
- if (untouched.length === 0) return;
32332
+ if (untouched.length === 0) return false;
32881
32333
  const stmt = this.db.prepare(
32882
32334
  `UPDATE policies SET action = 'log'
32883
32335
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32888,6 +32340,7 @@ var SqlitePoliciesRepository = class {
32888
32340
  stmt.run({ category: row.category, seeded: row.action });
32889
32341
  }
32890
32342
  });
32343
+ return true;
32891
32344
  }
32892
32345
  // Insert-or-update the single global per-category policy row, keyed on the
32893
32346
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32904,6 +32357,7 @@ var SqlitePoliciesRepository = class {
32904
32357
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32905
32358
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32906
32359
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32360
+ this.onChange();
32907
32361
  }
32908
32362
  // Caps every global per-category policy currently set to block/redact down
32909
32363
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32914,6 +32368,7 @@ var SqlitePoliciesRepository = class {
32914
32368
  WHERE scope='global' AND action IN ('block','redact')
32915
32369
  AND json_extract(target,'$.category') IS NOT NULL`
32916
32370
  ).run({ now: Date.now() });
32371
+ if (Number(info.changes) > 0) this.onChange();
32917
32372
  return Number(info.changes);
32918
32373
  }
32919
32374
  // Whether the category's row was ever written after it was created — by the
@@ -33233,31 +32688,45 @@ var SqliteScanLedgerRepository = class {
33233
32688
  constructor(db) {
33234
32689
  this.db = db;
33235
32690
  this.upsertStmt = db.prepare(
33236
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33237
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32691
+ `INSERT INTO scan_ledger
32692
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32693
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33238
32694
  ON CONFLICT (path) DO UPDATE SET
33239
32695
  mtime = excluded.mtime,
33240
32696
  content_hash = excluded.content_hash,
33241
32697
  ruleset_hash = excluded.ruleset_hash,
32698
+ scope_key = excluded.scope_key,
32699
+ scope_root = excluded.scope_root,
33242
32700
  scanned_at = excluded.scanned_at`
33243
32701
  );
33244
32702
  this.readStmt = db.prepare(
33245
- `SELECT path, mtime, content_hash AS contentHash
32703
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32704
+ scope_root AS scopeRoot
33246
32705
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33247
32706
  );
33248
32707
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32708
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33249
32709
  }
33250
32710
  db;
33251
32711
  upsertStmt;
33252
32712
  readStmt;
33253
32713
  pathsStmt;
32714
+ pathKeysStmt;
33254
32715
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33255
32716
  // older ruleset are simply absent, which reads as "never scanned".
33256
32717
  entriesForRuleset(rulesetHash) {
33257
- const rows = allRows(this.readStmt, {
33258
- rulesetHash
33259
- });
33260
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
32718
+ const rows = allRows(this.readStmt, { rulesetHash });
32719
+ return new Map(
32720
+ rows.map((r) => [
32721
+ r.path,
32722
+ {
32723
+ mtime: r.mtime,
32724
+ contentHash: r.contentHash,
32725
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32726
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32727
+ }
32728
+ ])
32729
+ );
33261
32730
  }
33262
32731
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33263
32732
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33266,6 +32735,14 @@ var SqliteScanLedgerRepository = class {
33266
32735
  allPaths() {
33267
32736
  return allRows(this.pathsStmt).map((r) => r.path);
33268
32737
  }
32738
+ // Every ledgered path with the repository it was in when it was last read,
32739
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32740
+ // which repository a vanished file belonged to. `undefined` for a row with no
32741
+ // key, which is every row written before the column existed.
32742
+ pathKeys() {
32743
+ const rows = allRows(this.pathKeysStmt);
32744
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32745
+ }
33269
32746
  upsertEntries(entries) {
33270
32747
  if (entries.length === 0) return;
33271
32748
  const scannedAt = Date.now();
@@ -33276,6 +32753,8 @@ var SqliteScanLedgerRepository = class {
33276
32753
  mtime: entry.mtime,
33277
32754
  contentHash: entry.contentHash,
33278
32755
  rulesetHash: entry.rulesetHash,
32756
+ scopeKey: entry.scopeKey ?? null,
32757
+ scopeRoot: entry.scopeRoot ?? null,
33279
32758
  scannedAt
33280
32759
  });
33281
32760
  }
@@ -34363,6 +33842,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34363
33842
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34364
33843
  };
34365
33844
  }
33845
+ function withoutTrailingSlashes(path) {
33846
+ let end = path.length;
33847
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33848
+ return path.slice(0, end);
33849
+ }
34366
33850
  function toEndpointSummary(row) {
34367
33851
  return {
34368
33852
  id: row.id,
@@ -34650,7 +34134,7 @@ var SqliteSharesRepository = class {
34650
34134
  */
34651
34135
  reconcileCallSites(projectKey, reconcile) {
34652
34136
  if (reconcile.mode === "walk") {
34653
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
34137
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34654
34138
  this.db.prepare(
34655
34139
  `DELETE FROM share_call_site
34656
34140
  WHERE project_key = :key
@@ -35218,7 +34702,7 @@ function backupLegacyStore(db, file2) {
35218
34702
  discardStore(file2, backup);
35219
34703
  return backup;
35220
34704
  }
35221
- function openAndInitialize(file2, base, skipTags) {
34705
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35222
34706
  let db = openWithPragmas(file2);
35223
34707
  try {
35224
34708
  if (isForeignSqliteLineage(db)) {
@@ -35230,8 +34714,15 @@ function openAndInitialize(file2, base, skipTags) {
35230
34714
  }
35231
34715
  applyMigrations(db, file2, { skipTags });
35232
34716
  tightenPerms(file2);
35233
- const policies = new SqlitePoliciesRepository(db);
35234
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34717
+ const modPolicy = {};
34718
+ const onPolicyStateChange = () => {
34719
+ if (modPolicy.current !== void 0)
34720
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34721
+ };
34722
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34723
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34724
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34725
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35235
34726
  const repositories = {
35236
34727
  events: new SqliteEventsRepository(db),
35237
34728
  findings: new SqliteFindingsRepository(db),
@@ -35240,9 +34731,9 @@ function openAndInitialize(file2, base, skipTags) {
35240
34731
  scanLedger: new SqliteScanLedgerRepository(db),
35241
34732
  historySync: new SqliteHistorySyncRepository(db),
35242
34733
  secretVault: new SqliteSecretVaultRepository(db),
35243
- exceptions: new SqliteExceptionsRepository(db),
34734
+ exceptions,
35244
34735
  resolutions: new SqliteResolutionsRepository(db),
35245
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34736
+ ruleProbeCache,
35246
34737
  bodyRetention: new SqliteBodyRetentionRepository(db),
35247
34738
  security: new SqliteSecurityRepository(db),
35248
34739
  detections: new SqliteDetectionsRepository(db),
@@ -35260,6 +34751,13 @@ function openAndInitialize(file2, base, skipTags) {
35260
34751
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35261
34752
  configInventory: new SqliteConfigInventoryRepository(db)
35262
34753
  };
34754
+ modPolicy.current = {
34755
+ installedRuleset: () => installedPacks.installedRuleset(),
34756
+ readPolicies: () => policies.listPolicies(),
34757
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34758
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34759
+ bundledRegexMatchers: () => shippedRegexMatchers2
34760
+ };
35263
34761
  policies.seedDefaults();
35264
34762
  return { db, ...repositories };
35265
34763
  } catch (err) {
@@ -35271,7 +34769,7 @@ function openAndInitialize(file2, base, skipTags) {
35271
34769
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35272
34770
  function openLocalDatabase(dir, options = {}) {
35273
34771
  ensureDataDirSync(dir);
35274
- const file2 = join7(dir, DB_FILENAME);
34772
+ const file2 = join8(dir, DB_FILENAME);
35275
34773
  reapStalePartials(file2);
35276
34774
  const {
35277
34775
  db,
@@ -35307,7 +34805,8 @@ function openLocalDatabase(dir, options = {}) {
35307
34805
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35308
34806
  // settings/ and data/, and the pack-policy floor needs both halves.
35309
34807
  dirname2(dir),
35310
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34808
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34809
+ options.shippedRegexMatchers ?? []
35311
34810
  );
35312
34811
  function captureRowId(event) {
35313
34812
  return captureId(
@@ -35572,7 +35071,7 @@ function openLocalDatabase(dir, options = {}) {
35572
35071
  }
35573
35072
 
35574
35073
  // ../../packages/persistence/src/egress-wire.ts
35575
- import { createHash as createHash3 } from "crypto";
35074
+ import { createHash as createHash4 } from "crypto";
35576
35075
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35577
35076
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35578
35077
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35604,7 +35103,7 @@ function canonicalGitUrl(url2) {
35604
35103
  }
35605
35104
  function hashProjectKey(projectKey) {
35606
35105
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
35607
- return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35106
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35608
35107
  }
35609
35108
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35610
35109
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35669,24 +35168,23 @@ function toEgressIngestRequest(input2) {
35669
35168
  }
35670
35169
 
35671
35170
  // ../../packages/persistence/src/finding-key.ts
35672
- import { createHash as createHash4 } from "crypto";
35171
+ import { createHash as createHash5 } from "crypto";
35673
35172
  function normalizeFilePath(filePath) {
35674
35173
  return filePath.replaceAll("\\", "/");
35675
35174
  }
35676
35175
  function computeFindingKey(input2) {
35677
35176
  const normalizedPath = normalizeFilePath(input2.filePath);
35678
- return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35177
+ return createHash5("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35679
35178
  }
35680
35179
 
35681
35180
  // ../../packages/persistence/src/fingerprint.ts
35682
35181
  import { createHmac, randomBytes } from "crypto";
35683
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35684
- import { join as join8 } from "path";
35685
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35182
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
35183
+ import { join as join9 } from "path";
35686
35184
  var EXCEPTION_KEY_FILENAME = "exception.key";
35687
35185
  var KEY_MATERIAL_BYTES = 32;
35688
35186
  function keyFilePath(dataDir2) {
35689
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
35187
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35690
35188
  }
35691
35189
  function parseKeyFile(raw) {
35692
35190
  const parsed2 = JSON.parse(raw);
@@ -35713,6 +35211,12 @@ var KEY_VERSION_COLUMNS = {
35713
35211
  };
35714
35212
  var SQLITE_ERROR2 = 1;
35715
35213
  var FLOOR_BUSY_TIMEOUT_MS = 250;
35214
+ function openReadOnly(file2) {
35215
+ const host = process;
35216
+ const sqlite = host.getBuiltinModule?.("node:sqlite");
35217
+ if (sqlite === void 0) throw new Error("this Node runtime cannot load node:sqlite");
35218
+ return new sqlite.DatabaseSync(file2, { readOnly: true });
35219
+ }
35716
35220
  var FloorUnreadableError = class extends Error {
35717
35221
  code = "floor-unreadable";
35718
35222
  constructor(cause) {
@@ -35724,11 +35228,11 @@ var FloorUnreadableError = class extends Error {
35724
35228
  }
35725
35229
  };
35726
35230
  function storedKeyVersionFloor(dataDir2) {
35727
- const file2 = join8(dataDir2, DB_FILENAME);
35231
+ const file2 = join9(dataDir2, DB_FILENAME);
35728
35232
  if (!existsSync3(file2)) return 0;
35729
35233
  let db;
35730
35234
  try {
35731
- db = new DatabaseSync2(file2, { readOnly: true });
35235
+ db = openReadOnly(file2);
35732
35236
  db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
35733
35237
  let floor = 0;
35734
35238
  for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
@@ -35779,7 +35283,7 @@ function occupantMessage(file2, kind) {
35779
35283
  function readFingerprintKey(dataDir2) {
35780
35284
  let raw;
35781
35285
  try {
35782
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
35286
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35783
35287
  } catch (err) {
35784
35288
  if (err.code === "ENOENT") return null;
35785
35289
  throw err instanceof Error ? err : new Error(String(err));
@@ -35805,8 +35309,8 @@ function exactFingerprintValue(key, raw) {
35805
35309
  }
35806
35310
 
35807
35311
  // ../../packages/persistence/src/forward-health.ts
35808
- import { readFileSync as readFileSync7 } from "fs";
35809
- import { join as join9 } from "path";
35312
+ import { readFileSync as readFileSync8 } from "fs";
35313
+ import { join as join10 } from "path";
35810
35314
  var BREAKER_COOLDOWN_MS = 3e4;
35811
35315
  function parseForwardHealth(raw, nowMs) {
35812
35316
  try {
@@ -35830,20 +35334,21 @@ function isForwardPaused(health, nowMs) {
35830
35334
 
35831
35335
  // ../../packages/persistence/src/history-backfill.ts
35832
35336
  import { existsSync as existsSync4 } from "fs";
35833
- import { join as join10 } from "path";
35337
+ import { join as join11 } from "path";
35834
35338
 
35835
35339
  // ../../packages/persistence/src/history-preview.ts
35836
35340
  import { existsSync as existsSync5 } from "fs";
35837
- import { join as join11 } from "path";
35838
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
35341
+ import { join as join12 } from "path";
35342
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35839
35343
 
35840
35344
  // ../../packages/persistence/src/history-sync-state.ts
35841
- import { readFileSync as readFileSync8 } from "fs";
35842
- import { join as join12 } from "path";
35345
+ import { readFileSync as readFileSync9 } from "fs";
35346
+ import { join as join13 } from "path";
35347
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35843
35348
 
35844
35349
  // ../../packages/persistence/src/store-symlinks.ts
35845
35350
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35846
- import { dirname as dirname3, join as join13, resolve } from "path";
35351
+ import { dirname as dirname3, join as join14, resolve } from "path";
35847
35352
  var STORE_DB = "the store database (including the prompt corpus)";
35848
35353
  var STORE_SETTINGS = "your settings file";
35849
35354
  function storeContents(home) {
@@ -35852,11 +35357,11 @@ function storeContents(home) {
35852
35357
  [settingsDir(home), STORE_SETTINGS],
35853
35358
  [dataDir(home), STORE_DB],
35854
35359
  [keysDir(home), "the vault key"],
35855
- [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
35360
+ [join14(settingsDir(home), "settings.json"), STORE_SETTINGS],
35856
35361
  [dbPath(home), STORE_DB]
35857
35362
  ]);
35858
35363
  }
35859
- function symlinkedStorePaths(home, platform2 = process.platform) {
35364
+ function symlinkedStorePaths(home, platform = process.platform) {
35860
35365
  return [...storeContents(home)].flatMap(([path, holds]) => {
35861
35366
  try {
35862
35367
  if (!lstatSync3(path).isSymbolicLink()) return [];
@@ -35868,7 +35373,7 @@ function symlinkedStorePaths(home, platform2 = process.platform) {
35868
35373
  // existsSync follows the link, so a target that is gone reads as
35869
35374
  // absent here while lstat above still sees the link itself.
35870
35375
  missing: !existsSync6(path),
35871
- mode: targetMode(path, platform2)
35376
+ mode: targetMode(path, platform)
35872
35377
  }
35873
35378
  ];
35874
35379
  } catch {
@@ -35883,8 +35388,8 @@ function linkTarget(path) {
35883
35388
  return resolve(dirname3(path), readlinkSync(path));
35884
35389
  }
35885
35390
  }
35886
- function targetMode(path, platform2) {
35887
- if (platform2 === "win32") return void 0;
35391
+ function targetMode(path, platform) {
35392
+ if (platform === "win32") return void 0;
35888
35393
  try {
35889
35394
  return statSync4(path).mode & 511;
35890
35395
  } catch {
@@ -35904,19 +35409,19 @@ import {
35904
35409
  // ../../packages/persistence/src/vault/key-provider.ts
35905
35410
  import { execFileSync } from "child_process";
35906
35411
  import { randomBytes as randomBytes2 } from "crypto";
35907
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35908
- import { join as join14 } from "path";
35412
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35413
+ import { join as join15 } from "path";
35909
35414
 
35910
35415
  // ../../packages/persistence/src/vault/vault.ts
35911
35416
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35912
35417
 
35913
35418
  // ../../packages/persistence/src/warn-era-cap.ts
35914
35419
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35915
- import { join as join15 } from "path";
35420
+ import { join as join16 } from "path";
35916
35421
  var MARKER = "warn-era-capped";
35917
35422
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35918
35423
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35919
- const marker = join15(dataDir2, MARKER);
35424
+ const marker = join16(dataDir2, MARKER);
35920
35425
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35921
35426
  const capped = db.policies.capCategoryActions();
35922
35427
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35924,425 +35429,6 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35924
35429
  return { capped };
35925
35430
  }
35926
35431
 
35927
- // ../../packages/remote/src/http.ts
35928
- import { request as httpRequest } from "http";
35929
- import { request as httpsRequest } from "https";
35930
- var DEFAULT_TIMEOUT_MS = 1e4;
35931
- var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
35932
- var RemoteRequestError = class extends Error {
35933
- constructor(status) {
35934
- super(`control-plane request failed with status ${String(status)}`);
35935
- this.status = status;
35936
- this.name = "RemoteRequestError";
35937
- }
35938
- status;
35939
- };
35940
- var RemoteRouteAbsent = class extends Error {
35941
- constructor(route) {
35942
- super(`control plane does not serve ${route}`);
35943
- this.route = route;
35944
- this.name = "RemoteRouteAbsent";
35945
- }
35946
- route;
35947
- };
35948
- var RemoteRequestInvalid = class extends Error {
35949
- constructor(route, cause) {
35950
- super(`refusing to send a malformed body to ${route}`);
35951
- this.cause = cause;
35952
- this.name = "RemoteRequestInvalid";
35953
- }
35954
- cause;
35955
- };
35956
- var RemoteEndpointRefused = class extends Error {
35957
- constructor(endpoint) {
35958
- super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
35959
- this.name = "RemoteEndpointRefused";
35960
- }
35961
- };
35962
- var RemoteResponseInvalid = class extends Error {
35963
- constructor(route, detail) {
35964
- super(`control plane answered ${route} with ${detail}`);
35965
- this.name = "RemoteResponseInvalid";
35966
- }
35967
- };
35968
- var RemoteTransportError = class extends Error {
35969
- /**
35970
- * The status the peer sent, when headers arrived and only the BODY was
35971
- * refused.
35972
- *
35973
- * Undefined for the ordinary case this class was written for — no answer at
35974
- * all. It exists because two paths reject after a status has already been
35975
- * delivered: an oversized body and an aborted response. Discarding it there
35976
- * reported a deployment answering 401 with a verbose body as a network
35977
- * outage, which sends the reader to look at their network instead of their
35978
- * credential.
35979
- */
35980
- constructor(reason, status) {
35981
- super(`control-plane request did not complete: ${reason}`);
35982
- this.status = status;
35983
- this.name = "RemoteTransportError";
35984
- }
35985
- status;
35986
- };
35987
- async function send(options) {
35988
- const url2 = new URL(options.url);
35989
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
35990
- const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
35991
- const requestOptions = {
35992
- method: options.method,
35993
- headers: {
35994
- // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
35995
- // last they win, and two of the values below are ones no caller may
35996
- // replace: `x-api-key` is the credential, and `content-length` is the
35997
- // byte count that stops a multi-byte body being truncated by the
35998
- // receiver. `SendOptions.headers` is a free-form record on an exported
35999
- // function, so "no caller does that today" is not the guarantee to rely
36000
- // on. The one header any caller actually passes — `if-none-match` on the
36001
- // conditional GET — is untouched by this order.
36002
- ...options.headers,
36003
- // The credential. One header, matching what the deployment authenticates
36004
- // on; a second copy in an `Authorization` header would be one more place
36005
- // it can be logged by an intermediary for no gain.
36006
- //
36007
- // Spread conditionally rather than assigned as `undefined`: Node's header
36008
- // handling and `content-length` bookkeeping treat a present-but-undefined
36009
- // key differently from an absent one, and "the header is not there" is
36010
- // the property the attach flow needs.
36011
- ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
36012
- accept: "application/json",
36013
- ...options.body === void 0 ? {} : {
36014
- "content-type": "application/json",
36015
- // Byte length, not string length: a multi-byte body sent with a
36016
- // character count is truncated by the receiver.
36017
- "content-length": String(Buffer.byteLength(options.body))
36018
- }
36019
- }
36020
- };
36021
- return new Promise((resolve3, reject) => {
36022
- let settled = false;
36023
- const fail = (reason, status) => {
36024
- if (settled) return;
36025
- settled = true;
36026
- reject(new RemoteTransportError(reason, status));
36027
- };
36028
- const req = send_(url2, requestOptions, (res) => {
36029
- const chunks = [];
36030
- let size = 0;
36031
- res.on("data", (chunk) => {
36032
- size += chunk.length;
36033
- if (size > MAX_RESPONSE_BYTES) {
36034
- fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
36035
- res.destroy();
36036
- req.destroy();
36037
- return;
36038
- }
36039
- chunks.push(chunk);
36040
- });
36041
- res.on("aborted", () => {
36042
- fail("the response was aborted", res.statusCode);
36043
- });
36044
- res.on("end", () => {
36045
- if (settled) return;
36046
- settled = true;
36047
- resolve3({
36048
- status: res.statusCode ?? 0,
36049
- headers: res.headers,
36050
- body: Buffer.concat(chunks).toString("utf8")
36051
- });
36052
- });
36053
- });
36054
- const deadline = setTimeout(() => {
36055
- fail(`no response within ${String(timeoutMs)}ms`);
36056
- req.destroy();
36057
- }, timeoutMs);
36058
- deadline.unref();
36059
- req.on("upgrade", (_res, socket) => {
36060
- fail("the deployment answered with a protocol upgrade");
36061
- socket.destroy();
36062
- });
36063
- req.on("close", () => {
36064
- fail("the connection closed before a response was read");
36065
- clearTimeout(deadline);
36066
- });
36067
- req.on("error", (err) => {
36068
- fail(err.message);
36069
- });
36070
- if (options.body !== void 0) req.write(options.body);
36071
- req.end();
36072
- });
36073
- }
36074
-
36075
- // ../../packages/remote/src/client.ts
36076
- var ROUTES = {
36077
- events: "/v1/events",
36078
- auditEvents: "/v1/audit-events",
36079
- auditEventsBatch: "/v1/audit-events/batch",
36080
- inventory: "/v1/inventory",
36081
- storePosture: "/v1/store-posture",
36082
- policyBundle: "/v1/policy-bundle",
36083
- whoami: "/v1/plugin/whoami",
36084
- shares: "/v1/shares",
36085
- commands: "/v1/plugin/commands"
36086
- };
36087
- function ackRoute(id) {
36088
- return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
36089
- }
36090
- function headerValue(response, name) {
36091
- const raw = response.headers[name];
36092
- if (raw === void 0) return void 0;
36093
- return Array.isArray(raw) ? raw[0] : raw;
36094
- }
36095
- function okBody(response) {
36096
- if (response.status < 200 || response.status >= 300) {
36097
- throw new RemoteRequestError(response.status);
36098
- }
36099
- return response.body;
36100
- }
36101
- function parsed(schema, body, route) {
36102
- let json2;
36103
- try {
36104
- json2 = JSON.parse(body);
36105
- } catch {
36106
- throw new RemoteResponseInvalid(route, "a body that is not JSON");
36107
- }
36108
- const result = schema.safeParse(json2);
36109
- if (!result.success) {
36110
- throw new RemoteResponseInvalid(route, "a body this client cannot read");
36111
- }
36112
- return result.data;
36113
- }
36114
- function resolveBaseUrl(endpoint) {
36115
- if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
36116
- let end = endpoint.length;
36117
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
36118
- return endpoint.slice(0, end);
36119
- }
36120
- var SLASH2 = "/".charCodeAt(0);
36121
- function createRemoteClient(options) {
36122
- const base = resolveBaseUrl(options.endpoint);
36123
- const url2 = (route) => `${base}${route}`;
36124
- const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
36125
- const sendOne = async (event) => {
36126
- const validated = RecordAuditEventRequest.safeParse(event);
36127
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
36128
- const response = await send({
36129
- ...common,
36130
- method: "POST",
36131
- url: url2(ROUTES.auditEvents),
36132
- body: JSON.stringify(validated.data)
36133
- });
36134
- okBody(response);
36135
- };
36136
- return {
36137
- async ingestEvents(batch) {
36138
- const response = await send({
36139
- ...common,
36140
- method: "POST",
36141
- url: url2(ROUTES.events),
36142
- body: JSON.stringify(batch)
36143
- });
36144
- return parsed(IngestAck, okBody(response), ROUTES.events);
36145
- },
36146
- async ingestInventory(context) {
36147
- const response = await send({
36148
- ...common,
36149
- method: "POST",
36150
- url: url2(ROUTES.inventory),
36151
- body: JSON.stringify(context)
36152
- });
36153
- return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
36154
- },
36155
- async recordAuditEvent(event) {
36156
- await sendOne(event);
36157
- },
36158
- async recordAuditEvents(events, opts) {
36159
- const validated = RecordAuditEventBatch.safeParse({ events });
36160
- if (!validated.success) {
36161
- throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
36162
- }
36163
- const response = await send({
36164
- ...common,
36165
- method: "POST",
36166
- url: url2(ROUTES.auditEventsBatch),
36167
- body: JSON.stringify(validated.data)
36168
- });
36169
- if (response.status === 404) {
36170
- if (opts?.fallbackToSingleEvents !== true) {
36171
- throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
36172
- }
36173
- for (const event of validated.data.events) await sendOne(event);
36174
- return { accepted: validated.data.events.length };
36175
- }
36176
- return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
36177
- },
36178
- async reportStorePosture(snapshot) {
36179
- const response = await send({
36180
- ...common,
36181
- method: "POST",
36182
- url: url2(ROUTES.storePosture),
36183
- body: JSON.stringify(snapshot)
36184
- });
36185
- okBody(response);
36186
- },
36187
- async getPolicyBundle(etag) {
36188
- const response = await send({
36189
- ...common,
36190
- method: "GET",
36191
- url: url2(ROUTES.policyBundle),
36192
- ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
36193
- });
36194
- if (response.status === 304) {
36195
- return { changed: false, etag: headerValue(response, "etag") ?? etag };
36196
- }
36197
- const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
36198
- return { changed: true, bundle, etag: headerValue(response, "etag") };
36199
- },
36200
- async whoami() {
36201
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
36202
- return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
36203
- },
36204
- async recordProjectEgress(request) {
36205
- const validated = EgressIngestRequest.safeParse(request);
36206
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
36207
- const response = await send({
36208
- ...common,
36209
- method: "POST",
36210
- url: url2(ROUTES.shares),
36211
- body: JSON.stringify(validated.data)
36212
- });
36213
- if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
36214
- okBody(response);
36215
- },
36216
- async pollCommand() {
36217
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
36218
- if (response.status === 404) return null;
36219
- return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
36220
- },
36221
- async ackCommand(id, body) {
36222
- const validated = DeviceCommandAckBody.safeParse(body);
36223
- const route = ackRoute(id);
36224
- if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
36225
- const response = await send({
36226
- ...common,
36227
- method: "POST",
36228
- url: url2(route),
36229
- body: JSON.stringify(validated.data)
36230
- });
36231
- okBody(response);
36232
- }
36233
- };
36234
- }
36235
-
36236
- // ../../packages/remote/src/failure-kind.ts
36237
- function statusOf(err) {
36238
- if (typeof err !== "object" || err === null || !("status" in err)) return null;
36239
- const { status } = err;
36240
- if (typeof status !== "number" || !Number.isInteger(status)) return null;
36241
- return status >= 100 && status <= 599 ? status : null;
36242
- }
36243
- function nameOf(err) {
36244
- if (typeof err !== "object" || err === null || !("name" in err)) return null;
36245
- return typeof err.name === "string" ? err.name : null;
36246
- }
36247
- function classifyRemoteFailure(err) {
36248
- switch (nameOf(err)) {
36249
- case "RemoteRouteAbsent":
36250
- return "route-absent";
36251
- case "RemoteRequestInvalid":
36252
- case "RemoteEndpointRefused":
36253
- return "invalid-request";
36254
- case "RemoteResponseInvalid":
36255
- return "rejected";
36256
- default:
36257
- break;
36258
- }
36259
- const status = statusOf(err);
36260
- if (status === null) return "unreachable";
36261
- switch (status) {
36262
- case 401:
36263
- return "unauthorized";
36264
- case 403:
36265
- return "forbidden";
36266
- case 429:
36267
- return "unreachable";
36268
- case 404:
36269
- return "unreachable";
36270
- default:
36271
- return status >= 400 && status <= 499 ? "rejected" : "unreachable";
36272
- }
36273
- }
36274
-
36275
- // ../../packages/plugin-runtime/src/attached/failure.ts
36276
- function classifyFailure(err) {
36277
- switch (classifyRemoteFailure(err)) {
36278
- case "unauthorized":
36279
- return "unauthorized";
36280
- case "forbidden":
36281
- return "forbidden";
36282
- default:
36283
- return "unreachable";
36284
- }
36285
- }
36286
-
36287
- // ../../packages/plugin-runtime/src/attached/with-timeout.ts
36288
- var REQUEST_TIMEOUT_MS = 2e3;
36289
- function withTimeout(promise2, ms) {
36290
- let timer;
36291
- const timeout = new Promise((_, reject) => {
36292
- timer = setTimeout(() => {
36293
- reject(new Error("attached gateway request timed out"));
36294
- }, ms);
36295
- });
36296
- promise2.catch(() => void 0);
36297
- return Promise.race([promise2, timeout]).finally(() => {
36298
- clearTimeout(timer);
36299
- });
36300
- }
36301
-
36302
- // ../../packages/plugin-runtime/src/attached/forward-drops.ts
36303
- import { readFileSync as readFileSync10 } from "fs";
36304
- import { join as join16 } from "path";
36305
- var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
36306
- function forwardDropsPath(dataDir2) {
36307
- return join16(dataDir2, FORWARD_DROPS_FILENAME);
36308
- }
36309
- function recordForwardDrops(dataDir2, count, nowMs) {
36310
- if (count <= 0) return;
36311
- try {
36312
- ensureDataDirSync(dataDir2);
36313
- const previous = readForwardDrops(dataDir2);
36314
- const next = {
36315
- droppedForwards: (previous?.droppedForwards ?? 0) + count,
36316
- lastDropAtMs: nowMs
36317
- };
36318
- writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
36319
- `);
36320
- } catch {
36321
- }
36322
- }
36323
- function readForwardDrops(dataDir2) {
36324
- try {
36325
- const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
36326
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
36327
- const record2 = parsed2;
36328
- if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
36329
- return null;
36330
- }
36331
- if (record2.droppedForwards <= 0) return null;
36332
- if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
36333
- return null;
36334
- }
36335
- return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
36336
- } catch {
36337
- return null;
36338
- }
36339
- }
36340
-
36341
- // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36342
- import { randomUUID as randomUUID16 } from "crypto";
36343
- import { readFile, rename, writeFile } from "fs/promises";
36344
- import { join as join28 } from "path";
36345
-
36346
35432
  // ../../packages/plugin-sdk/src/config.ts
36347
35433
  import { existsSync as existsSync8 } from "fs";
36348
35434
  import { join as join17 } from "path";
@@ -36422,11 +35508,6 @@ function resolveProviderSafe(resolveProviderFn) {
36422
35508
  }
36423
35509
  }
36424
35510
 
36425
- // ../../packages/plugin-sdk/src/config-inventory.ts
36426
- import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
36427
- import { homedir as homedir2 } from "os";
36428
- import { basename as basename3, join as join19 } from "path";
36429
-
36430
35511
  // ../../packages/detections/src/egress/registry.ts
36431
35512
  var EXTRACTOR_VERSION = "3";
36432
35513
  var PROVIDER_REGISTRY = [
@@ -37190,12 +36271,12 @@ var RegexMatcher2 = class {
37190
36271
  rule.matcher,
37191
36272
  () => new RegExp(pattern, flags.includes("d") ? flags : `${flags}d`)
37192
36273
  );
37193
- const scanText2 = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
36274
+ const scanText = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
37194
36275
  const spans = [];
37195
36276
  let m;
37196
- const maxIterations = scanText2.length + 1;
36277
+ const maxIterations = scanText.length + 1;
37197
36278
  let iterations = 0;
37198
- while ((m = re.exec(scanText2)) !== null) {
36279
+ while ((m = re.exec(scanText)) !== null) {
37199
36280
  if (++iterations > maxIterations) break;
37200
36281
  const group = captureGroup != null ? m[captureGroup] : m[0];
37201
36282
  if (m[0].length === 0) re.lastIndex++;
@@ -37537,17 +36618,18 @@ function ruleEvidence(rule) {
37537
36618
 
37538
36619
  // ../../packages/detections/src/mask.ts
37539
36620
  function maskMatch(raw) {
37540
- if (raw.length <= 5) return "***";
37541
- const atIndex = raw.indexOf("@");
37542
- if (atIndex > 0 && atIndex < raw.length - 1) {
37543
- const domain2 = raw.slice(atIndex + 1);
36621
+ const visible = stripInvisiblePadding(raw);
36622
+ if (visible.length <= 5) return "***";
36623
+ const atIndex = visible.indexOf("@");
36624
+ if (atIndex > 0 && atIndex < visible.length - 1) {
36625
+ const domain2 = visible.slice(atIndex + 1);
37544
36626
  if (domain2.includes(".")) {
37545
- const local = raw.slice(0, atIndex);
36627
+ const local = visible.slice(0, atIndex);
37546
36628
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
37547
36629
  return `${maskedLocal}@${domain2}`;
37548
36630
  }
37549
36631
  }
37550
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
36632
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
37551
36633
  }
37552
36634
 
37553
36635
  // ../../packages/detections/src/pointer-shield.ts
@@ -37809,7 +36891,12 @@ var MIN_RAW_LEN = 4;
37809
36891
  var RAW_RUN_LEN = 8;
37810
36892
  function carriesRawRun(text, rawValues) {
37811
36893
  let windows = null;
37812
- for (const raw of new Set(rawValues)) {
36894
+ const values = /* @__PURE__ */ new Set();
36895
+ for (const raw of rawValues) {
36896
+ values.add(raw);
36897
+ values.add(stripInvisiblePadding(raw));
36898
+ }
36899
+ for (const raw of values) {
37813
36900
  if (raw.length < MIN_RAW_LEN) continue;
37814
36901
  if (raw.length < RAW_RUN_LEN) {
37815
36902
  if (text.includes(raw)) return true;
@@ -37833,11 +36920,16 @@ function carriesRawRun(text, rawValues) {
37833
36920
  return false;
37834
36921
  }
37835
36922
  function safeMaskedMatch(rawMatch) {
37836
- const masked = maskMatch(rawMatch);
37837
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
37838
- return "***";
36923
+ const visible = stripInvisiblePadding(rawMatch);
36924
+ const masked = maskMatch(visible);
36925
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
36926
+ if (!reveals(masked)) return masked;
36927
+ const atIndex = masked.indexOf("@");
36928
+ if (atIndex > 0 && atIndex < masked.length - 1) {
36929
+ const emailFallback = `*${masked.slice(atIndex)}`;
36930
+ if (!reveals(emailFallback)) return emailFallback;
37839
36931
  }
37840
- return masked;
36932
+ return "***";
37841
36933
  }
37842
36934
  function assertRawFree(text, rawValues) {
37843
36935
  if (carriesRawRun(text, rawValues)) {
@@ -40279,6 +39371,11 @@ function bundledDetections() {
40279
39371
  }));
40280
39372
  return cachedDetections;
40281
39373
  }
39374
+ function shippedRegexMatchers() {
39375
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
39376
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
39377
+ );
39378
+ }
40282
39379
  function uniqueRuleIds(findings) {
40283
39380
  return [...new Set(findings.map((f) => f.ruleId))].join(", ");
40284
39381
  }
@@ -40308,8 +39405,9 @@ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18,
40308
39405
  var ATTRIBUTION_MEMO_LIMIT = 64;
40309
39406
  var attributionMemo = /* @__PURE__ */ new Map();
40310
39407
  var NO_ATTRIBUTION = Object.freeze({});
40311
- function resolveRepoAttribution(cwd) {
39408
+ function resolveRepoAttribution(cwd, options) {
40312
39409
  try {
39410
+ if (options?.cache === false) return attributeRepo(cwd);
40313
39411
  const remembered = attributionMemo.get(cwd);
40314
39412
  if (remembered !== void 0) return remembered;
40315
39413
  const attribution = attributeRepo(cwd);
@@ -40409,9 +39507,9 @@ function slugFromUrl(url2) {
40409
39507
  }
40410
39508
 
40411
39509
  // ../../packages/plugin-sdk/src/events.ts
40412
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
39510
+ import { createHash as createHash6, randomUUID as randomUUID13 } from "crypto";
40413
39511
  function contentHashOf(text) {
40414
- return createHash5("sha256").update(text).digest("hex");
39512
+ return createHash6("sha256").update(text).digest("hex");
40415
39513
  }
40416
39514
  function buildIngestEvent(input2) {
40417
39515
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -40925,11 +40023,11 @@ function createGuardedScanner(partition, gateway, opts) {
40925
40023
  }
40926
40024
 
40927
40025
  // ../../packages/plugin-sdk/src/hook-fail-opens.ts
40928
- import { readFileSync as readFileSync13 } from "fs";
40929
- import { join as join20 } from "path";
40026
+ import { readFileSync as readFileSync12 } from "fs";
40027
+ import { join as join19 } from "path";
40930
40028
  var HOOK_FAIL_OPENS_FILENAME = "hook-fail-opens.json";
40931
40029
  function hookFailOpensPath(dataDir2) {
40932
- return join20(dataDir2, HOOK_FAIL_OPENS_FILENAME);
40030
+ return join19(dataDir2, HOOK_FAIL_OPENS_FILENAME);
40933
40031
  }
40934
40032
  function recordHookFailOpen(dataDir2, nowMs) {
40935
40033
  try {
@@ -40948,7 +40046,7 @@ function recordHookFailOpen(dataDir2, nowMs) {
40948
40046
  }
40949
40047
  function readHookFailOpens(dataDir2) {
40950
40048
  try {
40951
- const parsed2 = JSON.parse(readFileSync13(hookFailOpensPath(dataDir2), "utf8"));
40049
+ const parsed2 = JSON.parse(readFileSync12(hookFailOpensPath(dataDir2), "utf8"));
40952
40050
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
40953
40051
  const record2 = parsed2;
40954
40052
  if (!isPositiveSafeInteger(record2.failOpens)) return null;
@@ -40962,67 +40060,6 @@ function isPositiveSafeInteger(value) {
40962
40060
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
40963
40061
  }
40964
40062
 
40965
- // ../../packages/plugin-sdk/src/host-floor.ts
40966
- import { readFileSync as readFileSync15 } from "fs";
40967
- import { join as join22 } from "path";
40968
-
40969
- // ../../packages/plugin-sdk/src/model-governance.ts
40970
- import {
40971
- closeSync as closeSync2,
40972
- fstatSync,
40973
- mkdirSync as mkdirSync2,
40974
- openSync as openSync2,
40975
- readFileSync as readFileSync14,
40976
- readSync,
40977
- writeFileSync as writeFileSync5
40978
- } from "fs";
40979
- import { join as join21 } from "path";
40980
- var TAIL_BYTES = 256 * 1024;
40981
-
40982
- // ../../packages/plugin-sdk/src/host-floor.ts
40983
- var HOST_FEATURE = {
40984
- ModelSwitch: "model-switch",
40985
- VaultPointerDisplay: "vault-pointer-display"
40986
- };
40987
- var HOST_FLOORS = {
40988
- [HOST_FEATURE.ModelSwitch]: {
40989
- label: "model-switch protection",
40990
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
40991
- since: "2.1.251"
40992
- },
40993
- [HOST_FEATURE.VaultPointerDisplay]: {
40994
- label: "vault pointer display",
40995
- hookEvents: ["MessageDisplay"],
40996
- since: "2.1.152"
40997
- }
40998
- };
40999
- var ANTIGRAVITY_HOST_FEATURE = {
41000
- EndOfTurnCapture: "end-of-turn-capture"
41001
- };
41002
- var ANTIGRAVITY_HOST_FLOORS = {
41003
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
41004
- label: "end-of-turn history capture",
41005
- hookEvents: ["Stop"],
41006
- since: "1.1.10"
41007
- }
41008
- };
41009
-
41010
- // ../../packages/plugin-sdk/src/ignore-layers.ts
41011
- var import_ignore = __toESM(require_ignore(), 1);
41012
- import { readFileSync as readFileSync16 } from "fs";
41013
- import { join as join23 } from "path";
41014
-
41015
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
41016
- import { arch, hostname as hostname4, platform, release } from "os";
41017
-
41018
- // ../../packages/plugin-sdk/src/nudge.ts
41019
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync17, writeFileSync as writeFileSync6 } from "fs";
41020
- import { join as join24 } from "path";
41021
-
41022
- // ../../packages/plugin-sdk/src/paths.ts
41023
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
41024
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
41025
-
41026
40063
  // ../../packages/plugin-sdk/src/policy-resolver.ts
41027
40064
  import { randomUUID as randomUUID14 } from "crypto";
41028
40065
  function createPolicyResolver(bundle) {
@@ -41067,36 +40104,6 @@ function assignedRulePolicies(installed) {
41067
40104
  return out;
41068
40105
  }
41069
40106
 
41070
- // ../../packages/plugin-sdk/src/project-files.ts
41071
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
41072
- import { basename as basename5, join as join25 } from "path";
41073
-
41074
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
41075
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
41076
- if (typeof v === "string" && v.trim() === "") return void 0;
41077
- return v;
41078
- }, external_exports.string().optional()).catch(void 0);
41079
- var optionalFlag = external_exports.preprocess((v) => {
41080
- if (typeof v !== "string") return false;
41081
- const normalized = v.trim().toLowerCase();
41082
- return normalized !== "" && normalized !== "0" && normalized !== "false";
41083
- }, external_exports.boolean()).catch(false);
41084
- var antigravityProviderEnvShape = {
41085
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
41086
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
41087
- };
41088
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
41089
-
41090
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
41091
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
41092
- if (typeof v === "string" && v.trim() === "") return void 0;
41093
- return v;
41094
- }, external_exports.string().optional()).catch(void 0);
41095
- var codexProviderEnvShape = {
41096
- OPENAI_BASE_URL: optionalBaseUrl3
41097
- };
41098
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
41099
-
41100
40107
  // ../../packages/plugin-sdk/src/runtime.ts
41101
40108
  import { randomUUID as randomUUID15 } from "crypto";
41102
40109
  var ENFORCEMENT_CEILING_ENABLED = false;
@@ -41383,12 +40390,11 @@ function createPluginRuntime(gateway, settings, opts) {
41383
40390
  async function processText(text, context, opts2 = {}) {
41384
40391
  return (await evaluate(text, context, {}, opts2.rewritable)).decision;
41385
40392
  }
41386
- async function capture(input2, opts2 = {}) {
40393
+ async function evaluateCapture(input2, opts2) {
41387
40394
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
41388
- const filePath = input2.metadata?.filePath;
41389
40395
  const { decision, excepted, exceptionIds } = await evaluate(
41390
40396
  input2.text,
41391
- { filePath, eventKind: input2.kind },
40397
+ { filePath: input2.metadata?.filePath, eventKind: input2.kind },
41392
40398
  {
41393
40399
  sourceTool: input2.sourceTool,
41394
40400
  metadata: input2.metadata,
@@ -41396,7 +40402,11 @@ function createPluginRuntime(gateway, settings, opts) {
41396
40402
  },
41397
40403
  opts2.rewritable
41398
40404
  );
41399
- if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
40405
+ return { decision, excepted, exceptionIds, timingStartedAt };
40406
+ }
40407
+ async function persistCapture(input2, opts2, { decision, excepted, exceptionIds, timingStartedAt }) {
40408
+ const filePath = input2.metadata?.filePath;
40409
+ if (opts2.persist === "with-findings" && decision.findings.length === 0) return;
41400
40410
  try {
41401
40411
  const contentHash = contentHashOf(input2.text);
41402
40412
  const maskedFindings = decision.findings.filter(
@@ -41439,6 +40449,8 @@ function createPluginRuntime(gateway, settings, opts) {
41439
40449
  // exceptions/blocked_detections when a key is available;
41440
40450
  // falls back to the masked match so at-rest findings still get
41441
40451
  // a stable (if weaker) identity on a workspace with no dataDir.
40452
+ // Both ignore the same invisible padding, so a clean and a
40453
+ // padded occurrence of one secret key alike on either path.
41442
40454
  valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
41443
40455
  }) : void 0;
41444
40456
  return {
@@ -41466,7 +40478,37 @@ function createPluginRuntime(gateway, settings, opts) {
41466
40478
  }
41467
40479
  } catch {
41468
40480
  }
41469
- return decision;
40481
+ }
40482
+ async function enforcedIn(text, context) {
40483
+ try {
40484
+ await ensureInitialized();
40485
+ if (!scanner) return [];
40486
+ const shielded = shieldPointers(text);
40487
+ const matched = await scanner.scan(shielded.text, context);
40488
+ return dropShieldedFindings(matched, shielded.spans).filter((finding) => {
40489
+ const action = resolveAction(finding.ruleId, finding.category);
40490
+ return action === "block" || action === "redact";
40491
+ });
40492
+ } catch {
40493
+ return [];
40494
+ }
40495
+ }
40496
+ async function capture(input2, opts2 = {}) {
40497
+ const evaluated = await evaluateCapture(input2, opts2);
40498
+ await persistCapture(input2, opts2, evaluated);
40499
+ return evaluated.decision;
40500
+ }
40501
+ async function captureDeferred(input2, opts2 = {}) {
40502
+ const evaluated = await evaluateCapture(input2, opts2);
40503
+ let recorded = false;
40504
+ return {
40505
+ result: evaluated.decision,
40506
+ record: async () => {
40507
+ if (recorded) return;
40508
+ recorded = true;
40509
+ await persistCapture(input2, opts2, evaluated);
40510
+ }
40511
+ };
41470
40512
  }
41471
40513
  async function rulesetFingerprint() {
41472
40514
  try {
@@ -41487,21 +40529,435 @@ function createPluginRuntime(gateway, settings, opts) {
41487
40529
  }
41488
40530
  await gateway.close();
41489
40531
  }
41490
- return { processText, capture, rulesetFingerprint, scanIsolationDegraded, close };
40532
+ return {
40533
+ processText,
40534
+ capture,
40535
+ captureDeferred,
40536
+ enforcedIn,
40537
+ rulesetFingerprint,
40538
+ scanIsolationDegraded,
40539
+ close
40540
+ };
40541
+ }
40542
+
40543
+ // ../../packages/remote/src/http.ts
40544
+ import { request as httpRequest } from "http";
40545
+ import { request as httpsRequest } from "https";
40546
+ var DEFAULT_TIMEOUT_MS = 1e4;
40547
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
40548
+ var RemoteRequestError = class extends Error {
40549
+ constructor(status) {
40550
+ super(`control-plane request failed with status ${String(status)}`);
40551
+ this.status = status;
40552
+ this.name = "RemoteRequestError";
40553
+ }
40554
+ status;
40555
+ };
40556
+ var RemoteRouteAbsent = class extends Error {
40557
+ constructor(route) {
40558
+ super(`control plane does not serve ${route}`);
40559
+ this.route = route;
40560
+ this.name = "RemoteRouteAbsent";
40561
+ }
40562
+ route;
40563
+ };
40564
+ var RemoteRequestInvalid = class extends Error {
40565
+ constructor(route, cause) {
40566
+ super(`refusing to send a malformed body to ${route}`);
40567
+ this.cause = cause;
40568
+ this.name = "RemoteRequestInvalid";
40569
+ }
40570
+ cause;
40571
+ };
40572
+ var RemoteEndpointRefused = class extends Error {
40573
+ constructor(endpoint) {
40574
+ super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
40575
+ this.name = "RemoteEndpointRefused";
40576
+ }
40577
+ };
40578
+ var RemoteResponseInvalid = class extends Error {
40579
+ constructor(route, detail) {
40580
+ super(`control plane answered ${route} with ${detail}`);
40581
+ this.name = "RemoteResponseInvalid";
40582
+ }
40583
+ };
40584
+ var RemoteTransportError = class extends Error {
40585
+ /**
40586
+ * The status the peer sent, when headers arrived and only the BODY was
40587
+ * refused.
40588
+ *
40589
+ * Undefined for the ordinary case this class was written for — no answer at
40590
+ * all. It exists because two paths reject after a status has already been
40591
+ * delivered: an oversized body and an aborted response. Discarding it there
40592
+ * reported a deployment answering 401 with a verbose body as a network
40593
+ * outage, which sends the reader to look at their network instead of their
40594
+ * credential.
40595
+ */
40596
+ constructor(reason, status) {
40597
+ super(`control-plane request did not complete: ${reason}`);
40598
+ this.status = status;
40599
+ this.name = "RemoteTransportError";
40600
+ }
40601
+ status;
40602
+ };
40603
+ async function send(options) {
40604
+ const url2 = new URL(options.url);
40605
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
40606
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
40607
+ const requestOptions = {
40608
+ method: options.method,
40609
+ headers: {
40610
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
40611
+ // last they win, and two of the values below are ones no caller may
40612
+ // replace: `x-api-key` is the credential, and `content-length` is the
40613
+ // byte count that stops a multi-byte body being truncated by the
40614
+ // receiver. `SendOptions.headers` is a free-form record on an exported
40615
+ // function, so "no caller does that today" is not the guarantee to rely
40616
+ // on. The one header any caller actually passes — `if-none-match` on the
40617
+ // conditional GET — is untouched by this order.
40618
+ ...options.headers,
40619
+ // The credential. One header, matching what the deployment authenticates
40620
+ // on; a second copy in an `Authorization` header would be one more place
40621
+ // it can be logged by an intermediary for no gain.
40622
+ //
40623
+ // Spread conditionally rather than assigned as `undefined`: Node's header
40624
+ // handling and `content-length` bookkeeping treat a present-but-undefined
40625
+ // key differently from an absent one, and "the header is not there" is
40626
+ // the property the attach flow needs.
40627
+ ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
40628
+ accept: "application/json",
40629
+ ...options.body === void 0 ? {} : {
40630
+ "content-type": "application/json",
40631
+ // Byte length, not string length: a multi-byte body sent with a
40632
+ // character count is truncated by the receiver.
40633
+ "content-length": String(Buffer.byteLength(options.body))
40634
+ }
40635
+ }
40636
+ };
40637
+ return new Promise((resolve3, reject) => {
40638
+ let settled = false;
40639
+ const fail = (reason, status) => {
40640
+ if (settled) return;
40641
+ settled = true;
40642
+ reject(new RemoteTransportError(reason, status));
40643
+ };
40644
+ const req = send_(url2, requestOptions, (res) => {
40645
+ const chunks = [];
40646
+ let size = 0;
40647
+ res.on("data", (chunk) => {
40648
+ size += chunk.length;
40649
+ if (size > MAX_RESPONSE_BYTES) {
40650
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
40651
+ res.destroy();
40652
+ req.destroy();
40653
+ return;
40654
+ }
40655
+ chunks.push(chunk);
40656
+ });
40657
+ res.on("aborted", () => {
40658
+ fail("the response was aborted", res.statusCode);
40659
+ });
40660
+ res.on("end", () => {
40661
+ if (settled) return;
40662
+ settled = true;
40663
+ resolve3({
40664
+ status: res.statusCode ?? 0,
40665
+ headers: res.headers,
40666
+ body: Buffer.concat(chunks).toString("utf8")
40667
+ });
40668
+ });
40669
+ });
40670
+ const deadline = setTimeout(() => {
40671
+ fail(`no response within ${String(timeoutMs)}ms`);
40672
+ req.destroy();
40673
+ }, timeoutMs);
40674
+ deadline.unref();
40675
+ req.on("upgrade", (_res, socket) => {
40676
+ fail("the deployment answered with a protocol upgrade");
40677
+ socket.destroy();
40678
+ });
40679
+ req.on("close", () => {
40680
+ fail("the connection closed before a response was read");
40681
+ clearTimeout(deadline);
40682
+ });
40683
+ req.on("error", (err) => {
40684
+ fail(err.message);
40685
+ });
40686
+ if (options.body !== void 0) req.write(options.body);
40687
+ req.end();
40688
+ });
40689
+ }
40690
+
40691
+ // ../../packages/remote/src/client.ts
40692
+ var ROUTES = {
40693
+ events: "/v1/events",
40694
+ auditEvents: "/v1/audit-events",
40695
+ auditEventsBatch: "/v1/audit-events/batch",
40696
+ inventory: "/v1/inventory",
40697
+ storePosture: "/v1/store-posture",
40698
+ policyBundle: "/v1/policy-bundle",
40699
+ whoami: "/v1/plugin/whoami",
40700
+ shares: "/v1/shares",
40701
+ commands: "/v1/plugin/commands"
40702
+ };
40703
+ function ackRoute(id) {
40704
+ return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
40705
+ }
40706
+ function headerValue(response, name) {
40707
+ const raw = response.headers[name];
40708
+ if (raw === void 0) return void 0;
40709
+ return Array.isArray(raw) ? raw[0] : raw;
40710
+ }
40711
+ function okBody(response) {
40712
+ if (response.status < 200 || response.status >= 300) {
40713
+ throw new RemoteRequestError(response.status);
40714
+ }
40715
+ return response.body;
40716
+ }
40717
+ function parsed(schema, body, route) {
40718
+ let json2;
40719
+ try {
40720
+ json2 = JSON.parse(body);
40721
+ } catch {
40722
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
40723
+ }
40724
+ const result = schema.safeParse(json2);
40725
+ if (!result.success) {
40726
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
40727
+ }
40728
+ return result.data;
40729
+ }
40730
+ function resolveBaseUrl(endpoint) {
40731
+ if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
40732
+ let end = endpoint.length;
40733
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
40734
+ return endpoint.slice(0, end);
40735
+ }
40736
+ var SLASH2 = "/".charCodeAt(0);
40737
+ function createRemoteClient(options) {
40738
+ const base = resolveBaseUrl(options.endpoint);
40739
+ const url2 = (route) => `${base}${route}`;
40740
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
40741
+ const sendOne = async (event) => {
40742
+ const validated = RecordAuditEventRequest.safeParse(event);
40743
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
40744
+ const response = await send({
40745
+ ...common,
40746
+ method: "POST",
40747
+ url: url2(ROUTES.auditEvents),
40748
+ body: JSON.stringify(validated.data)
40749
+ });
40750
+ okBody(response);
40751
+ };
40752
+ return {
40753
+ async ingestEvents(batch) {
40754
+ const response = await send({
40755
+ ...common,
40756
+ method: "POST",
40757
+ url: url2(ROUTES.events),
40758
+ body: JSON.stringify(batch)
40759
+ });
40760
+ return parsed(IngestAck, okBody(response), ROUTES.events);
40761
+ },
40762
+ async ingestInventory(context) {
40763
+ const response = await send({
40764
+ ...common,
40765
+ method: "POST",
40766
+ url: url2(ROUTES.inventory),
40767
+ body: JSON.stringify(context)
40768
+ });
40769
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
40770
+ },
40771
+ async recordAuditEvent(event) {
40772
+ await sendOne(event);
40773
+ },
40774
+ async recordAuditEvents(events, opts) {
40775
+ const validated = RecordAuditEventBatch.safeParse({ events });
40776
+ if (!validated.success) {
40777
+ throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
40778
+ }
40779
+ const response = await send({
40780
+ ...common,
40781
+ method: "POST",
40782
+ url: url2(ROUTES.auditEventsBatch),
40783
+ body: JSON.stringify(validated.data)
40784
+ });
40785
+ if (response.status === 404) {
40786
+ if (opts?.fallbackToSingleEvents !== true) {
40787
+ throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
40788
+ }
40789
+ for (const event of validated.data.events) await sendOne(event);
40790
+ return { accepted: validated.data.events.length };
40791
+ }
40792
+ return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
40793
+ },
40794
+ async reportStorePosture(snapshot) {
40795
+ const response = await send({
40796
+ ...common,
40797
+ method: "POST",
40798
+ url: url2(ROUTES.storePosture),
40799
+ body: JSON.stringify(snapshot)
40800
+ });
40801
+ okBody(response);
40802
+ },
40803
+ async getPolicyBundle(etag) {
40804
+ const response = await send({
40805
+ ...common,
40806
+ method: "GET",
40807
+ url: url2(ROUTES.policyBundle),
40808
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
40809
+ });
40810
+ if (response.status === 304) {
40811
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
40812
+ }
40813
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
40814
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
40815
+ },
40816
+ async whoami() {
40817
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
40818
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
40819
+ },
40820
+ async recordProjectEgress(request) {
40821
+ const validated = EgressIngestRequest.safeParse(request);
40822
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
40823
+ const response = await send({
40824
+ ...common,
40825
+ method: "POST",
40826
+ url: url2(ROUTES.shares),
40827
+ body: JSON.stringify(validated.data)
40828
+ });
40829
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
40830
+ okBody(response);
40831
+ },
40832
+ async pollCommand() {
40833
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
40834
+ if (response.status === 404) return null;
40835
+ return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
40836
+ },
40837
+ async ackCommand(id, body) {
40838
+ const validated = DeviceCommandAckBody.safeParse(body);
40839
+ const route = ackRoute(id);
40840
+ if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
40841
+ const response = await send({
40842
+ ...common,
40843
+ method: "POST",
40844
+ url: url2(route),
40845
+ body: JSON.stringify(validated.data)
40846
+ });
40847
+ okBody(response);
40848
+ }
40849
+ };
40850
+ }
40851
+
40852
+ // ../../packages/remote/src/failure-kind.ts
40853
+ function statusOf(err) {
40854
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
40855
+ const { status } = err;
40856
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
40857
+ return status >= 100 && status <= 599 ? status : null;
40858
+ }
40859
+ function nameOf(err) {
40860
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
40861
+ return typeof err.name === "string" ? err.name : null;
40862
+ }
40863
+ function classifyRemoteFailure(err) {
40864
+ switch (nameOf(err)) {
40865
+ case "RemoteRouteAbsent":
40866
+ return "route-absent";
40867
+ case "RemoteRequestInvalid":
40868
+ case "RemoteEndpointRefused":
40869
+ return "invalid-request";
40870
+ case "RemoteResponseInvalid":
40871
+ return "rejected";
40872
+ default:
40873
+ break;
40874
+ }
40875
+ const status = statusOf(err);
40876
+ if (status === null) return "unreachable";
40877
+ switch (status) {
40878
+ case 401:
40879
+ return "unauthorized";
40880
+ case 403:
40881
+ return "forbidden";
40882
+ case 429:
40883
+ return "unreachable";
40884
+ case 404:
40885
+ return "unreachable";
40886
+ default:
40887
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
40888
+ }
41491
40889
  }
41492
40890
 
41493
- // ../../packages/plugin-sdk/src/scope-key.ts
41494
- import { existsSync as existsSync12 } from "fs";
41495
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join26, normalize } from "path";
40891
+ // ../../packages/plugin-runtime/src/attached/failure.ts
40892
+ function classifyFailure(err) {
40893
+ switch (classifyRemoteFailure(err)) {
40894
+ case "unauthorized":
40895
+ return "unauthorized";
40896
+ case "forbidden":
40897
+ return "forbidden";
40898
+ default:
40899
+ return "unreachable";
40900
+ }
40901
+ }
41496
40902
 
41497
- // ../../packages/plugin-sdk/src/suppressions.ts
41498
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
40903
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
40904
+ var REQUEST_TIMEOUT_MS = 2e3;
40905
+ function withTimeout(promise2, ms) {
40906
+ let timer;
40907
+ const timeout = new Promise((_, reject) => {
40908
+ timer = setTimeout(() => {
40909
+ reject(new Error("attached gateway request timed out"));
40910
+ }, ms);
40911
+ });
40912
+ promise2.catch(() => void 0);
40913
+ return Promise.race([promise2, timeout]).finally(() => {
40914
+ clearTimeout(timer);
40915
+ });
40916
+ }
41499
40917
 
41500
- // ../../packages/plugin-sdk/src/throttle.ts
41501
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
41502
- import { join as join27 } from "path";
40918
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
40919
+ import { readFileSync as readFileSync13 } from "fs";
40920
+ import { join as join20 } from "path";
40921
+ var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
40922
+ function forwardDropsPath(dataDir2) {
40923
+ return join20(dataDir2, FORWARD_DROPS_FILENAME);
40924
+ }
40925
+ function recordForwardDrops(dataDir2, count, nowMs) {
40926
+ if (count <= 0) return;
40927
+ try {
40928
+ ensureDataDirSync(dataDir2);
40929
+ const previous = readForwardDrops(dataDir2);
40930
+ const next = {
40931
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
40932
+ lastDropAtMs: nowMs
40933
+ };
40934
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
40935
+ `);
40936
+ } catch {
40937
+ }
40938
+ }
40939
+ function readForwardDrops(dataDir2) {
40940
+ try {
40941
+ const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
40942
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
40943
+ const record2 = parsed2;
40944
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
40945
+ return null;
40946
+ }
40947
+ if (record2.droppedForwards <= 0) return null;
40948
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
40949
+ return null;
40950
+ }
40951
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
40952
+ } catch {
40953
+ return null;
40954
+ }
40955
+ }
41503
40956
 
41504
40957
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
40958
+ import { randomUUID as randomUUID16 } from "crypto";
40959
+ import { readFile, rename, writeFile } from "fs/promises";
40960
+ import { join as join21 } from "path";
41505
40961
  function isInvalidRequest(err) {
41506
40962
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
41507
40963
  }
@@ -41520,7 +40976,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
41520
40976
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
41521
40977
  function createForwardPolicy(deps) {
41522
40978
  const now = deps.now ?? (() => Date.now());
41523
- const file2 = join28(deps.dir, STATE_FILENAME);
40979
+ const file2 = join21(deps.dir, STATE_FILENAME);
41524
40980
  let state = null;
41525
40981
  let loading = null;
41526
40982
  async function readState() {
@@ -41686,6 +41142,9 @@ var AttachedDataGateway = class {
41686
41142
  *
41687
41143
  * Machine mode answers before any key is read, so a machine attachment pays
41688
41144
  * nothing for scoping and forwards exactly what it always has.
41145
+ *
41146
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
41147
+ * forwarding key for key.
41689
41148
  */
41690
41149
  verdictFor(keyOf) {
41691
41150
  try {
@@ -41702,24 +41161,27 @@ var AttachedDataGateway = class {
41702
41161
  * the key its row holds in the local store, recorded per root (see
41703
41162
  * `rootVerdict`), not the key on the root event just handed in: roots are
41704
41163
  * first-write-wins in the store, so when two producers record a root for one
41705
- * session (the session-start hook, then a reconcile pass) the second leaves
41706
- * the stored row as it was, and the history drain decides that row, not this
41707
- * event. Whether this root EVENT is itself sent takes both keys: the stored
41708
- * one AND its own. The event's attributes (cwd, project, repo) describe where
41709
- * it was recorded from, so a root event keyed to a personal directory is never
41710
- * sent under an enrolled stored root, though the enrolled leaves still forward
41711
- * under it: the instance that wrote the stored root is expected to have
41712
- * forwarded it. If it did not (the root was written while standalone or under
41713
- * another attachment, or its forward failed), the plane refuses those leaves
41714
- * and the history drain ships the root first. Any other row with a root
41715
- * reference (`rootSessionId`, else `parentId`) forwards only when its own key
41716
- * is in scope AND this instance recorded an in-scope verdict for that root.
41717
- * The audit-event route has real foreign keys on both columns and stubs no
41718
- * missing root, so a leaf sent after its root was kept local is refused
41719
- * there, and a refused forward counts toward the breaker that guards every
41720
- * other one. A root this instance never recorded is therefore `'local'`: the
41721
- * only answer that cannot orphan a row. A row with no root reference at all
41722
- * has nothing to orphan, and is decided by its own key.
41164
+ * session (the session-start hook, then a reconcile pass) the second leaves the
41165
+ * stored row as it was. That stored row, not this event, is what a history
41166
+ * drain pass would decide, if the root started before the attach; the drain
41167
+ * never offers one that started after it (`started_at < backlogBefore`).
41168
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
41169
+ * its own. The event's attributes (cwd, project, repo) describe where it was
41170
+ * recorded from, so a root event keyed to a personal directory is never sent
41171
+ * under an enrolled stored root, though the enrolled leaves still forward under
41172
+ * it: the instance that wrote the stored root is expected to have forwarded it.
41173
+ * If it did not (the root was written while standalone or under another
41174
+ * attachment, or its forward failed), the plane refuses those leaves. A root
41175
+ * that started before the attach is shipped, ahead of its leaves, by the
41176
+ * history drain; one that started after it is never offered by the drain. Any
41177
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
41178
+ * only when its own key is in scope AND this instance recorded an in-scope
41179
+ * verdict for that root. The audit-event route has real foreign keys on both
41180
+ * columns and stubs no missing root, so a leaf sent after its root was kept
41181
+ * local is refused there, and a refused forward counts toward the breaker that
41182
+ * guards every other one. A root this instance never recorded is therefore
41183
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
41184
+ * reference at all has nothing to orphan, and is decided by its own key.
41723
41185
  *
41724
41186
  * What this costs is stated rather than discovered. A session whose stored
41725
41187
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -41790,6 +41252,87 @@ var AttachedDataGateway = class {
41790
41252
  return [];
41791
41253
  }
41792
41254
  }
41255
+ /**
41256
+ * The verdict for the repositories nested in a scanned project, answered
41257
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
41258
+ *
41259
+ * A walk descends into a nested clone or submodule and folds its files into
41260
+ * the project it is walking, so one register can carry several
41261
+ * repositories' call sites under one project key. Each of them must be in
41262
+ * scope for it to forward. One key out of scope, or a nested repository with
41263
+ * no remote (an `undefined` key), keeps the whole register local.
41264
+ *
41265
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
41266
+ * what is nested in it, and every scan passes the list, empty when nothing
41267
+ * is nested. A register nobody vouched for is not one a scoped attachment
41268
+ * may send.
41269
+ *
41270
+ * Machine mode answers before reading the context, so a machine attachment
41271
+ * forwards exactly what it always has.
41272
+ */
41273
+ nestedVerdict(context) {
41274
+ try {
41275
+ if (this.deps.attachment.mode === "machine") return "forward";
41276
+ const keys = context?.nestedScopeKeys;
41277
+ if (keys === void 0) return "local";
41278
+ for (const key of keys) {
41279
+ if (this.verdictFor(() => key) === "local") return "local";
41280
+ }
41281
+ return "forward";
41282
+ } catch {
41283
+ return "local";
41284
+ }
41285
+ }
41286
+ /**
41287
+ * The register a scoped attachment sends, once the project and the repositories
41288
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
41289
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
41290
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
41291
+ *
41292
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
41293
+ * and the ledger holds every file the scanner ever read under the root, nested
41294
+ * clones' included. So a clone that was removed, or one an ignore file now
41295
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
41296
+ * paths come back as deleted. The scan names the repository of each deleted
41297
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
41298
+ * and each is held to the same verdict as any other key. A path whose key is
41299
+ * absent, or out of scope, is not sent.
41300
+ *
41301
+ * The list is asked for here, and only here: it is an async read of the scan
41302
+ * ledger that the scan makes on being called, so a machine attachment, which
41303
+ * returns before this, and a register already kept local never cause it.
41304
+ *
41305
+ * Anything the scan did not vouch for sends no deleted path, and the register
41306
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
41307
+ * list whose length is not the register's. Deleting is the only thing a dropped
41308
+ * path could have done on the server, so the cost of a refusal is a stored row
41309
+ * that stays, never a path that leaves.
41310
+ *
41311
+ * Machine mode returns `input` itself, the same object and unread, so a machine
41312
+ * attachment's request is exactly what it was. A register that lists no deleted
41313
+ * path, or that is not a ledger register, has nothing to cut and is returned
41314
+ * as it came, with the list unread.
41315
+ */
41316
+ async registerForWire(input2, context) {
41317
+ try {
41318
+ if (this.deps.attachment.mode === "machine") return input2;
41319
+ const { reconcile } = input2;
41320
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
41321
+ const deleted = reconcile.deletedFiles;
41322
+ let kept = [];
41323
+ try {
41324
+ const keys = await context?.deletedFileKeys?.();
41325
+ if (keys?.length === deleted.length) {
41326
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
41327
+ }
41328
+ } catch {
41329
+ kept = [];
41330
+ }
41331
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
41332
+ } catch {
41333
+ return void 0;
41334
+ }
41335
+ }
41793
41336
  /**
41794
41337
  * The event `recordCapture` sends for a capture the verdict let through, or
41795
41338
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -42115,12 +41658,24 @@ var AttachedDataGateway = class {
42115
41658
  * payload onto the wire-boundary-safe shape (no snippet, hashed
42116
41659
  * projectKey), and its result is discarded: `forward.run` never throws or
42117
41660
  * rejects, so there is nothing here to act on.
41661
+ *
41662
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
41663
+ * not say: the key of every repository nested below the scan root, whose
41664
+ * files the walk folded into this register. On a scoped attachment the
41665
+ * register is forwarded only when the project's own key AND every one of
41666
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
41667
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
41668
+ * `registerForWire`). Machine mode never reads either, and the local write
41669
+ * never receives the context and gets the register whole.
42118
41670
  */
42119
- async recordProjectEgress(input2) {
41671
+ async recordProjectEgress(input2, context) {
42120
41672
  const summary = await this.deps.local.recordProjectEgress(input2);
42121
41673
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
41674
+ if (this.nestedVerdict(context) === "local") return summary;
41675
+ const register = await this.registerForWire(input2, context);
41676
+ if (register === void 0) return summary;
42122
41677
  await this.deps.forward.run(
42123
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
41678
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
42124
41679
  );
42125
41680
  return summary;
42126
41681
  }
@@ -42174,6 +41729,11 @@ var AttachedDataGateway = class {
42174
41729
  async scanLedgerPaths() {
42175
41730
  return this.deps.local.scanLedgerPaths();
42176
41731
  }
41732
+ // Delegated, like the path list. An inner gateway that cannot say answers an
41733
+ // empty map, which gives every deleted path no key.
41734
+ async scanLedgerPathKeys() {
41735
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
41736
+ }
42177
41737
  async recordScanned(entries) {
42178
41738
  return this.deps.local.recordScanned(entries);
42179
41739
  }
@@ -42240,6 +41800,12 @@ var AttachedDataGateway = class {
42240
41800
  // and the spread above would otherwise drop the field silently — which is
42241
41801
  // exactly what it did, leaving the whole control inert on every device
42242
41802
  // while every test around it stayed green.
41803
+ //
41804
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
41805
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
41806
+ // reads this bundle once to build detection, so the detections it carries
41807
+ // apply to every event on the machine. Where a prohibition applies is
41808
+ // answered per event by `governanceAppliesTo` below.
42243
41809
  prohibitedModels: cached2.prohibitedModels,
42244
41810
  // NAMED for the same reason as the line above, and it is the same defect
42245
41811
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -42299,6 +41865,30 @@ var AttachedDataGateway = class {
42299
41865
  };
42300
41866
  }
42301
41867
  // ---------------------------------------------------------------------
41868
+ // GovernanceScope — where the organization's model policy applies
41869
+ // ---------------------------------------------------------------------
41870
+ /**
41871
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
41872
+ * the question a model-guard site asks once it has decided to refuse.
41873
+ *
41874
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
41875
+ * with the same key would be forwarded. A machine-wide attachment governs
41876
+ * every event, keyless included, exactly as before. A scoped one governs an
41877
+ * event only when its key names an enrolled repository. An event in a
41878
+ * personal repository, in no repository, with an empty key, or met by a fault
41879
+ * is not governed.
41880
+ *
41881
+ * The event's OWN key, never its session root's. The root rule in
41882
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
41883
+ * this decides whether a refusal applies, which is a question about where the
41884
+ * event happened.
41885
+ *
41886
+ * Answered from memory: no store read, no bundle read, nothing sent.
41887
+ */
41888
+ governanceAppliesTo(scopeKey) {
41889
+ return this.verdictFor(() => scopeKey) === "forward";
41890
+ }
41891
+ // ---------------------------------------------------------------------
42302
41892
  // LocalStoreMaintenance — by delegation (D3).
42303
41893
  //
42304
41894
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -42407,8 +41997,8 @@ function toWireInspection(insp) {
42407
41997
  }
42408
41998
 
42409
41999
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
42410
- import { createHash as createHash6 } from "crypto";
42411
- import { hostname as hostname5 } from "os";
42000
+ import { createHash as createHash7 } from "crypto";
42001
+ import { hostname as hostname4 } from "os";
42412
42002
 
42413
42003
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
42414
42004
  var CORRELATION_ID = EventMetadata.shape.correlationId;
@@ -42426,17 +42016,17 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
42426
42016
 
42427
42017
  // ../../packages/plugin-runtime/src/attached/install-record.ts
42428
42018
  import { readFile as readFile2, stat } from "fs/promises";
42429
- import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
42019
+ import { basename as basename3, dirname as dirname5, join as join22, resolve as resolve2 } from "path";
42430
42020
  async function readInstalledVersion(installRoot) {
42431
42021
  try {
42432
42022
  const versionDir = resolve2(installRoot);
42433
- const pluginDir = dirname7(versionDir);
42434
- const marketplaceDir = dirname7(pluginDir);
42435
- const cacheDir = dirname7(marketplaceDir);
42436
- if (basename6(cacheDir) !== "cache") return null;
42437
- const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
42023
+ const pluginDir = dirname5(versionDir);
42024
+ const marketplaceDir = dirname5(pluginDir);
42025
+ const cacheDir = dirname5(marketplaceDir);
42026
+ if (basename3(cacheDir) !== "cache") return null;
42027
+ const key = `${basename3(pluginDir)}@${basename3(marketplaceDir)}`;
42438
42028
  const record2 = JSON.parse(
42439
- await readFile2(join29(dirname7(cacheDir), "installed_plugins.json"), "utf8")
42029
+ await readFile2(join22(dirname5(cacheDir), "installed_plugins.json"), "utf8")
42440
42030
  );
42441
42031
  const plugins = record2?.plugins;
42442
42032
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -42468,7 +42058,7 @@ async function exists(path) {
42468
42058
  }
42469
42059
 
42470
42060
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
42471
- import { readFileSync as readFileSync18 } from "fs";
42061
+ import { readFileSync as readFileSync14 } from "fs";
42472
42062
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
42473
42063
  function createPluginBlock(build, policyStore) {
42474
42064
  return async () => {
@@ -42498,7 +42088,7 @@ async function readInstalledVersionBounded(installRoot) {
42498
42088
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42499
42089
  import { randomUUID as randomUUID17 } from "crypto";
42500
42090
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
42501
- import { join as join30 } from "path";
42091
+ import { join as join23 } from "path";
42502
42092
 
42503
42093
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
42504
42094
  import { rename as rename2 } from "fs/promises";
@@ -42527,7 +42117,7 @@ async function publishByRename(tmp, file2, move = rename2) {
42527
42117
 
42528
42118
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42529
42119
  function createPolicyStore(dir = dataDir()) {
42530
- const file2 = join30(dir, "policy-cache.json");
42120
+ const file2 = join23(dir, "policy-cache.json");
42531
42121
  async function read() {
42532
42122
  try {
42533
42123
  const raw = await readFile3(file2, "utf8");
@@ -42597,8 +42187,8 @@ function createPolicyStore(dir = dataDir()) {
42597
42187
  }
42598
42188
 
42599
42189
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
42600
- import { readFileSync as readFileSync19 } from "fs";
42601
- import { join as join31 } from "path";
42190
+ import { readFileSync as readFileSync15 } from "fs";
42191
+ import { join as join24 } from "path";
42602
42192
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
42603
42193
  var OUTCOME_KEYS = {
42604
42194
  ok: true,
@@ -42612,7 +42202,7 @@ var OUTCOME_KEYS = {
42612
42202
  };
42613
42203
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
42614
42204
  function postureReportStatePath(dataDir2) {
42615
- return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42205
+ return join24(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42616
42206
  }
42617
42207
  function writePostureReportState(dataDir2, state) {
42618
42208
  try {
@@ -42653,10 +42243,19 @@ function createPostureReporter(deps) {
42653
42243
  hostname: deps.hostname(),
42654
42244
  capturedAt: nowMs,
42655
42245
  ...measurement,
42656
- // Omit the key rather than spread an explicit `undefined` —
42657
- // exactOptionalPropertyTypes distinguishes the two, and the bridge in
42658
- // factory.ts keys on presence.
42659
- ...plugin === void 0 ? {} : { plugin }
42246
+ // Omit the key rather than spread an explicit `undefined`. The type
42247
+ // admits `undefined` here (the schema's optional member), and
42248
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
42249
+ // in-memory object free of an explicit `undefined` member, which the
42250
+ // tests pin by key presence.
42251
+ ...plugin === void 0 ? {} : { plugin },
42252
+ // LAST, and only for a scoped attachment. A machine attachment omits
42253
+ // the key the same way, so its body is byte for byte the one it sent
42254
+ // before the member existed. Anything but exactly `machine` reports the
42255
+ // constant `scoped`, never the raw value: that is resolveScope's own
42256
+ // fail direction, and a value outside the wire's vocabulary would fail
42257
+ // the whole snapshot at the receiver, the wipe signal with it.
42258
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
42660
42259
  };
42661
42260
  } catch {
42662
42261
  return null;
@@ -42679,8 +42278,8 @@ function createPostureReporter(deps) {
42679
42278
  }
42680
42279
 
42681
42280
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
42682
- import { statSync as statSync9 } from "fs";
42683
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
42281
+ import { statSync as statSync7 } from "fs";
42282
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
42684
42283
 
42685
42284
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
42686
42285
  function emptyActionCounts() {
@@ -42710,7 +42309,7 @@ function emptyReadout(readError = false) {
42710
42309
  }
42711
42310
  function readStorePosture(dbPath2) {
42712
42311
  try {
42713
- statSync9(dbPath2);
42312
+ statSync7(dbPath2);
42714
42313
  } catch (err) {
42715
42314
  const code = err.code;
42716
42315
  if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
@@ -42738,7 +42337,7 @@ function readStorePosture(dbPath2) {
42738
42337
  readError: false
42739
42338
  });
42740
42339
  try {
42741
- db = new DatabaseSync4(dbPath2, { readOnly: true });
42340
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
42742
42341
  db.exec("PRAGMA busy_timeout = 2000");
42743
42342
  version2 = db.prepare("PRAGMA user_version").get().user_version;
42744
42343
  try {
@@ -42792,11 +42391,11 @@ function readStorePosture(dbPath2) {
42792
42391
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
42793
42392
  import { randomUUID as randomUUID18 } from "crypto";
42794
42393
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
42795
- import { join as join32 } from "path";
42394
+ import { join as join25 } from "path";
42796
42395
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
42797
42396
  function createPostureStore(dir = settingsDir(), legacyDir) {
42798
- const file2 = join32(dir, "posture-state.json");
42799
- const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
42397
+ const file2 = join25(dir, "posture-state.json");
42398
+ const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
42800
42399
  async function persist(state) {
42801
42400
  await ensureDataDir(dir);
42802
42401
  const tmp = `${file2}.${randomUUID18()}.tmp`;
@@ -42864,8 +42463,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42864
42463
  }
42865
42464
 
42866
42465
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
42867
- import { readFileSync as readFileSync20 } from "fs";
42868
- import { join as join33 } from "path";
42466
+ import { readFileSync as readFileSync16 } from "fs";
42467
+ import { join as join26 } from "path";
42869
42468
 
42870
42469
  // ../../packages/plugin-runtime/src/attached/status.ts
42871
42470
  var REFUSAL_LINES = {
@@ -42895,7 +42494,7 @@ import { fileURLToPath as fileURLToPath4 } from "url";
42895
42494
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
42896
42495
 
42897
42496
  // ../../packages/plugin-runtime/src/attached/factory.ts
42898
- import { hostname as hostname6 } from "os";
42497
+ import { hostname as hostname5 } from "os";
42899
42498
 
42900
42499
  // ../../packages/plugin-runtime/src/recorder.ts
42901
42500
  var PLUGIN_RECORDER_BINARY = "plugin";
@@ -42908,7 +42507,7 @@ var StandaloneDataGateway = class {
42908
42507
  // One notice per gateway — see warnRulesetDiscarded.
42909
42508
  warnedRulesetDiscarded = false;
42910
42509
  constructor(dataDir2, detections = [], meta4) {
42911
- this.db = openLocalDatabase(dataDir2);
42510
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
42912
42511
  this.dataDir = dataDir2;
42913
42512
  this.db.installedPacks.recordInventory(detections, meta4);
42914
42513
  }
@@ -43257,6 +42856,9 @@ var StandaloneDataGateway = class {
43257
42856
  scanLedgerPaths() {
43258
42857
  return Promise.resolve(this.db.scanLedger.allPaths());
43259
42858
  }
42859
+ scanLedgerPathKeys() {
42860
+ return Promise.resolve(this.db.scanLedger.pathKeys());
42861
+ }
43260
42862
  recordScanned(entries) {
43261
42863
  this.db.scanLedger.upsertEntries(entries);
43262
42864
  return Promise.resolve();
@@ -43342,13 +42944,17 @@ function resolveGatewayForConfig(config2, meta4) {
43342
42944
  },
43343
42945
  store: postureStore,
43344
42946
  readStore: () => readStorePosture(config2.dbPath),
43345
- hostname: () => hostname6(),
42947
+ hostname: () => hostname5(),
43346
42948
  now: () => Date.now(),
42949
+ // The mode THIS gateway enforces, from the attachment resolved above,
42950
+ // so the report cannot name a mode the forward paths are not using.
42951
+ attachmentMode: attachment.mode,
43347
42952
  // The reporting build's identity, when the caller knows it (the plugin
43348
42953
  // adapters do; an embedder or a test may not). Composed with the SAME
43349
42954
  // policy store the sync child writes, so the block names the bundle
43350
- // actually in force. Key omitted rather than set undefined — the
43351
- // reporter keys on presence.
42955
+ // actually in force. The dependency key is omitted when no build is
42956
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
42957
+ // then adds no block.
43352
42958
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
43353
42959
  })
43354
42960
  });
@@ -43480,7 +43086,7 @@ function responseEmitPayload(outcome) {
43480
43086
  }
43481
43087
 
43482
43088
  // src/hooks/shared.ts
43483
- import { isAbsolute as isAbsolute3, normalize as normalize2, resolve as resolvePath } from "path";
43089
+ import { isAbsolute as isAbsolute2, normalize, resolve as resolvePath } from "path";
43484
43090
  async function readStdin() {
43485
43091
  return new Promise((resolve3) => {
43486
43092
  let data = "";
@@ -43540,9 +43146,9 @@ function captureScopeKey(input2, filePath) {
43540
43146
  if (filePath === void 0 || filePath === "") {
43541
43147
  return resolveRepoAttribution(getString(input2, "cwd") ?? process.cwd()).scopeKey;
43542
43148
  }
43543
- if (isAbsolute3(filePath)) return resolveRepoAttribution(normalize2(filePath)).scopeKey;
43149
+ if (isAbsolute2(filePath)) return resolveRepoAttribution(normalize(filePath)).scopeKey;
43544
43150
  const cwd = getString(input2, "cwd") ?? process.cwd();
43545
- if (!isAbsolute3(cwd)) return void 0;
43151
+ if (!isAbsolute2(cwd)) return void 0;
43546
43152
  return resolveRepoAttribution(resolvePath(cwd, filePath)).scopeKey;
43547
43153
  } catch {
43548
43154
  return void 0;
@@ -43556,16 +43162,16 @@ function countFailOpen(base) {
43556
43162
  }
43557
43163
 
43558
43164
  // src/hooks/store-health.ts
43559
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
43560
- import { dirname as dirname8, join as join34 } from "path";
43165
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync17, writeFileSync as writeFileSync5 } from "fs";
43166
+ import { dirname as dirname6, join as join27 } from "path";
43561
43167
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
43562
43168
  function markerDirs(dataDir2) {
43563
- return [dataDir2, dirname8(dataDir2)];
43169
+ return [dataDir2, dirname6(dataDir2)];
43564
43170
  }
43565
43171
  function alreadyClaimed(dirs, marker, sessionId) {
43566
43172
  return dirs.some((dir) => {
43567
43173
  try {
43568
- return readFileSync21(join34(dir, marker), "utf8") === sessionId;
43174
+ return readFileSync17(join27(dir, marker), "utf8") === sessionId;
43569
43175
  } catch {
43570
43176
  return false;
43571
43177
  }
@@ -43574,14 +43180,14 @@ function alreadyClaimed(dirs, marker, sessionId) {
43574
43180
  function recordClaim(dirs, marker, sessionId) {
43575
43181
  for (const dir of dirs) {
43576
43182
  try {
43577
- mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
43578
- writeFileSync8(join34(dir, marker), sessionId, { mode: DATA_FILE_MODE });
43183
+ mkdirSync2(dir, { recursive: true, mode: DATA_DIR_MODE });
43184
+ writeFileSync5(join27(dir, marker), sessionId, { mode: DATA_FILE_MODE });
43579
43185
  return;
43580
43186
  } catch {
43581
43187
  }
43582
43188
  }
43583
43189
  }
43584
- function storeRedirectedMessage(paths, platform2 = process.platform) {
43190
+ function storeRedirectedMessage(paths, platform = process.platform) {
43585
43191
  const where = paths.map(({ path, target, holds, missing, mode }) => {
43586
43192
  if (missing) return `${path} -> ${target} (which does not exist; ${holds} cannot land there)`;
43587
43193
  const loose = mode !== void 0 && (mode & 63) !== 0 ? ", NOT owner-only" : "";
@@ -43591,7 +43197,7 @@ function storeRedirectedMessage(paths, platform2 = process.platform) {
43591
43197
  const subject = paths.length === 1 ? "a store path is a symlink" : `${String(paths.length)} store paths are symlinks`;
43592
43198
  const anyResolves = paths.some(({ missing }) => !missing);
43593
43199
  const lead = anyResolves ? `${subject}, so AKA is writing into the target instead: ${where}. ` : `${subject} resolving nowhere, so AKA cannot write there: ${where}. `;
43594
- const kept = anyResolves && platform2 !== "win32" ? "Permissions are never changed through a symlink, so the store keeps whatever the target already had. " : "";
43200
+ const kept = anyResolves && platform !== "win32" ? "Permissions are never changed through a symlink, so the store keeps whatever the target already had. " : "";
43595
43201
  return `[aka] ${lead}${kept}If you did not create that link, treat it as untrusted and run \`aka init\` for the full report.
43596
43202
  `;
43597
43203
  }
@@ -43600,7 +43206,7 @@ function formatMode(mode) {
43600
43206
  }
43601
43207
  function warnIfStoreRedirected(config2, sessionId, write = (message) => void process.stderr.write(message)) {
43602
43208
  try {
43603
- const paths = symlinkedStorePaths(dirname8(config2.dataDir));
43209
+ const paths = symlinkedStorePaths(dirname6(config2.dataDir));
43604
43210
  if (paths.length === 0) return;
43605
43211
  if (!sessionId) {
43606
43212
  write(storeRedirectedMessage(paths));