open-memex 0.2.0-alpha → 0.3.0-alpha.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/src/redact.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
- * Redaction: secrets must never land in memory files or the index.
2
+ * Redaction: secrets must never land in memory files or the index in
3
+ * readable form.
3
4
  *
4
- * Three layers, checked in order by redact():
5
+ * Layers, in order:
5
6
  * 1. <private>...</private> regions are stripped first (explicit opt-out —
6
7
  * the author marked this span as sensitive, so it is replaced with
7
8
  * [REDACTED] before any detection runs).
@@ -10,8 +11,11 @@
10
11
  * 4. High-entropy assignment heuristic (catches secrets whose provider we
11
12
  * don't have a pattern for, e.g. `deploy_key = "aB3d..."`).
12
13
  *
13
- * Any hit refuses the whole write — a memory with a hole in it is worse
14
- * than no memory, because the hole invites reconstruction.
14
+ * A detected secret does NOT refuse the write: the matched string is masked
15
+ * in place — first 4 characters kept, the rest replaced with 'x' — and the
16
+ * write proceeds with the masked content. hadSecret reports that masking
17
+ * happened so callers can surface a notice. A partially-masked memory still
18
+ * identifies which credential it referred to without storing the secret.
15
19
  */
16
20
 
17
21
  export interface SecretPattern {
@@ -21,6 +25,13 @@ export interface SecretPattern {
21
25
  source: string;
22
26
  /** Optional RegExp flags, e.g. "i". */
23
27
  flags?: string;
28
+ /**
29
+ * Capture-group index holding the secret value. When set, masking replaces
30
+ * only that group — the credential name stays readable (D14: a masked
31
+ * memory should still identify which key it referred to). Default: mask
32
+ * the whole match.
33
+ */
34
+ valueGroup?: number;
24
35
  }
25
36
 
26
37
  /**
@@ -56,8 +67,9 @@ export const BUILTIN_SECRET_PATTERNS: SecretPattern[] = [
56
67
  {
57
68
  id: "aws-secret-access-key",
58
69
  source:
59
- "aws[_-]?secret[_-]?access[_-]?key[\"']?\\s*[:=]\\s*[\"']?[A-Za-z0-9/+=]{40}",
70
+ "(aws[_-]?secret[_-]?access[_-]?key)([\"']?\\s*[:=]\\s*[\"']?)([A-Za-z0-9/+=]{40})",
60
71
  flags: "i",
72
+ valueGroup: 3,
61
73
  },
62
74
  { id: "slack-token", source: `${TOKEN_BOUNDARY}xox[baprs]-[A-Za-z0-9-]{10,}` },
63
75
  { id: "google-api-key", source: `${TOKEN_BOUNDARY}AIza[0-9A-Za-z_-]{30,}` },
@@ -71,7 +83,19 @@ export const BUILTIN_SECRET_PATTERNS: SecretPattern[] = [
71
83
  id: "stripe-webhook-secret",
72
84
  source: `${TOKEN_BOUNDARY}whsec_[A-Za-z0-9]{20,}`,
73
85
  },
74
- { id: "private-key-block", source: "-----BEGIN [A-Z ]*PRIVATE KEY-----" },
86
+ {
87
+ id: "private-key-block",
88
+ // Whole block: masking only the BEGIN header would leave the base64 body
89
+ // readable in the memory file. Non-greedy so two blocks mask separately.
90
+ source:
91
+ "-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----",
92
+ },
93
+ {
94
+ id: "private-key-truncated",
95
+ // No END marker: mask from the header to end of text. A header without a
96
+ // body is still key material; over-masking is the safe direction.
97
+ source: "-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*$",
98
+ },
75
99
  {
76
100
  id: "jwt",
77
101
  source: `${TOKEN_BOUNDARY}eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}`,
@@ -79,8 +103,9 @@ export const BUILTIN_SECRET_PATTERNS: SecretPattern[] = [
79
103
  {
80
104
  id: "generic-secret-assignment",
81
105
  source:
82
- "(api[_-]?key|secret|passwd|password|auth[_-]?token|access[_-]?token)[\"']?\\s*[:=]\\s*[\"']?[A-Za-z0-9_\\-./+=]{16,}[\"']?",
106
+ "(api[_-]?key|secret|passwd|password|auth[_-]?token|access[_-]?token)([\"']?\\s*[:=]\\s*[\"']?)([A-Za-z0-9_\\-./+=]{16,})([\"']?)",
83
107
  flags: "i",
108
+ valueGroup: 3,
84
109
  },
85
110
  ];
86
111
 
@@ -139,12 +164,31 @@ export function findHighEntropySecret(text: string): string | null {
139
164
  for (const m of text.matchAll(ASSIGNMENT_RE)) {
140
165
  const name = m[1];
141
166
  const value = m[2];
142
- if (value.includes("://")) continue; // URL, not a secret
143
- if (shannonEntropy(value) >= 4.5) return `high-entropy-secret:${name}`;
167
+ if (!isSuspectAssignmentValue(value, m[0], m.index ?? 0, text)) continue;
168
+ return `high-entropy-secret:${name}`;
144
169
  }
145
170
  return null;
146
171
  }
147
172
 
173
+ /**
174
+ * Shared benign-value rule for detection AND masking: a URL (e.g. the value
175
+ * after "https:") or a low-entropy value must never be touched. Note the
176
+ * "://" check: ASSIGNMENT_RE consumes the colon of "https:" as the separator,
177
+ * so the captured value starts with "//..." — check for "://" in the
178
+ * original text around the match, not just inside the value.
179
+ */
180
+ function isSuspectAssignmentValue(value: string, fullMatch: string, offset: number, text: string): boolean {
181
+ // Bare URL: ASSIGNMENT_RE consumed the scheme colon ("https:") as the
182
+ // separator, so the match itself starts with "scheme://".
183
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(fullMatch)) return false;
184
+ if (value.includes("://")) return false;
185
+ // Reconstruct what preceded the value inside the match (name + separator);
186
+ // if the text right before the value looks like scheme://, it is a URL.
187
+ const before = text.slice(Math.max(0, offset - 12), offset);
188
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:(\/\/)?$/.test(before.trim()) || before.includes("://")) return false;
189
+ return shannonEntropy(value) >= 4.5;
190
+ }
191
+
148
192
  export function stripPrivate(text: string): string {
149
193
  // Closed pairs first...
150
194
  let out = text.replace(/<private>[\s\S]*?<\/private>/gi, "[REDACTED]");
@@ -154,18 +198,78 @@ export function stripPrivate(text: string): string {
154
198
  return out;
155
199
  }
156
200
 
201
+ /**
202
+ * Mask a matched secret: keep the first 4 characters, replace the rest
203
+ * with 'x' (length-preserving). "sk-1234567890abcdefghij" → "sk-1xxxxxxxxxxxxx".
204
+ */
205
+ function maskMatch(m: string): string {
206
+ return m.slice(0, 4) + "x".repeat(Math.max(0, m.length - 4));
207
+ }
208
+
209
+ /** Apply the builtin patterns as masking (global, all matches). */
210
+ function maskBuiltin(content: string): string {
211
+ let out = content;
212
+ for (const p of BUILTIN_SECRET_PATTERNS) {
213
+ const re = compile(p);
214
+ if (!re) continue;
215
+ const g = new RegExp(re.source, re.flags + "g");
216
+ if (p.valueGroup == null) {
217
+ out = out.replace(g, (m) => maskMatch(m));
218
+ } else {
219
+ // Mask only the secret-value group; the credential name stays readable.
220
+ out = out.replace(g, (...args: unknown[]) => {
221
+ const m = args[0] as string;
222
+ const val = args[p.valueGroup as number] as string | undefined;
223
+ if (!val) return m;
224
+ const idx = m.lastIndexOf(val);
225
+ if (idx < 0) return m;
226
+ return m.slice(0, idx) + maskMatch(val) + m.slice(idx + val.length);
227
+ });
228
+ }
229
+ }
230
+ return out;
231
+ }
232
+
233
+ /** Apply user patterns as masking. Invalid regexes are ignored. */
234
+ function maskUser(content: string, patterns: string[]): string {
235
+ let out = content;
236
+ for (const p of patterns) {
237
+ try {
238
+ out = out.replace(new RegExp(p, "g"), (m) => maskMatch(m));
239
+ } catch {
240
+ // ignore malformed regex
241
+ }
242
+ }
243
+ return out;
244
+ }
245
+
246
+ /** Mask the value side of high-entropy assignments (name stays readable).
247
+ * Uses the exact same benign-value rule as detection, so URLs and
248
+ * low-entropy values are never touched even when another secret triggers. */
249
+ function maskEntropy(content: string): string {
250
+ return content.replace(
251
+ ASSIGNMENT_RE,
252
+ (m, name: string, value: string, offset: number) => {
253
+ if (!isSuspectAssignmentValue(value, m, offset, content)) return m;
254
+ return m.split(value).join(maskMatch(value));
255
+ },
256
+ );
257
+ }
258
+
157
259
  export function redact(
158
260
  text: string,
159
261
  patterns: string[],
160
262
  ): { content: string; hadSecret: boolean; matchedPattern: string | null } {
161
263
  const stripped = stripPrivate(text);
264
+ // Detection (for reporting) runs in priority order: builtin → user → entropy.
162
265
  const builtin = findBuiltinSecret(stripped);
163
- if (builtin)
164
- return { content: stripped, hadSecret: true, matchedPattern: builtin };
165
- const user = findSecret(stripped, patterns);
166
- if (user) return { content: stripped, hadSecret: true, matchedPattern: user };
167
- const entropic = findHighEntropySecret(stripped);
168
- if (entropic)
169
- return { content: stripped, hadSecret: true, matchedPattern: entropic };
170
- return { content: stripped, hadSecret: false, matchedPattern: null };
266
+ const user = builtin ? null : findSecret(stripped, patterns);
267
+ const entropic =
268
+ builtin || user ? null : findHighEntropySecret(stripped);
269
+ const matched = builtin ?? user ?? entropic;
270
+ if (!matched) return { content: stripped, hadSecret: false, matchedPattern: null };
271
+ // Masking runs every family over the text (not just the reported one) so
272
+ // multiple credentials in one memory are all masked.
273
+ const masked = maskEntropy(maskUser(maskBuiltin(stripped), patterns));
274
+ return { content: masked, hadSecret: true, matchedPattern: matched };
171
275
  }
@@ -1,233 +1,58 @@
1
1
  import { tool } from "@opencode-ai/plugin/tool";
2
2
  import type { Scope } from "../scope.ts";
3
3
  import type { MyOMemoryConfig } from "../config.ts";
4
- import { PERSONAL_SCOPE } from "../scope.ts";
5
- import { search, list } from "../retrieve/search.ts";
6
4
  import {
7
- writeMemoryFile,
8
- deleteMemoryFile,
9
- readMemoryFile,
10
- ulid,
11
- msToRfc3339,
12
- MEMORY_TYPE_TAXONOMY,
13
- type Frontmatter,
14
- } from "../store/markdown.ts";
15
- import { upsertFromFile, deleteFromIndex } from "../store/sync.ts";
16
- import { findDuplicates, supersede } from "../store/lifecycle.ts";
17
- import { db } from "../store/db.ts";
18
- import { redact } from "../redact.ts";
19
-
20
- const z = tool.schema;
21
-
22
- /** v2 content-kind taxonomy (V2-DESIGN §3.1). */
23
- const MEMORY_TYPES = MEMORY_TYPE_TAXONOMY;
5
+ addMemory,
6
+ searchMemories,
7
+ listMemories,
8
+ supersedeMemory,
9
+ forgetMemory,
10
+ memoryAddArgs,
11
+ memorySearchArgs,
12
+ memoryListArgs,
13
+ memorySupersedeArgs,
14
+ memoryForgetArgs,
15
+ TOOL_DESCRIPTIONS,
16
+ } from "./ops.ts";
24
17
 
25
18
  export function makeTools(getScope: () => Scope, cfg: MyOMemoryConfig) {
26
- const scopeArg = z
27
- .enum(["project", "personal", "user"])
28
- .optional()
29
- .describe(
30
- "Memory scope. `project` = tied to this repo. `personal` = global across all your projects. `user` is a deprecated alias of `personal`. Default: project.",
31
- );
32
-
33
- function resolveScope(kind?: "project" | "personal" | "user"): Scope {
34
- return kind === "personal" || kind === "user" ? PERSONAL_SCOPE : getScope();
35
- }
36
-
37
19
  const memory_add = tool({
38
- description:
39
- "Save a fact, preference, decision, or note to persistent local memory. Call this whenever the user tells you something you should remember in future sessions (project conventions, tool choices, personal preferences, error fixes). Keep each memory to one self-contained statement.",
40
- args: {
41
- content: z.string().min(1).describe("The fact to remember. One idea per memory."),
42
- type: z
43
- .enum(MEMORY_TYPES)
44
- .optional()
45
- .describe("Category of memory. Default: note."),
46
- scope: scopeArg,
47
- tags: z.array(z.string()).optional().describe("Optional tags for filtering."),
48
- },
20
+ description: TOOL_DESCRIPTIONS.memory_add,
21
+ args: memoryAddArgs,
49
22
  async execute(args) {
50
- const { content: redacted, hadSecret, matchedPattern } = redact(
51
- args.content,
52
- cfg.redactPatterns,
53
- );
54
- if (hadSecret) {
55
- return {
56
- title: "memory: rejected (secret detected)",
57
- output: `Refused to save: content matched a secret pattern (${matchedPattern}). Wrap the sensitive part in <private>...</private> tags or paraphrase, then try again.`,
58
- };
59
- }
60
- const s = resolveScope(args.scope);
61
- // Dedup on write (§3.4): identical content is idempotent; near-duplicates
62
- // are reported so the caller can supersede instead of duplicating.
63
- const dups = findDuplicates(s.key, redacted);
64
- if (dups.exact) {
65
- return {
66
- title: "memory: already exists",
67
- output: `Identical memory already exists: id=${dups.exact.id}. Not duplicated.`,
68
- };
69
- }
70
- const rfc = msToRfc3339(Date.now());
71
- const fm: Frontmatter = {
72
- id: ulid(),
73
- schema_version: 2,
74
- scope_key: s.key,
75
- scope: s.kind === "project" ? "project" : "personal",
76
- visibility: s.kind === "project" ? "internal" : "private",
77
- project_name: s.projectName,
78
- type: args.type ?? "fact",
79
- role: "knowledge",
80
- importance: "normal",
81
- status: "active",
82
- tags: args.tags ?? [],
83
- source: "tool",
84
- created_at: rfc,
85
- updated_at: rfc,
86
- supersedes: null,
87
- superseded_by: null,
88
- };
89
- const { filePath } = writeMemoryFile(fm, redacted);
90
- const mf = readMemoryFile(filePath);
91
- if (mf) upsertFromFile(mf);
92
- let output = `Saved to ${s.key} as ${fm.type}. id=${fm.id}`;
93
- for (const n of dups.near) {
94
- output += `\nNote: similar memory exists (score ${n.score.toFixed(2)}): id=${n.id} — ${n.snippet}. Use memory_supersede if this replaces it.`;
95
- }
96
- return {
97
- title: `memory: saved ${fm.id}`,
98
- output,
99
- };
23
+ return addMemory(getScope, cfg, args);
100
24
  },
101
25
  });
102
26
 
103
27
  const memory_search = tool({
104
- description:
105
- "Search persistent memory by keyword (BM25 full-text). Returns matching memories from the current project and/or personal scope. Use before asking the user something they may have told you before.",
106
- args: {
107
- query: z
108
- .string()
109
- .min(1)
110
- .describe("Free-text query. File paths, error strings, identifiers work well."),
111
- scope: z
112
- .enum(["project", "personal", "user", "both"])
113
- .optional()
114
- .describe("Which scope(s) to search. Default: both."),
115
- type: z.string().optional().describe("Restrict to memories of this type."),
116
- limit: z.number().int().min(1).max(50).optional(),
117
- },
28
+ description: TOOL_DESCRIPTIONS.memory_search,
29
+ args: memorySearchArgs,
118
30
  async execute(args) {
119
- const project = getScope();
120
- const scopeKeys =
121
- args.scope === "personal" || args.scope === "user"
122
- ? [PERSONAL_SCOPE.key]
123
- : args.scope === "project"
124
- ? [project.key]
125
- : [project.key, PERSONAL_SCOPE.key];
126
- const hits = search(args.query, {
127
- scopeKeys,
128
- limit: args.limit,
129
- type: args.type,
130
- });
131
- if (hits.length === 0) {
132
- return {
133
- title: "memory: 0 results",
134
- output: `No memories matched "${args.query}".`,
135
- };
136
- }
137
- const lines = hits.map(
138
- (h) =>
139
- `- [${h.scope_key === PERSONAL_SCOPE.key ? "personal" : "project"}/${h.type}] id=${h.id}\n ${h.snippet.replace(/\s+/g, " ").trim()}`,
140
- );
141
- return {
142
- title: `memory: ${hits.length} result(s)`,
143
- output: lines.join("\n"),
144
- };
31
+ return searchMemories(getScope, args);
145
32
  },
146
33
  });
147
34
 
148
35
  const memory_list = tool({
149
- description: "List memories in a scope, newest first. Useful for browsing.",
150
- args: {
151
- scope: scopeArg,
152
- type: z.string().optional(),
153
- limit: z.number().int().min(1).max(100).optional(),
154
- },
36
+ description: TOOL_DESCRIPTIONS.memory_list,
37
+ args: memoryListArgs,
155
38
  async execute(args) {
156
- const s = resolveScope(args.scope);
157
- const hits = list(s.key, { type: args.type, limit: args.limit });
158
- if (hits.length === 0) {
159
- return { title: "memory: empty", output: `No memories in scope ${s.key}.` };
160
- }
161
- const lines = hits.map(
162
- (h) => `- [${h.type}] id=${h.id} — ${h.snippet.replace(/\s+/g, " ").trim()}`,
163
- );
164
- return {
165
- title: `memory: ${hits.length} in ${s.key}`,
166
- output: lines.join("\n"),
167
- };
39
+ return listMemories(getScope, args);
168
40
  },
169
41
  });
170
42
 
171
43
  const memory_supersede = tool({
172
- description:
173
- "Replace an existing memory with a newer version. The old memory is kept as history (status: superseded) and retrieval returns the new one. Use when a saved fact becomes outdated and should be replaced rather than duplicated.",
174
- args: {
175
- id: z.string().min(1).describe("ID of the memory being replaced."),
176
- content: z.string().min(1).describe("The new, corrected content."),
177
- type: z
178
- .enum(MEMORY_TYPES)
179
- .optional()
180
- .describe("Category of the new memory. Defaults to the old memory's type."),
181
- tags: z.array(z.string()).optional().describe("Optional tags for the new memory."),
182
- },
44
+ description: TOOL_DESCRIPTIONS.memory_supersede,
45
+ args: memorySupersedeArgs,
183
46
  async execute(args) {
184
- const { content: redacted, hadSecret, matchedPattern } = redact(
185
- args.content,
186
- cfg.redactPatterns,
187
- );
188
- if (hadSecret) {
189
- return {
190
- title: "memory: rejected (secret detected)",
191
- output: `Refused to save: content matched a secret pattern (${matchedPattern}). Wrap the sensitive part in <private>...</private> tags or paraphrase, then try again.`,
192
- };
193
- }
194
- try {
195
- const { oldMf, newMf } = supersede(args.id, {
196
- body: redacted,
197
- type: args.type,
198
- tags: args.tags,
199
- source: "tool",
200
- });
201
- upsertFromFile(oldMf);
202
- upsertFromFile(newMf);
203
- return {
204
- title: `memory: superseded ${oldMf.fm.id}`,
205
- output: `Replaced ${oldMf.fm.id} with ${newMf.fm.id} (old kept as history).`,
206
- };
207
- } catch (e) {
208
- return {
209
- title: "memory: supersede failed",
210
- output: (e as Error).message,
211
- };
212
- }
47
+ return supersedeMemory(cfg, args);
213
48
  },
214
49
  });
215
50
 
216
51
  const memory_forget = tool({
217
- description: "Delete a memory by id. Use when the user asks to forget something.",
218
- args: {
219
- id: z.string().min(1),
220
- },
52
+ description: TOOL_DESCRIPTIONS.memory_forget,
53
+ args: memoryForgetArgs,
221
54
  async execute(args) {
222
- const row = db()
223
- .prepare(`SELECT scope_key FROM memories WHERE id = ?`)
224
- .get(args.id) as { scope_key: string } | undefined;
225
- if (!row) {
226
- return { title: "memory: not found", output: `No memory with id ${args.id}.` };
227
- }
228
- deleteMemoryFile(row.scope_key, args.id);
229
- deleteFromIndex(args.id);
230
- return { title: "memory: forgotten", output: `Deleted ${args.id}.` };
55
+ return forgetMemory(args);
231
56
  },
232
57
  });
233
58