open-memex 0.8.2-alpha.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.
@@ -1,6 +1,6 @@
1
1
  import { PERSONAL_SCOPE } from "../scope.js";
2
2
  import { syncScope } from "../store/sync.js";
3
- import { addMemory, searchMemories, listMemories, supersedeMemory, forgetMemory, memoryAddArgs, memorySearchArgs, memoryListArgs, memorySupersedeArgs, memoryForgetArgs, TOOL_DESCRIPTIONS, withOutboxNote, } from "./ops.js";
3
+ import { addMemory, searchMemories, listMemories, supersedeMemory, forgetMemory, workingStateMemory, memoryAddArgs, memorySearchArgs, memoryListArgs, memorySupersedeArgs, memoryForgetArgs, memoryWorkingStateArgs, TOOL_DESCRIPTIONS, withOutboxNote, } from "./ops.js";
4
4
  // Local stand-in for the SDK's tool() helper — same signature, and the SDK
5
5
  // function is a runtime identity (`return input`). Do NOT import it from
6
6
  // @opencode-ai/plugin at runtime: that package is a devDependency, and when
@@ -72,5 +72,14 @@ export function makeTools(getScope, cfg) {
72
72
  return withOutboxNote(getScope().key, forgetMemory(args));
73
73
  },
74
74
  });
75
- return { memory_add, memory_search, memory_list, memory_forget, memory_supersede };
75
+ // §3.6 (D89): no scope/index work needed — the note lives beside the
76
+ // store, not in it.
77
+ const memory_workingstate = tool({
78
+ description: TOOL_DESCRIPTIONS.memory_workingstate,
79
+ args: memoryWorkingStateArgs,
80
+ async execute(args) {
81
+ return workingStateMemory(getScope, cfg, args);
82
+ },
83
+ });
84
+ return { memory_add, memory_search, memory_list, memory_forget, memory_supersede, memory_workingstate };
76
85
  }
package/dist/tools/ops.js CHANGED
@@ -20,6 +20,7 @@ import { redact } from "../redact.js";
20
20
  import { getSyncStatus, formatSyncStatus, submitMemories, outboxDraftCount } from "../submit.js";
21
21
  import { getPrStatus, formatPrStatus, applyPrStatus } from "../github.js";
22
22
  import { isInRepoMemoryFile } from "../paths.js";
23
+ import { writeWorkingState, readWorkingState, clearWorkingState, } from "../working-state.js";
23
24
  import { proposeMemories, promoteMemory, listConflicts, resolveConflict, formatReviewHistory, } from "../review.js";
24
25
  /**
25
26
  * D53: push, don't poll. Append the project-outbox pending count to mutating
@@ -49,6 +50,7 @@ export const TOOL_DESCRIPTIONS = {
49
50
  memory_promote: "Advance a project memory one step up the review ladder (proposed → approved → published), or reject it with a note. Rejected memories are never deleted — they can be revised and resubmitted. One step per call; an unknown id or a memory already published errors. Pass `by` to record the reviewer when it should differ from the default (e.g. approving on the strength of someone else's review). For brand-new outbox drafts, memory_submit is the entry point. (MCP server and the `open-memex promote` CLI; the opencode native plugin does not expose this tool.)",
50
51
  memory_resolve: "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.)",
51
52
  memory_pr_status: "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.)",
53
+ memory_workingstate: "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.",
52
54
  };
53
55
  /** Shared zod input shapes (raw shape, not z.object — hosts wrap as needed). */
54
56
  export const scopeArg = z
@@ -174,6 +176,16 @@ export const memoryPrStatusArgs = {
174
176
  .optional()
175
177
  .describe("Perform the mapped review transitions locally (no push). Default: report only."),
176
178
  };
179
+ export const memoryWorkingStateArgs = {
180
+ action: z
181
+ .enum(["read", "write", "clear"])
182
+ .default("read")
183
+ .describe("read = show the current note (empty when none); write = create or refresh it; clear = delete it."),
184
+ content: z
185
+ .string()
186
+ .optional()
187
+ .describe("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."),
188
+ };
177
189
  function resolveScope(getScope, kind) {
178
190
  return kind === "personal" ? PERSONAL_SCOPE : getScope();
179
191
  }
@@ -537,3 +549,59 @@ export async function prStatusOp(args) {
537
549
  }
538
550
  return { title: "memory: pr-status", output: lines.join("\n") };
539
551
  }
552
+ /**
553
+ * §3.6 (D89): the one ephemeral per-project working-state note. Scratch
554
+ * state, not knowledge — it never enters the review ladder or the
555
+ * retrieval index; durable conclusions still go through memory_add (agent
556
+ * proposes, user approves). The tool description and the session-start
557
+ * block must keep saying the same thing on this.
558
+ */
559
+ export async function workingStateMemory(getScope, cfg, args) {
560
+ if (!cfg.workingStateEnabled) {
561
+ return {
562
+ title: "memory: working-state",
563
+ output: "The working-state note is disabled (config workingStateEnabled=false). Enable it in the config file, or record durable facts with memory_add instead.",
564
+ };
565
+ }
566
+ const scope = getScope();
567
+ if (args.action === "clear") {
568
+ const gone = clearWorkingState(scope.key);
569
+ return {
570
+ title: "memory: working-state",
571
+ output: gone
572
+ ? `Working-state note for ${scope.projectName} deleted.`
573
+ : "Failed to delete the working-state note — it may still be on disk.",
574
+ };
575
+ }
576
+ if (args.action === "write") {
577
+ const content = (args.content ?? "").trim();
578
+ if (!content) {
579
+ return {
580
+ title: "memory: working-state",
581
+ output: "Refusing an empty working-state note: pass content (task summary, open files, last commands, where the work stands, next step).",
582
+ };
583
+ }
584
+ const r = writeWorkingState(scope.key, content, cfg.workingStateTtlDays, cfg.redactPatterns);
585
+ const secretNote = r.hadSecret
586
+ ? `\n[open-memex: a secret was masked in place (${r.matchedPattern}) before saving]`
587
+ : "";
588
+ return {
589
+ title: "memory: working-state",
590
+ output: `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}`,
591
+ };
592
+ }
593
+ const note = readWorkingState(scope.key, cfg.workingStateTtlDays);
594
+ if (!note) {
595
+ return {
596
+ title: "memory: working-state",
597
+ output: `No working-state note for ${scope.projectName}. Write one at wrap-up (action=write) so an interrupted task can resume.`,
598
+ };
599
+ }
600
+ const status = note.expired
601
+ ? `EXPIRED (${note.ageDays} day${note.ageDays === 1 ? "" : "s"} old, ttl ${note.ttlDays}) — stale until a write refreshes it`
602
+ : `updated ${note.ageDays} day${note.ageDays === 1 ? "" : "s"} ago, ttl ${note.ttlDays} day${note.ttlDays === 1 ? "" : "s"}`;
603
+ return {
604
+ title: "memory: working-state",
605
+ output: `[${status}]\n\n${note.content}`,
606
+ };
607
+ }
@@ -0,0 +1,118 @@
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.js";
20
+ import { redact } from "./redact.js";
21
+ import { atomicWriteTextSync } from "./store/markdown.js";
22
+ const DAY_MS = 86_400_000;
23
+ /** Read-only path helper — never creates the directory (D70 discipline;
24
+ * contrast the write path below, which mkdirs on demand). */
25
+ export function workingStatePath(scopeKey) {
26
+ return path.join(paths().root, "working-state", `${scopeKey}.md`);
27
+ }
28
+ /**
29
+ * Write or refresh the note. The agent composes the body (task summary /
30
+ * open files / last commands / where the work stands / next step). Content
31
+ * passes through `redact()` so command paste-through from an interrupted
32
+ * session cannot park a readable secret in storage. TTL days is stamped
33
+ * into frontmatter so the user's per-note edit survives config changes.
34
+ */
35
+ export function writeWorkingState(scopeKey, content, defaultTtlDays, redactPatterns) {
36
+ const { content: redacted, hadSecret, matchedPattern } = redact(content, redactPatterns);
37
+ const filePath = workingStatePath(scopeKey);
38
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
39
+ const ttlDays = Number.isInteger(defaultTtlDays) && defaultTtlDays > 0 ? defaultTtlDays : 7;
40
+ const text = "---\n" +
41
+ "schema: working-state\n" +
42
+ `updated_at: ${new Date().toISOString()}\n` +
43
+ `ttl_days: ${ttlDays}\n` +
44
+ "---\n" +
45
+ redacted.trimEnd() +
46
+ "\n";
47
+ atomicWriteTextSync(filePath, text);
48
+ return { filePath, hadSecret, matchedPattern };
49
+ }
50
+ /**
51
+ * Read the note and compute expiry. Missing file → null. A note older than
52
+ * its TTL is marked expired (surfacing ignores it; audit reports it).
53
+ */
54
+ export function readWorkingState(scopeKey, defaultTtlDays) {
55
+ const filePath = workingStatePath(scopeKey);
56
+ let raw;
57
+ try {
58
+ raw = fs.readFileSync(filePath, "utf8");
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(raw);
64
+ if (!m)
65
+ return null;
66
+ const fm = m[1] ?? "";
67
+ const updatedAt = /^updated_at:\s*(.+)$/m.exec(fm)?.[1]?.trim() ?? "";
68
+ const t = Date.parse(updatedAt);
69
+ if (Number.isNaN(t))
70
+ return null;
71
+ const ttlDaysRaw = /^ttl_days:\s*(\d+)\s*$/m.exec(fm)?.[1];
72
+ const ttlDays = ttlDaysRaw
73
+ ? Number.parseInt(ttlDaysRaw, 10)
74
+ : Number.isInteger(defaultTtlDays) && defaultTtlDays > 0
75
+ ? defaultTtlDays
76
+ : 7;
77
+ const ageDays = Math.max(0, Math.floor((Date.now() - t) / DAY_MS));
78
+ return {
79
+ content: raw.slice(m[0].length).trimEnd(),
80
+ updatedAtMs: t,
81
+ ttlDays,
82
+ ageDays,
83
+ expired: ageDays > ttlDays,
84
+ };
85
+ }
86
+ /**
87
+ * Delete the note. Honest delete (D63 spirit): true — deleted or already
88
+ * gone; false — the unlink failed (keeps reporting to worry about).
89
+ */
90
+ export function clearWorkingState(scopeKey) {
91
+ const filePath = workingStatePath(scopeKey);
92
+ try {
93
+ fs.unlinkSync(filePath);
94
+ return true;
95
+ }
96
+ catch (err) {
97
+ return err.code === "ENOENT";
98
+ }
99
+ }
100
+ /**
101
+ * D89: surfaced at session start, outside the review ladder. Returns null
102
+ * when nothing should surface: the feature is off, or no note exists, or
103
+ * the note has expired (audit is the reporter; silence at session start).
104
+ */
105
+ export function workingStateBlock(scopeKey, projectName, cfg) {
106
+ if (!cfg.workingStateEnabled)
107
+ return null;
108
+ const note = readWorkingState(scopeKey, cfg.workingStateTtlDays);
109
+ if (!note || note.expired || !note.content)
110
+ return null;
111
+ return (`[OPEN-MEMEX WORKING STATE — ${projectName}]\n` +
112
+ "Scratch state from an interrupted task, not durable knowledge; do not save it as a memory.\n" +
113
+ note.content +
114
+ "\n\n" +
115
+ "This is the user's own recent work state, for resuming where the work stands. " +
116
+ "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. " +
117
+ "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.");
118
+ }
package/docs/CONCEPTS.md CHANGED
@@ -175,6 +175,22 @@ outbox drafts — drafts stay findable, but never pose as vetted.
175
175
  - **personal never enters git** (§1) — not by `submit`, not by `export`
176
176
  defaults, not ever.
177
177
 
178
+ ## 8. The working-state note: resuming an interrupted task (D89, §3.6)
179
+
180
+ Durable knowledge answers "what is true here"; a scheduled task also needs
181
+ "where am I in it". One ephemeral Markdown note per project lives under
182
+ `<data root>/working-state/<scope key>.md` — outside `memories/`, outside git,
183
+ off the retrieval index. The agent writes it at wrap-up via the
184
+ `memory_workingstate` tool (opencode has no Stop hook, so wrap-up means the
185
+ user signaling the task is ending); the content rubric is task summary, open
186
+ files, last commands, where the work stands, next step. The note surfaces at
187
+ session start next to the first-turn injection, framed as scratch state; it
188
+ never enters the review ladder — if something here deserves to outlive the
189
+ task, the normal propose-first flow turns it into a memory. TTL defaults to 7
190
+ days (`config set workingStateTtlDays`); expired notes stay silent at session
191
+ start and are reported by `audit`. `open-memex wstate` reads/clears it; edit
192
+ the plain file directly if you like.
193
+
178
194
  ---
179
195
 
180
196
  *Design record: `docs/V2-DESIGN.md` (append-only decision log). Per-scope
@@ -157,6 +157,19 @@ draft 找得到,但绝不冒充已审。
157
157
  - **personal 永不进 git**(§1)——`submit` 不行、`export` 默认不行、
158
158
  任何方式都不行。
159
159
 
160
+ ## 8. 工作状态笔记:续接被中断的任务(D89,§3.6)
161
+
162
+ 耐久知识回答"这里什么是真的";过了一天的任务还要回答"我做到哪了"。
163
+ 每个项目一份临时 Markdown 笔记,存放在 `<数据根>/working-state/<作用域键>.md`
164
+ ——在 `memories/` 之外、git 之外、检索索引之外。助手在收尾时通过
165
+ `memory_workingstate` 工具写(opencode 没有 Stop 钩子,所以"收尾"指用户发出
166
+ 任务结束的信号);正文骨架是任务摘要、打开的文件、最后的命令、进度在哪、
167
+ 下一步。笔记在会话开始时随首轮注入一起浮现,并被明确定位为草稿状态;它
168
+ 永不进入评审阶梯——若其中有值得留下的内容,走正常的先提议流程转成记忆。
169
+ TTL 默认 7 天(`config set workingStateTtlDays`);过期笔记在会话开始时
170
+ 保持沉默、由 `audit` 报告。`open-memex wstate` 读取/清除;文件本身是纯文本,
171
+ 想直接编辑也行。
172
+
160
173
  ---
161
174
 
162
175
  *设计记录:`docs/V2-DESIGN.md`(只追加的决策日志)。按作用域的细节: