@staix/agent-mem 0.26.0 → 0.26.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/.claude-plugin/plugin.json +1 -1
- package/README.md +2 -2
- package/package.json +1 -1
- package/src/ingest.ts +3 -3
- package/src/memory/bridge.ts +3 -1
- package/src/memory/capture-input.ts +152 -1
- package/src/memory/platform.ts +18 -15
- package/src/memory/sync-placement-capture.ts +26 -9
- package/src/memory/sync-placement-inspection.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.26.
|
|
6
|
+
Version: 0.26.2. Requires Bun 1.4.2 or later; no runtime dependencies.
|
|
7
7
|
<!-- /facts:version -->
|
|
8
8
|
|
|
9
9
|
## Quick start
|
|
@@ -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/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;
|
package/src/memory/bridge.ts
CHANGED
|
@@ -62,11 +62,13 @@ export class SegmentReader {
|
|
|
62
62
|
/** Optional inspection limits do not change ordinary incremental-reader semantics. */
|
|
63
63
|
readonly sourceByteLimit?: number;
|
|
64
64
|
readonly sourceFileLimit?: number;
|
|
65
|
+
private readonly sourceRowLimit?: number;
|
|
65
66
|
constructor(private remainingBytes = Infinity, limits: { maxSourceBytes?: number; maxRows?: number } = {}) {
|
|
66
67
|
for (const value of [remainingBytes, limits.maxSourceBytes ?? Infinity, limits.maxRows ?? Infinity]) if (value !== Infinity && (!Number.isSafeInteger(value) || value < 0)) failure();
|
|
67
68
|
this.sourceByteLimit = limits.maxSourceBytes;
|
|
68
69
|
this.remainingSourceBytes = limits.maxSourceBytes ?? Infinity;
|
|
69
70
|
this.remainingRows = limits.maxRows ?? Infinity;
|
|
71
|
+
this.sourceRowLimit = limits.maxRows;
|
|
70
72
|
this.sourceFileLimit = limits.maxRows;
|
|
71
73
|
this.remainingFiles = limits.maxRows ?? Infinity;
|
|
72
74
|
}
|
|
@@ -113,7 +115,7 @@ export class SegmentReader {
|
|
|
113
115
|
if (!read(end).equals(bytes) || fstatSync(fd, { bigint: true }).size < opened.size) failure();
|
|
114
116
|
// Count physical nonblank source rows before any canonical source map can grow.
|
|
115
117
|
if (this.remainingRows !== Infinity) for (const line of completeLines(bytes)) if (line.toString("utf8").trim()) {
|
|
116
|
-
if (this.remainingRows < 1) throw new SegmentReadBudgetError({ kind: "rows", limit: this.
|
|
118
|
+
if (this.remainingRows < 1) throw new SegmentReadBudgetError({ kind: "rows", limit: this.sourceRowLimit!, observed: this.sourceRows + 1 });
|
|
117
119
|
this.remainingRows--; this.sourceRows++;
|
|
118
120
|
}
|
|
119
121
|
const after = lstatSync(path, { bigint: true });
|
|
@@ -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
|
}
|
package/src/memory/platform.ts
CHANGED
|
@@ -24,24 +24,27 @@ export function canonicalPath(path: string): string {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
* stored on disk
|
|
30
|
-
* pass for another file. A missing path or a dangling symlink still throws, which guardPath relies on. Other paths take
|
|
31
|
-
* realpathSync's answer unchanged.
|
|
27
|
+
* Resolve existing paths physically. Bun folds `..` after symlinks lexically (#403), so parent segments use the
|
|
28
|
+
* system realpath. Bun versions that reject literal backslashes also use that fallback (#26, #121). It returns
|
|
29
|
+
* names as stored on disk for guardPath's name checks and refuses missing paths and dangling symlinks.
|
|
32
30
|
*/
|
|
33
31
|
export function realPath(path: string): string {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
return r.stdout.slice(0, -1);
|
|
32
|
+
const hasParent = path.split(sep).includes("..");
|
|
33
|
+
let error: unknown;
|
|
34
|
+
if (!hasParent) {
|
|
35
|
+
try {
|
|
36
|
+
return realpathSync(path);
|
|
37
|
+
} catch (caught) {
|
|
38
|
+
if (!resolve(path).includes("\\")) throw caught; // a relative path can sit under a backslash directory too
|
|
39
|
+
error = caught;
|
|
40
|
+
}
|
|
44
41
|
}
|
|
42
|
+
// Keep the original spelling: resolve() would fold a `..` after a symlink by text. GNU realpath accepts a
|
|
43
|
+
// dangling last component unless told -e; the BSD one on macOS refuses it by default.
|
|
44
|
+
const argv = process.platform === "darwin" ? ["/bin/realpath", "--", path] : ["realpath", "-e", "--", path];
|
|
45
|
+
const r = childProcess().spawnSync(argv[0]!, argv.slice(1), { encoding: "utf8" });
|
|
46
|
+
if (r.status !== 0 || !r.stdout.endsWith("\n")) throw error ?? new Error(`Cannot resolve existing path: ${path}`);
|
|
47
|
+
return r.stdout.slice(0, -1);
|
|
45
48
|
}
|
|
46
49
|
|
|
47
50
|
/** One denylist for core extraction, hub path guards, sandbox rules and capture. */
|
|
@@ -22,6 +22,19 @@ import { assertPlacementRuntime } from "./sync-placement-guard.ts";
|
|
|
22
22
|
import { activationSourceMarkers, assertPlacementActivationOwner, type PlacementActivationOwner, type PlacementActivationCaptureProof } from "./sync-placement-activation-proof.ts";
|
|
23
23
|
import { readEffectiveSyncPlacementWriters, writerBoundPlacementContextHash, writerInventoryEvidence, type EffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
24
24
|
import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
|
|
25
|
+
import { inspectionBoundReceipt, type InspectionBound } from "./inspection-bound.ts";
|
|
26
|
+
|
|
27
|
+
/** Home-wide source capture ceilings. Every file is read twice (bytes, then a stable recheck), so the read budget is 2x. */
|
|
28
|
+
export const PLACEMENT_CAPTURE_MAX_SOURCE_BYTES = 64 * 1024 * 1024, PLACEMENT_CAPTURE_MAX_ROWS = 20000;
|
|
29
|
+
/** Source capture refusal before any effect. Code stays "bound" for existing callers; the message names the phase and bound. */
|
|
30
|
+
export class PlacementSourceBoundError extends SyncPlacementJournalError {
|
|
31
|
+
constructor(readonly bound?: InspectionBound) {
|
|
32
|
+
super("bound");
|
|
33
|
+
const detail = bound ? `${bound.kind} bound (observed ${bound.observed}, limit ${bound.limit})` : "read bound";
|
|
34
|
+
this.message = `Sync placement source capture exceeds its supported ${detail}; no journal, marker or source was changed. This is not journal corruption; retain the inputs and report this bound.`;
|
|
35
|
+
this.name = "PlacementSourceBoundError";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
25
38
|
|
|
26
39
|
/** Host authentication/compatibility facts are re-read at every effect boundary, never inferred from a session marker. */
|
|
27
40
|
export interface PlacementCapturePort {
|
|
@@ -64,12 +77,14 @@ function ownedDirectory(dir: string): BigIntStats {
|
|
|
64
77
|
if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== BigInt(process.getuid!()) || (s.mode & 0o022n) !== 0n) fail();
|
|
65
78
|
return s;
|
|
66
79
|
}
|
|
67
|
-
/** ponytail: capture
|
|
68
|
-
*
|
|
80
|
+
/** ponytail: capture holds the whole home in memory, capped at 256 metadata objects and 64 MiB/20000 source rows
|
|
81
|
+
* across all realms (#414 raised 8 MiB; a 23 MB/10,248-row home was refused). Larger homes need a reviewed
|
|
82
|
+
* chunked/streaming activation proof; no input is silently omitted at this ceiling. */
|
|
69
83
|
function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[], pending: readonly PlacementPendingSource[] = [], policyVersion?: string, ownerProof?: PlacementActivationCaptureProof, sourceOwner?:PlacementActivationOwner): PlacementSourcePreview {
|
|
70
84
|
let selection: PlacementRealm[] | undefined;
|
|
71
85
|
if (selected !== undefined) {
|
|
72
|
-
if (!Array.isArray(selected) || types.isProxy(selected)
|
|
86
|
+
if (!Array.isArray(selected) || types.isProxy(selected)) fail();
|
|
87
|
+
if (selected.length > 256) throw new PlacementSourceBoundError({ kind: "source-files", limit: 256, observed: selected.length });
|
|
73
88
|
const copied = memoryPolicySnapshot(selected); if (!copied) fail();
|
|
74
89
|
selection = copied.map(realm => validatePlacementKey({ realm, id: "0".repeat(32), rowHash: "0".repeat(64) }).realm);
|
|
75
90
|
if (!selection.length || new Set(selection.map(realm => canonicalJSON(realm))).size !== selection.length) fail();
|
|
@@ -87,7 +102,9 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
87
102
|
const bytes = (file: string, optional = false): Buffer | undefined => {
|
|
88
103
|
const before = lstatSync(file, { bigint: true, throwIfNoEntry: false });
|
|
89
104
|
if (!before) { if (!optional) fail(); facts.push([file, null]); sourceChecks.push(() => { if(lstatSync(file,{throwIfNoEntry:false})) fail(); }); return undefined; }
|
|
90
|
-
if (++metadataObjects > 256
|
|
105
|
+
if (++metadataObjects > 256) throw new PlacementSourceBoundError({ kind: "source-files", limit: 256, observed: metadataObjects });
|
|
106
|
+
if (before.size > 262144n) throw new PlacementSourceBoundError({ kind: "metadata-bytes", limit: 262144, observed: Number(before.size) });
|
|
107
|
+
if (metadataBytes + Number(before.size) > 8 * 1024 * 1024) throw new PlacementSourceBoundError({ kind: "metadata-bytes", limit: 8 * 1024 * 1024, observed: metadataBytes + Number(before.size) });
|
|
91
108
|
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n || before.uid !== root.uid || (before.mode & 0o022n) !== 0n) fail();
|
|
92
109
|
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
93
110
|
try {
|
|
@@ -137,7 +154,7 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
137
154
|
if(name==="profile.lock"&&sourceOwner){assertPlacementActivationOwner(sourceOwner,home);continue;}
|
|
138
155
|
if (lstatSync(join(home,name),{throwIfNoEntry:false})) fail();
|
|
139
156
|
}
|
|
140
|
-
const reader = new SegmentReader(
|
|
157
|
+
const reader = new SegmentReader(2 * PLACEMENT_CAPTURE_MAX_SOURCE_BYTES, { maxSourceBytes: PLACEMENT_CAPTURE_MAX_SOURCE_BYTES, maxRows: PLACEMENT_CAPTURE_MAX_ROWS });
|
|
141
158
|
const rows = new Map<string, PlacementSourceRow>(), specialRows = new Map<string, PlacementSpecialSourceRow>(), sourceRowsByRealm = new Map<string, readonly PruneSourceRow[]>();
|
|
142
159
|
const directories = [home], prefixes: PlacementPublicationSource[] = [];
|
|
143
160
|
const realms: SyncPlacementActivationContext["realms"][number][] = [];
|
|
@@ -147,7 +164,7 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
147
164
|
directoryFact(dir); const listStamp = lstatSync(dir,{bigint:true});
|
|
148
165
|
sourceChecks.push(() => { if(!same(listStamp,lstatSync(dir,{bigint:true}))) fail(); });
|
|
149
166
|
const iterator = opendirSync(dir), names: string[] = [];
|
|
150
|
-
try { for (;;) { const item = iterator.readSync(); if (!item) break; if (names.length >= 256)
|
|
167
|
+
try { for (;;) { const item = iterator.readSync(); if (!item) break; if (names.length >= 256) throw new PlacementSourceBoundError({ kind: "source-files", limit: 256, observed: names.length + 1 }); names.push(item.name); } }
|
|
151
168
|
finally { iterator.closeSync(); }
|
|
152
169
|
names.sort(); facts.push([dir, names]); return names;
|
|
153
170
|
};
|
|
@@ -300,7 +317,7 @@ function previewSources(home:string,owner?:PlacementActivationOwner):PlacementSo
|
|
|
300
317
|
catch (error) {
|
|
301
318
|
if (error && typeof error === "object" && !types.isProxy(error)) {
|
|
302
319
|
if (error instanceof SyncPlacementJournalError) throw error;
|
|
303
|
-
if (error instanceof SegmentReadBudgetError)
|
|
320
|
+
if (error instanceof SegmentReadBudgetError) throw new PlacementSourceBoundError(inspectionBoundReceipt(error));
|
|
304
321
|
}
|
|
305
322
|
return fail();
|
|
306
323
|
}
|
|
@@ -352,7 +369,7 @@ export function captureSyncPlacementContext(home: string, port: PlacementCapture
|
|
|
352
369
|
if (error && typeof error === "object" && !types.isProxy(error)) {
|
|
353
370
|
if(error instanceof SharedWriterRevisionError){const code=Object.getOwnPropertyDescriptor(error,"code")?.value;if(code==="staging"||code==="pending")throw new SharedWriterRevisionError(code);}
|
|
354
371
|
if (error instanceof SyncPlacementJournalError) throw error;
|
|
355
|
-
if (error instanceof SegmentReadBudgetError)
|
|
372
|
+
if (error instanceof SegmentReadBudgetError) throw new PlacementSourceBoundError(inspectionBoundReceipt(error));
|
|
356
373
|
}
|
|
357
374
|
return fail();
|
|
358
375
|
}
|
|
@@ -366,7 +383,7 @@ export function captureSyncPlacementActivationContext(home: string, port: Placem
|
|
|
366
383
|
} catch (error) {
|
|
367
384
|
if (error && typeof error === "object" && !types.isProxy(error)) {
|
|
368
385
|
if (error instanceof SyncPlacementJournalError) throw error;
|
|
369
|
-
if (error instanceof SegmentReadBudgetError)
|
|
386
|
+
if (error instanceof SegmentReadBudgetError) throw new PlacementSourceBoundError(inspectionBoundReceipt(error));
|
|
370
387
|
}
|
|
371
388
|
return fail();
|
|
372
389
|
}
|
|
@@ -64,7 +64,7 @@ const remedies: Record<SyncPlacementInspectionIncompleteReason, string> = {
|
|
|
64
64
|
"placement-not-active": "Placement is not active; complete the person-reviewed shard/public-prune migrations and separately authorized placement activation before inspecting placement.",
|
|
65
65
|
"binding-changed": "Selected placement bindings changed; inspect the retained activation to restore matching markers when required, then reopen the selected project/user handles and inspect again.",
|
|
66
66
|
"input-unavailable": "Selected source or placement-context inputs are unreadable, incomplete or unsupported; inspect retained source metadata and any recorded partial request, verify compatible writer pins, then inspect again.",
|
|
67
|
-
"input-bound": "Placement inspection exceeds its supported
|
|
67
|
+
"input-bound": "Placement inspection exceeds its supported 64 MiB/20000-row source-capture or retained-evidence bounds; request a person-reviewed bounded epoch transition before inspecting again.",
|
|
68
68
|
"input-changed": "The selected placement inspection context changed; wait for stable source, journal and policy bindings, then inspect again.",
|
|
69
69
|
"journal-unavailable": "The retained placement journal is incomplete or inconsistent; preserve it and resume its exact recorded request with a compatible runtime before inspecting again.",
|
|
70
70
|
"policy-unavailable": "The policy callback/version or configured/default-deny epoch is unavailable or changed; restore a stable policy and policyVersion before inspecting again.",
|