@vasilvestre/opencode-dream-memory 0.3.1 → 0.5.0

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.
@@ -75,9 +75,20 @@ export default {
75
75
  const location = ctx.location ?? {};
76
76
  const directory =
77
77
  location.project?.canonical || location.project?.directory || location.directory;
78
- await ctx.session.hook('context', (event) => {
79
- const block = memoryBlock(directory);
80
- if (block) event.system.push({ type: 'text', text: block });
81
- });
78
+ const register = async (name) => {
79
+ await ctx.session.hook(name, (event) => {
80
+ try {
81
+ const block = memoryBlock(directory);
82
+ // Both events carry a system array of text parts. Compaction reads the
83
+ // same memory the agent loop does, so the summary keeps it. We append
84
+ // and never set event.result: the model still writes the summary.
85
+ if (block) event.system.push({ type: 'text', text: block });
86
+ } catch {
87
+ // A throwing hook breaks the request it runs on. Inject nothing.
88
+ }
89
+ });
90
+ };
91
+ await register('context');
92
+ await register('compaction');
82
93
  },
83
94
  };
package/README.md CHANGED
@@ -10,10 +10,15 @@ Two pieces that give an OpenCode agent memory across sessions:
10
10
  summarizes the conversation and the instructions file goes with it. A plugin
11
11
  hook runs on every agent-loop request, so the same block is re-sent each turn.
12
12
 
13
+ The plugin also registers the `compaction` hook, so the memory reaches the
14
+ request that writes the summary. The model still writes the summary; the plugin
15
+ only adds context. Without that hook, a long session could compact away the
16
+ memory it just read.
17
+
13
18
  ## Install
14
19
 
15
20
  Requirements: `opencode` and `jq` on `PATH`, `curl` or `wget` to download, and
16
- systemd for the timer.
21
+ systemd for the timer. `dream discover` also needs the `sqlite3` command.
17
22
 
18
23
  ```bash
19
24
  curl -fsSL https://raw.githubusercontent.com/vasilvestre/opencode-dream-memory/main/install.sh | sh
@@ -52,7 +57,9 @@ symlinks its own copy keeps working.
52
57
 
53
58
  The deep pass leaves an audit trail: `dreaming/deep/<date>.md` lists each
54
59
  promoted fact with the light-report line that supports it, so a fact stays
55
- checkable after the corpus is gone.
60
+ checkable after the corpus is gone. A reverted pass puts the report and the
61
+ diary entry back as they were and adds one `Reverted` line, so the audit trail
62
+ only describes facts that are still in memory.
56
63
 
57
64
  If `opencode` is not on the systemd default `PATH`, write its directory to
58
65
  `~/.config/dream.env`, which the unit reads when present:
@@ -102,9 +109,14 @@ Two files, read fresh on every request:
102
109
 
103
110
  `<name>` is the base name of the project directory: `~/homelab` reads
104
111
  `projects/homelab/MEMORY.md`. The corpus uses the same tag, so a candidate
105
- lands in the file of the project it came from. OpenCode creates one plugin
106
- instance per project location, so the hook knows which project it serves; a
107
- worktree uses the name of its main repository.
112
+ lands there by default; the deep pass may move a fact to the file of another
113
+ project it is about, but only when that project is already tracked (listed in
114
+ `dream-projects`). `dream` restores shared memory, the diary entry, the deep
115
+ report and every project file from before the run as soon as the deep pass
116
+ writes outside that list, whatever the pass exit code. The run then exits
117
+ non-zero, so the timer reports the night as failed.
118
+ OpenCode creates one plugin instance per project location, so the hook knows
119
+ which project it serves; a worktree uses the name of its main repository.
108
120
 
109
121
  The block opens with a header saying the content comes from a nightly pass and
110
122
  may be stale. Top-level titles are dropped. A part that is missing, empty or
@@ -181,6 +193,7 @@ and that flag beats the agent's pinned model. Override the file path with
181
193
  | `dream` | builds the corpus, then the light and deep passes |
182
194
  | `dream corpus` | only the corpus, no model, no cost |
183
195
  | `dream status` | one screen of state, read-only |
196
+ | `dream discover` | lists the git repositories opencode saw but the project list omits |
184
197
  | `dream reset` | deletes memory, diary, staging and corpus under `DREAM_HOME` |
185
198
 
186
199
  `dream reset` asks for confirmation; add `--yes` to skip it. It never touches
@@ -197,10 +210,11 @@ the same thing as the two subcommands.
197
210
  npm test
198
211
  ```
199
212
 
200
- The plugin checks: the hook registers, missing files inject nothing, shared
213
+ The plugin checks: both hooks register, missing files inject nothing, shared
201
214
  memory alone injects one block, the current project's file is appended after it
202
215
  while another project's stays out, an oversized file is truncated without the
203
- whole block growing, and titles are dropped. Then the corpus checks: the dream's
216
+ whole block growing, titles are dropped, the `compaction` hook injects the same
217
+ block as the `context` hook, and it never sets `result`. Then the corpus checks: the dream's
204
218
  own sessions stay out, a labelled secret is redacted, a torn session export is
205
219
  skipped instead of fatal, and a git data directory gets a preimage commit before
206
220
  the deep pass.
@@ -44,9 +44,19 @@ Two destinations:
44
44
 
45
45
  - `MEMORY.md` holds facts that are true in every project: how the user wants
46
46
  work done, their general preferences. Keep it under **900 characters**.
47
- - `projects/<project>/MEMORY.md` holds facts about one project. The
48
- `project:` line of the candidate gives the name: `project: homelab` means
49
- `projects/homelab/MEMORY.md`. Keep each file under **2 800 characters**.
47
+ - `projects/<project>/MEMORY.md` holds facts about one project. The `project:`
48
+ line is the default name: `project: homelab` means `projects/homelab/MEMORY.md`.
49
+ The `subject:` line is the project the fact is about; write the fact to
50
+ `projects/<subject>/MEMORY.md` when it differs from the tag. The subject must
51
+ be tracked: a name from the tracked projects list in your prompt, the entries
52
+ of `dream-projects`, and a single path segment matching `[A-Za-z0-9._-]+`,
53
+ never `.`, `..`, or a string with `/`. A file left over from a project that
54
+ left `dream-projects` is not tracked, even though the file exists. When the
55
+ subject is not tracked, ignore it and keep the fact under its tag; name the
56
+ skipped subject in the report. Never write a project file outside the tracked
57
+ list: `dream` restores shared memory, the diary entry and the project files
58
+ from before the pass when it sees one, and drops that run's report. Keep each
59
+ file under **2 800 characters**.
50
60
 
51
61
  The plugin injects shared memory into every session, and the current project's
52
62
  file only. It cuts shared memory at 1 000 characters and a project file at
@@ -66,12 +76,14 @@ fits. Deleting a stale fact is part of this pass, not an exception to it.
66
76
  - When a file would exceed its budget, delete the weakest facts to make room.
67
77
  Never shorten a line below readability to make it fit.
68
78
  - Write a fact about a machine, a repository or a setup into that project's
69
- file, not into shared memory.
79
+ file, not into shared memory, when the project is tracked.
70
80
  - If shared memory holds a fact about one project, move it into that project's
71
- file and delete it from shared memory.
81
+ file and delete it from shared memory. When that project is untracked, leave
82
+ the fact in shared memory: no tracked project file may hold it.
72
83
  - Never write a secret, a token, or a password.
73
- - If a project file does not exist, create it with a `# <project>` title. Never
74
- create one for a project that has no candidate today.
84
+ - Never create a `projects/<name>/MEMORY.md` file here. The tracked set is the
85
+ entries of `dream-projects`; a fact whose subject is untracked stays under
86
+ its tag, and the report names the skipped subject.
75
87
 
76
88
  ## 2. Report
77
89
 
@@ -85,6 +97,7 @@ Write `dreaming/deep/<today>.md`:
85
97
  - Removed <n> stale entr(y|ies).
86
98
  - Pruned <n> candidate(s) as one-off.
87
99
  - Changed: MEMORY.md, projects/<name>/MEMORY.md.
100
+ - Moved: projects/<tag> -> projects/<subject>.
88
101
 
89
102
  ## Sources
90
103
 
@@ -34,6 +34,7 @@ For each candidate, write:
34
34
  ```
35
35
  - Candidate: <one sentence, under 200 characters>
36
36
  - project: <the tag from the corpus>
37
+ - subject: <the project the fact is about; the tag when unsure>
37
38
  - confidence: <0.00 to 1.00>
38
39
  - evidence: .dreams/session-corpus/<today>.txt:<line>
39
40
  - recalls: 0
@@ -42,13 +43,17 @@ For each candidate, write:
42
43
 
43
44
  Rules:
44
45
 
46
+ - `subject` names the project the fact is about. Keep it equal to `project`
47
+ unless the candidate is clearly about another project; use that project's
48
+ directory base name, never a paraphrase or a guess.
45
49
  - At most 15 candidates. Keep the ones a future session would actually need.
46
50
  - Prefer what concerns the user: their preferences, corrections, decisions,
47
51
  recurring problems, and verified facts about their machines.
48
52
  - Ignore project documentation that already lives in the repository.
49
53
  - Never record secrets, tokens, passwords, API keys, or file contents that
50
54
  look like credentials. If the corpus holds one, do not quote it.
51
- - Skip anything already written in `MEMORY.md`, in `projects/<project>/MEMORY.md`
52
- or in a previous light file.
55
+ - Skip anything already written in `MEMORY.md`, in
56
+ `projects/<project>/MEMORY.md`, in `projects/<subject>/MEMORY.md` or in a
57
+ previous light file.
53
58
  - If the corpus is empty or holds nothing durable, write only the heading and
54
59
  the line `- No candidates today.`
package/dream/dream CHANGED
@@ -4,6 +4,7 @@
4
4
  # Usage: dream corpus, then the light and deep passes (two agent runs)
5
5
  # dream corpus corpus only, no model, no cost
6
6
  # dream status one screen of state, read-only
7
+ # dream discover git repos seen by opencode, missing from the list
7
8
  # dream reset delete memory, diary, staging and corpus (asks first)
8
9
  #
9
10
  # Everything is written under $DREAM_HOME (default ~/dreams), never in the
@@ -50,8 +51,39 @@ EOF
50
51
  echo "dream: reset done, $root is empty" >&2
51
52
  exit 0
52
53
  ;;
54
+ discover)
55
+ # Print the git repositories opencode has seen but the project list omits,
56
+ # so you can paste the missing ones in by hand. No model, no writes.
57
+ db="${DREAM_DB:-$HOME/.local/share/opencode/opencode.db}"
58
+ config="${XDG_CONFIG_HOME:-$HOME/.config}/opencode"
59
+ command -v sqlite3 >/dev/null 2>&1 || { echo "dream: discover needs sqlite3" >&2; exit 1; }
60
+ [ -r "$db" ] || { echo "dream: no opencode database at $db" >&2; exit 1; }
61
+ listed="${DREAM_PROJECTS:-$HOME/.config/opencode/dream-projects}"
62
+ # The live database is in WAL mode. A read-only open needs a -shm that only
63
+ # a running server holds, and a read-write open would create one. Query a
64
+ # private copy instead, so the server's files stay untouched.
65
+ tmp=$(mktemp -d) || { echo "dream: cannot create a temporary directory" >&2; exit 1; }
66
+ trap 'rm -rf "$tmp"' EXIT
67
+ # The -wal goes first: a checkpoint between the two copies must not leave
68
+ # the db ahead of the frames the copy still holds.
69
+ if [ -e "${db}-wal" ]; then
70
+ cp "${db}-wal" "$tmp/db-wal" || { echo "dream: cannot read ${db}-wal" >&2; exit 1; }
71
+ fi
72
+ cp "$db" "$tmp/db" || { echo "dream: cannot read $db" >&2; exit 1; }
73
+ # A failed query is fatal: an empty result reads as "nothing is missing".
74
+ rows=$(sqlite3 -readonly "$tmp/db" 'select distinct worktree from project') ||
75
+ { echo "dream: cannot query $db" >&2; exit 1; }
76
+ printf '%s\n' "$rows" | while IFS= read -r dir; do
77
+ case $dir in ''|/|"$HOME"|"$HOME/"|"$config"|"$root"|"$root/"|"$HOME/.cache"*|*/.local/share/opencode|*/state/work/*) continue ;; esac
78
+ # A nested worktree has a .git file, not a directory; skip it.
79
+ [ -d "$dir/.git" ] || continue
80
+ if [ -r "$listed" ] && grep -Fxq "$dir" "$listed"; then continue; fi
81
+ printf '%s\n' "$dir"
82
+ done | sort -u
83
+ exit 0
84
+ ;;
53
85
  '') ;;
54
- *) echo "dream: unknown command '$1' (try: dream, dream status, dream corpus, dream reset)" >&2; exit 2 ;;
86
+ *) echo "dream: unknown command '$1' (try: dream, dream status, dream corpus, dream discover, dream reset)" >&2; exit 2 ;;
55
87
  esac
56
88
 
57
89
  list="${DREAM_PROJECTS:-$HOME/.config/opencode/dream-projects}"
@@ -78,16 +110,97 @@ cd "$root"
78
110
  # One memory file per tracked project, so the deep pass only ever edits files
79
111
  # that exist. Named after the project directory, the same tag dream-corpus
80
112
  # writes into the corpus.
113
+ tracked=
81
114
  while IFS= read -r project; do
82
115
  case $project in ''|\#*) continue ;; esac
83
116
  name=$(basename "$project")
84
117
  case $name in ''|.|..) continue ;; esac
118
+ tracked="${tracked}${tracked:+, }$name"
85
119
  memory="$root/projects/$name/MEMORY.md"
86
120
  [ -f "$memory" ] && continue
87
121
  mkdir -p "$(dirname "$memory")"
88
122
  printf '# %s\n' "$name" > "$memory"
89
123
  done < "$list"
90
124
 
125
+ # The deep pass may write only tracked project files: the plugin injects
126
+ # projects/<name>/MEMORY.md for any directory of that name, so a line planted in
127
+ # an untracked file outlives the run. Snapshot shared memory, the project files,
128
+ # the diary and today's deep report, then, after the pass, restore all of them
129
+ # unless every changed project file is tracked.
130
+ backup=$(mktemp -d)
131
+ keep_backup=0
132
+ trap '[ "$keep_backup" = 1 ] || rm -rf "$backup"' EXIT
133
+ mkdir -p "$root/projects" "$backup/projects"
134
+
135
+ # Copy one file into the snapshot, or stop before spending a model call: a
136
+ # partial snapshot restored later would overwrite the real file. An absent file
137
+ # stays absent, so the restore removes one the pass creates.
138
+ snapshot() {
139
+ [ -e "$root/$1" ] || return 0
140
+ mkdir -p "$(dirname "$backup/$1")"
141
+ cp "$root/$1" "$backup/$1" ||
142
+ { echo "dream: cannot snapshot $root/$1, stopping before the deep pass" >&2; exit 1; }
143
+ }
144
+ snapshot MEMORY.md
145
+ snapshot DREAMS.md
146
+ snapshot "dreaming/deep/$day.md"
147
+ cp -R "$root/projects/." "$backup/projects/" ||
148
+ { echo "dream: cannot snapshot $root/projects, stopping before the deep pass" >&2; exit 1; }
149
+
150
+ is_tracked() {
151
+ while IFS= read -r project; do
152
+ case $project in ''|\#*) continue ;; esac
153
+ [ "$(basename "$project")" = "$1" ] && return 0
154
+ done < "$list"
155
+ return 1
156
+ }
157
+
158
+ # Print the first changed or new project file whose name is not tracked, so the
159
+ # caller can report it; exit 1 when every change stayed inside the tracked set.
160
+ untracked_write() {
161
+ for memory in "$root"/projects/*/MEMORY.md; do
162
+ [ -f "$memory" ] || continue
163
+ name=$(basename "$(dirname "$memory")")
164
+ is_tracked "$name" && continue
165
+ before="$backup/projects/$name/MEMORY.md"
166
+ if [ -f "$before" ] && cmp -s "$before" "$memory"; then
167
+ continue
168
+ fi
169
+ printf 'projects/%s/MEMORY.md\n' "$name"
170
+ return 0
171
+ done
172
+ return 1
173
+ }
174
+
175
+ # Copy one snapshotted file back, or remove the one the pass created.
176
+ restore_file() {
177
+ if [ -f "$backup/$1" ]; then
178
+ mkdir -p "$(dirname "$root/$1")"
179
+ cp "$backup/$1" "$root/$1" || return 1
180
+ else
181
+ rm -f "$root/$1"
182
+ fi
183
+ }
184
+
185
+ # Put shared memory, the project files, the diary and today's deep report back
186
+ # exactly as before the pass. The project tree is copied beside the target and
187
+ # swapped in: a failed copy leaves the old tree in place, and a failed swap puts
188
+ # it back before returning. Return 1 on any failure: the caller then keeps
189
+ # $backup and reports where it is.
190
+ restore_memory() {
191
+ rm -rf "$root/projects.new" "$root/projects.old"
192
+ cp -R "$backup/projects" "$root/projects.new" || return 1
193
+ mv "$root/projects" "$root/projects.old" || return 1
194
+ if ! mv "$root/projects.new" "$root/projects"; then
195
+ mv "$root/projects.old" "$root/projects" || true
196
+ return 1
197
+ fi
198
+ rm -rf "$root/projects.old"
199
+ restore_file MEMORY.md || return 1
200
+ restore_file DREAMS.md || return 1
201
+ restore_file "dreaming/deep/$day.md" || return 1
202
+ }
203
+
91
204
  # Per-stage model choice: "<stage> <model> [<model> ...]", first that works wins.
92
205
  # The light pass reads raw session text, so this is where a local or paid
93
206
  # provider matters. Missing file or missing stage falls back to the paid
@@ -141,8 +254,30 @@ if git -C "$root" rev-parse --git-dir >/dev/null 2>&1; then
141
254
  fi
142
255
 
143
256
  echo "dream: deep"
144
- if run_agent dream-deep \
145
- "Promote today's candidates and write the diary entry for $day." "deep $day"; then
257
+ deep_ok=1
258
+ run_agent dream-deep \
259
+ "Promote today's candidates and write the diary entry for $day. Tracked projects: ${tracked:-none}." "deep $day" || deep_ok=0
260
+
261
+ # Restore memory, diary and report unless the pass stayed inside the tracked
262
+ # set, whatever its exit code. A crash after an edit is undone the same way, and
263
+ # a restore skips the cursor advance so the session is read again. The run then
264
+ # fails, so a night that keeps reverting shows up as a failed unit.
265
+ reverted=$(untracked_write || true)
266
+ if [ "$deep_ok" = 0 ] || [ -n "$reverted" ]; then
267
+ if ! restore_memory; then
268
+ keep_backup=1
269
+ echo "dream: restore failed, the pre-pass copy stays in $backup" >&2
270
+ exit 1
271
+ fi
272
+ if [ -n "$reverted" ]; then
273
+ printf '\n- Reverted (not tracked, read again next run): %s\n' "$reverted" \
274
+ >> "$root/dreaming/deep/$day.md"
275
+ else
276
+ printf '\n- Reverted (deep pass failed, read again next run)\n' \
277
+ >> "$root/dreaming/deep/$day.md"
278
+ fi
279
+ exit 1
280
+ else
146
281
  # Advance each project's cursor only after both passes succeeded, so a failed
147
282
  # run is retried on the same slice instead of losing it. A project without a
148
283
  # git repo is skipped by dream-corpus, so it keeps a zero cursor and its full
package/install.sh CHANGED
@@ -25,6 +25,7 @@ ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
25
25
 
26
26
  command -v opencode >/dev/null || { echo "install: opencode is not on PATH" >&2; exit 1; }
27
27
  command -v jq >/dev/null || { echo "install: jq is not on PATH" >&2; exit 1; }
28
+ command -v sqlite3 >/dev/null || echo "install: sqlite3 is not on PATH, 'dream discover' will not run" >&2
28
29
 
29
30
  # A piped install has no dream/ next to the script, so fetch the archive.
30
31
  if [ ! -d "$ROOT/dream" ]; then
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vasilvestre/opencode-dream-memory",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "Injects shared and per-project memory files into every OpenCode request, so they survive context compaction.",
5
5
  "keywords": [
6
6
  "opencode-plugin",
@@ -26,7 +26,7 @@
26
26
  "./plugin": "./.opencode/plugins/dream-memory.js"
27
27
  },
28
28
  "scripts": {
29
- "test": "node scripts/check-plugin.mjs && sh scripts/check-corpus.sh"
29
+ "test": "node scripts/check-plugin.mjs && sh scripts/check-corpus.sh && sh scripts/check-discover.sh"
30
30
  },
31
31
  "files": [
32
32
  ".opencode/",