fullcourtdefense 2.3.0 → 2.3.2

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.
package/README.md CHANGED
@@ -806,7 +806,8 @@ Every call that ran during the outage is reported with `ranDuringOutage: true` (
806
806
  `failsafeRuleId` / `failsafeRuleName` when a rule applied). When the API is up and answers "pending" (a manager has to
807
807
  decide), the call does not run and returns at once: a manager who does not answer is not our failure.
808
808
 
809
- Records survive a short-lived process: sends are tracked, the end of the process waits at most 1.5 s for them, and what is
809
+ Records survive a short-lived process: when it ends the SDK **sends** what is unsent (at most 4 s), reports straight to
810
+ FullCourtDefense how many it could not deliver (shown in the console even if the disk is gone), and what is
810
811
  still unsent (or failed) is kept in a small file in the user cache directory (`~/.cache/fullcourtdefense/sdk-spool`, or
811
812
  `%LOCALAPPDATA%` / `~/Library/Caches`) that the next start with the same shield sends. `FCD_SDK_SPOOL=off` disables it,
812
813
  `FCD_SDK_SPOOL_DIR` moves it.
package/dist/client.d.ts CHANGED
@@ -95,10 +95,16 @@ export declare class FullCourtDefense {
95
95
  private _enqueueRecord;
96
96
  /** Send the records an earlier process left in the local spool (once per shield per process, off the first tick). */
97
97
  private _replaySpooledRecords;
98
+ /** Once the replayed records left the queue, clear the pending gaps an earlier process reported for them. */
99
+ private _resolveReplayedGaps;
98
100
  /** @internal Calls held in memory, as request bodies for the local spool (called at exit). */
99
101
  _takeUnsentForSpool(): SpooledRecord[];
100
102
  /** @internal Send the calls spooled while the API was down and the queued records (called at `beforeExit`; the caller bounds the wait). */
101
103
  _flushForExit(): Promise<void>;
104
+ /** @internal This client's shield (the end of the process groups leftovers by shield). */
105
+ _shieldIdForExit(): string;
106
+ /** @internal The one direct gap report at the end of the process; true when the server took it. */
107
+ _postExitReport(body: Record<string, unknown>, timeoutMs: number): Promise<boolean>;
102
108
  /**
103
109
  * How the background record upload is doing (observability for the app and the load tests): records waiting, sent,
104
110
  * refused, dropped because the upload could not keep up (`dropped`; `unreported` is the part no accepted upload has told
package/dist/client.js CHANGED
@@ -210,7 +210,21 @@ async function settleWithin(work, ms) {
210
210
  if (cap !== undefined)
211
211
  clearTimeout(cap);
212
212
  }
213
- const EXIT_FLUSH_MAX_MS = 1500;
213
+ /** The end of the process SENDS its last records for at most this long (owner 2026-11-21: the SDK sends the data). */
214
+ const EXIT_FLUSH_MAX_MS = 4000;
215
+ /** Requests at once at the end of the process. */
216
+ const EXIT_SENDERS = 8;
217
+ /** The one direct gap report at the end of the process (after the send window). */
218
+ const EXIT_GAP_TIMEOUT_MS = 1000;
219
+ const RECORD_PATH = '/api/agent-security/runtime/tool-call';
220
+ /** Spooled records an earlier process left that this process queued and has not confirmed yet: shield -> gap id -> count. */
221
+ const replayedGaps = new Map();
222
+ /**
223
+ * Aborted once the end of the process has kept and reported what was left: the SDK's own requests still open would
224
+ * otherwise keep the process alive until their timeouts (seen on the lab VM: 7-10 s). Their records are already kept.
225
+ */
226
+ const exitAbort = new AbortController();
227
+ let exitKept = false;
214
228
  const FAILED_RECORDS_MAX = 200;
215
229
  const pendingRecords = new Set();
216
230
  const failedRecords = [];
@@ -229,8 +243,16 @@ function toSpooled(entry) {
229
243
  return undefined;
230
244
  }
231
245
  }
232
- /** Write everything still unsent to the local spool (synchronous: it runs at `exit`). */
233
- function persistLeftovers() {
246
+ /** How many tool-call records a spooled request carries (a single record, or the records of a batch that was on the wire). */
247
+ function recordsIn(record) {
248
+ if (record.path === RECORD_PATH)
249
+ return 'actionId' in record.body && 'outcome' in record.body ? 0 : 1;
250
+ if (record.path === recordSpool_1.GAP_PATH && Array.isArray(record.body.records))
251
+ return record.body.records.length;
252
+ return 0;
253
+ }
254
+ /** Everything still unsent, records tagged with their shield's exit gap; and per shield the one gap report to send. */
255
+ function collectLeftovers() {
234
256
  const records = [];
235
257
  const keep = (entry) => {
236
258
  const record = toSpooled(entry);
@@ -243,11 +265,63 @@ function persistLeftovers() {
243
265
  for (const entry of failedRecords)
244
266
  keep(entry);
245
267
  failedRecords.length = 0;
246
- for (const client of liveClients)
268
+ const clients = new Map();
269
+ for (const client of liveClients) {
270
+ clients.set(client._shieldIdForExit(), client);
247
271
  records.push(...client._takeUnsentForSpool());
272
+ }
248
273
  liveClients.clear();
249
- (0, recordSpool_1.writeSpool)(records);
274
+ const counts = new Map();
275
+ const gapIds = new Map();
276
+ const at = new Date().toISOString();
277
+ for (const record of records) {
278
+ const n = recordsIn(record);
279
+ if (n === 0)
280
+ continue;
281
+ if (!gapIds.has(record.shieldId))
282
+ gapIds.set(record.shieldId, `gap-exit-${(0, crypto_1.randomUUID)()}`);
283
+ record.gapId = gapIds.get(record.shieldId);
284
+ counts.set(record.shieldId, (counts.get(record.shieldId) ?? 0) + n);
285
+ }
286
+ const reports = [];
287
+ for (const shieldId of new Set([...counts.keys(), ...replayedGaps.keys()])) {
288
+ const body = { records: [] };
289
+ const n = counts.get(shieldId) ?? 0;
290
+ if (n > 0)
291
+ body.gap = { dropped: n, from: at, to: at, id: gapIds.get(shieldId), pending: true };
292
+ const held = replayedGaps.get(shieldId);
293
+ if (held && held.size > 0)
294
+ body.resolveGaps = Array.from(held, ([id, count]) => ({ id, count })).slice(0, 20);
295
+ reports.push({ shieldId, client: clients.get(shieldId), body, at });
296
+ }
297
+ replayedGaps.clear();
298
+ return { records, reports };
250
299
  }
300
+ /** Write everything still unsent to the local spool, with its gap report (synchronous: it runs at `exit`, which cannot send). */
301
+ function persistLeftovers() {
302
+ const { records, reports } = collectLeftovers();
303
+ (0, recordSpool_1.writeSpool)([...records, ...reports.filter((r) => r.body.gap).map((r) => ({ path: recordSpool_1.GAP_PATH, body: { ...r.body, shieldId: r.shieldId }, shieldId: r.shieldId, at: r.at }))]);
304
+ }
305
+ /** Spool what is left, then send each shield's gap report directly (the console shows it even if this disk is gone). */
306
+ async function keepAndReport() {
307
+ const { records, reports } = collectLeftovers();
308
+ const kept = (0, recordSpool_1.writeSpool)(records);
309
+ const unsent = [];
310
+ await Promise.all(reports.map(async (report) => {
311
+ const gap = report.body.gap;
312
+ if (gap && kept < records.length)
313
+ gap.pending = false;
314
+ const ok = report.client ? await report.client._postExitReport(report.body, EXIT_GAP_TIMEOUT_MS) : false;
315
+ if (!ok && gap)
316
+ unsent.push({ path: recordSpool_1.GAP_PATH, body: { ...report.body, shieldId: report.shieldId }, shieldId: report.shieldId, at: report.at });
317
+ }));
318
+ (0, recordSpool_1.writeSpool)(unsent);
319
+ }
320
+ /**
321
+ * The end of the process (owner 2026-11-21: the SDK sends the data, nothing to configure): SEND every unsent record in
322
+ * parallel batches for at most EXIT_FLUSH_MAX_MS; keep what is still left on this machine; report it to the server at once
323
+ * (one gap per shield, `pending` when it was kept; the next start clears it as it delivers the records).
324
+ */
251
325
  async function flushAtExit() {
252
326
  if (exitFlushRunning)
253
327
  return;
@@ -263,7 +337,14 @@ async function flushAtExit() {
263
337
  await settleWithin(Promise.all(work), EXIT_FLUSH_MAX_MS);
264
338
  }
265
339
  finally {
266
- persistLeftovers();
340
+ try {
341
+ await settleWithin(keepAndReport(), EXIT_GAP_TIMEOUT_MS + 500);
342
+ }
343
+ catch {
344
+ persistLeftovers();
345
+ }
346
+ exitKept = true;
347
+ exitAbort.abort();
267
348
  exitFlushRunning = false;
268
349
  }
269
350
  }
@@ -280,12 +361,15 @@ function installExitHooks() {
280
361
  for (const signal of ['SIGINT', 'SIGTERM']) {
281
362
  const handler = () => {
282
363
  // Another handler of the host shuts down its own way (and `exit` still runs); when ours is the only
283
- // one, the signal would have ended the process: keep the records, then end it the same way.
364
+ // one, the signal would have ended the process: send the records (bounded), then end it the same way.
284
365
  if (proc.listenerCount(signal) > 1)
285
366
  return;
286
- persistLeftovers();
287
- proc.removeListener(signal, handler);
288
- proc.kill(proc.pid, signal);
367
+ const end = () => {
368
+ persistLeftovers();
369
+ proc.removeListener(signal, handler);
370
+ proc.kill(proc.pid, signal);
371
+ };
372
+ void flushAtExit().then(end, end);
289
373
  };
290
374
  proc.on(signal, handler);
291
375
  }
@@ -295,6 +379,8 @@ function installExitHooks() {
295
379
  }
296
380
  }
297
381
  function keepFailed(entry) {
382
+ if (exitKept)
383
+ return; // already kept by the end of the process (an aborted request)
298
384
  if (failedRecords.length >= FAILED_RECORDS_MAX)
299
385
  failedRecords.shift();
300
386
  failedRecords.push(entry);
@@ -497,6 +583,10 @@ class FullCourtDefense {
497
583
  if (typeof body.toolCallId !== 'string' || !body.toolCallId) {
498
584
  body = { ...body, toolCallId: `fcd-${(0, crypto_1.randomUUID)()}`, decisionSource: 'sdk' };
499
585
  }
586
+ // The record's OWN id, made once and kept on every resend (batches, spool): the server stores a record once by it,
587
+ // never by the provider's tool-call id, which scripted models and some providers repeat (sdk-albtech-e2e 2026-11-22).
588
+ if (typeof body.recordId !== 'string' || !body.recordId)
589
+ body = { ...body, recordId: `r${(0, crypto_1.randomUUID)().replace(/-/g, '')}` };
500
590
  this.records.push(body);
501
591
  liveClients.add(this);
502
592
  installExitHooks();
@@ -509,14 +599,61 @@ class FullCourtDefense {
509
599
  replayedShields.add(shieldId);
510
600
  setTimeout(() => {
511
601
  try {
512
- for (const record of (0, recordSpool_1.claimSpooled)(shieldId))
513
- void this._postAgentSecurity(record.path, record.body, 'full');
602
+ const spooled = (0, recordSpool_1.claimSpooled)(shieldId);
603
+ // Gap reports first (one request each), then the records through the batched queue (#4087), then clear the gaps.
604
+ const queued = spooled.filter((r) => r.path === RECORD_PATH && !('actionId' in r.body && 'outcome' in r.body));
605
+ for (const record of spooled)
606
+ if (!queued.includes(record))
607
+ void this._postAgentSecurity(record.path, record.body, 'full');
608
+ const gaps = new Map();
609
+ for (const record of queued) {
610
+ if (record.gapId)
611
+ gaps.set(record.gapId, (gaps.get(record.gapId) ?? 0) + 1);
612
+ const { shieldId: _drop, ...body } = record.body;
613
+ this._enqueueRecord(body);
614
+ }
615
+ for (const record of spooled) {
616
+ if (record.path === recordSpool_1.GAP_PATH && record.gapId && Array.isArray(record.body.records))
617
+ gaps.set(record.gapId, (gaps.get(record.gapId) ?? 0) + record.body.records.length);
618
+ }
619
+ if (gaps.size > 0) {
620
+ const held = replayedGaps.get(shieldId) ?? new Map();
621
+ for (const [id, n] of gaps)
622
+ held.set(id, (held.get(id) ?? 0) + n);
623
+ replayedGaps.set(shieldId, held);
624
+ this._resolveReplayedGaps(gaps);
625
+ }
514
626
  }
515
627
  catch {
516
628
  // never reaches the agent
517
629
  }
518
630
  }, 0);
519
631
  }
632
+ /** Once the replayed records left the queue, clear the pending gaps an earlier process reported for them. */
633
+ _resolveReplayedGaps(gaps) {
634
+ const shieldId = this.config.shieldId;
635
+ const started = Date.now();
636
+ const tick = () => {
637
+ if (exitFlushRunning)
638
+ return; // the end of the process clears them in its own report
639
+ if (this.records.size > 0 && Date.now() - started < 600000) {
640
+ const t = setTimeout(tick, 500);
641
+ t.unref?.();
642
+ return;
643
+ }
644
+ if (this.records.size > 0)
645
+ return;
646
+ void this._postAgentSecurity(recordSpool_1.GAP_PATH, { records: [], resolveGaps: Array.from(gaps, ([id, count]) => ({ id, count })).slice(0, 20) }).then((result) => {
647
+ if (!result.success)
648
+ return;
649
+ const held = replayedGaps.get(shieldId);
650
+ for (const id of gaps.keys())
651
+ held?.delete(id);
652
+ });
653
+ };
654
+ const t = setTimeout(tick, 500);
655
+ t.unref?.();
656
+ }
520
657
  /** @internal Calls held in memory, as request bodies for the local spool (called at exit). */
521
658
  _takeUnsentForSpool() {
522
659
  for (const item of this.awaitingMode) {
@@ -549,7 +686,17 @@ class FullCourtDefense {
549
686
  }
550
687
  /** @internal Send the calls spooled while the API was down and the queued records (called at `beforeExit`; the caller bounds the wait). */
551
688
  _flushForExit() {
552
- return Promise.all([this._flushSkippedChecks(), this.records.flush()]).then(() => undefined);
689
+ this.records.boost(EXIT_SENDERS);
690
+ return Promise.all([this._flushSkippedChecks(), this.records.flush(EXIT_FLUSH_MAX_MS, EXIT_FLUSH_MAX_MS)]).then(() => undefined);
691
+ }
692
+ /** @internal This client's shield (the end of the process groups leftovers by shield). */
693
+ _shieldIdForExit() {
694
+ return this.config.shieldId;
695
+ }
696
+ /** @internal The one direct gap report at the end of the process; true when the server took it. */
697
+ async _postExitReport(body, timeoutMs) {
698
+ const result = await this._postAgentSecurity(recordSpool_1.GAP_PATH, { agentName: this._identity.agentId, ...body }, undefined, timeoutMs);
699
+ return result.success === true;
553
700
  }
554
701
  /**
555
702
  * How the background record upload is doing (observability for the app and the load tests): records waiting, sent,
@@ -1350,7 +1497,8 @@ class FullCourtDefense {
1350
1497
  return this._postAgentSecurity('/api/agent-security/runtime/register-agent', input);
1351
1498
  }
1352
1499
  async recordToolCall(rawInput) {
1353
- return this._postAgentSecurity('/api/agent-security/runtime/tool-call', this.withIdentity(rawInput), 'full');
1500
+ const withId = rawInput.recordId ? rawInput : { ...rawInput, recordId: `r${(0, crypto_1.randomUUID)().replace(/-/g, '')}` };
1501
+ return this._postAgentSecurity('/api/agent-security/runtime/tool-call', this.withIdentity(withId), 'full');
1354
1502
  }
1355
1503
  async checkToolCall(rawInput) {
1356
1504
  const input = this.withIdentity(rawInput);
@@ -2051,7 +2199,7 @@ class FullCourtDefense {
2051
2199
  return this._postEncoded(path, encoded.json, timeoutMs);
2052
2200
  // A record: tracked while on the wire so the end of the process can wait for it briefly or spool it.
2053
2201
  const entry = { path, json: encoded.json, shieldId: this.config.shieldId, at: new Date().toISOString() };
2054
- const sending = this._postEncoded(path, encoded.json);
2202
+ const sending = this._postEncoded(path, encoded.json, timeoutMs);
2055
2203
  entry.done = sending;
2056
2204
  pendingRecords.add(entry);
2057
2205
  installExitHooks();
@@ -2059,8 +2207,19 @@ class FullCourtDefense {
2059
2207
  if (pendingRecords.delete(entry) && durable === 'full' && !result.success) {
2060
2208
  const noAnswer = typeof result.error === 'string' && result.error.startsWith('fcd_unavailable');
2061
2209
  const status = typeof result.status === 'number' ? result.status : undefined;
2062
- if (noAnswer || (status !== undefined && (status >= 500 || status === 408 || status === 429)))
2063
- keepFailed(entry);
2210
+ if (noAnswer || (status !== undefined && (status >= 500 || status === 408 || status === 429))) {
2211
+ // A record the server could not take goes to the batched queue, which sends it again with back-off while the process
2212
+ // runs (and keeps it at exit). Before, it waited for the next start (CI 2026-11-22: a burst lost records).
2213
+ const record = input;
2214
+ if (path === RECORD_PATH && !(record.actionId && record.outcome)) {
2215
+ const { shieldId: _drop, ...body } = record;
2216
+ void _drop;
2217
+ this._enqueueRecord(body);
2218
+ }
2219
+ else {
2220
+ keepFailed(entry);
2221
+ }
2222
+ }
2064
2223
  }
2065
2224
  return result;
2066
2225
  }
@@ -2071,12 +2230,23 @@ class FullCourtDefense {
2071
2230
  // when FullCourtDefense cannot be reached only once the agent itself reports it.
2072
2231
  if (this.failMode && this.failMode !== 'open')
2073
2232
  headers[failMode_1.FAIL_MODE_HEADER] = this.failMode;
2074
- const resp = await fetch(`${this.config.apiUrl}${path}`, {
2075
- method: 'POST',
2076
- headers,
2077
- body: json,
2078
- signal: AbortSignal.timeout(timeoutMs ?? this.config.scanTimeoutMs),
2079
- });
2233
+ // The request's own timeout, or the end of the process (exitAbort), whichever comes first (Node 18 has no AbortSignal.any).
2234
+ const controller = new AbortController();
2235
+ const limit = setTimeout(() => controller.abort(), timeoutMs ?? this.config.scanTimeoutMs);
2236
+ limit.unref?.();
2237
+ const onExit = () => controller.abort();
2238
+ if (exitAbort.signal.aborted)
2239
+ controller.abort();
2240
+ else
2241
+ exitAbort.signal.addEventListener('abort', onExit, { once: true });
2242
+ let resp;
2243
+ try {
2244
+ resp = await fetch(`${this.config.apiUrl}${path}`, { method: 'POST', headers, body: json, signal: controller.signal });
2245
+ }
2246
+ finally {
2247
+ clearTimeout(limit);
2248
+ exitAbort.signal.removeEventListener('abort', onExit);
2249
+ }
2080
2250
  const data = await resp.json().catch(() => ({}));
2081
2251
  if (!resp.ok) {
2082
2252
  // The runtime API's error body: { error, message?, code, category, retryable } (G-04).
@@ -2863,7 +2863,7 @@ function isSensitivePathContext(toolName, candidate) {
2863
2863
  // or when a language interpreter does and the program spawns a process.
2864
2864
  // `$( )` / a backtick pair in a double-quoted program still runs first.
2865
2865
  // Top-level stages only (not inside $( ) or backticks). See editCommandParts.
2866
- const DATA_TO_INTERPRETER = /\b(?:iex|icm|invoke-expression|invoke-command)\b|\[scriptblock\]::create\b|(?<![\w./\\]|[\w.]-)eval(?![\w./\\]|-\w)|\bxargs\b(?!(?:\s+(?:-[0prtx]+|--(?:null|no-run-if-empty|verbose|exit)|-[ILnPsdE]\s*[^\s;&|-][^\s;&|]*|--(?:replace|max-lines|max-args|max-procs|max-chars|delimiter|eof)=[^\s;&|]+))*\s+(?:sudo\s+)?(?:(?:e|f|z|ze|zf)?grep|rg|ugrep|ag|ack)(?:\.exe)?(?=\s|$))|\bbase64\b[^\n]*(?:-d\b|--decode\b)|frombase64string|-encodedcommand\b|\s-enc\s|(?<!\|)\|(?!\|)\s*&?\s*(?:sh|bash|zsh|dash|ksh|csh|pwsh|powershell(?:\.exe)?|cmd(?:\.exe)?|node|python[0-9.]*|perl|ruby)\b|\b(?:sh|bash|zsh|dash|ksh|csh|pwsh|powershell(?:\.exe)?|cmd(?:\.exe)?)\s+(?:-c|\/c|-e|-command|-scriptblock)\b|\b(?:ssh|wsl(?:\.exe)?|chroot)\b|\b(?:docker|kubectl|podman|nerdctl)(?:\.exe)?\s+(?:exec|run)\b/i;
2866
+ const DATA_TO_INTERPRETER = /\b(?:iex|icm|invoke-expression|invoke-command)\b|\[scriptblock\]::create\b|(?<![\w./\\]|[\w.]-)eval(?![\w./\\]|-\w)|\bxargs\b(?!(?:\s+(?:-[0prtx]+|--(?:null|no-run-if-empty|verbose|exit)|-[ILnPsdE]\s*[^\s;&|-][^\s;&|]*|--(?:replace|max-lines|max-args|max-procs|max-chars|delimiter|eof)=[^\s;&|]+))*\s+(?:sudo\s+)?(?:(?:e|f|z|ze|zf)?grep|rg|ugrep|ag|ack)(?:\.exe)?(?=\s|$))|\bbase64\b[^\n]*(?:-d\b|--decode\b)|frombase64string|-encodedcommand\b|\s-enc\s|(?<!\|)\|(?!\|)\s*&?\s*(?:sh|bash|zsh|dash|ksh|csh|pwsh|powershell(?:\.exe)?|cmd(?:\.exe)?|node|python[0-9.]*|perl|ruby|psql|mysql|mariadb|sqlite3|sqlcmd)\b|\b(?:sh|bash|zsh|dash|ksh|csh|pwsh|powershell(?:\.exe)?|cmd(?:\.exe)?)\s+(?:-c|\/c|-e|-command|-scriptblock)\b|\b(?:ssh|wsl(?:\.exe)?|chroot)\b|\b(?:docker|kubectl|podman|nerdctl)(?:\.exe)?\s+(?:exec|run)\b/i;
2867
2867
  // A LANGUAGE interpreter's `-c` / `-e` argument is CODE in another language, not
2868
2868
  // a shell command line. `node -e "console.log('rm -rf /')"` prints a string;
2869
2869
  // `python -c "print('DROP TABLE')"` prints a string. That code only reaches the
@@ -2967,6 +2967,42 @@ const INERT_DATA = ' fcd_inert_data ';
2967
2967
  // Code position immediately before a quoted span: interpreter code flags or a
2968
2968
  // remote/nested executor earlier in the same statement (no ; & | between).
2969
2969
  const CODE_CONTEXT_BEFORE = /(?:(?:^|[;&|(]|\s)(?:-c|\/c|-e|-command|-scriptblock|-filter|-q|--query|-query|--execute|--command|--eval)[= ]\s*|(?:^|[;&|(]\s*)(?:\S*[\\/])?(?:sudo\s+|doas\s+)?(?:ssh|wsl(?:\.exe)?|chroot|su|screen|tmux)(?:\s[^;&|"']*)?\s|(?:\S*[\\/])?(?:docker|kubectl|podman|nerdctl)(?:\.exe)?\s+(?:exec|run)\b[^;&|"']*\s)$/i;
2970
+ /** Programs whose bundled short flags end in their inline-code flag: shells and `su` (`-c`), SQL clients (`-c`, mysql `-e`). */
2971
+ const BUNDLED_CODE_FLAG_PROGRAMS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'su', 'psql', 'mysql', 'mariadb', 'sqlite3', 'sqlcmd']);
2972
+ /**
2973
+ * A bundled short-flag group ending in the inline-code flag right before a quoted span, on a shell or SQL client
2974
+ * (`psql -Atc "…"`, `bash -ec '…'`, `mysql -Ne "…"`): the same code position as `-c` (sdk-albtech 2026-11-22: a
2975
+ * customer's `psql -Atc "DROP DATABASE …"` read as prose). Only those programs, so a word flag (`find -exec`,
2976
+ * `pwsh -enc`) never qualifies. Plain character reads, no regex: a class added to CODE_CONTEXT_BEFORE costs the Rust
2977
+ * twin its fast path on hostile lines. Twin of `ends_with_bundled_code_flag` (inert.rs).
2978
+ */
2979
+ function endsWithBundledCodeFlag(before) {
2980
+ const space = (c) => c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\v' || c === '\f';
2981
+ let end = before.length;
2982
+ while (end > 0 && space(before[end - 1]))
2983
+ end--;
2984
+ if (end > 0 && before[end - 1] === '=')
2985
+ end--;
2986
+ else if (end === before.length || before[end] !== ' ')
2987
+ return false;
2988
+ let start = end;
2989
+ while (start > 0 && /^[A-Za-z]$/.test(before[start - 1]))
2990
+ start--;
2991
+ const letters = before.slice(start, end).toLowerCase();
2992
+ if (letters.length < 2 || letters.length > 5 || start === 0 || before[start - 1] !== '-')
2993
+ return false;
2994
+ const dash = start - 1;
2995
+ if (dash > 0 && !';&|('.includes(before[dash - 1]) && !space(before[dash - 1]))
2996
+ return false;
2997
+ let from = dash;
2998
+ while (from > 0 && !';&|(\n'.includes(before[from - 1]))
2999
+ from--;
3000
+ const programs = before.slice(from, dash).split(/[ \t\r\v\f]+/).map(word => word.replace(/^.*[\\/]/, '').replace(/\.exe$/i, '').toLowerCase());
3001
+ const program = programs.find(word => BUNDLED_CODE_FLAG_PROGRAMS.has(word));
3002
+ if (!program)
3003
+ return false;
3004
+ return letters.endsWith('c') || ((program === 'mysql' || program === 'mariadb') && letters.endsWith('e'));
3005
+ }
2970
3006
  // ---- search programs: the pattern operand is search text (invariant 6) ------
2971
3007
  /** Programs whose pattern operand is text to look for, never a command or a file. */
2972
3008
  const SEARCH_PATTERN_PROGRAMS = new Set(['grep', 'egrep', 'fgrep', 'zgrep', 'zegrep', 'zfgrep', 'rg', 'ugrep', 'ag', 'ack', 'findstr', 'select-string', 'sls']);
@@ -4401,7 +4437,7 @@ function stripQuotedData(text) {
4401
4437
  if (LANG_INTERPRETER_CODE_BEFORE.test(before))
4402
4438
  return interpreterCodeSpawnsProcess(before, body) || interpreterCodeRequestsMetadata(body) ? whole : INERT_DATA;
4403
4439
  // Code position: executes — unless it is a search program's own pattern operand (invariant 6).
4404
- if (CODE_CONTEXT_BEFORE.test(before) && !searchPatterns.isPattern(offset))
4440
+ if ((CODE_CONTEXT_BEFORE.test(before) || endsWithBundledCodeFlag(before)) && !searchPatterns.isPattern(offset))
4405
4441
  return whole;
4406
4442
  if (dq !== undefined && doubleQuotedInterpolates(body, powershell))
4407
4443
  return whole; // $( )/`cmd` executes first
@@ -53,7 +53,7 @@ export declare class RecordQueue {
53
53
  private readonly max;
54
54
  private readonly batch;
55
55
  private readonly maxBytes;
56
- private readonly concurrency;
56
+ private concurrency;
57
57
  private readonly delayMs;
58
58
  private readonly onDrop?;
59
59
  private readonly dropNoticeMs;
@@ -95,8 +95,10 @@ export declare class RecordQueue {
95
95
  private scheduleNotice;
96
96
  /** The API answered again (a bundle refresh): send now instead of waiting out the backoff. */
97
97
  resume(): void;
98
- /** One bounded attempt to send everything queued (exit, end of a serverless handler); never rejects, never waits past FLUSH_MAX_MS. */
99
- flush(maxMs?: number): Promise<void>;
98
+ /** More requests at once for the end of the process: its last records go out in parallel batches. */
99
+ boost(concurrency: number): void;
100
+ /** One bounded attempt to send everything queued (exit, end of a serverless handler); never rejects, never waits past `cap` (FLUSH_MAX_MS). */
101
+ flush(maxMs?: number, cap?: number): Promise<void>;
100
102
  /** Everything still queued, removed from the queue (handed to the local spool at exit). */
101
103
  drain(): QueuedRecord[];
102
104
  /** The gap not yet reported, removed (handed to the local spool at exit, so the next process reports it). */
@@ -137,8 +137,12 @@ class RecordQueue {
137
137
  if (this.items.length > 0 || this.unreportedLoss > 0)
138
138
  this.schedule(0);
139
139
  }
140
- /** One bounded attempt to send everything queued (exit, end of a serverless handler); never rejects, never waits past FLUSH_MAX_MS. */
141
- async flush(maxMs = exports.FLUSH_MAX_MS) {
140
+ /** More requests at once for the end of the process: its last records go out in parallel batches. */
141
+ boost(concurrency) {
142
+ this.concurrency = Math.max(this.concurrency, concurrency);
143
+ }
144
+ /** One bounded attempt to send everything queued (exit, end of a serverless handler); never rejects, never waits past `cap` (FLUSH_MAX_MS). */
145
+ async flush(maxMs = exports.FLUSH_MAX_MS, cap = exports.FLUSH_MAX_MS) {
142
146
  this.pausedUntil = 0;
143
147
  this.backoffMs = BACKOFF_MIN_MS;
144
148
  const work = (async () => {
@@ -154,7 +158,7 @@ class RecordQueue {
154
158
  }
155
159
  })().catch(() => undefined);
156
160
  let timer;
157
- await Promise.race([work, new Promise((resolve) => { timer = setTimeout(resolve, Math.max(0, Math.min(maxMs, exports.FLUSH_MAX_MS))); })]);
161
+ await Promise.race([work, new Promise((resolve) => { timer = setTimeout(resolve, Math.max(0, Math.min(maxMs, cap))); })]);
158
162
  if (timer !== undefined)
159
163
  clearTimeout(timer);
160
164
  }
@@ -5,11 +5,20 @@ export interface SpooledRecord {
5
5
  body: Record<string, unknown>;
6
6
  shieldId: string;
7
7
  at: string;
8
+ /** The exit gap that counts this record (the next start clears it as it delivers the record). */
9
+ gapId?: string;
8
10
  }
11
+ /** Route of a gap report (and of a pending gap's resolution). */
12
+ export declare const GAP_PATH = "/api/agent-security/runtime/tool-calls";
9
13
  /** The spool directory, or undefined when the spool is switched off or no home can be found. */
10
14
  export declare function spoolDir(): string | undefined;
11
15
  /** Write records for the next start. Synchronous (it runs at `exit`); never throws. */
12
- export declare function writeSpool(records: readonly SpooledRecord[]): void;
16
+ /**
17
+ * Write records for the next start; answers how many were kept. Every record that fits FILES_MAX files of
18
+ * RECORDS_PER_FILE_MAX is kept (#4087: it kept only the last 200 and lost the rest without a word); for the older ones
19
+ * that do not fit, one gap record per shield says how many, written first.
20
+ */
21
+ export declare function writeSpool(records: readonly SpooledRecord[]): number;
13
22
  /**
14
23
  * Take every spooled record of this shield (synchronous, cheap when the directory is absent). Files are
15
24
  * claimed by rename; records of other shields go back to a fresh file; files older than 7 days are dropped.
@@ -12,12 +12,34 @@
12
12
  // written; the replaying client uses its own. Bounds: 200 records per file, 20 files, 7 days.
13
13
  // FCD_SDK_SPOOL=off disables it; FCD_SDK_SPOOL_DIR moves it.
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.GAP_PATH = void 0;
15
16
  exports.spoolDir = spoolDir;
16
17
  exports.writeSpool = writeSpool;
17
18
  exports.claimSpooled = claimSpooled;
18
19
  const fs = require('fs');
19
20
  const os = require('os');
20
21
  const path = require('path');
22
+ /** Route of a gap report (and of a pending gap's resolution). */
23
+ exports.GAP_PATH = '/api/agent-security/runtime/tool-calls';
24
+ function packLines(lines) {
25
+ const files = [];
26
+ let current = [];
27
+ let size = 0;
28
+ for (const line of lines) {
29
+ if (line.length + 1 > FILE_BYTES_MAX)
30
+ continue;
31
+ if (current.length > 0 && (current.length >= RECORDS_PER_FILE_MAX || size + line.length + 1 > FILE_BYTES_MAX)) {
32
+ files.push(current);
33
+ current = [];
34
+ size = 0;
35
+ }
36
+ current.push(line);
37
+ size += line.length + 1;
38
+ }
39
+ if (current.length > 0)
40
+ files.push(current);
41
+ return files;
42
+ }
21
43
  const FILE_PREFIX = 'rec-';
22
44
  const RECORDS_PER_FILE_MAX = 200;
23
45
  const FILES_MAX = 20;
@@ -57,37 +79,59 @@ function listFiles(dir) {
57
79
  }
58
80
  }
59
81
  /** Write records for the next start. Synchronous (it runs at `exit`); never throws. */
82
+ /**
83
+ * Write records for the next start; answers how many were kept. Every record that fits FILES_MAX files of
84
+ * RECORDS_PER_FILE_MAX is kept (#4087: it kept only the last 200 and lost the rest without a word); for the older ones
85
+ * that do not fit, one gap record per shield says how many, written first.
86
+ */
60
87
  function writeSpool(records) {
61
88
  if (records.length === 0)
62
- return;
89
+ return 0;
90
+ let written = 0;
63
91
  try {
64
92
  const dir = spoolDir();
65
93
  if (!dir)
66
- return;
94
+ return 0;
67
95
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
68
- // Oldest files go first once the directory is full.
96
+ const lines = records.map((record) => JSON.stringify(record));
97
+ const shields = Array.from(new Set(records.map((record) => record.shieldId))).sort();
98
+ const room = FILES_MAX * RECORDS_PER_FILE_MAX - shields.length;
99
+ let keepFrom = 0;
100
+ let packed = packLines(lines);
101
+ while (packed.length > FILES_MAX - (keepFrom ? 1 : 0) || lines.length - keepFrom > room) {
102
+ keepFrom += Math.max(1, Math.floor((lines.length - keepFrom) / 20));
103
+ packed = packLines(lines.slice(keepFrom));
104
+ }
105
+ if (keepFrom > 0) {
106
+ const gaps = [];
107
+ for (const shieldId of shields) {
108
+ const lost = records.slice(0, keepFrom).filter((record) => record.shieldId === shieldId);
109
+ if (lost.length === 0)
110
+ continue;
111
+ const at = new Date().toISOString();
112
+ const gap = { dropped: lost.length, from: lost[0].at || at, to: lost[lost.length - 1].at || at, id: `gap-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}` };
113
+ gaps.push(JSON.stringify({ path: exports.GAP_PATH, body: { records: [], gap, shieldId }, shieldId, at }));
114
+ }
115
+ packed = [gaps, ...packed];
116
+ }
117
+ // Room for this process's files: the oldest files of earlier processes give way.
69
118
  const files = listFiles(dir);
70
- for (const name of files.slice(0, Math.max(0, files.length - (FILES_MAX - 1)))) {
119
+ for (const name of files.slice(0, Math.max(0, files.length - (FILES_MAX - packed.length)))) {
71
120
  try {
72
121
  fs.unlinkSync(path.join(dir, name));
73
122
  }
74
123
  catch { /* best effort */ }
75
124
  }
76
- let text = '';
77
- for (const record of records.slice(-RECORDS_PER_FILE_MAX)) {
78
- const line = JSON.stringify(record);
79
- if (text.length + line.length + 1 > FILE_BYTES_MAX)
80
- break;
81
- text += `${line}\n`;
82
- }
83
- if (!text)
84
- return;
85
- const name = `${FILE_PREFIX}${process.pid}-${Math.random().toString(36).slice(2, 10)}.jsonl`;
86
- fs.writeFileSync(path.join(dir, name), text, { mode: 0o600 });
125
+ const stamp = `${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
126
+ packed.forEach((chunk, index) => {
127
+ fs.writeFileSync(path.join(dir, `${FILE_PREFIX}${stamp}-${String(index).padStart(2, '0')}.jsonl`), `${chunk.join('\n')}\n`, { mode: 0o600 });
128
+ written += chunk.length;
129
+ });
87
130
  }
88
131
  catch {
89
132
  // a full disk or a read-only home never reaches the agent
90
133
  }
134
+ return written;
91
135
  }
92
136
  /**
93
137
  * Take every spooled record of this shield (synchronous, cheap when the directory is absent). Files are
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fullcourtdefense",
3
- "version": "2.3.0",
3
+ "version": "2.3.2",
4
4
  "description": "Control what your AI agents do: check every tool call against your company's FullCourtDefense policy (Monitor or Enforce).",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",