open-memex 0.8.2 → 0.9.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.
@@ -11,6 +11,7 @@ import {
11
11
  type Frontmatter,
12
12
  } from "./store/markdown.ts";
13
13
  import { buildContextBlock } from "./retrieve/inject.ts";
14
+ import { workingStateBlock } from "./working-state.ts";
14
15
  import { detectKeywords } from "./capture/keywords.ts";
15
16
  import {
16
17
  TURN_ECHO_WINDOW_MS,
@@ -34,6 +35,8 @@ export interface PluginState {
34
35
  scope: Scope;
35
36
  /** Sessions that already received the one-time context injection. */
36
37
  injectedSessions: Set<string>;
38
+ /** Sessions that already received the D89 working-state surfacing. */
39
+ workingStateSessions: Set<string>;
37
40
  /**
38
41
  * D73: what the keyword hook stored this session, so the agent can be told
39
42
  * before it re-saves the same statement. In memory only, like
@@ -72,7 +75,7 @@ export function bootstrapPlugin(root: string): PluginState {
72
75
  } catch (err) {
73
76
  console.error("[open-memex] init failed:", err);
74
77
  }
75
- return { cfg, scope, injectedSessions: new Set<string>(), captures: new Map() };
78
+ return { cfg, scope, injectedSessions: new Set<string>(), workingStateSessions: new Set<string>(), captures: new Map() };
76
79
  }
77
80
 
78
81
  /**
@@ -209,3 +212,31 @@ export function injectOnce(
209
212
  }
210
213
  return false;
211
214
  }
215
+
216
+ /**
217
+ * §3.6 (D89): surface the working-state note once per session, alongside
218
+ * the context injection. Scratch state, not knowledge — the block itself
219
+ * says what it is. Exactly-once uses the same in-memory Set discipline as
220
+ * `injectOnce` (not persisted; restarting the host re-surfaces). Expired
221
+ * or missing notes surface nothing.
222
+ */
223
+ export function surfaceWorkingStateOnce(
224
+ sessionID: string,
225
+ state: PluginState,
226
+ push: (block: string) => void,
227
+ ): boolean {
228
+ const { cfg, scope } = state;
229
+ if (!cfg.workingStateEnabled) return false;
230
+ if (state.workingStateSessions.has(sessionID)) return false;
231
+ state.workingStateSessions.add(sessionID);
232
+ try {
233
+ const block = workingStateBlock(scope.key, scope.projectName, cfg);
234
+ if (block) {
235
+ push(block);
236
+ return true;
237
+ }
238
+ } catch (err) {
239
+ console.error("[open-memex] working-state surfacing failed:", err);
240
+ }
241
+ return false;
242
+ }
@@ -8,6 +8,7 @@ import {
8
8
  import { similarity, NEAR_DUP_THRESHOLD } from "./lifecycle.ts";
9
9
  import { projectRoot } from "../paths.ts";
10
10
  import { loadConfig } from "../config.ts";
11
+ import { readWorkingState, workingStatePath } from "../working-state.ts";
11
12
 
12
13
  // Memory health audit (D57). Read-only: reports, never mutates.
13
14
  // Checks, per open question "retrieval explainability & memory health":
@@ -46,6 +47,9 @@ export interface AuditReport {
46
47
  brokenChains: { id: string; scopeKey: string; missingTarget: string }[];
47
48
  personalInRepo: string[];
48
49
  drift: { filesNotIndexed: number; rowsMissingFiles: number };
50
+ /** D89: working-state notes past their TTL. Reports only, never
51
+ * auto-deletes (D57 posture) — the next wrap-up write overwrites. */
52
+ workingStateExpired: { scopeKey: string; filePath: string; ageDays: number; ttlDays: number }[];
49
53
  }
50
54
 
51
55
  export function runAudit(scopeKeys: string[]): AuditReport {
@@ -125,6 +129,21 @@ export function runAudit(scopeKeys: string[]): AuditReport {
125
129
  }
126
130
  }
127
131
 
132
+ // D89: expired working-state notes. Reports only, never auto-deletes
133
+ // (D57 posture) — the next wrap-up write overwrites them.
134
+ const cfg = loadConfig();
135
+ const workingStateExpired = scopeKeys
136
+ .map((key) => ({ key, note: readWorkingState(key, cfg.workingStateTtlDays) }))
137
+ .filter((e): e is { key: string; note: NonNullable<ReturnType<typeof readWorkingState>> } =>
138
+ Boolean(e.note?.expired),
139
+ )
140
+ .map((e) => ({
141
+ scopeKey: e.key,
142
+ filePath: workingStatePath(e.key),
143
+ ageDays: e.note!.ageDays,
144
+ ttlDays: e.note!.ttlDays,
145
+ }));
146
+
128
147
  return {
129
148
  totalMemories: inScope.length,
130
149
  duplicatePairs: pairs,
@@ -132,5 +151,6 @@ export function runAudit(scopeKeys: string[]): AuditReport {
132
151
  brokenChains,
133
152
  personalInRepo,
134
153
  drift: { filesNotIndexed, rowsMissingFiles },
154
+ workingStateExpired,
135
155
  };
136
156
  }
@@ -10,11 +10,13 @@ import {
10
10
  listMemories,
11
11
  supersedeMemory,
12
12
  forgetMemory,
13
+ workingStateMemory,
13
14
  memoryAddArgs,
14
15
  memorySearchArgs,
15
16
  memoryListArgs,
16
17
  memorySupersedeArgs,
17
18
  memoryForgetArgs,
19
+ memoryWorkingStateArgs,
18
20
  TOOL_DESCRIPTIONS,
19
21
  withOutboxNote,
20
22
  } from "./ops.ts";
@@ -100,5 +102,15 @@ export function makeTools(getScope: () => Scope, cfg: MyOMemoryConfig) {
100
102
  },
101
103
  });
102
104
 
103
- return { memory_add, memory_search, memory_list, memory_forget, memory_supersede };
105
+ // §3.6 (D89): no scope/index work needed — the note lives beside the
106
+ // store, not in it.
107
+ const memory_workingstate = tool({
108
+ description: TOOL_DESCRIPTIONS.memory_workingstate,
109
+ args: memoryWorkingStateArgs,
110
+ async execute(args) {
111
+ return workingStateMemory(getScope, cfg, args);
112
+ },
113
+ });
114
+
115
+ return { memory_add, memory_search, memory_list, memory_forget, memory_supersede, memory_workingstate };
104
116
  }
package/src/tools/ops.ts CHANGED
@@ -30,6 +30,11 @@ import { redact } from "../redact.ts";
30
30
  import { getSyncStatus, formatSyncStatus, submitMemories, outboxDraftCount } from "../submit.ts";
31
31
  import { getPrStatus, formatPrStatus, applyPrStatus } from "../github.ts";
32
32
  import { isInRepoMemoryFile } from "../paths.ts";
33
+ import {
34
+ writeWorkingState,
35
+ readWorkingState,
36
+ clearWorkingState,
37
+ } from "../working-state.ts";
33
38
  import {
34
39
  proposeMemories,
35
40
  promoteMemory,
@@ -87,6 +92,8 @@ export const TOOL_DESCRIPTIONS = {
87
92
  "List git-conflicted memory files, or attempt a field-level 3-way merge of one. Semantic conflicts are reported, never auto-resolved. Run it when a git pull or merge leaves memory files conflicted; the merged file is written in place (undo with git if the merge is wrong). For PR review state rather than file conflicts, use memory_pr_status. (MCP server and the `open-memex resolve` CLI; the opencode native plugin does not expose this tool.)",
88
93
  memory_pr_status:
89
94
  "Read the current branch's GitHub PR and map its review state onto each in-repo memory: merged PR → published, PR approval → approved (approved_by = reviewer), changes-requested → suggestion only. Report by default — that mode changes nothing; apply=true writes the mapped transitions to the local files (still no push). (MCP server and the `open-memex pr-status` CLI; the opencode native plugin does not expose this tool.)",
95
+ memory_workingstate:
96
+ "Read, write, or clear the one ephemeral per-project working-state note (§3.6, D89): where an interrupted task stands, so a fresh session can resume. Scratch state, NOT durable knowledge — it never enters memory retrieval or a review ladder; any conclusion here that should outlive the task goes through the normal memory_add/checkpoint-proposal path instead. WRITE it (action=write, content required) when the user signals the session or task is wrapping up — body rubric: task summary (one paragraph), open files, last commands, where the work stands, next step; short by design, a scratch note, not a transcript. READ it when resuming work or when the user asks what they were doing. CLEAR it on the user's request only. The note lives outside memories/, the user can edit the plain file directly, and it expires after ttl_days (default 7) — expired notes are ignored and `audit` reports them.",
90
97
  } as const;
91
98
 
92
99
  /** Shared zod input shapes (raw shape, not z.object — hosts wrap as needed). */
@@ -263,6 +270,22 @@ export const memoryPrStatusArgs = {
263
270
  };
264
271
  export type MemoryPrStatusArgs = z.infer<z.ZodObject<typeof memoryPrStatusArgs>>;
265
272
 
273
+ export const memoryWorkingStateArgs = {
274
+ action: z
275
+ .enum(["read", "write", "clear"])
276
+ .default("read")
277
+ .describe(
278
+ "read = show the current note (empty when none); write = create or refresh it; clear = delete it.",
279
+ ),
280
+ content: z
281
+ .string()
282
+ .optional()
283
+ .describe(
284
+ "Note body, Markdown, short by design (required for write). Rubric: task summary (one paragraph), open files, last commands, where the work stands, next step. A scratch note, not a transcript.",
285
+ ),
286
+ };
287
+ export type MemoryWorkingStateArgs = z.infer<z.ZodObject<typeof memoryWorkingStateArgs>>;
288
+
266
289
  function resolveScope(
267
290
  getScope: () => Scope,
268
291
  kind?: "project" | "personal",
@@ -682,3 +705,67 @@ export async function prStatusOp(args: MemoryPrStatusArgs): Promise<ToolResult>
682
705
  }
683
706
  return { title: "memory: pr-status", output: lines.join("\n") };
684
707
  }
708
+
709
+ /**
710
+ * §3.6 (D89): the one ephemeral per-project working-state note. Scratch
711
+ * state, not knowledge — it never enters the review ladder or the
712
+ * retrieval index; durable conclusions still go through memory_add (agent
713
+ * proposes, user approves). The tool description and the session-start
714
+ * block must keep saying the same thing on this.
715
+ */
716
+ export async function workingStateMemory(
717
+ getScope: () => Scope,
718
+ cfg: MyOMemoryConfig,
719
+ args: MemoryWorkingStateArgs,
720
+ ): Promise<ToolResult> {
721
+ if (!cfg.workingStateEnabled) {
722
+ return {
723
+ title: "memory: working-state",
724
+ output:
725
+ "The working-state note is disabled (config workingStateEnabled=false). Enable it in the config file, or record durable facts with memory_add instead.",
726
+ };
727
+ }
728
+ const scope = getScope();
729
+ if (args.action === "clear") {
730
+ const gone = clearWorkingState(scope.key);
731
+ return {
732
+ title: "memory: working-state",
733
+ output: gone
734
+ ? `Working-state note for ${scope.projectName} deleted.`
735
+ : "Failed to delete the working-state note — it may still be on disk.",
736
+ };
737
+ }
738
+ if (args.action === "write") {
739
+ const content = (args.content ?? "").trim();
740
+ if (!content) {
741
+ return {
742
+ title: "memory: working-state",
743
+ output:
744
+ "Refusing an empty working-state note: pass content (task summary, open files, last commands, where the work stands, next step).",
745
+ };
746
+ }
747
+ const r = writeWorkingState(scope.key, content, cfg.workingStateTtlDays, cfg.redactPatterns);
748
+ const secretNote = r.hadSecret
749
+ ? `\n[open-memex: a secret was masked in place (${r.matchedPattern}) before saving]`
750
+ : "";
751
+ return {
752
+ title: "memory: working-state",
753
+ output:
754
+ `Working-state note written to ${r.filePath}. Surfaces at session start; expires after ${cfg.workingStateTtlDays} day${cfg.workingStateTtlDays === 1 ? "" : "s"} or at the next write.${secretNote}`,
755
+ };
756
+ }
757
+ const note = readWorkingState(scope.key, cfg.workingStateTtlDays);
758
+ if (!note) {
759
+ return {
760
+ title: "memory: working-state",
761
+ output: `No working-state note for ${scope.projectName}. Write one at wrap-up (action=write) so an interrupted task can resume.`,
762
+ };
763
+ }
764
+ const status = note.expired
765
+ ? `EXPIRED (${note.ageDays} day${note.ageDays === 1 ? "" : "s"} old, ttl ${note.ttlDays}) — stale until a write refreshes it`
766
+ : `updated ${note.ageDays} day${note.ageDays === 1 ? "" : "s"} ago, ttl ${note.ttlDays} day${note.ttlDays === 1 ? "" : "s"}`;
767
+ return {
768
+ title: "memory: working-state",
769
+ output: `[${status}]\n\n${note.content}`,
770
+ };
771
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * D89 / §3.6 — session working state note.
3
+ *
4
+ * One ephemeral Markdown note per project scope, at
5
+ * `working-state/<scope_key>.md` under the data root — beside the store,
6
+ * never inside `memories/`, never committed to a repo. The note is written
7
+ * or refreshed by the agent at wrap-up, surfaced at session start alongside
8
+ * the §7 injection, and never enters the review ladder: it is scratch
9
+ * state, not knowledge. Worth-keeping content routes through the D61
10
+ * checkpoint-proposal flow — the note is raw material, the ladder is the
11
+ * gate. Expired notes are reported by `audit` (reports only, never
12
+ * auto-deletes — the D57 posture); the next wrap-up write overwrites.
13
+ *
14
+ * Hermetic on purpose: only fs, paths and config types are imported, no
15
+ * sqlite — scripts/smoke-pure.ts keeps its no-sqlite guarantee.
16
+ */
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import { paths } from "./paths.ts";
20
+ import { redact } from "./redact.ts";
21
+ import { atomicWriteTextSync } from "./store/markdown.ts";
22
+ import type { MyOMemoryConfig } from "./config.ts";
23
+
24
+ const DAY_MS = 86_400_000;
25
+
26
+ export interface WorkingStateFile {
27
+ content: string;
28
+ /** Filesystem write time in ms (the note's own age anchor). */
29
+ updatedAtMs: number;
30
+ /** TTL days effective for this note (frontmatter `ttl_days`, falling
31
+ * back to the given default). */
32
+ ttlDays: number;
33
+ /** Whole-day age of the note. */
34
+ ageDays: number;
35
+ /** True when ageDays > ttlDays — ignored by surfacing, reported by audit. */
36
+ expired: boolean;
37
+ }
38
+
39
+ export interface WriteWorkingStateResult {
40
+ filePath: string;
41
+ hadSecret: boolean;
42
+ matchedPattern: string | null;
43
+ }
44
+
45
+ /** Read-only path helper — never creates the directory (D70 discipline;
46
+ * contrast the write path below, which mkdirs on demand). */
47
+ export function workingStatePath(scopeKey: string): string {
48
+ return path.join(paths().root, "working-state", `${scopeKey}.md`);
49
+ }
50
+
51
+ /**
52
+ * Write or refresh the note. The agent composes the body (task summary /
53
+ * open files / last commands / where the work stands / next step). Content
54
+ * passes through `redact()` so command paste-through from an interrupted
55
+ * session cannot park a readable secret in storage. TTL days is stamped
56
+ * into frontmatter so the user's per-note edit survives config changes.
57
+ */
58
+ export function writeWorkingState(
59
+ scopeKey: string,
60
+ content: string,
61
+ defaultTtlDays: number,
62
+ redactPatterns: string[],
63
+ ): WriteWorkingStateResult {
64
+ const { content: redacted, hadSecret, matchedPattern } = redact(content, redactPatterns);
65
+ const filePath = workingStatePath(scopeKey);
66
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
67
+ const ttlDays = Number.isInteger(defaultTtlDays) && defaultTtlDays > 0 ? defaultTtlDays : 7;
68
+ const text =
69
+ "---\n" +
70
+ "schema: working-state\n" +
71
+ `updated_at: ${new Date().toISOString()}\n` +
72
+ `ttl_days: ${ttlDays}\n` +
73
+ "---\n" +
74
+ redacted.trimEnd() +
75
+ "\n";
76
+ atomicWriteTextSync(filePath, text);
77
+ return { filePath, hadSecret, matchedPattern };
78
+ }
79
+
80
+ /**
81
+ * Read the note and compute expiry. Missing file → null. A note older than
82
+ * its TTL is marked expired (surfacing ignores it; audit reports it).
83
+ */
84
+ export function readWorkingState(
85
+ scopeKey: string,
86
+ defaultTtlDays: number,
87
+ ): WorkingStateFile | null {
88
+ const filePath = workingStatePath(scopeKey);
89
+ let raw: string;
90
+ try {
91
+ raw = fs.readFileSync(filePath, "utf8");
92
+ } catch {
93
+ return null;
94
+ }
95
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(raw);
96
+ if (!m) return null;
97
+ const fm = m[1] ?? "";
98
+ const updatedAt = /^updated_at:\s*(.+)$/m.exec(fm)?.[1]?.trim() ?? "";
99
+ const t = Date.parse(updatedAt);
100
+ if (Number.isNaN(t)) return null;
101
+ const ttlDaysRaw = /^ttl_days:\s*(\d+)\s*$/m.exec(fm)?.[1];
102
+ const ttlDays = ttlDaysRaw
103
+ ? Number.parseInt(ttlDaysRaw, 10)
104
+ : Number.isInteger(defaultTtlDays) && defaultTtlDays > 0
105
+ ? defaultTtlDays
106
+ : 7;
107
+ const ageDays = Math.max(0, Math.floor((Date.now() - t) / DAY_MS));
108
+ return {
109
+ content: raw.slice(m[0].length).trimEnd(),
110
+ updatedAtMs: t,
111
+ ttlDays,
112
+ ageDays,
113
+ expired: ageDays > ttlDays,
114
+ };
115
+ }
116
+
117
+ /**
118
+ * Delete the note. Honest delete (D63 spirit): true — deleted or already
119
+ * gone; false — the unlink failed (keeps reporting to worry about).
120
+ */
121
+ export function clearWorkingState(scopeKey: string): boolean {
122
+ const filePath = workingStatePath(scopeKey);
123
+ try {
124
+ fs.unlinkSync(filePath);
125
+ return true;
126
+ } catch (err) {
127
+ return (err as NodeJS.ErrnoException).code === "ENOENT";
128
+ }
129
+ }
130
+
131
+ /**
132
+ * D89: surfaced at session start, outside the review ladder. Returns null
133
+ * when nothing should surface: the feature is off, or no note exists, or
134
+ * the note has expired (audit is the reporter; silence at session start).
135
+ */
136
+ export function workingStateBlock(
137
+ scopeKey: string,
138
+ projectName: string,
139
+ cfg: MyOMemoryConfig,
140
+ ): string | null {
141
+ if (!cfg.workingStateEnabled) return null;
142
+ const note = readWorkingState(scopeKey, cfg.workingStateTtlDays);
143
+ if (!note || note.expired || !note.content) return null;
144
+ return (
145
+ `[OPEN-MEMEX WORKING STATE — ${projectName}]\n` +
146
+ "Scratch state from an interrupted task, not durable knowledge; do not save it as a memory.\n" +
147
+ note.content +
148
+ "\n\n" +
149
+ "This is the user's own recent work state, for resuming where the work stands. " +
150
+ "If something in it deserves to outlive the task, propose it as a distilled memory — the checkpoint-proposal flow is the gate, the note never enters a review ladder. " +
151
+ "When the user signals the session or task is wrapping up, refresh this note via `memory_workingstate` (action=write) before finishing: task summary, open files, last commands, where the work stands, next step."
152
+ );
153
+ }