@staix/agent-mem 0.26.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.26.0",
3
+ "version": "0.26.1",
4
4
  "description": "Bounded project memory tools and seven deterministic capture hooks, without a resident worker.",
5
5
  "mcpServers": {
6
6
  "agent-mem": {
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.0. Requires Bun 1.4.2 or later; no runtime dependencies.
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
@@ -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.2. Tests use synthetic fixtures and isolated homes, not personal memory stores.
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.26.0",
3
+ "version": "0.26.1",
4
4
  "description": "Curated, shared memory for coding agents: append-only logs, a derived index, tiers and a typed graph.",
5
5
  "license": "MIT",
6
6
  "type": "module",
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;
@@ -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
  }
@@ -24,24 +24,27 @@ export function canonicalPath(path: string): string {
24
24
  }
25
25
 
26
26
  /**
27
- * realpathSync, except that Bun (1.3.14, and 1.4.2 still: #121) throws ENOENT for an existing path containing a
28
- * backslash (issue #26). Such a path goes to the system realpath, which handles it and returns every component as
29
- * stored on disk: guardPath checks names, and on a case-insensitive disk `.GIT/config` or `id_rſa` would otherwise
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
- try {
35
- return realpathSync(path);
36
- } catch (error) {
37
- if (!resolve(path).includes("\\")) throw error; // a relative path can sit under a backslash directory too
38
- // The path as given: resolve() would fold a `..` after a symlink by text. GNU realpath accepts a dangling last
39
- // component unless told -e; the BSD one on macOS refuses it by default.
40
- const argv = process.platform === "darwin" ? ["/bin/realpath", "--", path] : ["realpath", "-e", "--", path];
41
- const r = childProcess().spawnSync(argv[0]!, argv.slice(1), { encoding: "utf8" });
42
- if (r.status !== 0 || !r.stdout.endsWith("\n")) throw error;
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. */