notesoup 0.51.9 → 0.52.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.
Files changed (72) hide show
  1. package/README.md +3 -10
  2. package/dist/plugins/claude/src/history.js +3 -7
  3. package/dist/plugins/pi/notes/tools.d.ts +1 -1
  4. package/dist/plugins/pi/notes/tools.js +26 -7
  5. package/dist/plugins/pi/tool-result.d.ts +3 -2
  6. package/dist/plugins/pi/tool-result.js +3 -1
  7. package/dist/src/dream/git.d.ts +2 -3
  8. package/dist/src/dream/git.js +3 -8
  9. package/dist/src/dream/lock.d.ts +10 -27
  10. package/dist/src/dream/lock.js +16 -79
  11. package/dist/src/notes/errors.d.ts +1 -1
  12. package/dist/src/notes/identity.d.ts +2 -0
  13. package/dist/src/notes/identity.js +3 -1
  14. package/dist/src/notes/store.d.ts +2 -0
  15. package/dist/src/notes/store.js +40 -4
  16. package/dist/src/tools/dream.d.ts +113 -0
  17. package/dist/src/tools/dream.js +112 -0
  18. package/dist/src/tools/notes.d.ts +15 -1
  19. package/dist/src/tools/notes.js +4 -4
  20. package/dist/test/claude-history.test.js +18 -2
  21. package/dist/test/claude-mod.test.js +115 -30
  22. package/dist/test/dependencies.test.js +3 -6
  23. package/dist/test/dream-skill.test.js +2 -3
  24. package/dist/test/dream-tools.test.js +67 -0
  25. package/docs/claude-code-mod.md +1 -1
  26. package/docs/notes-library.md +1 -1
  27. package/docs/skills.md +12 -15
  28. package/package.json +2 -5
  29. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  30. package/plugins/claude/dist/claude/helper.js +30 -22
  31. package/plugins/claude/hooks/register.ts +52 -33
  32. package/plugins/claude/src/history.ts +3 -6
  33. package/plugins/pi/notes/tools.ts +25 -8
  34. package/plugins/pi/tool-result.ts +4 -1
  35. package/src/dream/git.ts +3 -8
  36. package/src/dream/lock.ts +18 -66
  37. package/src/notes/errors.ts +1 -1
  38. package/src/notes/identity.ts +4 -1
  39. package/src/notes/store.ts +37 -4
  40. package/src/tools/dream.ts +112 -0
  41. package/src/tools/notes.ts +4 -4
  42. package/dist/plugins/pi/dream/cli.d.ts +0 -10
  43. package/dist/plugins/pi/dream/cli.js +0 -173
  44. package/dist/plugins/pi/dream/runner.d.ts +0 -27
  45. package/dist/plugins/pi/dream/runner.js +0 -91
  46. package/dist/plugins/pi/dream/settings.d.ts +0 -7
  47. package/dist/plugins/pi/dream/settings.js +0 -17
  48. package/dist/src/dream/doctor.d.ts +0 -2
  49. package/dist/src/dream/doctor.js +0 -161
  50. package/dist/src/dream/gates.d.ts +0 -10
  51. package/dist/src/dream/gates.js +0 -26
  52. package/dist/src/dream/jail.d.ts +0 -11
  53. package/dist/src/dream/jail.js +0 -71
  54. package/dist/src/dream/report.d.ts +0 -7
  55. package/dist/src/dream/report.js +0 -34
  56. package/dist/src/dream/result.d.ts +0 -9
  57. package/dist/src/dream/settings.d.ts +0 -9
  58. package/dist/src/dream/settings.js +0 -16
  59. package/dist/test/doctor.test.d.ts +0 -1
  60. package/dist/test/doctor.test.js +0 -37
  61. package/dist/test/dream.test.d.ts +0 -1
  62. package/dist/test/dream.test.js +0 -150
  63. package/plugins/pi/dream/cli.ts +0 -118
  64. package/plugins/pi/dream/runner.ts +0 -92
  65. package/plugins/pi/dream/settings.ts +0 -17
  66. package/src/dream/doctor.ts +0 -118
  67. package/src/dream/gates.ts +0 -26
  68. package/src/dream/jail.ts +0 -62
  69. package/src/dream/report.ts +0 -32
  70. package/src/dream/result.ts +0 -2
  71. package/src/dream/settings.ts +0 -19
  72. /package/dist/{src/dream/result.js → test/dream-tools.test.d.ts} +0 -0
package/docs/skills.md CHANGED
@@ -1,30 +1,27 @@
1
- # Skills, dream, and the notes doctor
1
+ # Skills and dream
2
2
 
3
3
  ## Memory skill
4
4
 
5
5
  The package provides `/skill:memory`, a short self-contained guide to the notes and history tools: note addresses and homes, finding and paging notes, searching and paging history, saving recovery state, and what to do when a memory tool is unavailable. It is a fallback for sessions where the boot protocol is missing or unclear and a reference on demand; normal tool calls do not require reading it. It is written independently of the boot text rather than generated from it. The Claude Code Mod ships the same guide; its history tools require the documented main-session transcript path and a confirmed append head.
6
6
 
7
- ## Dream skill
7
+ ## Dream
8
8
 
9
- The package also provides `/skill:dream` for reviewing notes in the current agent session. The skill reads the same `playbook.md` used by the `dream` CLI; there is only one set of dream instructions.
9
+ `/skill:dream` reviews notes in the current agent session, following the shared `playbook.md`.
10
10
 
11
- Scope comes from the invocation directory: inside the notes store, dream may inspect across homes; in a project, it extracts from that project's material and all session notes with matching project metadata, and organizes only that project's notes. New session notes record their project key in the frontmatter `project` field. Standard linked Git worktrees resolve to the main checkout's repository root, sharing its project key and `@project/` home. Older metadata and homes remain untouched by the code: there is no automatic migration or backfill; existing data can be migrated manually. Notes without project metadata are skipped in project-only discovery. Changing directories later does not broaden the scope.
11
+ In Pi the session gets three hidden `dream_*` tools; they are not declared to the model and are found with `tool_search` or codemode's `searchTools("dream")`:
12
12
 
13
- The skill stays in the current agent session. Its wrapper and shared playbook describe the dreamer's task, not runtime setup: the execution entry point is responsible for supplying readable/writable scope and establishing write permission, including locking and Git audit safeguards. The CLI supplies its own safeguards; the bare skill does not install them. Without an established scope and write permission, the dreamer asks rather than improvising runtime setup. Session records and unapproved homes stay untouched.
13
+ - `dream_begin(project?)` opens one project, by default the current one, as in `@projects/<name>/`. It lists that project's notes and every session note whose frontmatter `project` names it, crumpled notes included. While it is open, `notes_write` and `notes_update` may edit those addresses (existing notes only in other sessions), and reads leave no access stamp. Other projects stay read-only.
14
+ - `dream_forget(address)` permanently deletes one crumpled note within reach; live notes refuse.
15
+ - `dream_end()` closes the dream.
14
16
 
15
- ## Check the notes store
17
+ One session dreams over one project at a time. New session notes record their project key in `project`; notes without it never appear in a project's dream. Standard linked Git worktrees share the main checkout's project key.
16
18
 
17
- Run `dream doctor` (or `dream doctor --notes-home <dir>`) to check home layout, note frontmatter, concrete backtick-quoted note addresses, MAP entries, and lock presence/format. It is read-only: no model, git commits, directory creation, or repairs. Exit status is 0 when clean and 1 when issues are found. References needing an unavailable project context are reported as unresolved; prose and example/glob addresses are not validated. A present lock is reported without inferring process liveness.
19
+ ## The dream lock and Git audit
18
20
 
19
- ## The dream lock
21
+ `dream_begin` takes an exclusive `.dream.lock.<project>` in the notes home with a single O_CREAT|O_EXCL creation, then commits a baseline of the notes home to its Git repository (initialized on first use). `dream_end` commits the dream's changes and releases the lock, so `git show` reviews a dream and `git revert` rolls it back. A session shutdown releases the lock without the final commit.
20
22
 
21
- The `dream` CLI takes an exclusive `.dream.lock` in the notes home with a single O_CREAT|O_EXCL creation. The lock is Git-style existence locking: an existing lock refuses a new run regardless of its contents, PID, or age, and `--force` bypasses only the scheduling and material gates, never the lock. A lock is released only by the run that acquired it (and repeated cleanup is harmless), so a live dream is never displaced.
22
-
23
- If a dream process crashed, its lock remains and later runs refuse to start. There is no automatic recovery and no force-unlock command: after you have confirmed that no dream process is running, remove the stale lock by hand.
23
+ An existing lock refuses a new dream regardless of its age. If a Pi process crashed mid-dream, remove the stale lock by hand after confirming no dream is running:
24
24
 
25
25
  ```sh
26
- # only when no dream is running
27
- rm "${NOTESOUP_HOME:-$HOME/.agents/notes}/.dream.lock"
26
+ rm "${NOTESOUP_HOME:-$HOME/.agents/notes}/.dream.lock.<project>"
28
27
  ```
29
-
30
- Removing a lock while a holder is running is outside the supported cooperative protocol and can let two dreams run at once.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.51.9",
3
+ "version": "0.52.1",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -56,11 +56,8 @@
56
56
  "!plugins/claude/tsconfig.json",
57
57
  "cordis.patch.yml"
58
58
  ],
59
- "bin": {
60
- "dream": "dist/plugins/pi/dream/cli.js"
61
- },
62
59
  "scripts": {
63
- "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json && node scripts/build-extension.mjs && node -e \"require('node:fs').chmodSync('dist/plugins/pi/dream/cli.js', 0o755)\"",
60
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json && node scripts/build-extension.mjs",
64
61
  "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p plugins/claude/tsconfig.json",
65
62
  "test": "npm run build && node --test --test-concurrency=4 $(ls dist/test/*.test.js | grep -v dist/test/claude-validation.test.js) && node --test dist/test/claude-validation.test.js",
66
63
  "prepublishOnly": "npm run typecheck",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.51.9",
3
+ "version": "0.52.1",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -7975,7 +7975,7 @@ function isFilesystemError(error) {
7975
7975
 
7976
7976
  // src/notes/store.ts
7977
7977
  import { randomUUID as randomUUID2 } from "node:crypto";
7978
- import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
7978
+ import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
7979
7979
  import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
7980
7980
 
7981
7981
  // src/text-match.ts
@@ -8146,8 +8146,9 @@ function snapshotNotesIdentity(value) {
8146
8146
  if (!SLUG_PATTERN.test(projectKey2)) throw new TypeError("notes context projectKey must be a canonical lowercase slug");
8147
8147
  if (!SLUG_PATTERN.test(agent)) throw new TypeError("notes context agent must be a canonical lowercase slug");
8148
8148
  if (!SLUG_PATTERN.test(model)) throw new TypeError("notes context model must be a canonical lowercase slug");
8149
+ if (value.dreaming !== void 0 && !SLUG_PATTERN.test(value.dreaming)) throw new TypeError("notes context dreaming must be a canonical lowercase slug");
8149
8150
  const home = resolve(homeValue);
8150
- return Object.freeze({ home, sessionId, projectKey: projectKey2, agent, model });
8151
+ return Object.freeze({ home, sessionId, projectKey: projectKey2, agent, model, ...value.dreaming === void 0 ? {} : { dreaming: value.dreaming } });
8151
8152
  }
8152
8153
 
8153
8154
  // src/notes/constants.ts
@@ -8510,6 +8511,7 @@ function frontmatterOf(meta) {
8510
8511
  }
8511
8512
  function assertWritableHome(scope, who, identity2) {
8512
8513
  if (who === void 0) return;
8514
+ if (identity2.dreaming !== void 0 && (scope === "session" || scope === "project" && who === identity2.dreaming)) return;
8513
8515
  if (scope === "session") throw new NoteError("invalid_scope", `@sessions/${who}/ is read-only; use a bare path to write to this session.`);
8514
8516
  if (scope === "project") throw new NoteError("invalid_scope", `@projects/${who}/ is read-only; use @project/ to write to your own project.`);
8515
8517
  const current = scope === "agent" ? identity2.agent : identity2.model;
@@ -8517,6 +8519,11 @@ function assertWritableHome(scope, who, identity2) {
8517
8519
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
8518
8520
  throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
8519
8521
  }
8522
+ function assertDreamSessionNote(scope, who, identity2, raw, address) {
8523
+ if (scope !== "session" || who === void 0 || identity2.dreaming === void 0) return;
8524
+ if (raw !== void 0 && parseNote(raw).meta.project === identity2.dreaming) return;
8525
+ throw new NoteError("invalid_scope", raw === void 0 ? `${address}: a dream edits other sessions' existing notes, it doesn't create new ones there.` : `${address} belongs to another project, not the one being dreamed over (${identity2.dreaming}).`);
8526
+ }
8520
8527
  function createNotesStore(input) {
8521
8528
  const identity2 = snapshotNotesIdentity(input);
8522
8529
  async function write(address, content, options = {}) {
@@ -8531,6 +8538,7 @@ function createNotesStore(input) {
8531
8538
  const now = writeStamp();
8532
8539
  const cleanBody = stripLeadingFrontmatter(content);
8533
8540
  const existingRaw = await readFileIfExists(path);
8541
+ assertDreamSessionNote(scope, destination.who, identity2, existingRaw, address);
8534
8542
  const existing = existingRaw === void 0 ? void 0 : parseNote(existingRaw, now).meta;
8535
8543
  const outcome = existing === void 0 ? "created" : existing.crumpledAt === void 0 ? "overwrote" : "uncrumpled";
8536
8544
  const meta = existing ?? {
@@ -8561,7 +8569,7 @@ function createNotesStore(input) {
8561
8569
  if (raw === void 0) return void 0;
8562
8570
  const now = Date.now();
8563
8571
  const parsed = parseNote(raw, now);
8564
- if ((scope === "project" || scope === "session") && destination.who !== void 0) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
8572
+ if (identity2.dreaming !== void 0 || (scope === "project" || scope === "session") && destination.who !== void 0) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
8565
8573
  const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
8566
8574
  await atomicWrite(path, serializeNote(meta, parsed.body));
8567
8575
  return { meta, body: parsed.body, resolvedScope: scope };
@@ -8586,6 +8594,8 @@ function createNotesStore(input) {
8586
8594
  const raw = await readFileIfExists(fromPath);
8587
8595
  if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
8588
8596
  const targetRaw = differentPaths ? await readFileIfExists(path) : void 0;
8597
+ assertDreamSessionNote(from.scope, from.who, identity2, raw, address);
8598
+ if (differentPaths) assertDreamSessionNote(scope, destination.who, identity2, targetRaw, stableOptions.renameTo);
8589
8599
  const sourceReal = targetRaw === void 0 ? void 0 : await realpath(fromPath);
8590
8600
  const sameFile = sourceReal !== void 0 && sourceReal === await realpath(path);
8591
8601
  const moved = differentPaths && !sameFile;
@@ -8642,6 +8652,21 @@ function createNotesStore(input) {
8642
8652
  const { meta, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
8643
8653
  return { meta, replacedCrumpledTarget };
8644
8654
  }
8655
+ async function forget(address) {
8656
+ if (identity2.dreaming === void 0) throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
8657
+ const target = assertAddress(address);
8658
+ assertWritableHome(target.scope, target.who, identity2);
8659
+ const path = physicalPath(target.scope, target.path, identity2, target.who);
8660
+ return withPathQueue(path, async () => {
8661
+ const raw = await readFileIfExists(path);
8662
+ if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
8663
+ assertDreamSessionNote(target.scope, target.who, identity2, raw, address);
8664
+ const { meta } = parseNote(raw);
8665
+ if (meta.crumpledAt === void 0) throw new NoteError("not_crumpled", `${noteIdentity(identity2, address).address} isn't crumpled; crumple it before deleting.`);
8666
+ await unlink(path);
8667
+ return { ...meta, scope: target.scope };
8668
+ });
8669
+ }
8645
8670
  async function* scan(options, status) {
8646
8671
  const glob = assertGlobPattern(options.glob);
8647
8672
  const pattern = glob === "@default" ? void 0 : glob;
@@ -8723,7 +8748,7 @@ function createNotesStore(input) {
8723
8748
  function searchWithStatus(queries, options = {}) {
8724
8749
  return searchRows(queries, options, { homesUnavailable: [] });
8725
8750
  }
8726
- return { write, read, update, rename: rename2, list, search, listWithStatus, searchWithStatus };
8751
+ return { write, read, update, rename: rename2, forget, list, search, listWithStatus, searchWithStatus };
8727
8752
  }
8728
8753
 
8729
8754
  // src/tools/output.ts
@@ -9640,22 +9665,6 @@ var historyRead = {
9640
9665
  // plugins/claude/src/history.ts
9641
9666
  import { readFile as readFile2 } from "node:fs/promises";
9642
9667
  import { isDeepStrictEqual } from "node:util";
9643
- var METADATA = /* @__PURE__ */ new Set([
9644
- "queue-operation",
9645
- "last-prompt",
9646
- "atis-latch",
9647
- "mode",
9648
- "permission-mode",
9649
- "file-history-snapshot",
9650
- "cost-state",
9651
- "summary",
9652
- "custom-title",
9653
- "agent-name",
9654
- "agent-color",
9655
- "tag",
9656
- "session-title",
9657
- "progress"
9658
- ]);
9659
9668
  var MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "assistant", "system", "attachment"]);
9660
9669
  var NON_TEXT_BLOCKS = /* @__PURE__ */ new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
9661
9670
  function object(value) {
@@ -9752,8 +9761,7 @@ function claudeHistoryFromJsonl(text, source) {
9752
9761
  const nodes = /* @__PURE__ */ new Map();
9753
9762
  let nextSeq = 1;
9754
9763
  for (const row of rowsOf(text)) {
9755
- if (METADATA.has(row.type)) continue;
9756
- if (!MESSAGE_TYPES.has(row.type)) throw new Error(`unsupported Claude transcript record type: ${row.type}`);
9764
+ if (!MESSAGE_TYPES.has(row.type)) continue;
9757
9765
  const uuid = requiredString(row.uuid, "uuid");
9758
9766
  parent(row);
9759
9767
  if (row.sessionId !== source.sessionId) throw new Error("Claude transcript belongs to a different session");
@@ -1,4 +1,4 @@
1
- import type { EngineInterface, On, ProcessRunResult, ToolCallResult, ToolSpec } from "claude-code"
1
+ import type { EngineInterface, On, ProcessRunResult, ToolCallInput, ToolCallResult, ToolSpec } from "claude-code"
2
2
 
3
3
  const PREFIX = "mcp__notesoup__"
4
4
  const HELPER = `${import.meta.dir}/../dist/claude/helper.js`
@@ -22,7 +22,7 @@ type ResetState = {
22
22
  manualPending: boolean; headless: boolean; usageFailureLogged: boolean; preparedBoot?: string; retainedBoot?: string
23
23
  continuation?: string; continuationWindow?: number
24
24
  compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsWindow: number
25
- limits?: ClaudeLimits; warnedWindow?: number; texts?: SharedTexts; settingsFailureLogged: boolean
25
+ limits?: ClaudeLimits; warnedWindow?: number; warningPending?: number; texts?: SharedTexts; settingsFailureLogged: boolean
26
26
  }
27
27
  const HEADLESS = "No brain when headless"
28
28
  const COMPACT_DISABLED = "Brain can't be emptied with DISABLE_COMPACT"
@@ -104,12 +104,9 @@ async function compactDisabled($: Engine): Promise<boolean> {
104
104
  // The same presence convention as the helper's flag parsing: "off"/"no" mean not disabled.
105
105
  return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off"
106
106
  }
107
- /** Presence-style kill switch for the whole mod; the same convention as DISABLE_COMPACT. */
108
- async function notesoupDisabled($: Engine): Promise<boolean> {
109
- let value: string | undefined
110
- try { value = await $.env.get("NOTESOUP_DISABLED") } catch { return false }
111
- if (value === undefined) return false
112
- const text = value.trim().toLowerCase()
107
+ /** Presence-style env switch; the same convention as DISABLE_COMPACT. The loader requires literal env names. */
108
+ function envFlag(value: string | undefined): boolean {
109
+ const text = value?.trim().toLowerCase() ?? ""
113
110
  return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off"
114
111
  }
115
112
  async function readSettings($: Engine, state: ResetState): Promise<unknown> {
@@ -267,7 +264,7 @@ function forgetSession(state: ResetState) {
267
264
  state.continuationWindow = undefined
268
265
  state.limitsAttempts = state.limitsWindow = 0
269
266
  state.settingsFailureLogged = state.limitsFailureLogged = false
270
- state.warnedWindow = undefined
267
+ state.warnedWindow = state.warningPending = undefined
271
268
  }
272
269
  async function modelOf($: Engine): Promise<string> {
273
270
  // session.model() is the documented main-loop model API. Match the notes library's slug.
@@ -319,6 +316,7 @@ export function register(on: On) {
319
316
  const manualSignal: { wake?: () => void } = {}
320
317
  const state: ResetState = { generation: 0, window: 0, disabled: false, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, limitsWindow: 0, settingsFailureLogged: false }
321
318
  const registered = new Set<string>()
319
+ let keepMemory = false
322
320
  // Classic SessionStart precedes typed session.start and startup appends. Keep this binding
323
321
  // across forgetSession; re-key it only against the actual session id, never a guessed path.
324
322
  on("classic.SessionStart", async ($, e, next) => {
@@ -339,12 +337,13 @@ export function register(on: On) {
339
337
  })
340
338
  on("session.start", async ($, e, next) => {
341
339
  forgetSession(state)
342
- state.disabled = await notesoupDisabled($)
340
+ state.disabled = envFlag(await $.env.get("NOTESOUP_DISABLED").catch(() => undefined))
343
341
  if (state.disabled) {
344
342
  registered.clear()
345
343
  log($, NOTESOUP_DISABLED)
346
344
  return next(e)
347
345
  }
346
+ keepMemory = envFlag(await $.env.get("NOTESOUP_KEEP_MEMORY").catch(() => undefined))
348
347
  await refreshIdentity($, state)
349
348
  state.headless = !e.isInteractive
350
349
  if (state.headless) log($, HEADLESS)
@@ -371,19 +370,13 @@ export function register(on: On) {
371
370
  })
372
371
  on("tool.call", async ($, e, next) => {
373
372
  if (state.disabled) return next(e)
374
- if (!registered.has(e.tool)) return next(e)
375
- const identity = await refreshIdentity($, state)
376
- if (!identity) return errorResult("session changed during identity lookup")
377
- const { tool, tool_use_id: _toolUseId, agentId, ...params } = e
378
- const name = tool.slice(PREFIX.length)
379
- if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
380
- const result = await run($, { op: "tool", tool: name, params, identity, history: state.history })
381
- if (!result.ok) return errorResult(result.error)
382
- // The outcome already decided success or refusal; Claude requires isError: true on errors and no discriminator on success.
383
- const outcome = toolResultOf(result.result)
384
- if (!outcome) return errorResult("helper returned an invalid tool result")
385
- return outcome.ok ? { result: outcome.text } : { result: outcome.text, isError: true }
373
+ const generation = state.generation
374
+ const result = registered.has(e.tool) ? await callNotesTool($, state, e) : await next(e)
375
+ if (e.agentId !== undefined || result.deny !== undefined || generation !== state.generation) return result
376
+ return withWarning($, state, (warning) => warning === undefined ? result : { ...result, context: [...(result.context ?? []), warning] })
386
377
  })
378
+ on("prompt.submit", ($, e, next) => withWarning($, state, (warning) =>
379
+ next(warning === undefined ? e : { ...e, context: [...(e.context ?? []), warning] })))
387
380
  on("turn.start", async ($, e, next) => {
388
381
  // The documented turn.start is main-loop only. Guard tagged host events too:
389
382
  // only a main-agent turn.complete clears this latch.
@@ -465,6 +458,9 @@ export function register(on: On) {
465
458
  }
466
459
  return { messages: built.messages }
467
460
  })
461
+ // notesoup replaces Claude's summarization and auto-memory guidance; memory can be kept on request.
462
+ on("prompt.section", { name: "context_management" }, ($, e, next) => state.disabled ? next(e) : { text: null })
463
+ on("prompt.section", { name: "memory" }, ($, e, next) => state.disabled || keepMemory ? next(e) : { text: null })
468
464
  on("prompt.context", async ($, e, next) => {
469
465
  if (state.disabled) return next(e)
470
466
  const result = await next(e)
@@ -485,18 +481,27 @@ export function register(on: On) {
485
481
  }
486
482
  blocks = [...blocks, { name: "notesoup:boot", text: boot.ok ? String(boot.result) : `# notesoup\nYour notes didn't load this time (${boot.error}). Try \`${PREFIX}notes_list\`; if it fails too, tell the human.` }]
487
483
  }
488
- const warning = await warningBlock($, state)
489
- return { ...result, blocks: warning === undefined ? blocks : [...blocks, warning] }
484
+ return { ...result, blocks }
490
485
  })
491
486
 
492
487
  }
493
488
 
494
- /**
495
- * The one warning per window: injected only once the measured context crosses the resolved
496
- * warn point, and only until the window changes. The reset decision runs independently.
497
- */
498
- async function warningBlock($: Engine, state: ResetState): Promise<{ name: string; text: string } | undefined> {
499
- if (state.headless || state.compactDisabled || !state.identity || state.warnedWindow === state.window) return undefined
489
+ async function callNotesTool($: Engine, state: ResetState, e: ToolCallInput): Promise<ToolCallResult> {
490
+ const identity = await refreshIdentity($, state)
491
+ if (!identity) return errorResult("session changed during identity lookup")
492
+ const { tool, tool_use_id: _toolUseId, agentId, ...params } = e
493
+ const name = tool.slice(PREFIX.length)
494
+ if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
495
+ const result = await run($, { op: "tool", tool: name, params, identity, history: state.history })
496
+ if (!result.ok) return errorResult(result.error)
497
+ const outcome = toolResultOf(result.result)
498
+ if (!outcome) return errorResult("helper returned an invalid tool result")
499
+ return outcome.ok ? { result: outcome.text } : { result: outcome.text, isError: true }
500
+ }
501
+
502
+ /** Read the warning without consuming this window's delivery. */
503
+ async function warningText($: Engine, state: ResetState): Promise<string | undefined> {
504
+ if (state.disabled || state.headless || state.compactDisabled || !state.identity || state.warnedWindow === state.window || state.warningPending === state.window) return undefined
500
505
  const generation = state.generation
501
506
  const usage = await contextUsage($, state)
502
507
  if (generation !== state.generation || usage === undefined) return undefined
@@ -505,9 +510,23 @@ async function warningBlock($: Engine, state: ResetState): Promise<{ name: strin
505
510
  const measured = measuredValue(limits, usage)
506
511
  if (measured === undefined || measured < limits.warn) return undefined
507
512
  const texts = await loadTexts($, state)
508
- if (generation !== state.generation || texts?.warning === undefined) return undefined
509
- state.warnedWindow = state.window
510
- return { name: "notesoup:warning", text: texts.warning }
513
+ return generation === state.generation ? texts?.warning : undefined
514
+ }
515
+
516
+ /** Reserve across next(), but consume only context the chain actually accepted. */
517
+ async function withWarning<T extends { context?: readonly string[]; drop?: string; deny?: string }>($: Engine, state: ResetState, deliver: (warning?: string) => T | Promise<T>): Promise<T> {
518
+ if (state.disabled || state.headless || state.compactDisabled || !await refreshIdentity($, state)) return deliver()
519
+ const generation = state.generation, window = state.window
520
+ const warning = await warningText($, state)
521
+ if (warning === undefined || generation !== state.generation || window !== state.window || state.warnedWindow === window || state.warningPending === window) return deliver()
522
+ state.warningPending = window
523
+ try {
524
+ const result = await deliver(warning)
525
+ if (generation === state.generation && window === state.window && result.drop === undefined && result.deny === undefined && result.context?.includes(warning)) state.warnedWindow = window
526
+ return result
527
+ } finally {
528
+ if (generation === state.generation && state.warningPending === window) state.warningPending = undefined
529
+ }
511
530
  }
512
531
 
513
532
  /** The boot's identity line; `context_window` is the pre-rename tag still in old transcripts. */
@@ -7,10 +7,6 @@ type Row = Record<string, unknown>;
7
7
  type Version = { row: Row; ancestorUuid?: string; ancestor?: Version; ordinal?: number };
8
8
  type Node = { first: Version; latest: Version; items: DecodedHistoryItem[] };
9
9
  export type ClaudeHistorySource = { sessionId: string; transcriptPath: string; headUuid?: string };
10
- const METADATA = new Set([
11
- "queue-operation", "last-prompt", "atis-latch", "mode", "permission-mode", "file-history-snapshot", "cost-state",
12
- "summary", "custom-title", "agent-name", "agent-color", "tag", "session-title", "progress",
13
- ]);
14
10
  const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
15
11
  const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
16
12
  function object(value: unknown): value is Row { return typeof value === "object" && value !== null && !Array.isArray(value); }
@@ -119,8 +115,9 @@ export function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistoryS
119
115
  const nodes = new Map<string, Node>();
120
116
  let nextSeq = 1;
121
117
  for (const row of rowsOf(text)) {
122
- if (METADATA.has(row.type as string)) continue;
123
- if (!MESSAGE_TYPES.has(row.type as string)) throw new Error(`unsupported Claude transcript record type: ${row.type}`);
118
+ // Ignore non-message records, including future metadata. A skipped UUID that
119
+ // the selected branch actually requires still fails ancestry resolution below.
120
+ if (!MESSAGE_TYPES.has(row.type as string)) continue;
124
121
  const uuid = requiredString(row.uuid, "uuid");
125
122
  parent(row);
126
123
  if (row.sessionId !== source.sessionId) throw new Error("Claude transcript belongs to a different session");
@@ -1,19 +1,36 @@
1
- import { generateDiffString, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import { generateDiffString, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { notesWrite, notesUpdate, notesRead, notesList, notesSearch } from "../../../src/tools/notes.js";
3
+ import { abandonDream, dreamBegin, dreamEnd, dreamForget, dreamingIdentity, type DreamState } from "../../../src/tools/dream.js";
3
4
  import { notesIdentityFromPi } from "./adapter.js";
4
5
  import { notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../render.js";
5
- import { NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
6
+ import { DREAM_NAMESPACE, NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
6
7
  import type { NoteChange } from "../../../src/notes/index.js";
7
8
 
8
9
  function renderDiff(change: NoteChange): string {
9
10
  return change.kind === "none" ? "" : generateDiffString(change.before, change.after, 1).diff;
10
11
  }
11
12
 
12
- /** Register the five shared note operations; each one supplies Pi's session identity and nothing else. */
13
+ /** Register the five shared note operations and the three hidden dream tools; an open dream widens the note identity. */
13
14
  export function registerNotesTools(pi: ExtensionAPI) {
14
- registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
15
- registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, notesIdentityFromPi(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
16
- registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE, notesReadRenderers);
17
- registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
18
- registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
15
+ // One open dream per session, in memory: shutdown releases its lock without the end commit.
16
+ const dreams = new Map<string, DreamState>();
17
+ pi.on("session_shutdown", () => {
18
+ for (const state of dreams.values()) abandonDream(state);
19
+ dreams.clear();
20
+ });
21
+ const dreamOf = (ctx: ExtensionContext): DreamState => {
22
+ const id = ctx.sessionManager.getSessionId();
23
+ let state = dreams.get(id);
24
+ if (!state) dreams.set(id, state = {});
25
+ return state;
26
+ };
27
+ const identity = (ctx: ExtensionContext) => dreamingIdentity(notesIdentityFromPi(ctx), dreamOf(ctx));
28
+ registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, identity(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
29
+ registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, identity(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
30
+ registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, identity(ctx)), NOTES_NAMESPACE, notesReadRenderers);
31
+ registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, identity(ctx)), NOTES_NAMESPACE);
32
+ registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, identity(ctx)), NOTES_NAMESPACE);
33
+ registerOperation(pi, dreamBegin, (params, ctx) => dreamBegin.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
34
+ registerOperation(pi, dreamForget, (params, ctx) => dreamForget.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
35
+ registerOperation(pi, dreamEnd, (params, ctx) => dreamEnd.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
19
36
  }
@@ -1,5 +1,5 @@
1
1
  /** Pi transport for host-neutral operations. */
2
- import { defineTool, type ExtensionAPI, type ExtensionToolContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ import { defineTool, type ExtensionAPI, type ExtensionToolContext, type ToolDefinition, type ToolExposure } from "@earendil-works/pi-coding-agent";
3
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
4
  import type { JsonValue } from "@earendil-works/pi-ai";
5
5
  import type { Static, TSchema } from "typebox";
@@ -24,6 +24,7 @@ function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TDat
24
24
 
25
25
  export type ToolNamespace = { name: string; description: string };
26
26
  export const NOTES_NAMESPACE: ToolNamespace = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
27
+ export const DREAM_NAMESPACE: ToolNamespace = { name: "dream", description: "Consolidate one project's notes: begin, edit with notes_*, forget crumpled notes, end." };
27
28
  export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
28
29
 
29
30
  /** Optional TUI renderers; without them the host draws its default call line and receipt text. */
@@ -36,6 +37,7 @@ export function registerOperation<TParams extends TSchema, TData, TRest extends
36
37
  run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>,
37
38
  namespace?: ToolNamespace,
38
39
  renderers?: OperationRenderers<TParams>,
40
+ exposure?: ToolExposure,
39
41
  ): void {
40
42
  pi.registerTool(defineTool<TParams, undefined>({
41
43
  name: operation.name,
@@ -45,6 +47,7 @@ export function registerOperation<TParams extends TSchema, TData, TRest extends
45
47
  outputSchema: operation.outputSchema,
46
48
  executionMode: operation.executionMode,
47
49
  ...(namespace ? { namespace } : {}),
50
+ ...(exposure ? { exposure } : {}),
48
51
  ...renderers,
49
52
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
50
53
  return piOperationResult(operation.render, await run(params, ctx));
package/src/dream/git.ts CHANGED
@@ -28,9 +28,8 @@ function ensureRuntimeIgnored(home: string): void {
28
28
  }
29
29
 
30
30
  /**
31
- * Git audit layer for a dream run: one commit before (baseline) and one after (dream),
32
- * so the human gate reviews `git show` instead of trusting a report, and rollback is
33
- * `git revert`. The caller decides how loud a failure is; this function only reports it.
31
+ * Git audit layer for a dream: one commit at dream_begin (baseline) and one at dream_end,
32
+ * so the human reviews `git show` instead of trusting a report, and rollback is `git revert`. The caller decides how loud a failure is; this function only reports it.
34
33
  * A clean tree on an established repository commits nothing; a repository with no HEAD
35
34
  * gets an empty baseline commit, because an audit run with no snapshot is not a success.
36
35
  */
@@ -49,19 +48,15 @@ export function gitCommit(home: string, message: string): AuditResult {
49
48
  const before = headCommit(home);
50
49
  if (!clean) {
51
50
  execFileSync("git", ["commit", "-q", "-m", message], { cwd: home, stdio: "ignore" });
52
- console.log(`git: committed "${message}"`);
53
51
  } else if (before === undefined) {
54
52
  // A newly initialized repository has no snapshot at all; give the audit one.
55
53
  execFileSync("git", ["commit", "-q", "--allow-empty", "-m", message], { cwd: home, stdio: "ignore" });
56
- console.log(`git: committed "${message}"`);
57
54
  }
58
55
  const commit = headCommit(home);
59
56
  if (commit === undefined) return { ok: false, error: "audit commit produced no snapshot (no HEAD)" };
60
57
  return { ok: true, commit, empty: clean };
61
58
  } catch (error) {
62
- const reason = errorMessage(error);
63
- console.log(`git audit layer failed: ${reason}`);
64
- return { ok: false, error: reason };
59
+ return { ok: false, error: errorMessage(error) };
65
60
  }
66
61
  }
67
62
 
package/src/dream/lock.ts CHANGED
@@ -1,76 +1,28 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
2
+ import { readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
3
4
 
4
- export type LockState = {
5
- path: string;
6
- held: boolean;
7
- reason?: string;
8
- startedAt: number;
9
- /** mtime of the last-run sidecar before this run took the lock; failLock restores it. */
10
- priorStampMtime?: number;
11
- /** Random identity written into the lock file; cleanup only removes the lock it wrote. */
12
- token?: string;
13
- };
5
+ /** One held dream lock; only the holder that wrote the token removes it. */
6
+ export type DreamLock = { path: string; token: string };
14
7
 
15
- /**
16
- * The scheduler's last-run timestamp lives in a sidecar beside the lock, never in the
17
- * lock file itself: acquiring, releasing or cleaning up the lock touches only the PID
18
- * marker, so lock lifecycle does not destroy the timestamp the time gate reads.
19
- */
20
- export function lastRunPath(lockPath: string): string {
21
- return `${lockPath}.last-run`;
22
- }
23
-
24
- function readText(path: string): string | undefined {
25
- try { return readFileSync(path, "utf8"); } catch { return undefined; }
26
- }
27
-
28
- function ownsLock(lock: LockState): boolean {
29
- if (!lock.held || !lock.token) return false;
30
- return readText(lock.path)?.trim() === `${process.pid} ${lock.token}`;
8
+ /** The per-project lock file in the notes home; `.dream.lock*` is excluded from the Git audit. */
9
+ export function dreamLockPath(home: string, project: string): string {
10
+ return join(home, `.dream.lock.${project}`);
31
11
  }
32
12
 
33
13
  /**
34
- * Acquire the dream lock with Git-style exclusive existence locking: one O_CREAT|O_EXCL
35
- * creation. An existing path refuses acquisition regardless of its contents, PID, or age,
36
- * and is never read for permission, replaced, or removed. There is no automatic stale
37
- * recovery; a crash-left lock is human cleanup after confirming no dream is running.
14
+ * Git-style exclusive existence lock: one O_CREAT|O_EXCL creation. An existing lock refuses,
15
+ * whatever its age; a crash-left lock is removed by hand after confirming no dream runs.
38
16
  */
39
- export function acquireLock(path: string): LockState {
40
- const now = Date.now();
41
- // The sidecar's mtime is the scheduler's timestamp; a missing one means no prior dream.
42
- let priorStampMtime: number | undefined;
43
- try { priorStampMtime = statSync(lastRunPath(path)).mtimeMs; } catch { /* no sidecar yet */ }
44
- const token = randomUUID();
45
- try {
46
- writeFileSync(path, `${process.pid} ${token}`, { flag: "wx" });
47
- } catch {
48
- return { path, held: false, reason: "lock gate: lock already exists", startedAt: now };
49
- }
50
- // Only a held lock advances the scheduler timestamp.
51
- try { writeFileSync(lastRunPath(path), new Date(now).toISOString()); } catch { /* advisory */ }
52
- return { path, held: true, startedAt: now, priorStampMtime, token };
53
- }
54
-
55
- /** Release only the lock this run acquired. Idempotent: repeated cleanup does nothing. */
56
- export function releaseLock(lock: LockState): void {
57
- if (!lock.held) return;
58
- if (ownsLock(lock)) { try { unlinkSync(lock.path); } catch { /* best effort */ } }
59
- lock.held = false;
17
+ export function acquireDreamLock(path: string): DreamLock | undefined {
18
+ const token = `${process.pid} ${randomUUID()}`;
19
+ try { writeFileSync(path, token, { flag: "wx" }); } catch { return undefined; }
20
+ return { path, token };
60
21
  }
61
22
 
62
- /**
63
- * A failed run must not advance the scheduler: restore the previous timestamp, or remove
64
- * the one this run wrote when there was none. Only this run's own marker is removed, and
65
- * the state is marked released so a later cleanup attempt is harmless.
66
- */
67
- export function failLock(lock: LockState): void {
68
- if (!lock.held) return;
69
- if (ownsLock(lock)) {
70
- const stampPath = lastRunPath(lock.path);
71
- if (lock.priorStampMtime === undefined) { try { unlinkSync(stampPath); } catch { /* best effort */ } }
72
- else { try { utimesSync(stampPath, new Date(), new Date(lock.priorStampMtime)); } catch { /* best effort */ } }
73
- try { unlinkSync(lock.path); } catch { /* best effort */ }
74
- }
75
- lock.held = false;
23
+ /** Release only a lock this holder wrote; repeated release is harmless. */
24
+ export function releaseDreamLock(lock: DreamLock): void {
25
+ try {
26
+ if (readFileSync(lock.path, "utf8") === lock.token) unlinkSync(lock.path);
27
+ } catch { /* already gone */ }
76
28
  }
@@ -1,4 +1,4 @@
1
- export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "io_error" | "internal_error";
1
+ export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "not_crumpled" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "io_error" | "internal_error";
2
2
 
3
3
  /** Typed store refusal. Edit locations are exposed in camelCase. */
4
4
  export class NoteError extends Error {