@staix/agent-mem 0.25.0 → 0.26.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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +6 -6
- package/package.json +1 -1
- package/src/hook-spool.ts +72 -10
- package/src/hooks.ts +5 -3
- package/src/ingest.ts +13 -5
- package/src/memory/bridge.ts +32 -7
- package/src/memory/capture-input.ts +152 -1
- package/src/memory/generation-index.ts +114 -50
- package/src/memory/inspection-bound.ts +27 -0
- package/src/memory/inspection-stream.ts +153 -0
- package/src/memory/metrics.ts +2 -2
- package/src/memory/platform.ts +18 -15
- package/src/memory/shard-bridge.ts +10 -5
- package/src/memory/store.ts +1 -1
- package/src/memory/sync-policy-inspection.ts +5 -4
- package/src/memory/sync-screen.ts +3 -3
- package/src/memory/sync.ts +26 -4
- package/src/session-brief-worker.ts +5 -2
- package/src/ui/plugin.ts +1 -1
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
|
|
4
4
|
|
|
5
5
|
<!-- facts:version -->
|
|
6
|
-
Version: 0.
|
|
6
|
+
Version: 0.26.1. Requires Bun 1.4.2 or later; no runtime dependencies.
|
|
7
7
|
<!-- /facts:version -->
|
|
8
8
|
|
|
9
9
|
## Quick start
|
|
@@ -119,7 +119,7 @@ The machine-local file `amem.config.json` in the memory home (see `amem status`
|
|
|
119
119
|
|
|
120
120
|
A repository may add `.amem/config` (same shape, only `denyPaths`, `piiPatterns`, `briefBytes`, `excerptBytes`, `capturePaths` and `records`). It can only narrow: its lists are added to yours and its budgets count only when lower. It cannot remove an entry, raise a budget, move the home or change the capture bounds, and any other key is an error (a malformed repository file stops amem in that repository until fixed; it never falls back to no policy). A stricter policy a host passes through the library always wins over both files.
|
|
121
121
|
|
|
122
|
-
On non-placement profiles, `amem sync` screens this machine's owned outbound segments before staging. One declined row refuses the whole sync and names its id (never its text); the log remains append-only. On active placement v3, permitted originals can publish while declined rows receive sticky holds, subject to the policy and dependency checks described under [placement activation](#initial-sync-placement-activation). Malformed or unavailable source metadata still fails closed. Other machines' segments are not the source of the non-placement outbound preflight.
|
|
122
|
+
On non-placement profiles with an explicit or configured remote, `amem sync` screens this machine's owned outbound segments before staging. A home without either remote returns its existing no-remote diagnostic before screening. One declined row refuses the whole sync and names its id (never its text); the log remains append-only. On active placement v3, permitted originals can publish while declined rows receive sticky holds, subject to the policy and dependency checks described under [placement activation](#initial-sync-placement-activation). Malformed or unavailable source metadata still fails closed. Other machines' segments are not the source of the non-placement outbound preflight.
|
|
123
123
|
|
|
124
124
|
`--policy-free` is still accepted by `promote`, `import`, `sync` and `review accept` so existing scripts keep working, and it means nothing more: the configured policy always applies. It does not bypass the secret screen or the sync remote's privacy checks. Forgetting a shared note appends an operation; its previous content remains in the remote's git history.
|
|
125
125
|
|
|
@@ -316,15 +316,15 @@ The standalone brief prioritizes open work lists, recent curated notes and then
|
|
|
316
316
|
|
|
317
317
|
Before optional work starts, the parent screens the complete hook input and bounded normalized capture fields, then closes and atomically publishes a private immutable record in `<memory-home>/hook-spool/`. It retains normalized capture data and a physical-cwd/scope stamp, never the raw native envelope or native argument vector. Non-SessionStart events use the fixed Bun `--smol` worker in a short-lived owned process group. The worker resolves the current project, rechecks scope, drains by a stable receipt, and acknowledges only after append or capture-spool publication. The parent reaps it, and it has its own deadline. SessionStart computes context in the already-running CLI, avoiding a second Bun boot. Its native metadata commands have owned shell supervisors with the same remaining deadline, an armed self-watchdog and group cleanup even if the CLI dies. A timeout leaves accepted capture pending for later replay; unresolved pending records never enter context.
|
|
318
318
|
|
|
319
|
-
Pending capture has an ordinary soft tier of 256 files/2 MiB and a separate private reserve of 32 files/256 KiB, admitted before optional recovery. Replay
|
|
319
|
+
Pending capture has an ordinary soft tier of 256 files/2 MiB and a separate private reserve of 32 files/256 KiB, admitted before optional recovery. Replay first processes the current cwd's records oldest-first across both tiers, then considers the newest eligible non-project rows from the same session. Both paths share the existing 32-file/256 KiB replay budget. A record replays only when its original non-null scope positively matches. Null scope is never adopted later, even with a physical cwd receipt: protecting project privacy takes priority over recovering an unattested event. Alias/profile/shard changes invalidate the derived identity cache and reader binding without changing pending scope. Positive fresh native project identity may still supply known-work context when pending scope is unknown; it does not authorize replay of those records.
|
|
320
320
|
|
|
321
|
-
Known-format pending records whose cwd is positively absent can retire after one hour (capture and file modification time must both exceed the grace). Other undrainable records keep the seven-day rule; a changed device/root/scope alone never proves cwd removal. Fair-share pressure can retire known-format records with a counted `scope_capacity` loss, while unknown/newer schemas retain seven-day protection. Each retirement persists numeric reason/count metrics before removing the body; a failed receipt leaves it pending. Retired bodies never become replay or context sources,
|
|
321
|
+
Known-format pending records whose cwd is positively absent can retire after one hour (capture and file modification time must both exceed the grace). Unattributed non-project records can also retire after that one-hour grace, or under a repository cwd's global-cap pressure, with the counted `nonproject_unattributed` reason. Other undrainable records keep the seven-day rule; a changed device/root/scope alone never proves cwd removal. Fair-share pressure can retire known-format records with a counted `scope_capacity` loss, while unknown/newer schemas retain seven-day protection. Each retirement persists numeric reason/count metrics before removing the body; a failed receipt leaves it pending. Retired bodies never become replay or context sources. A repository hook may attribute a non-project record only on an exact session match, with its original non-null scope still valid and current policy checks passing. Malformed publications still use bounded owned-file cleanup. See [the spool admission contract](docs/contracts.md#pending-spool-identity-and-admission-217) for identity, N-1 and retention details.
|
|
322
322
|
|
|
323
323
|
If both replayable tiers fill, or SessionStart's reserve alone fills, the current event can be dropped. The library receipt reports `dropped: true`, `dropReason: "spool_full"`, `dropCount: 1`, and the metric reports `captureDrops: 1` with `captureDropReason: "spool_full"`. Non-SessionStart native stdout remains empty. Native SessionStart emits only `hookSpecificOutput`, placing a bounded notice with reason counts from the last 200 metric samples after its untrusted-data header inside `additionalContext`, not in new top-level fields. These are rolling-window counts, not all-time totals. The header stays before all memory data even when the brief is otherwise unavailable; the optional trusted Record instruction precedes it. The combined instruction and context stay within the same byte bound. Finite-capacity and retirement losses are observable rather than reported as captured. Exact-once replay applies to positively bound retained records that can progress; unlimited lossless intake is not promised. Soft-cap overshoot, unpublished `.writing/` leftovers and power-loss durability retain the [contracts ceiling](docs/contracts.md#p3-hook-and-native-intake-boundaries-13).
|
|
324
324
|
|
|
325
325
|
SessionStart prioritizes known open work. Native curated notes use a private prebuilt section prepared after curated writes and sync, with current policy screening before work and whole-line output after work. Admission requires all writers to be upgraded and a person-raised `home` or `curated` floor of 0.24.0 or later; code never changes that floor. Below it, native curated stays deferred. Migration and profile/selector changes invalidate caches without rebuilding; a later curated write or explicit trigger prepares them. Only an unmarked person `amem brief` or an explicit off-hook host call to the root export `prepareCuratedBriefCache(base, project)` prepares a quiet project cache. The export is a write: it opens one selected store, reads at most four 32-row pages and writes one file up to 32 KiB. MCP, agent-marked CLI reads and library `sessionStartBrief()` never prepare it. A project with no curated writes and neither explicit trigger keeps native curated unavailable; mutations rebuild only their touched projects after invalidating old derived files. Missing and stale files report `curated cache missing` or `curated cache stale` without rebuilding. Profile/generation binding, selected-note expiry and a 24-hour age cap bound freshness; see [the curated cache contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228). Native capture uses the prebuilt Record/Recap/Compact section; raw chronological history remains a library source. Neither native cache path creates schema/FTS or repairs indexes. Missing/locked/incompatible sources are explicitly unavailable. The standalone `sessionStartBrief()` retains all its original sources. Recovery failure cannot discard a computed brief. Work and reader-lease host ports use zero busy-wait and cooperative deadline checks; ordinary library callers retain their original defaults, including 3,000 ms waits. No watcher, resident worker, model/network call, embedding job or vault access is added. Host policy callbacks remain unsupported by `runHook`, while the standalone brief composes them normally.
|
|
326
326
|
|
|
327
|
-
SessionStart admits directly to the reserve with at most 32 metadata entries and performs no active-tier scan or replay. Both tiers use per-cwd fair shares (64 active records, 8 reserve records), grouping together all HOME/scope variants of a cwd. Admission can retire native records from an overrepresented cwd, counting each loss as `scope_capacity` before removal. Accepted summaries survive same-cwd pressure; new summaries backpressure without advancing their transcript cursor. A fully verified foreign all-summary inventory can use counted `summary_capacity` eviction; otherwise it stays pending for replay. All admission maintenance shares a 32-file/256 KiB body-read bound; unknown/newer schemas retain their seven-day protection. Non-SessionStart hooks maintain and drain both tiers. This is bounded reserve admission, not O(1) accounting; an atomic slot-reservation protocol is the upgrade. Parent brief storage still contains synchronous filesystem/SQLite work between cooperative deadline checks; asynchronous/deadline-aware storage remains the upgrade, not a larger handler limit. The R2
|
|
327
|
+
SessionStart admits directly to the reserve with at most 32 metadata entries and performs no active-tier scan or replay. Both tiers use per-cwd fair shares (64 active records, 8 reserve records), grouping together all HOME/scope variants of a cwd. Admission can retire native records from an overrepresented cwd, counting each loss as `scope_capacity` before removal. Accepted summaries survive same-cwd pressure; new summaries backpressure without advancing their transcript cursor. A fully verified foreign all-summary inventory can use counted `summary_capacity` eviction; otherwise it stays pending for replay. All admission maintenance shares a 32-file/256 KiB body-read bound; unknown/newer schemas retain their seven-day protection. Non-SessionStart hooks maintain and drain both tiers. This is bounded reserve admission, not O(1) accounting; an atomic slot-reservation protocol is the upgrade. Parent brief storage still contains synchronous filesystem/SQLite work between cooperative deadline checks; asynchronous/deadline-aware storage remains the upgrade, not a larger handler limit. The default R2 wall limit remains 150 ms p95, with the scoped hosted-runner exceptions in [the R2 contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228), including 181 ms for hosted macOS M1 transcript hooks. The production handler budget remains 140 ms; the absolute 100 MB peak RSS was retired by #228 for a 150 MB per-invocation ceiling plus a per-runner baseline regression gate. Functional tests construct a programmatic host-only deadline; the actual executable exposes no environment or CLI deadline extension. Its exec-only boot-clock handoff can only shorten the deadline and is cleared before hook import. Dedicated budget scripts retain the actual CLI, original sample counts, cold attempt 0 and timeout/reaper assertions. The [P3 receipt](docs/p3-hook-budget-2026-10-23.md) identifies prior-head evidence separately from current acceptance; the current rework has no newly claimed both-OS green CI result.
|
|
328
328
|
|
|
329
329
|
A private admission cursor rotates bounded inspection across pending records (at most 32 files/256 KiB per pass), so a healthy first slice cannot indefinitely hide later removed/unknown entries from retirement checks. Git include/conditional identity dependencies are traversed within depth four and 16 files. Pending scope hashes relevant semantic project-identity values rather than unrelated full-config or HEAD churn; derived cache validity may additionally hash raw configuration/HEAD bytes. Unconditional and `gitdir` includes bind semantic identity values. Dynamic `onbranch`/`hasconfig` or unknown conditional trees without identity keys bind nothing; if they contain origin/rewrite/worktree identity keys, scope stays unknown. Native read-only identity may still supply known work, but it never adopts that pending capture; counted `scope_unknown` retirement needs seven days. This conservative ceiling is upgraded by evaluating `onbranch` against HEAD at drain time, not by adding a condition interpreter in this PR.
|
|
330
330
|
|
|
@@ -517,7 +517,7 @@ bun test
|
|
|
517
517
|
npm pack --dry-run
|
|
518
518
|
```
|
|
519
519
|
|
|
520
|
-
CI runs the typecheck, boundary check, README facts and documentation stamp checks and tests on Ubuntu and macOS with Bun 1.4.
|
|
520
|
+
CI runs the typecheck, boundary check, README facts and documentation stamp checks and tests on Ubuntu and macOS with Bun 1.4.4. Tests use synthetic fixtures and isolated homes, not personal memory stores.
|
|
521
521
|
|
|
522
522
|
## Publishing
|
|
523
523
|
|
package/package.json
CHANGED
package/src/hook-spool.ts
CHANGED
|
@@ -65,6 +65,19 @@ function physicalRoot(cwd: string): string {
|
|
|
65
65
|
return hash(`${stat.ino}:${stat.birthtimeMs}`);
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
/** #385: a cwd with no `.git` in itself or its ancestors (32 levels, the captureScope walk) belongs to no repository.
|
|
69
|
+
* Its per-directory fallback key is not a project the person works in. An unprovable walk, or a missing cwd (cwd_removed owns it), counts as a project cwd. */
|
|
70
|
+
function nonProjectCwd(cwd: string): boolean {
|
|
71
|
+
try {
|
|
72
|
+
if (!lstatSync(cwd).isDirectory()) return false;
|
|
73
|
+
for (let folder = cwd, depth = 0; depth < 32; depth++) {
|
|
74
|
+
if (lstatSync(join(folder, ".git"), { throwIfNoEntry: false })) return false;
|
|
75
|
+
const parent = dirname(folder); if (parent === folder) return true; folder = parent;
|
|
76
|
+
}
|
|
77
|
+
} catch { /* Unprovable ancestry keeps the ordinary per-cwd rules. */ }
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
|
|
68
81
|
function privateDirectory(dir: string): void {
|
|
69
82
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
70
83
|
const stat = lstatSync(dir);
|
|
@@ -536,6 +549,9 @@ function retireUnresolved(base: string, admittingCwd: string | undefined, invent
|
|
|
536
549
|
const match = namePattern.exec(row.name); if (match) groups.set(match[2]!, (groups.get(match[2]!) ?? 0) + 1);
|
|
537
550
|
}
|
|
538
551
|
const quota = () => cwdHash !== undefined && (groups.get(cwdHash) ?? 0) >= share;
|
|
552
|
+
// #385 AC3: a repository cwd under pressure may retire non-project rows; a non-project cwd never evicts for itself.
|
|
553
|
+
let admittingKnown: boolean | undefined; const orphans = new Map<string, boolean>();
|
|
554
|
+
const admittingProject = () => admittingCwd !== undefined && (admittingKnown ??= !nonProjectCwd(admittingCwd));
|
|
539
555
|
const pressure = () => cwdHash !== undefined && (quota() || count >= maximum || bytes + incomingBytes > byteMaximum);
|
|
540
556
|
const due = inventory.some(row => Date.now() - row.modified >= MISSING_CWD_AFTER_MS);
|
|
541
557
|
const pressured = pressure();
|
|
@@ -580,6 +596,13 @@ function retireUnresolved(base: string, admittingCwd: string | undefined, invent
|
|
|
580
596
|
try { lstatSync(record.value.cwd); }
|
|
581
597
|
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") reason = "cwd_removed"; }
|
|
582
598
|
}
|
|
599
|
+
// #385 route B: a non-project row that neither its own cwd's hook nor a same-session project hook drained within
|
|
600
|
+
// one hour retires with a counted reason; so does one crowding a repository cwd out of the global caps (never its own share).
|
|
601
|
+
if (!reason) {
|
|
602
|
+
if (!orphans.has(record.value.cwd)) orphans.set(record.value.cwd, nonProjectCwd(record.value.cwd));
|
|
603
|
+
if (orphans.get(record.value.cwd) && (age >= MISSING_CWD_AFTER_MS && Date.now() - row.modified >= MISSING_CWD_AFTER_MS
|
|
604
|
+
|| admittingProject() && (count >= maximum || bytes + incomingBytes > byteMaximum) && match[2] !== cwdHash)) reason = "nonproject_unattributed";
|
|
605
|
+
}
|
|
583
606
|
if (!reason && age >= RETIRE_AFTER_MS) {
|
|
584
607
|
if (record.value.scope === null) reason = "scope_unknown";
|
|
585
608
|
else {
|
|
@@ -786,8 +809,16 @@ function publishCapture(event: string, capture: NormalizedCaptureFields, options
|
|
|
786
809
|
if (!withinShare(reserved, CAPACITY_FILES) || reserved.length >= CAPACITY_FILES || reserved.reduce((sum, row) => sum + row.size, 0) + Buffer.byteLength(bytes) > CAPACITY_BYTES) throw new HookSpoolFull();
|
|
787
810
|
deferred = true; backlog = reserved.length > 0;
|
|
788
811
|
} else {
|
|
789
|
-
|
|
790
|
-
|
|
812
|
+
let inventory = activeInventory ?? entries(base);
|
|
813
|
+
const overCap = (rows: typeof inventory) => rows.length >= MAX_FILES || rows.reduce((sum, row) => sum + row.size, 0) + incomingBytes > MAX_BYTES;
|
|
814
|
+
if (summaryEvent(event) && (!withinShare(inventory, MAX_FILES) || overCap(inventory))) {
|
|
815
|
+
// #385 AC3: a repository cwd's summary first retires non-project rows that fill the shared caps.
|
|
816
|
+
// ponytail: one bounded maintenance pass (32 files); a cap of repository rows still refuses. Upgrade: a reserved non-project tier.
|
|
817
|
+
if (!withinShare(inventory, MAX_FILES) || nonProjectCwd(cwd)) throw new HookSpoolFull();
|
|
818
|
+
const freed = retireUnresolved(base, cwd, inventory, incomingBytes, false, false, maintenanceBudget());
|
|
819
|
+
inventory = inventory.filter(row => !freed.has(row.name));
|
|
820
|
+
if (overCap(inventory)) throw new HookSpoolFull();
|
|
821
|
+
}
|
|
791
822
|
let reserved = reserveInventory ?? entries(base, true);
|
|
792
823
|
// Split a nonempty two-tier backlog's inspection budget so neither tier starves.
|
|
793
824
|
const retired = retireUnresolved(base, cwd, inventory, incomingBytes, false, false, budget, reserved.length ? DRAIN_FILES / 2 : DRAIN_FILES);
|
|
@@ -833,7 +864,8 @@ export function hookCapturePending(base: string, name: string): boolean {
|
|
|
833
864
|
} catch { return true; } // Unreadable evidence is pending, never an acknowledgement.
|
|
834
865
|
}
|
|
835
866
|
|
|
836
|
-
|
|
867
|
+
/** `session` (a captureSessionKey) lets a repository cwd's hook attribute that session's non-project rows to its project (#385 route A). */
|
|
868
|
+
export async function drainHookCaptures(options: Options & { project: string; expectedScope?: string; current?: string; timeRemaining?: () => number; replayBudget?: HookReplayBudget; session?: string },
|
|
837
869
|
append: (input: CaptureInput, receipt: string) => CaptureAppend): Promise<{ captured: string[]; blocked: number }> {
|
|
838
870
|
const budget = options.replayBudget ?? hookReplayBudget();
|
|
839
871
|
if (!Number.isSafeInteger(budget.files) || budget.files < 0 || budget.files > HOOK_REPLAY_MAX_FILES
|
|
@@ -850,23 +882,53 @@ export async function drainHookCaptures(options: Options & { project: string; ex
|
|
|
850
882
|
const matching = (rows: ReturnType<typeof entries>, capacity: boolean) => rows.filter(row => {
|
|
851
883
|
const m = namePattern.exec(row.name); return m && m[2] === hash(cwd) && accepts(m[3]!);
|
|
852
884
|
}).sort((a, b) => a.modified - b.modified || a.name.localeCompare(b.name)).map(row => ({ ...row, capacity }));
|
|
853
|
-
const
|
|
854
|
-
|
|
885
|
+
const reserve = entries(base, true), active = entries(base), ownNonProject = nonProjectCwd(cwd);
|
|
886
|
+
const own = [...matching(reserve, true), ...matching(active, false)]
|
|
887
|
+
.sort((a, b) => a.modified - b.modified || a.name.localeCompare(b.name)).map(row => ({ ...row, foreign: false }));
|
|
888
|
+
// #385 route A: other-cwd rows after this cwd's own. Eligibility is decided before the loop and never spends a replay slot:
|
|
889
|
+
// one bounded decode per cwd group proves the cwd is non-project, so repository cwds' rows are skipped for free.
|
|
890
|
+
// ponytail: at most 32 newest foreign rows and 8 group probes per hook. Upgrade: an owned session cursor over the spool.
|
|
891
|
+
const groupNonProject = new Map<string, boolean>();
|
|
892
|
+
const eligibleGroup = (row: { name: string; capacity: boolean }, group: string): boolean => {
|
|
893
|
+
const known = groupNonProject.get(group); if (known !== undefined) return known;
|
|
894
|
+
if (groupNonProject.size >= 8) return false;
|
|
895
|
+
let probe: OwnedFile | undefined, ok = false;
|
|
896
|
+
try { probe = openOwned(join(row.capacity ? join(dir, ".capacity") : dir, row.name)); const value = decoded(probe)?.value; ok = !!value && hash(value.cwd) === group && nonProjectCwd(value.cwd); }
|
|
897
|
+
catch { /* Unreadable evidence is not eligible. */ } finally { if (probe) closeSync(probe.fd); }
|
|
898
|
+
groupNonProject.set(group, ok); return ok;
|
|
899
|
+
};
|
|
900
|
+
const foreign = options.session === undefined || ownNonProject ? [] : [...reserve.map(row => ({ ...row, capacity: true })), ...active.map(row => ({ ...row, capacity: false }))]
|
|
901
|
+
.filter(row => { const m = namePattern.exec(row.name); return m && m[2] !== hash(cwd); })
|
|
902
|
+
.sort((a, b) => b.modified - a.modified || a.name.localeCompare(b.name))
|
|
903
|
+
.filter(row => eligibleGroup(row, namePattern.exec(row.name)![2]!)).slice(0, DRAIN_FILES).map(row => ({ ...row, foreign: true }));
|
|
904
|
+
const rows = [...own, ...foreign];
|
|
855
905
|
const identity = (row: typeof rows[number]) => `${namePattern.exec(row.name)![1]}:${row.dev}:${row.ino}`;
|
|
856
906
|
let remaining = budget.bytes, blocked = 0;
|
|
857
|
-
for (const row of
|
|
907
|
+
for (const row of [...own.filter(row => !budget.seen.has(identity(row))).slice(0, budget.files), ...foreign.filter(row => !budget.seen.has(identity(row)))]) {
|
|
858
908
|
if (options.timeRemaining && options.timeRemaining() < 8 || row.size <= RECORD_BYTES && row.size > remaining) break;
|
|
859
909
|
const match = namePattern.exec(row.name)!, name = match[1]!;
|
|
860
|
-
|
|
910
|
+
// A foreign row is charged a replay slot only once it is proven attributable below (#385).
|
|
911
|
+
if (!row.foreign) { budget.files--; budget.seen.add(identity(row)); }
|
|
861
912
|
let file: OwnedFile | undefined;
|
|
862
913
|
try {
|
|
863
914
|
file = openOwned(join(row.capacity ? join(dir, ".capacity") : dir, row.name));
|
|
864
|
-
if (file.initial.size !== row.size || file.initial.mtimeMs !== row.modified) { blocked++; continue; }
|
|
915
|
+
if (file.initial.size !== row.size || file.initial.mtimeMs !== row.modified) { if (!row.foreign) blocked++; continue; }
|
|
916
|
+
let foreignCwd: string | undefined;
|
|
917
|
+
if (row.foreign) {
|
|
918
|
+
// Attribute only an exact session match from a non-project cwd whose recorded scope still holds; never claim another row.
|
|
919
|
+
if (file.initial.size > RECORD_BYTES || file.initial.size > remaining) continue;
|
|
920
|
+
const probe = decoded(file)?.value;
|
|
921
|
+
if (!probe || probe.scope === null || hash(probe.cwd) !== match[2] || probe.capture.session === undefined || probe.capture.session !== options.session
|
|
922
|
+
|| !nonProjectCwd(probe.cwd) || hookCaptureScope(probe.cwd, base) !== probe.scope) continue;
|
|
923
|
+
foreignCwd = probe.cwd;
|
|
924
|
+
if (budget.files <= 0) break;
|
|
925
|
+
budget.files--; budget.seen.add(identity(row));
|
|
926
|
+
}
|
|
865
927
|
const claim = claimOwned(base, row.name, file);
|
|
866
928
|
if (!claim) { blocked++; continue; }
|
|
867
929
|
if (claim.initial.size <= RECORD_BYTES) { remaining -= claim.initial.size; budget.bytes -= claim.initial.size; }
|
|
868
930
|
const record = decoded(claim);
|
|
869
|
-
if (!record || record.value.cwd !== cwd || record.value.scope !== match[3] || record.value.nonce !== match[4]) {
|
|
931
|
+
if (!record || record.value.cwd !== (foreignCwd ?? cwd) || record.value.scope !== match[3] || record.value.nonce !== match[4]) {
|
|
870
932
|
retireClaim(base, claim, false); blocked++; continue;
|
|
871
933
|
}
|
|
872
934
|
// #199: an unknown or newer schema stays claimed and pending (later passes reclaim it) until the TTL, then retires with a counted reason.
|
|
@@ -892,7 +954,7 @@ export async function drainHookCaptures(options: Options & { project: string; ex
|
|
|
892
954
|
...(c.tool === null ? {} : { tool: c.tool }), ...(c.status === null ? {} : { status: c.status }), excerpt: c.excerpt,
|
|
893
955
|
...(c.session === undefined ? {} : { session: c.session }), ...(c.subagent === undefined ? {} : { subagent: c.subagent }) };
|
|
894
956
|
if (!await policy.screen(value) || !await policy.screen(input)) { retireClaim(base, claim, true); blocked++; continue; }
|
|
895
|
-
if (!owns(claim) || hookCaptureScope(cwd, base) !== stamp || value.scope === legacyStamp && captureScope(cwd, base, false, undefined, true) !== legacyStamp) { blocked++; continue; }
|
|
957
|
+
if (!owns(claim) || hookCaptureScope(cwd, base) !== stamp || foreignCwd !== undefined && hookCaptureScope(foreignCwd, base) !== value.scope || value.scope === legacyStamp && captureScope(cwd, base, false, undefined, true) !== legacyStamp) { blocked++; continue; }
|
|
896
958
|
try {
|
|
897
959
|
append(input, hash(record.bytes));
|
|
898
960
|
}
|
package/src/hooks.ts
CHANGED
|
@@ -180,7 +180,7 @@ let hookStartedAt = performance.now();
|
|
|
180
180
|
* scans as soon as its first stdin line (scan options) arrives and drains after the second (the native receipt). At the
|
|
181
181
|
* deadline the parent kills it and waits at most REAP_BOUND_MS; a kill skips that call's drain (counted, never a drop).
|
|
182
182
|
* Host callbacks cannot cross this boundary; a host needing them calls sessionStartBrief in-process instead. */
|
|
183
|
-
async function hookWorker(options: HookOptions, base: string, deadline: number, pending: PendingHookCapture, event: string, transcript?: unknown): Promise<{ context: string; rssKB: number; rawRssKB: number; captured: boolean; valid: boolean; rssSources?: HookRssSources; transcript?: HookTranscriptProgress }> {
|
|
183
|
+
async function hookWorker(options: HookOptions, base: string, deadline: number, pending: PendingHookCapture, event: string, transcript?: unknown, session?: string): Promise<{ context: string; rssKB: number; rawRssKB: number; captured: boolean; valid: boolean; rssSources?: HookRssSources; transcript?: HookTranscriptProgress }> {
|
|
184
184
|
const workDeadline = deadline - WORKER_CLEANUP_MS;
|
|
185
185
|
if (options.policy?.host || workDeadline - performance.now() < 5) return { context: unavailable, rssKB: 0, rawRssKB: 0, captured: false, valid: false };
|
|
186
186
|
const early = transcript !== undefined;
|
|
@@ -233,7 +233,7 @@ async function hookWorker(options: HookOptions, base: string, deadline: number,
|
|
|
233
233
|
result.rssSources.unavailable++;
|
|
234
234
|
// The worker reads the configuration itself (same base, same cwd), so it screens with exactly the policy the parent did.
|
|
235
235
|
// Without a receipt the worker still finishes the scan and reports it, but drains nothing.
|
|
236
|
-
send({ cwd: options.cwd, base, current: pending.name, event, identity: metadata.receipt, maxTokens, ownedGroup: true, deadlineAt: performance.timeOrigin + workDeadline, hookStartAt: performance.timeOrigin + hookStartedAt, policy });
|
|
236
|
+
send({ cwd: options.cwd, base, current: pending.name, event, identity: metadata.receipt, maxTokens, ownedGroup: true, deadlineAt: performance.timeOrigin + workDeadline, hookStartAt: performance.timeOrigin + hookStartedAt, policy, ...(session ? { session } : {}) });
|
|
237
237
|
close();
|
|
238
238
|
const answer = await Promise.race([
|
|
239
239
|
Promise.all([exit!, output!]),
|
|
@@ -354,7 +354,9 @@ async function captureAndWork(event: string, input: unknown, options: HookOption
|
|
|
354
354
|
// exits keep reporting nothing, so they cannot pass for bounded progress.
|
|
355
355
|
const deadlineEvidence = () => transcript !== undefined && deadline - WORKER_CLEANUP_MS - performance.now() < 5;
|
|
356
356
|
const withDeadline = <T extends { transcript?: HookTranscriptProgress }>(value: T): T => value.transcript === undefined && deadlineEvidence() ? { ...value, transcript: { stopReason: "deadline" } } : value;
|
|
357
|
-
|
|
357
|
+
// #385: the hashed session key lets a repository cwd's drain attribute this session's non-project rows.
|
|
358
|
+
const session = captureSessionKey(input !== null && typeof input === "object" ? (input as { session_id?: unknown }).session_id : undefined);
|
|
359
|
+
const work = async (pending: PendingHookCapture) => withDeadline(await hookWorker({ ...options, cwd: pending.cwd }, base, deadline, pending, event, transcript, session));
|
|
358
360
|
let result: Awaited<ReturnType<typeof work>> | undefined;
|
|
359
361
|
let pending: PendingHookCapture | undefined;
|
|
360
362
|
try { pending = await stageHookCapture(event, input, { ...options, base, deferAtCapacity: true }); }
|
package/src/ingest.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { memoryHome } from "./memory/home.ts";
|
|
|
8
8
|
import { canonicalPath, processLiveness, processSignature, realPath } from "./memory/platform.ts";
|
|
9
9
|
import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
|
|
10
10
|
import { configuredPolicyOptions, recordsEnabled } from "./memory/config.ts";
|
|
11
|
-
import { captureSessionKey } from "./memory/capture-input.ts";
|
|
11
|
+
import { captureSessionKey, withholdToolArguments } from "./memory/capture-input.ts";
|
|
12
12
|
import { drainHookCaptures, stageTranscriptCapture } from "./hook-spool.ts";
|
|
13
13
|
import { recordIntakeCounts, recordRefusal, type RecordIntakeCounts, type RecordDropReason } from "./hook-record.ts";
|
|
14
14
|
import { IngestRecordReader, recordMainHeader, type NativeRecordTurn } from "./ingest-records.ts";
|
|
@@ -243,7 +243,7 @@ function extractQwen(raw: Record<string, any>, project: string): CaptureInput |
|
|
|
243
243
|
if (typeof part.text === "string") { if (part.text) { excerpts.push(part.text); events.push("message"); } }
|
|
244
244
|
else if (object(part.functionCall)) {
|
|
245
245
|
const call = part.functionCall;
|
|
246
|
-
excerpts.push(JSON.stringify({ functionCall: { name: call.name, ...(call.id !== undefined ? { id: call.id } : {}), ...(call.args !== undefined ? { args: call.args } : {}) } }));
|
|
246
|
+
excerpts.push(withholdToolArguments(JSON.stringify({ functionCall: { name: call.name, ...(call.id !== undefined ? { id: call.id } : {}), ...(call.args !== undefined ? { args: call.args } : {}) } })));
|
|
247
247
|
tools.push(call.name); events.push("function_call");
|
|
248
248
|
} else if (object(part.functionResponse)) {
|
|
249
249
|
const response = part.functionResponse;
|
|
@@ -263,7 +263,7 @@ function extract(kind: IngestKind, raw: Record<string, any>, project: string): C
|
|
|
263
263
|
: kind === "kimi" && raw.type === "context.append_message" ? raw.message : undefined;
|
|
264
264
|
if (!object(message)) return undefined;
|
|
265
265
|
if (kind === "codex" && ["function_call", "function_call_output"].includes(message.type)) {
|
|
266
|
-
const excerpt = typeof message.arguments === "string" ? message.arguments : typeof message.output === "string" ? message.output : "";
|
|
266
|
+
const excerpt = typeof message.arguments === "string" ? withholdToolArguments(message.arguments) : typeof message.output === "string" ? message.output : "";
|
|
267
267
|
return { project, agent: kind, event: message.type, ...(typeof message.name === "string" ? { tool: message.name.slice(0, 64) } : {}), excerpt: excerpt.slice(0, 2000) };
|
|
268
268
|
}
|
|
269
269
|
if (!["assistant", "user", "tool", "toolResult"].includes(message.role)) return undefined;
|
|
@@ -404,6 +404,8 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
|
|
|
404
404
|
}
|
|
405
405
|
return mainHeader;
|
|
406
406
|
};
|
|
407
|
+
// #369 N1: receipts this call counted as `staged` and has not yet seen drained; bounded by this call's Records.
|
|
408
|
+
const freshThisCall = new Set<string>();
|
|
407
409
|
const intakeRecords = async (turns: NativeRecordTurn[]) => {
|
|
408
410
|
for (const turn of turns) {
|
|
409
411
|
const stagedReceipts = new Map<string, { fresh: boolean; checked: boolean; current: () => void }>();
|
|
@@ -438,15 +440,21 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
|
|
|
438
440
|
// duplicate; the exact-duplicate witness is the only signal that this call added nothing.
|
|
439
441
|
if (pending.duplicate) recordCounts.duplicatesSkipped++; else recordCounts.staged++;
|
|
440
442
|
if (!stagedReceipts.has(pending.receipt)) stagedReceipts.set(pending.receipt, { fresh: !pending.duplicate, checked: false, current });
|
|
443
|
+
if (!pending.duplicate) freshThisCall.add(pending.receipt);
|
|
441
444
|
}
|
|
442
445
|
if (stagedReceipts.size) await drainHookCaptures({ cwd, base, project, policy: options.policy }, (input, receipt) => {
|
|
443
446
|
const staged = stagedReceipts.get(receipt);
|
|
444
447
|
staged?.current();
|
|
445
448
|
const appended = capture!.append(input, { receipt });
|
|
446
|
-
|
|
449
|
+
const already = "already" in appended && appended.already;
|
|
450
|
+
if (staged && !staged.checked && staged.fresh && already) {
|
|
451
|
+
recordCounts.staged--; recordCounts.duplicatesSkipped++;
|
|
452
|
+
} else if (!staged && already && freshThisCall.delete(receipt)) {
|
|
453
|
+
// #369 N1: a Record this call counted as staged in an earlier turn, drained here, was already stored. The append
|
|
454
|
+
// result is the witness, so no second store read. A Record this call never found leaves its counts unchanged.
|
|
447
455
|
recordCounts.staged--; recordCounts.duplicatesSkipped++;
|
|
448
456
|
}
|
|
449
|
-
if (staged) staged.checked = true;
|
|
457
|
+
if (staged) { staged.checked = true; freshThisCall.delete(receipt); }
|
|
450
458
|
return appended;
|
|
451
459
|
});
|
|
452
460
|
}
|
package/src/memory/bridge.ts
CHANGED
|
@@ -6,10 +6,13 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
6
6
|
import { memoryGitArgv, memoryGitEnv, realPath } from "./platform.ts";
|
|
7
7
|
import { canonicalJSON, fsyncDirectory, readProfileJSON, writeProfileJSON } from "./generation.ts";
|
|
8
8
|
import { OP_CONTRACTS } from "./ops-contract.ts";
|
|
9
|
+
import type { InspectionBound } from "./inspection-bound.ts";
|
|
9
10
|
import { entryId, type Entry } from "./store.ts";
|
|
10
11
|
|
|
11
12
|
export interface LegacyCheckpoint { source: string; path: string; offset: number; hash: string; commit?: string; tailBytes?: number; stamp?: string }
|
|
12
13
|
export interface LegacySegment extends LegacyCheckpoint { bytes: Buffer; local: boolean; tailBytes: number; start?: number }
|
|
14
|
+
/** A readonly body visitor returns pinned metadata only; source bytes are never retained by the bridge. */
|
|
15
|
+
export type LegacySegmentInspector = (file: string, context: { source: string; path: string; local: boolean; commit?: string }, prior?: LegacyCheckpoint) => LegacySegment;
|
|
13
16
|
export interface LegacySnapshotOptions {
|
|
14
17
|
generation?: string;
|
|
15
18
|
commit?: string;
|
|
@@ -40,7 +43,7 @@ function directory(path: string, optional = false): boolean {
|
|
|
40
43
|
|
|
41
44
|
export class SegmentReadBudgetError extends Error {
|
|
42
45
|
readonly code = "retained_read_budget";
|
|
43
|
-
constructor() { super("retained history unavailable within the read byte budget"); this.name = "SegmentReadBudgetError"; }
|
|
46
|
+
constructor(readonly bound?: InspectionBound) { super("retained history unavailable within the read byte budget"); this.name = "SegmentReadBudgetError"; }
|
|
44
47
|
}
|
|
45
48
|
export interface SegmentReadMetrics { bytesRead: number; bytesHashed: number; coldChanged: number }
|
|
46
49
|
interface PrefixState { offset: number; hash: string; hasher: Hash; bytes: Buffer }
|
|
@@ -73,7 +76,8 @@ export class SegmentReader {
|
|
|
73
76
|
* Upgrade with a separately budgeted catalog proof if valid profiles need a larger metadata frontier.
|
|
74
77
|
*/
|
|
75
78
|
reserveSourceFiles(count: number): void {
|
|
76
|
-
if (!Number.isSafeInteger(count) || count < 0
|
|
79
|
+
if (!Number.isSafeInteger(count) || count < 0) failure();
|
|
80
|
+
if (count > this.remainingFiles) throw new SegmentReadBudgetError({ kind: "source-files", limit: this.sourceFileLimit!, observed: this.sourceFileLimit! - this.remainingFiles + count });
|
|
77
81
|
this.remainingFiles -= count;
|
|
78
82
|
}
|
|
79
83
|
listFiles(dir: string): string[] {
|
|
@@ -92,7 +96,7 @@ export class SegmentReader {
|
|
|
92
96
|
const stamp = statStamp(before), size = Number(before.size);
|
|
93
97
|
if (prior && size < prior.offset) failure();
|
|
94
98
|
if (!full && prior?.stamp === stamp) return { bytes: Buffer.alloc(0), start: prior.offset, offset: prior.offset, hash: prior.hash, tailBytes: size - prior.offset, stamp };
|
|
95
|
-
if (size > this.remainingSourceBytes) throw new SegmentReadBudgetError();
|
|
99
|
+
if (size > this.remainingSourceBytes) throw new SegmentReadBudgetError({ kind: "bytes", limit: this.sourceByteLimit!, observed: this.sourceBytes + size });
|
|
96
100
|
this.remainingSourceBytes -= size; this.sourceBytes += size;
|
|
97
101
|
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
98
102
|
try {
|
|
@@ -109,7 +113,7 @@ export class SegmentReader {
|
|
|
109
113
|
if (!read(end).equals(bytes) || fstatSync(fd, { bigint: true }).size < opened.size) failure();
|
|
110
114
|
// Count physical nonblank source rows before any canonical source map can grow.
|
|
111
115
|
if (this.remainingRows !== Infinity) for (const line of completeLines(bytes)) if (line.toString("utf8").trim()) {
|
|
112
|
-
if (this.remainingRows < 1) throw new SegmentReadBudgetError();
|
|
116
|
+
if (this.remainingRows < 1) throw new SegmentReadBudgetError({ kind: "rows", limit: this.sourceRows, observed: this.sourceRows + 1 });
|
|
113
117
|
this.remainingRows--; this.sourceRows++;
|
|
114
118
|
}
|
|
115
119
|
const after = lstatSync(path, { bigint: true });
|
|
@@ -211,10 +215,17 @@ export function legacyEntries(segments: readonly LegacySegment[], options: { str
|
|
|
211
215
|
return [...rows.values()];
|
|
212
216
|
}
|
|
213
217
|
|
|
218
|
+
function inspectArchivedSegment(inspect: LegacySegmentInspector, file: string, context: { source: string; path: string; local: boolean; commit: string }, prior: LegacyCheckpoint | undefined, expected: { offset: number; hash: string; tailBytes: number }): LegacySegment {
|
|
219
|
+
const data = inspect(file, context, prior);
|
|
220
|
+
if (data.offset !== expected.offset || data.hash !== expected.hash || data.tailBytes || expected.tailBytes) failure();
|
|
221
|
+
return data;
|
|
222
|
+
}
|
|
223
|
+
|
|
214
224
|
/** Raw authoritative inputs only: never constructs a legacy store, opens its index or performs network I/O. */
|
|
215
|
-
function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[] {
|
|
225
|
+
function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: LegacySegmentInspector): LegacySegment[] {
|
|
216
226
|
const root = realPath(homeM);
|
|
217
227
|
directory(root);
|
|
228
|
+
if (inspect && (options.incremental || options.limits)) failure();
|
|
218
229
|
const checkpoints = checkpointMap(options.checkpoints), limits = options.limits === undefined ? undefined : checkpointMap(options.limits);
|
|
219
230
|
const result: LegacySegment[] = [];
|
|
220
231
|
const accept = (source: string, path: string, complete: Buffer, commit?: string, tailBytes = 0, stamp?: string) => {
|
|
@@ -242,6 +253,10 @@ function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[
|
|
|
242
253
|
const path = `${folder}/${name}`;
|
|
243
254
|
if (!segmentPath(path)) failure();
|
|
244
255
|
if (folder === "local" && name !== `${machineId}.jsonl`) continue;
|
|
256
|
+
if (inspect) {
|
|
257
|
+
result.push(inspect(join(dir, name), { source: diskSource, path, local: folder === "local" }, checkpoints.get(`${diskSource}:${path}`)));
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
245
260
|
const reader = options.reader ?? new SegmentReader();
|
|
246
261
|
const incremental = options.incremental && !limits;
|
|
247
262
|
const data = reader.read(join(dir, name), incremental ? checkpoints.get(`${diskSource}:${path}`) : undefined, !incremental);
|
|
@@ -258,6 +273,11 @@ function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[
|
|
|
258
273
|
directory(join(archiveDir(root, options.generation, commit), "log"));
|
|
259
274
|
for (const prior of new Set([...(options.previousCommit ? [options.previousCommit] : []), ...[...checkpoints.values()].filter(row => row.source === remoteSource).map(row => row.commit!)])) if (!archivedAncestor(root, options.generation, prior, commit, options.reader?.sourceByteLimit)) failure();
|
|
260
275
|
for (const segment of manifest.segments) {
|
|
276
|
+
if (inspect) {
|
|
277
|
+
result.push(inspectArchivedSegment(inspect, join(archiveDir(root, options.generation, commit), segment.path),
|
|
278
|
+
{ source: remoteSource, path: segment.path, local: false, commit }, checkpoints.get(`${remoteSource}:${segment.path}`), segment));
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
261
281
|
const reader = options.reader ?? new SegmentReader(), incremental = options.incremental && !limits;
|
|
262
282
|
const data = reader.read(join(archiveDir(root, options.generation, commit), segment.path), incremental ? checkpoints.get(`${remoteSource}:${segment.path}`) : undefined, !incremental, true);
|
|
263
283
|
if (data.offset !== segment.offset || data.hash !== segment.hash || data.tailBytes) failure();
|
|
@@ -268,6 +288,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[
|
|
|
268
288
|
}
|
|
269
289
|
const returned = new Set(result.map(key));
|
|
270
290
|
for (const receipt of [...checkpoints.values(), ...(limits?.values() ?? [])]) if (!returned.has(key(receipt))) failure();
|
|
291
|
+
if (inspect) return result; // The visitor strictly validates each complete row and every checkpoint prefix while streaming.
|
|
271
292
|
// Checkpointed complete prefixes were already validated; their full hashes prove unchanged bytes.
|
|
272
293
|
// Only newly completed suffixes need parsing on an incremental read.
|
|
273
294
|
const suffixes = result.map(segment => {
|
|
@@ -285,7 +306,7 @@ function capturedIdentity(path: string, maximum?: number): string {
|
|
|
285
306
|
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
286
307
|
try {
|
|
287
308
|
const stat = fstatSync(fd);
|
|
288
|
-
if (maximum !== undefined && (before.size > maximum || stat.size > maximum)) throw new SegmentReadBudgetError();
|
|
309
|
+
if (maximum !== undefined && (before.size > maximum || stat.size > maximum)) throw new SegmentReadBudgetError({ kind: "metadata-bytes", limit: maximum, observed: Math.max(before.size, stat.size) });
|
|
289
310
|
if (stat.dev !== before.dev || stat.ino !== before.ino || stat.size > (maximum ?? 4096)) failure();
|
|
290
311
|
if (maximum !== undefined && (stat.size !== before.size || stat.mtimeMs !== before.mtimeMs || stat.ctimeMs !== before.ctimeMs)) failure();
|
|
291
312
|
const bytes = Buffer.alloc(stat.size);
|
|
@@ -327,6 +348,10 @@ function head(homeM: string, generation: string, maximumArchiveBytes?: number, m
|
|
|
327
348
|
export function readLegacySnapshot(homeM: string, options: LegacySnapshotOptions = {}): LegacySegment[] {
|
|
328
349
|
try { return snapshot(homeM, options); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
|
|
329
350
|
}
|
|
351
|
+
/** Read-only enumeration reuses the legacy frontier checks without retaining source bodies or refreshing an index. */
|
|
352
|
+
export function inspectLegacySnapshot(homeM: string, options: LegacySnapshotOptions, inspect: LegacySegmentInspector): LegacySegment[] {
|
|
353
|
+
return snapshot(homeM, options, inspect);
|
|
354
|
+
}
|
|
330
355
|
export function legacyHead(homeM: string, generation: string, maximumArchiveBytes?: number, maximumArchiveSegments?: number): string | undefined {
|
|
331
356
|
try { return head(homeM, generation, maximumArchiveBytes, maximumArchiveSegments); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
|
|
332
357
|
}
|
|
@@ -351,7 +376,7 @@ function archived(root: string, generation: string, commit: string, maximumBytes
|
|
|
351
376
|
const file = join(archiveDir(root, generation, commit), "snapshot.json");
|
|
352
377
|
const value = (maximumBytes === undefined ? readProfileJSON(file, 32 * 1024 * 1024) : JSON.parse(capturedIdentity(file, Math.min(maximumBytes, 32 * 1024 * 1024)))) as LegacyArchive | undefined;
|
|
353
378
|
if (!value || value.schema !== "agent-mem.legacy-snapshot/v1" || value.generation !== generation || value.commit !== commit || value.previousCommit !== undefined && !commitId(value.previousCommit) || !Array.isArray(value.segments)) failure();
|
|
354
|
-
if (maximumSegments !== undefined && value.segments.length > maximumSegments) throw new SegmentReadBudgetError();
|
|
379
|
+
if (maximumSegments !== undefined && value.segments.length > maximumSegments) throw new SegmentReadBudgetError({ kind: "source-files", limit: maximumSegments, observed: value.segments.length });
|
|
355
380
|
const paths = new Set<string>();
|
|
356
381
|
for (const segment of value.segments) {
|
|
357
382
|
if (!segment || !segmentPath(segment.path) || !segment.path.startsWith("log/") || paths.has(segment.path) || !Number.isSafeInteger(segment.offset) || segment.offset < 0 || !/^[a-f0-9]{64}$/.test(segment.hash) || !Number.isSafeInteger(segment.tailBytes) || segment.tailBytes < 0) failure();
|
|
@@ -52,6 +52,157 @@ export function clipCaptureUtf8(text: string, maximumBytes: number): string {
|
|
|
52
52
|
return out;
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
interface CommandWord { end: number; text: string; complete: boolean; dynamic: boolean }
|
|
56
|
+
const commandBreak = (c: string): boolean => /[\s;&|()<>]/.test(c);
|
|
57
|
+
const assignmentWord = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
58
|
+
|
|
59
|
+
/** Read one literal shell word without executing expansions; offsets refer to the unchanged input. */
|
|
60
|
+
function commandWord(command: string, start: number): CommandWord {
|
|
61
|
+
let i = start, text = "", quote = "", dynamic = false;
|
|
62
|
+
for (; i < command.length; i++) {
|
|
63
|
+
const c = command[i]!;
|
|
64
|
+
if (!quote && commandBreak(c)) break;
|
|
65
|
+
if (c === quote) { quote = ""; continue; }
|
|
66
|
+
if (!quote && (c === "'" || c === '"')) { quote = c; continue; }
|
|
67
|
+
if (c === "\\" && quote !== "'") {
|
|
68
|
+
const next = command[i + 1];
|
|
69
|
+
if (next === undefined) return { end: command.length, text, complete: false, dynamic };
|
|
70
|
+
if (!quote || /["\\$`\n]/.test(next)) { i++; if (next !== "\n") text += next; continue; }
|
|
71
|
+
}
|
|
72
|
+
if (quote !== "'" && (c === "$" || c === "`")) dynamic = true;
|
|
73
|
+
text += c;
|
|
74
|
+
}
|
|
75
|
+
return { end: i, text, complete: !quote, dynamic };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Withhold ahub answer provenance before any capture cap. Only literal command words are interpreted, never a shell.
|
|
80
|
+
* ponytail: direct commands and shell lists only; computed program names/wrapper scripts need a shell parser contract.
|
|
81
|
+
* Once an answer is recognized, ambiguous quoting, expansions or redirection withhold its entire remaining tail.
|
|
82
|
+
*/
|
|
83
|
+
export function withholdAnswerCommand(command: string): string {
|
|
84
|
+
let i = 0, copied = 0, out = "", state: "program" | "subcommand" | "answer" | "other" = "program", answerPrefix = "";
|
|
85
|
+
const replace = (start: number, end: number, value: string) => { out += command.slice(copied, start) + value; copied = end; };
|
|
86
|
+
while (i < command.length) {
|
|
87
|
+
const c = command[i]!;
|
|
88
|
+
if (c === "\n" || /[;&|()]/.test(c)) { state = "program"; i++; continue; }
|
|
89
|
+
if (/\s/.test(c)) { i++; continue; }
|
|
90
|
+
if (c === "#") { const end = command.indexOf("\n", i); i = end < 0 ? command.length : end; continue; }
|
|
91
|
+
if (c === "<" || c === ">") {
|
|
92
|
+
if (state === "answer") return answerPrefix + " [withheld]";
|
|
93
|
+
state = "other"; i++; continue;
|
|
94
|
+
}
|
|
95
|
+
const start = i, word = commandWord(command, i); i = word.end;
|
|
96
|
+
if (state === "answer" && (!word.complete || word.dynamic)) return answerPrefix + " [withheld]";
|
|
97
|
+
if (state === "program" && word.complete && assignmentWord.test(command.slice(start, i))) continue;
|
|
98
|
+
if (state === "program") { state = word.complete && !word.dynamic && /^(?:.*\/)?ahub$/.test(word.text) ? "subcommand" : "other"; continue; }
|
|
99
|
+
if (state === "subcommand") {
|
|
100
|
+
state = word.complete && !word.dynamic && word.text === "answer" ? "answer" : "other";
|
|
101
|
+
if (state === "answer") answerPrefix = out + command.slice(copied, i);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (state !== "answer") continue;
|
|
105
|
+
const flag = /^(--(?:instructed|other))(=|$)/.exec(word.text);
|
|
106
|
+
if (!flag) continue;
|
|
107
|
+
if (flag[2] === "=") { replace(start, i, `${flag[1]}=[withheld]`); continue; }
|
|
108
|
+
while (i < command.length && /[^\S\n]/.test(command[i]!)) i++;
|
|
109
|
+
if (i === command.length || commandBreak(command[i]!) || command[i] === "#") return answerPrefix + " [withheld]";
|
|
110
|
+
const value = commandWord(command, i);
|
|
111
|
+
if (!value.complete || value.dynamic || value.text.startsWith("--")) return answerPrefix + " [withheld]";
|
|
112
|
+
replace(i, value.end, "[withheld]"); i = value.end;
|
|
113
|
+
}
|
|
114
|
+
return out + command.slice(copied);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Recover only JSON string boundaries in a truncated argument envelope; never execute or trust its structure. */
|
|
118
|
+
function withholdUnparsedArguments(text: string): string {
|
|
119
|
+
const direct = withholdAnswerCommand(text);
|
|
120
|
+
if (direct !== text) return direct;
|
|
121
|
+
if (!/^\s*[\[{]/.test(text)) return text;
|
|
122
|
+
const containers: ("program" | "subcommand" | "answer" | "other" | null)[] = [];
|
|
123
|
+
for (let i = 0; i < text.length; i++) {
|
|
124
|
+
const c = text[i]!;
|
|
125
|
+
const top = containers.length - 1;
|
|
126
|
+
if (c === "[" || c === "{") {
|
|
127
|
+
if (containers[top] === "program" || containers[top] === "subcommand") containers[top] = "other";
|
|
128
|
+
containers.push(c === "[" ? "program" : null); continue;
|
|
129
|
+
}
|
|
130
|
+
if (c === "]" || c === "}") { containers.pop(); continue; }
|
|
131
|
+
if (c !== '"') {
|
|
132
|
+
if (!/[\s,:]/.test(c) && (containers[top] === "program" || containers[top] === "subcommand")) containers[top] = "other";
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
const start = i++;
|
|
136
|
+
let escaped = false;
|
|
137
|
+
for (; i < text.length; i++) {
|
|
138
|
+
if (!escaped && text[i] === '"') break;
|
|
139
|
+
if (!escaped && text[i] === "\\") escaped = true; else escaped = false;
|
|
140
|
+
}
|
|
141
|
+
const closed = i < text.length;
|
|
142
|
+
// A dangling JSON escape cannot be part of a complete command value.
|
|
143
|
+
const raw = text.slice(start, closed ? i + 1 : escaped ? i - 1 : i) + (closed ? "" : '"');
|
|
144
|
+
try {
|
|
145
|
+
const value: unknown = JSON.parse(raw);
|
|
146
|
+
if (typeof value === "string") {
|
|
147
|
+
if (withholdAnswerCommand(value) !== value) return "[withheld]";
|
|
148
|
+
if (containers[top] === "program" && !assignmentWord.test(value)) containers[top] = /^(?:.*\/)?ahub$/.test(value) ? "subcommand" : "other";
|
|
149
|
+
else if (containers[top] === "subcommand") containers[top] = value === "answer" ? "answer" : "other";
|
|
150
|
+
else if (containers[top] === "answer" && /^--(?:instructed|other)(?:=|$)/.test(value)) return "[withheld]";
|
|
151
|
+
}
|
|
152
|
+
} catch {
|
|
153
|
+
if (/\bahub\s+answer\b/.test(raw)) return "[withheld]";
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return text;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Shape one explicit argv vector inside a freshly parsed argument envelope. */
|
|
160
|
+
function withholdAnswerArgv(argv: unknown[]): boolean {
|
|
161
|
+
let program = 0;
|
|
162
|
+
while (program < argv.length) {
|
|
163
|
+
const word = argv[program];
|
|
164
|
+
if (typeof word !== "string" || !assignmentWord.test(word)) break;
|
|
165
|
+
program++;
|
|
166
|
+
}
|
|
167
|
+
const executable = argv[program];
|
|
168
|
+
if (typeof executable !== "string" || !/^(?:.*\/)?ahub$/.test(executable) || argv[program + 1] !== "answer") return false;
|
|
169
|
+
let changed = false;
|
|
170
|
+
for (let i = program + 2; i < argv.length; i++) {
|
|
171
|
+
const word = argv[i], flag = typeof word === "string" ? /^(--(?:instructed|other))(=|$)/.exec(word) : null;
|
|
172
|
+
if (!flag) continue;
|
|
173
|
+
changed = true;
|
|
174
|
+
if (flag[2] === "=") argv[i] = `${flag[1]}=[withheld]`;
|
|
175
|
+
else {
|
|
176
|
+
const next = argv[i + 1];
|
|
177
|
+
if (typeof next === "string" && next.startsWith("--")) { argv.splice(program + 2, argv.length - program - 2, "[withheld]"); break; }
|
|
178
|
+
argv[++i] = "[withheld]";
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return changed;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Shape serialized transcript tool arguments without reserializing any unaffected input. */
|
|
185
|
+
export function withholdToolArguments(argumentsText: string): string {
|
|
186
|
+
let parsed: unknown;
|
|
187
|
+
try { parsed = JSON.parse(argumentsText); }
|
|
188
|
+
catch { return argumentsText.includes("ahub answer") ? "[withheld]" : withholdUnparsedArguments(argumentsText); }
|
|
189
|
+
const holder: Record<string, unknown> = { value: parsed };
|
|
190
|
+
const stack = [{ parent: holder, key: "value" }];
|
|
191
|
+
let changed = false;
|
|
192
|
+
while (stack.length) {
|
|
193
|
+
const { parent, key } = stack.pop()!, value = parent[key];
|
|
194
|
+
if (typeof value === "string") {
|
|
195
|
+
const shaped = withholdAnswerCommand(value);
|
|
196
|
+
if (shaped !== value) { parent[key] = shaped; changed = true; }
|
|
197
|
+
} else if (value && typeof value === "object") {
|
|
198
|
+
if (Array.isArray(value) && withholdAnswerArgv(value)) changed = true;
|
|
199
|
+
for (const child of Object.keys(value)) stack.push({ parent: value as Record<string, unknown>, key: child });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
// Parsing drops duplicate keys. Inspect all serialized literals before preserving an unchanged original.
|
|
203
|
+
return changed ? JSON.stringify(holder.value) : withholdUnparsedArguments(argumentsText);
|
|
204
|
+
}
|
|
205
|
+
|
|
55
206
|
/** Deterministic, value-only summary of Claude tool_input. Strip private spans before clipping. */
|
|
56
207
|
export function toolInputLine(input: unknown): string {
|
|
57
208
|
if (!input || typeof input !== "object" || Array.isArray(input)) return "";
|
|
@@ -61,7 +212,7 @@ export function toolInputLine(input: unknown): string {
|
|
|
61
212
|
const known = TOOL_INPUT_ORDER.filter(key => byKey.has(key));
|
|
62
213
|
const other = fields.map(([key]) => key).filter(key => !(TOOL_INPUT_ORDER as readonly string[]).includes(key)).sort();
|
|
63
214
|
const values = [...known, ...other].map(key => clipCaptureUtf8(
|
|
64
|
-
stripPrivateSpans(byKey.get(key) as string).replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, " "), TOOL_INPUT_LINE_BYTES,
|
|
215
|
+
withholdAnswerCommand(stripPrivateSpans(byKey.get(key) as string)).replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, " "), TOOL_INPUT_LINE_BYTES,
|
|
65
216
|
)).filter(Boolean);
|
|
66
217
|
return clipCaptureUtf8(values.join(" | "), TOOL_INPUT_LINE_BYTES).trimEnd();
|
|
67
218
|
}
|