notesoup 0.43.0 → 0.45.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.
Files changed (76) hide show
  1. package/README.md +1 -0
  2. package/cordis.patch.yml +14 -0
  3. package/dist/src/boot/snapshot.d.ts +2 -0
  4. package/dist/src/boot/snapshot.js +4 -0
  5. package/dist/src/boot/text.js +3 -1
  6. package/dist/src/claude/helper.js +2 -2
  7. package/dist/src/dsh/budget.d.ts +20 -0
  8. package/dist/src/dsh/budget.js +34 -0
  9. package/dist/src/dsh/engine.d.ts +22 -0
  10. package/dist/src/dsh/engine.js +193 -0
  11. package/dist/src/dsh/history.d.ts +6 -0
  12. package/dist/src/dsh/history.js +73 -0
  13. package/dist/src/dsh/index.d.ts +22 -0
  14. package/dist/src/dsh/index.js +63 -0
  15. package/dist/src/dsh/preflight.d.ts +8 -0
  16. package/dist/src/dsh/preflight.js +35 -0
  17. package/dist/src/dsh/tools.d.ts +3 -0
  18. package/dist/src/dsh/tools.js +111 -0
  19. package/dist/src/dsh/window.d.ts +46 -0
  20. package/dist/src/dsh/window.js +124 -0
  21. package/dist/src/notes/address.d.ts +2 -2
  22. package/dist/src/notes/address.js +5 -5
  23. package/dist/src/notes/identity.js +2 -1
  24. package/dist/src/notes/paths.d.ts +1 -6
  25. package/dist/src/notes/paths.js +5 -68
  26. package/dist/src/notes/project-home.d.ts +25 -0
  27. package/dist/src/notes/project-home.js +231 -0
  28. package/dist/src/notes/store.d.ts +3 -2
  29. package/dist/src/notes/store.js +14 -8
  30. package/dist/src/pi/boot.js +17 -5
  31. package/dist/src/pi/notes/adapter.js +1 -1
  32. package/dist/src/tools/notes.d.ts +47 -17
  33. package/dist/src/tools/notes.js +15 -4
  34. package/dist/test/claude-mod.test.js +32 -1
  35. package/dist/test/dependencies.test.js +27 -1
  36. package/dist/test/dsh-cli.test.d.ts +1 -0
  37. package/dist/test/dsh-cli.test.js +44 -0
  38. package/dist/test/dsh-compaction-parity.test.d.ts +1 -0
  39. package/dist/test/dsh-compaction-parity.test.js +143 -0
  40. package/dist/test/dsh.test.d.ts +1 -0
  41. package/dist/test/dsh.test.js +323 -0
  42. package/dist/test/helpers/dependency-graph.js +3 -3
  43. package/dist/test/helpers/dsh-messages.d.ts +29 -0
  44. package/dist/test/helpers/dsh-messages.js +33 -0
  45. package/dist/test/helpers/dsh.d.ts +17 -0
  46. package/dist/test/helpers/dsh.js +50 -0
  47. package/dist/test/notes.test.js +22 -19
  48. package/dist/test/project-home.test.d.ts +1 -0
  49. package/dist/test/project-home.test.js +134 -0
  50. package/docs/architecture.md +4 -1
  51. package/docs/dsh.md +61 -0
  52. package/docs/dsh.profile.patch.yml +34 -0
  53. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  54. package/mods/notesoup/dist/claude/helper.js +223 -56
  55. package/mods/notesoup/skills/memory/SKILL.md +1 -0
  56. package/package.json +63 -4
  57. package/skills/memory/SKILL.md +1 -0
  58. package/src/boot/snapshot.ts +5 -0
  59. package/src/boot/text.ts +3 -1
  60. package/src/claude/helper.ts +2 -2
  61. package/src/dsh/budget.ts +35 -0
  62. package/src/dsh/engine.ts +160 -0
  63. package/src/dsh/history.ts +57 -0
  64. package/src/dsh/index.ts +69 -0
  65. package/src/dsh/preflight.ts +29 -0
  66. package/src/dsh/tools.ts +107 -0
  67. package/src/dsh/window.ts +126 -0
  68. package/src/notes/address.ts +5 -5
  69. package/src/notes/identity.ts +1 -1
  70. package/src/notes/paths.ts +4 -60
  71. package/src/notes/project-home.ts +197 -0
  72. package/src/notes/store.ts +13 -9
  73. package/src/pi/boot.ts +15 -5
  74. package/src/pi/notes/adapter.ts +1 -1
  75. package/src/tools/notes.ts +16 -6
  76. package/mods/pi-context/dist/claude/helper.js +0 -9324
@@ -0,0 +1,33 @@
1
+ import { createServer } from "node:http";
2
+ /** Same Messages/SSE approach as /tmp/dsh-spike/mock/llm-server.mjs; no credentials or external traffic. */
3
+ export async function messagesServer() {
4
+ const requests = [];
5
+ const script = [];
6
+ const server = createServer(async (request, response) => {
7
+ let body = "";
8
+ for await (const chunk of request)
9
+ body += chunk;
10
+ if (request.method !== "POST" || !request.url?.endsWith("/messages")) {
11
+ response.writeHead(404).end();
12
+ return;
13
+ }
14
+ requests.push(JSON.parse(body));
15
+ const behavior = script.shift() ?? { text: "finished" };
16
+ if ("error" in behavior) {
17
+ response.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: behavior.error } }));
18
+ return;
19
+ }
20
+ response.writeHead(200, { "content-type": "text/event-stream" });
21
+ const send = (value) => response.write(`event: ${value.type}\ndata: ${JSON.stringify(value)}\n\n`);
22
+ send({ type: "message_start", message: { id: `msg-${requests.length}`, type: "message", role: "assistant", model: "mock", content: [], usage: { input_tokens: behavior.inputTokens ?? 10, output_tokens: 0 } } });
23
+ const tool = "tool" in behavior;
24
+ send({ type: "content_block_start", index: 0, content_block: tool ? { type: "tool_use", id: `call-${requests.length}`, name: behavior.tool, input: {} } : { type: "text", text: "" } });
25
+ send({ type: "content_block_delta", index: 0, delta: tool ? { type: "input_json_delta", partial_json: JSON.stringify(behavior.input) } : { type: "text_delta", text: behavior.text } });
26
+ send({ type: "content_block_stop", index: 0 });
27
+ send({ type: "message_delta", delta: { stop_reason: tool ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 20 } });
28
+ send({ type: "message_stop" });
29
+ response.end();
30
+ });
31
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
32
+ return { requests, script, url: `http://127.0.0.1:${server.address().port}`, close: () => new Promise((resolve, reject) => { server.closeAllConnections(); server.close((error) => error ? reject(error) : resolve()); }) };
33
+ }
@@ -0,0 +1,17 @@
1
+ import type { TestContext } from "node:test";
2
+ import { Context } from "@deepseek-ai/cordis";
3
+ import { type SessionEvent } from "@deepseek-ai/dsh-session";
4
+ import NotesoupEngine, { type EngineConfig } from "../../src/dsh/engine.js";
5
+ export declare function dshFixture(t: TestContext, config?: EngineConfig): Promise<{
6
+ ctx: Context;
7
+ engine: NotesoupEngine;
8
+ engineFiber: import("@deepseek-ai/cordis").Fiber;
9
+ directory: string;
10
+ mock: {
11
+ requests: import("./dsh-messages.js").WireRequest[];
12
+ script: import("./dsh-messages.js").Behavior[];
13
+ url: string;
14
+ close: () => Promise<void>;
15
+ };
16
+ create: (seed?: readonly SessionEvent[], id?: string) => Promise<import("@deepseek-ai/dsh-agent").Agent>;
17
+ }>;
@@ -0,0 +1,50 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { Context } from "@deepseek-ai/cordis";
6
+ import Agents from "@deepseek-ai/dsh-agent";
7
+ import AgentLoop from "@deepseek-ai/dsh-agent-loop";
8
+ import Llm from "@deepseek-ai/dsh-llm";
9
+ import * as DeepSeek from "@deepseek-ai/dsh-llm-deepseek-api-key";
10
+ import Sessions, { SessionId } from "@deepseek-ai/dsh-session";
11
+ import Projections from "@deepseek-ai/dsh-session-projection";
12
+ import SystemPrompt from "@deepseek-ai/dsh-system-prompt";
13
+ import Tools from "@deepseek-ai/dsh-tools";
14
+ import Meter from "@deepseek-ai/dsh-token-meter";
15
+ import Query from "@deepseek-ai/dsh-session-query-sqlite";
16
+ import { createLaunchEnvironmentSnapshot } from "@deepseek-ai/dsh-launch-environment";
17
+ import NotesoupEngine from "../../src/dsh/engine.js";
18
+ import notesoup from "../../src/dsh/index.js";
19
+ import { messagesServer } from "./dsh-messages.js";
20
+ export async function dshFixture(t, config = {}) {
21
+ const directory = await mkdtemp(join(tmpdir(), "ns-dsh-test-"));
22
+ const mock = await messagesServer();
23
+ const ctx = new Context();
24
+ const fibers = [];
25
+ t.after(async () => { for (const fiber of fibers.reverse())
26
+ await fiber.dispose(); await mock.close(); await ctx.fiber.dispose(); await rm(directory, { recursive: true, force: true }); });
27
+ ctx.provide("launchEnvironment", createLaunchEnvironmentSnapshot([{ source: "process", values: { DEEPSEEK_API_KEY: "mock-key" } }]));
28
+ fibers.push(await ctx.plugin(Sessions));
29
+ fibers.push(await ctx.plugin(Projections));
30
+ fibers.push(await ctx.plugin(Agents));
31
+ fibers.push(await ctx.plugin(Llm));
32
+ fibers.push(await ctx.plugin(SystemPrompt, { includeRuntimeContext: false }));
33
+ fibers.push(await ctx.plugin(Tools, {}));
34
+ fibers.push(await ctx.plugin(Meter, {}));
35
+ fibers.push(await ctx.plugin(Query, { path: ":memory:" }));
36
+ fibers.push(await ctx.plugin(DeepSeek, { baseURL: mock.url, models: [{ id: "mock-flash", name: "Mock", contextWindow: 200000, maxTokens: 8192 }] }));
37
+ const engineFiber = await ctx.plugin(NotesoupEngine, { notesHome: join(directory, "notes"), ...config });
38
+ fibers.push(engineFiber);
39
+ assert.ok(ctx.compaction instanceof NotesoupEngine);
40
+ const engine = ctx.compaction;
41
+ fibers.push(await ctx.plugin(notesoup));
42
+ fibers.push(await ctx.plugin(AgentLoop, { agents: [], maxParallelToolCalls: 10 }));
43
+ let count = 0;
44
+ const create = async (seed, id = `session-test-${++count}`) => {
45
+ const handle = await ctx.agents.create({ sessionId: SessionId(id), meta: { cwd: directory }, agentOptions: { provider: "deepseek-official", model: "mock-flash" }, ...(seed ? { seed } : {}) });
46
+ fibers.push(handle);
47
+ return handle.agent;
48
+ };
49
+ return { ctx, engine, engineFiber, directory, mock, create };
50
+ }
@@ -8,15 +8,16 @@
8
8
  */
9
9
  import assert from "node:assert/strict";
10
10
  import { execFileSync } from "node:child_process";
11
- import { createHash } from "node:crypto";
12
- import { existsSync, mkdirSync, readFileSync, realpathSync, symlinkSync, writeFileSync } from "node:fs";
13
- import { basename, join } from "node:path";
11
+ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
14
13
  import test from "node:test";
15
14
  import { Check } from "typebox/value";
16
15
  import { parseNote } from "../src/notes/frontmatter.js";
17
16
  import { projectKey } from "../src/notes/paths.js";
18
17
  import { globToRegExp } from "../src/notes/address.js";
19
18
  import { listNotes, physicalPath, scopeDir } from "./helpers/notes.js";
19
+ import { notesList, notesSearch } from "../src/tools/notes.js";
20
+ import { notesIdentityFromPi } from "../src/pi/notes/adapter.js";
20
21
  import { call, context, explicitBoot, makeExtension, manager, resultData, resultError, resultRead } from "./helpers/extension.js";
21
22
  import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
22
23
  const testEnvironment = installExtensionTestHooks("notesoup-notes");
@@ -25,7 +26,7 @@ function freshRoot() {
25
26
  }
26
27
  function assertReceiptIdentity(value, address, scope, ctx) {
27
28
  assert.equal(value.address, address);
28
- assert.equal(value.project_key, scope === "project" ? projectKey(ctx.cwd) : undefined);
29
+ assert.equal(value.project_key, scope === "project" ? projectKey(ctx.cwd, process.env.PI_NOTES_HOME) : undefined);
29
30
  }
30
31
  test("exactly the five notes tools are registered; the legacy five are gone", () => {
31
32
  const captured = makeExtension(manager());
@@ -112,7 +113,7 @@ test("write lands a real markdown file with harness frontmatter and a pure body"
112
113
  for (const key of ["createdAt", "updatedAt", "lastAccessed"]) {
113
114
  assert.match(raw, new RegExp(`^${key}: \\d{4}-\\d{2}-\\d{2}T`, "m"), `frontmatter renders ${key} via localIso`);
114
115
  }
115
- assert.equal(parseNote(raw).meta.project, projectKey(ctx.cwd), "a newly-created session note records its existing project key");
116
+ assert.equal(parseNote(raw).meta.project, projectKey(ctx.cwd, root), "a newly-created session note records its existing project key");
116
117
  assertReceiptIdentity(result, "a/b.md", "session", ctx);
117
118
  assert.equal(result.outcome, "created");
118
119
  assert.equal(existsSync(join(scopeDir("session", ctx), ".session.json")), false, "ownership is stored in note frontmatter, not a sidecar");
@@ -128,8 +129,8 @@ test("session-note project ownership is per note, persistent across sessions, an
128
129
  const cwdB = join(testEnvironment.cwd, "project-b");
129
130
  mkdirSync(cwdA, { recursive: true });
130
131
  mkdirSync(cwdB, { recursive: true });
131
- const projectA = projectKey(cwdA);
132
- const projectB = projectKey(cwdB);
132
+ const projectA = projectKey(cwdA, process.env.PI_NOTES_HOME);
133
+ const projectB = projectKey(cwdB, process.env.PI_NOTES_HOME);
133
134
  assert.notEqual(projectA, projectB);
134
135
  const firstSession = manager();
135
136
  const firstCaptured = makeExtension(firstSession);
@@ -177,8 +178,8 @@ test("linked git worktrees share the main checkout's project key", () => {
177
178
  git(["commit", "-q", "--allow-empty", "-m", "init"]);
178
179
  const worktree = join(root, "wt");
179
180
  git(["worktree", "add", "-q", "--detach", worktree]);
180
- assert.equal(projectKey(worktree), projectKey(main), "a linked worktree resolves to the main checkout's key");
181
- assert.equal(projectKey(join(worktree, "gone", "deeper")), projectKey(main), "a nonexistent subdirectory still resolves through its worktree");
181
+ assert.equal(projectKey(worktree, process.env.PI_NOTES_HOME), projectKey(main, process.env.PI_NOTES_HOME), "a linked worktree resolves to the main checkout's key");
182
+ assert.equal(projectKey(join(worktree, "gone", "deeper"), process.env.PI_NOTES_HOME), projectKey(main, process.env.PI_NOTES_HOME), "a nonexistent subdirectory still resolves through its worktree");
182
183
  assert.equal(scopeDir("project", context(manager(), undefined, undefined, true, worktree)), scopeDir("project", context(manager(), undefined, undefined, true, main)), "@project uses the same physical home from both checkouts");
183
184
  });
184
185
  test("unrecognized metadata remains ordinary frontmatter; invalid project ownership stays unknown", async () => {
@@ -224,7 +225,7 @@ project: 17
224
225
 
225
226
  invalid owner`);
226
227
  assert.equal(parseNote(readFileSync(invalidFile, "utf8")).meta.project, 17);
227
- assert.notEqual(parseNote(readFileSync(invalidFile, "utf8")).meta.project, projectKey(ctx.cwd), "invalid ownership does not match the current project key");
228
+ assert.notEqual(parseNote(readFileSync(invalidFile, "utf8")).meta.project, projectKey(ctx.cwd, process.env.PI_NOTES_HOME), "invalid ownership does not match the current project key");
228
229
  await call(captured, "notes_write", { address: "invalid.md", content: "still invalid" }, ctx);
229
230
  assert.equal(parseNote(readFileSync(invalidFile, "utf8")).meta.project, 17, "an invalid value remains unknown and is not replaced with cwd-derived ownership");
230
231
  assert.equal(existsSync(join(scopeDir("session", ctx), ".session.json")), false, "new notes use no ownership sidecar");
@@ -339,14 +340,19 @@ test("empty results distinguish hidden notes and unavailable homes", async () =>
339
340
  await call(captured, "notes_update", { address: "@human/hidden.md", crumpled: true }, ctx);
340
341
  const hidden = resultData(await call(captured, "notes_search", { query: "needle", glob: "@human/**" }, ctx));
341
342
  assert.deepEqual(hidden.files, [], "a crumpled note is hidden from search");
343
+ const identity = notesIdentityFromPi(ctx);
342
344
  const broken = scopeDir("project", ctx);
343
345
  mkdirSync(join(broken, ".."), { recursive: true });
346
+ rmSync(broken, { recursive: true });
344
347
  writeFileSync(broken, "not a directory");
345
- const partial = resultData(await call(captured, "notes_list", { glob: "**" }, ctx));
348
+ const partialResult = await notesList.execute({ glob: "**" }, identity);
349
+ assert.ok(partialResult.ok);
350
+ const partial = partialResult.data;
346
351
  assert.deepEqual(partial.homes_unavailable, ["@project"]);
347
352
  assert.deepEqual(partial.files, []);
348
- const searched = resultData(await call(captured, "notes_search", { query: "needle", glob: "**" }, ctx));
349
- assert.deepEqual(searched.homes_unavailable, ["@project"]);
353
+ const searchResult = await notesSearch.execute({ query: "needle", glob: "**" }, identity);
354
+ assert.ok(searchResult.ok);
355
+ assert.deepEqual(searchResult.data.homes_unavailable, ["@project"]);
350
356
  writeFileSync(join(process.env.PI_NOTES_HOME, "agents"), "not a directory");
351
357
  const namespace = resultData(await call(captured, "notes_list", { glob: "@agents/*/note.md" }, ctx));
352
358
  assert.deepEqual(namespace.homes_unavailable, ["@agents"]);
@@ -529,17 +535,14 @@ async function withAgent(name, run) {
529
535
  process.env.PI_NOTES_AGENT = previous;
530
536
  }
531
537
  }
532
- test("a symlinked checkout hashes the canonical root, so one checkout has one project home", () => {
538
+ test("a symlinked checkout resolves the canonical root, so one checkout has one project home", () => {
533
539
  const root = realpathSync(testEnvironment.cwd);
534
540
  const real = join(root, "real-repo");
535
541
  mkdirSync(join(real, ".git"), { recursive: true });
536
542
  const linked = join(root, "linked-repo");
537
543
  symlinkSync(real, linked);
538
- // The formula the key is documented to be: basename plus sha1 of the canonical root.
539
- const canonicalKey = `${basename(real)}-${createHash("sha1").update(real).digest("hex").slice(0, 8)}`;
540
- assert.equal(projectKey(linked), canonicalKey, "the symlinked spelling hashes the canonical root");
541
- assert.equal(projectKey(real), canonicalKey, "the canonical spelling hashes the same root");
542
- assert.notEqual(`${basename(linked)}-${createHash("sha1").update(linked).digest("hex").slice(0, 8)}`, canonicalKey, "a path-spelled key would differ");
544
+ assert.equal(projectKey(linked, process.env.PI_NOTES_HOME), "real-repo", "the name comes from the canonical root");
545
+ assert.equal(projectKey(real, process.env.PI_NOTES_HOME), "real-repo", "both spellings reuse one home");
543
546
  });
544
547
  test("a glob ? matches exactly one non-slash character", () => {
545
548
  const pattern = globToRegExp("a?.md");
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,134 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { Check } from "typebox/value";
7
+ import { createNotesStore } from "../src/notes/index.js";
8
+ import { assertAddress } from "../src/notes/address.js";
9
+ import { normalizeRemote, projectKey } from "../src/notes/project-home.js";
10
+ import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../src/tools/notes.js";
11
+ import { success } from "../src/tools/result.js";
12
+ function fixture(t) {
13
+ const root = realpathSync(mkdtempSync(join(tmpdir(), "notesoup-project-home-")));
14
+ t.after(() => rmSync(root, { recursive: true, force: true }));
15
+ const home = join(root, "notes");
16
+ const repo = (path, origin) => {
17
+ const cwd = join(root, path);
18
+ mkdirSync(join(cwd, ".git"), { recursive: true });
19
+ writeFileSync(join(cwd, ".git/config"), origin ? `[remote "origin"]\n\turl = ${origin}\n` : "");
20
+ return cwd;
21
+ };
22
+ const marker = (key) => JSON.parse(readFileSync(join(home, "project", key, ".project"), "utf8"));
23
+ const identity = (cwd) => ({ home, projectKey: projectKey(cwd, home), sessionId: "session", agent: "test", model: "test" });
24
+ return { root, home, repo, marker, identity };
25
+ }
26
+ function data(result) {
27
+ if (!result.ok)
28
+ assert.fail(result.error.message);
29
+ return result.data;
30
+ }
31
+ function refused(result) {
32
+ if (result.ok)
33
+ assert.fail("expected refusal");
34
+ return result.error.message;
35
+ }
36
+ test("origin identity normalizes https, scp and port-less ssh without invoking Git", t => {
37
+ const { home, repo, marker } = fixture(t);
38
+ for (const remote of ["https://user:secret@GitHub.COM/team/api.git/", "git@GitHub.COM:team/api.git", "ssh://git@GitHub.COM/team/api.git"]) {
39
+ assert.equal(normalizeRemote(remote), "github.com/team/api");
40
+ }
41
+ assert.equal(normalizeRemote("ssh://git@EXAMPLE.com:2222/team/api.git"), "example.com:2222/team/api");
42
+ const first = repo("one/api", "git@GitHub.COM:team/api.git");
43
+ const second = repo("two/renamed", "https://github.com/team/api.git");
44
+ assert.equal(projectKey(first, home), "api");
45
+ assert.equal(projectKey(second, home), "api");
46
+ assert.deepEqual(marker("api"), { id: "github.com/team/api", path: second });
47
+ });
48
+ test("same-basename repositories get readable suffixes and unmarked legacy names are taken", t => {
49
+ const { home, repo } = fixture(t);
50
+ const first = repo("one/x", "https://host/one/x");
51
+ const second = repo("two/x", "https://host/two/x");
52
+ assert.equal(projectKey(first, home), "x");
53
+ assert.equal(projectKey(second, home), "x-1");
54
+ mkdirSync(join(home, "project", "legacy"));
55
+ writeFileSync(join(home, "project", "legacy", "keep.md"), "old notes");
56
+ assert.equal(projectKey(repo("legacy"), home), "legacy-1");
57
+ assert.equal(readFileSync(join(home, "project", "legacy", "keep.md"), "utf8"), "old notes");
58
+ });
59
+ test("linked worktrees and nested directories share the main checkout home and origin", t => {
60
+ const { root, home, repo, marker } = fixture(t);
61
+ const main = repo("api", "ssh://git@HOST/team/api.git");
62
+ const worktree = join(root, "worktree");
63
+ mkdirSync(worktree);
64
+ mkdirSync(join(main, ".git/worktrees/wt"), { recursive: true });
65
+ writeFileSync(join(worktree, ".git"), `gitdir: ${join(main, ".git/worktrees/wt")}\n`);
66
+ writeFileSync(join(main, ".git/worktrees/wt/commondir"), "../..\n");
67
+ assert.equal(projectKey(main, home), "api");
68
+ assert.equal(projectKey(join(worktree, "missing/subdir"), home), "api");
69
+ assert.deepEqual(marker("api"), { id: "host/team/api", path: main });
70
+ });
71
+ test("a moved checkout reuses its remote home and updates only the display root", async (t) => {
72
+ const { root, home, repo, marker, identity } = fixture(t);
73
+ const old = repo("api", "https://host/team/api.git");
74
+ await createNotesStore(identity(old)).write("@project/decision", "keep me");
75
+ const moved = join(root, "new-name");
76
+ renameSync(old, moved);
77
+ const current = identity(moved);
78
+ assert.equal(current.projectKey, "api");
79
+ assert.deepEqual(marker("api"), { id: "host/team/api", path: moved });
80
+ assert.equal((await createNotesStore(current).read("@project/decision"))?.body, "keep me");
81
+ assert.equal(projectKey(moved, home), "api");
82
+ });
83
+ test("adding origin adopts the canonical path identity without orphaning notes", async (t) => {
84
+ const { home, repo, marker, identity } = fixture(t);
85
+ const cwd = repo("api");
86
+ await createNotesStore(identity(cwd)).write("@project/decision", "still here");
87
+ assert.deepEqual(marker("api"), { id: cwd, path: cwd });
88
+ writeFileSync(join(cwd, ".git/config"), '[remote "backup"]\nurl = https://host/wrong\n[remote "origin"]\nurl = git@HOST:team/api.git\n');
89
+ assert.equal(projectKey(cwd, home), "api");
90
+ assert.deepEqual(marker("api"), { id: "host/team/api", path: cwd });
91
+ assert.equal((await createNotesStore(identity(cwd)).read("@project/decision"))?.body, "still here");
92
+ });
93
+ test("named projects read/list/search with root and sibling receipts, without touching stored bytes", async (t) => {
94
+ const { home, repo, identity } = fixture(t);
95
+ const first = repo("one/api", "https://host/one/backend");
96
+ const second = repo("two/api", "https://host/two/service");
97
+ const own = identity(first);
98
+ const other = identity(second);
99
+ await createNotesStore(own).write("@project/decision", "needle first");
100
+ await createNotesStore(other).write("@project/decision", "needle second");
101
+ const address = "@projects/api-1/decision.md";
102
+ const file = join(home, "project/api-1/decision.md");
103
+ const before = readFileSync(file, "utf8");
104
+ const read = data(await notesRead.execute({ address }, own));
105
+ assert.equal(read.text, "needle second");
106
+ assert.equal(read.project_root, second);
107
+ assert.deepEqual(read.project_siblings, [{ name: "api", path: first }]);
108
+ assert.equal(Check(notesRead.outputSchema, read), true);
109
+ assert.match(notesRead.render(success(read)), /Same-basename projects: api \(/);
110
+ const listed = data(await notesList.execute({ glob: "@projects/*/**" }, own));
111
+ assert.deepEqual(listed.files.map(row => [row.address, row.project_root]).sort(), [["@projects/api-1/decision.md", second], ["@projects/api/decision.md", first]].sort());
112
+ assert.equal(Check(notesList.outputSchema, listed), true);
113
+ const searched = data(await notesSearch.execute({ glob: "@projects/api-1/**", query: "needle" }, own));
114
+ assert.equal(searched.files[0]?.project_root, second);
115
+ assert.equal(Check(notesSearch.outputSchema, searched), true);
116
+ assert.equal(readFileSync(file, "utf8"), before, "named-home reads never rewrite access metadata");
117
+ });
118
+ test("named project writes, edits, crumples and both move endpoints refuse, including the current home", async (t) => {
119
+ const { repo, identity } = fixture(t);
120
+ const own = identity(repo("api"));
121
+ await createNotesStore(own).write("@project/decision", "body");
122
+ const address = "@projects/api/decision";
123
+ for (const result of [
124
+ await notesWrite.execute({ address, content: "replacement" }, own),
125
+ await notesUpdate.execute({ address, edits: [{ oldText: "body", newText: "changed" }] }, own, () => ""),
126
+ await notesUpdate.execute({ address, crumpled: true }, own, () => ""),
127
+ await notesUpdate.execute({ address, rename_to: "@project/moved" }, own, () => ""),
128
+ await notesUpdate.execute({ address: "@project/decision", rename_to: "@projects/api/moved" }, own, () => ""),
129
+ ])
130
+ assert.match(refused(result), /read-only; use @project\//);
131
+ assert.equal(data(await notesRead.execute({ address }, own)).text, "body");
132
+ assert.throws(() => assertAddress("@projects/api/../decision"));
133
+ assert.throws(() => assertAddress("@projects/api"));
134
+ });
@@ -16,6 +16,7 @@ notesoup uses Pi's session branch as the durable source of truth. It does not ma
16
16
  | `tools/notes.ts`, `tools/history.ts`, `tools/schema.ts`, `tools/result.ts`, `tools/output.ts` | Schema-derived outcomes, note/history operations, bounded result selection and pure text rendering | Explicit identity/projection; one bounded result feeds both text and structured output |
17
17
  | `settings.ts`, `dream/settings.ts` | Settings keys, per-key merge and dreamer validation | Parsed values only; no SDK or I/O |
18
18
  | `dream/` | Jail, crumpled-only physical deletion, locks, gates, Git audit, doctor, playbook and result/report logic | Independent filesystem/policy functions; no reverse import into Pi |
19
+ | `dsh/` | Cordis registration, frozen prompt sections, plugin records/checkpoint recovery, token-meter budget, native reset transaction and session-query decoding | Host adapter; imports shared domains, never Pi or Claude |
19
20
  | `pi/extension.ts`, `pi/runtime.ts` | Compose registration, lifecycle hooks, commands, provider operations and UI | Public Pi SDK |
20
21
  | `pi/entries.ts` | Persisted native custom-entry/message tags | Pi persistence vocabulary, not an omnibus protocol barrel |
21
22
  | `pi/window.ts`, `pi/session-reader.ts` | Native `WindowMarker`, checkpoint validation, root/fork identity, branch scans, provider projection and usage | Pi entries/messages and read-only native session traversal |
@@ -26,10 +27,12 @@ notesoup uses Pi's session branch as the durable source of truth. It does not ma
26
27
  | `pi/reset/artifacts.ts`, `pi/reset/committed.ts` | Construct boundaries, repair only safe suffixes, independently confirm committed native boundaries | Active native branch; no shadow commit database |
27
28
  | `pi/dream/` | Pi dream sessions, native tool wrappers, settings reads and executable CLI composition | Pi backend over independent dream policy/filesystem functions |
28
29
 
29
- Dependencies flow from Pi composition into the domains, never back. Shared code cannot import an SDK, `src/pi`, or the root entry, even through erased types, re-exports, literal dynamic/import-type edges or intermediate modules. `test/dependencies.test.ts` uses TypeScript resolution and AST traversal, checks every shared source (including root settings/text matching), and tests rejecting indirect/aliased paths. Shared external packages must be declared in the package manifest. `typebox` is declared as a peer and development dependency rather than imported through Pi's SDK.
30
+ Dependencies flow from host composition into the domains, never back. Shared code cannot import an SDK, `src/pi`, `src/claude`, `src/dsh`, or the root entry, even through erased types, re-exports, literal dynamic/import-type edges or intermediate modules. `test/dependencies.test.ts` uses TypeScript resolution and AST traversal, checks every shared source (including root settings/text matching; excludes the three host adapters), and tests rejecting indirect/aliased paths. Shared external packages must be declared in the package manifest. `typebox` is declared as a peer and development dependency rather than imported through Pi's SDK.
30
31
 
31
32
  The configured extension is `src/index.ts`, loaded straight from TypeScript — no bundling step, so git installs work without a build. Its `pi-ai/utils/estimate` dependency is vendored in `src/pi/estimate.ts` because Pi's root-package aliases misresolve that public subpath on source loads; host-owned SDK APIs stay external. `/notes` is the intentional standalone library API. The CLI is `dist/src/pi/dream/cli.js`. Old internal bags, `NotesContext`, root history helpers and the deep-entry export alias are removed. This breaks source/import paths, not storage: note homes, metadata, session paths and raw history remain intact. There is no universal Harness, host-event emulator, registry, daemon or speculative second backend. No `src/window` exists because the current window responsibilities are genuinely native.
32
33
 
34
+ For the native dsh reset transaction, prompt ordering, capability checks and limits, see [DeepSeek Harness](dsh.md). Its adapter keeps the shared domains unchanged and uses only dsh public services.
35
+
33
36
  ## State and persistence
34
37
 
35
38
  `pi/reset/lifecycle.ts` is the sole `turn_end` composer: it accepts incoming drafts, drains budget-owned guidance/warning drafts, and appends a reset boundary for an explicit tool request or the hard-reserve safety path. Manual and budget close-outs stay armed across note/tool turns and commit from `agent_before_settle` after a successful stop with queued work drained; a manual close-out stops the run while a budget close-out continues in the fresh window. Repeated requests for the same window deduplicate. See [reset lifecycle](reset-lifecycle.md).
package/docs/dsh.md ADDED
@@ -0,0 +1,61 @@
1
+ # DeepSeek Harness adapter
2
+
3
+ notesoup for **dsh 0.2.1-alpha.2** gives the agent a fresh notebook when context runs low: frozen boot text, the five notes homes, eight notes/history tools, `get_context_remaining`, and `clear_memory`. A reset makes **zero model calls**. The old conversation leaves the model surface and remains in the session log for history reads. Dream is not registered on dsh.
4
+
5
+ Install the package in your chosen dsh profile with `dsh plugin --profile <profile> add notesoup`, then copy the model declaration from [the profile patch example](dsh.profile.patch.yml) into `$DSH_HOME/profiles/<profile>/cordis.patch.yml`. The package bundle patch disables `compaction-basic` and inserts `notesoup-engine` and `notesoup`. Do not duplicate those rows when adding the model declaration. A source checkout needs `npm ci --ignore-scripts` and `npm run build`; use absolute `file:///.../dist/src/dsh/engine.js` and `file:///.../dist/src/dsh/index.js` module names. The example shows all rows for a profile assembled without the package bundle.
6
+
7
+ Declare explicit `models` for `llm-deepseek`, with `contextWindow` and `maxTokens` appropriate to your provider. The shipped `deepseek-flash` declaration uses `systemPromptUpdate: in-history`; changing the boot under that route can leave an earlier system prompt in the leading slot. The example uses **200000 context tokens and 8192 output tokens**. Those numbers are test inputs, not a promise about your provider's capacity.
8
+
9
+ On load and before requests, preflight probes `systemPrompt.section`, `tools.register`, `sessionQuery.readSession`, `tokenMeter.measure`, and `llm.resolveModelInfo`. It requires our compaction service and its automatic listener. It inspects public loader entries when available and rejects an enabled `compaction-basic` row or registered `BasicCompactionEngine` fiber. An error names the row or capability to fix. Peer dependencies use `*`, so a newer preview is tested by capability rather than silently skipped by an upper version bound. Cordis can contain a plugin-load failure and continue loading other plugins: inspect startup errors before using a profile.
10
+
11
+ ## Notes, boot and history
12
+
13
+ `notesHome` defaults to `~/.agents/notes`; `agentName` defaults to `dsh`. The filesystem layout and addressing match Pi and Claude: bare paths are session notes, with `@project`, `@human`, `@self`, and `@model` durable homes. Project identity uses the shared `resolveProjectHome(cwd, notesHome)` resolver: readable slug homes with a `.project` marker, including repository/worktree and origin identity. Other marked projects are readable through `@projects/<name>/`; named-home reads do not update access metadata and named-home writes are refused. Receipts, boot protocol (including MAP Cheatsheets), and bounds come from the shared modules, not dsh copies. A model change changes subsequent tools' `@model` identity; the boot remains frozen until reset.
14
+
15
+ The boot is a `systemPrompt.section` at order **2450**, with `interpolate: false`. Shared snapshot/render functions read the five homes once, using a captured timestamp. Rendering is deterministic for those inputs. A `plugin:notesoup/window` record stores the ordinal, id, timestamp, digest and exact boot text. `agent/created` adopts it before the first assembly. Notes written later appear in the next window's boot. Missing records reconstruct from the notesoup compact checkpoint, or from the marked root system section. Neither path rereads notes or regenerates a summary. Records are informational; checkpoints control the model surface.
16
+
17
+ `history_windows`, `history_list`, and `history_read` obtain the full raw log through `ctx.sessionQuery.readSession`, then feed the shared pairing, paging and literal-search operations. Public history seq **1** is native dsh seq **0**; always use the seq a notesoup tool returns. A fork's selected seed prefix is available in its history; no sibling or parent suffix is fetched. Tool results are paired at their call seq. Text blocks are verbatim; other recorded blocks are shown as JSON. These tools browse one session, not the host's entire session corpus.
18
+
19
+ ## Reset and budget
20
+
21
+ The engine owns the compaction transaction, rather than inheriting a summarizer. It validates the complete balanced surface span at positions **1..last**, acquires `compaction/start`, loads and mints the new notebook, writes `compaction/summary` and the replacement checkpoint synchronously, closes with `compaction/end`, then appends the window record. Node **0** stays host-owned. Nothing from the old conversation is retained on the surface. The checkpoint contains only the frozen boot and continuation protocol. A one-message span can reset even when its replacement is larger.
22
+
23
+ Cancellation or a snapshot/checkpoint failure before replacement restores the old notebook. If replacement has already landed, it is authoritative even if closing or flushing fails; rolling back then would send stale boot text. An unmatched close keeps the durable lock until reload. A lost window record is recoverable from the checkpoint. Manual `compactNow` uses host maintenance and flushes through `ctx.sessions.flush`; the host `/compact` command, when installed, therefore uses this reset engine too.
24
+
25
+ Automatic resets run in the awaited prompt-assembly waterfall. Assembly happens before `agent/pre-step`, so the adapter refreshes its accepted section after reset to make the same request carry the new boot. It never adopts a window in pre-step; that listener always delegates with `return next()`.
26
+
27
+ The host-owned reset line is:
28
+
29
+ ```text
30
+ resetAt = floor(min(contextWindow * thresholdRatio,
31
+ contextWindow - maxTokens - headroomTokens))
32
+ reserve = contextWindow - resetAt
33
+ warning = reserve + 16384
34
+ reminder = reserve + reminderMarginTokens
35
+ ```
36
+
37
+ The defaults are `auto: true`, `thresholdRatio: 0.8`, `headroomTokens: 65536`, and `reminderMarginTokens: 24576`. For the example's **200000/8192/0.7/32768**, resetAt is **140000**, reserve **60000**, warning **76384** remaining, and reminder **84576** remaining. `get_context_remaining` subtracts the warning line and clamps at zero. Missing model capacity returns null. A profile with no positive reset budget fails with `BUDGET_CONFIG` and the numbers to fix. No independent percentage cutoff is added by notesoup.
38
+
39
+ The adapter uses `tokenMeter.measure`, model context from `resolveModelInfo`, and the mounted engine's resolved `config`. Alpha.2 keeps an old provider-usage anchor across surface replacement; until the fresh window has a response, notesoup uses the meter's current `surfaceTokens` plus its public tool-schema estimator instead of that stale anchor.
40
+
41
+ The reminder and close-out warning go through `agent.steer`. Close-out remains an instruction to write notes and call `clear_memory`; a normal stop alone does not consume the warning runway. `clear_memory` arms a reset after the entire tool batch. Independently, reaching the hard reserve resets at assembly or a successful stopping boundary and continues from the notes. Abort and ordinary errors drop the pending tool request. `auto: false` disables reminders and reserve resets while keeping explicit `clear_memory` and the listener installed.
42
+
43
+ ## What this does not promise
44
+
45
+ | Limit | What to expect / next step |
46
+ | --- | --- |
47
+ | dsh versions | Tested against **0.2.1-alpha.2**. Capability checks do not establish wire or persistence compatibility with every newer preview. Run the scripted tests before upgrading. |
48
+ | Model calls per reset | **0** auxiliary model calls. The agent's note-writing turns and fresh-window continuation still make ordinary calls. |
49
+ | Retention | Surface node **0**, one boot/continuation checkpoint, and subsequent messages. An unfinished tool batch postpones reset; no partial tool pairs are discarded. |
50
+ | Boot bounds | Up to **4096 code points per MAP** and **3 recent notes per home**, from the shared renderer. Slim large MAPs; follow note addresses for full bodies. |
51
+ | Tool output | Shared **32 KiB** bounds; use `next_offset_chars`, history cursors, or narrower filters. There is no unbounded hidden result. |
52
+ | Warning timing | Steering enters the next step; a large current response/tool batch can spend the runway. The hard reserve protects the next balanced boundary, not an in-flight provider call. |
53
+ | Unknown capacity | Countdown is **null** and automatic reserve checks skip. Add `models[].contextWindow` to `llm-deepseek`; explicit resets still work. |
54
+ | Storage | Raw log remains available while the host keeps it. Notesoup does not back up session files or guarantee that an unflushed append survives a crash. |
55
+ | Plugin records | Best-effort across dsh migrations. Missing records recover from native checkpoints/root system text; unknown future record or checkpoint formats are not migrated by notesoup. |
56
+ | Tools and errors | Full shared TypeBox validation runs in the adapter because dsh supports a smaller schema subset. Expected operation errors become dsh failures with the shared code; successes use the shared bounded value and renderer. |
57
+ | Notifications and commands | No custom UI notifications, settings card, runtime toggle or `/clear-memory` alias is installed. Configure engine rows in the profile/home patch; call `clear_memory` or the host's `/compact`. |
58
+ | Untested host features | Real providers, reasoning/image wire behavior, cache metrics, actual context-overflow retry, HMR, migrations, ACP/Web/SDK profiles and large histories are not established by the scripted tests. |
59
+ | Dream | **No dsh dream backend or dream skill registration.** Use the existing supported host workflow. |
60
+
61
+ Run `npm run typecheck` and `npm test` from a checkout. The dsh tests drive the actual loop and tools with a local Messages/SSE server, temporary notes homes and the SQLite session query service. The compaction parity test runs the installed `BasicCompactionEngine` and our own engine through open-turn and idle success paths and a rejected-checkpoint path. It pins native event/result fields, replacement references, and node-zero preservation; it names the intentional differences (Basic's LLM call fields and retained tail, notesoup's model-free template and ignorable window record). Other tests pin codes, token values, window ordinals and request content rather than prose.
@@ -0,0 +1,34 @@
1
+ # Add to $DSH_HOME/profiles/<profile>/cordis.patch.yml after installing notesoup.
2
+ # For a source checkout, run npm ci --ignore-scripts && npm run build, then replace
3
+ # notesoup/dsh[/engine] below with absolute file:///.../dist/src/dsh/...js paths.
4
+ - id: compaction-basic
5
+ disabled: true
6
+
7
+ # Explicit models avoid the shipped deepseek-flash in-history prompt update.
8
+ # Choose capacity and output limits for your provider; these are the tested values.
9
+ - id: llm-deepseek
10
+ name: '@deepseek-ai/dsh-llm-deepseek-api-key'
11
+ config:
12
+ models:
13
+ - id: deepseek-flash
14
+ name: DeepSeek Flash
15
+ contextWindow: 200000
16
+ maxTokens: 8192
17
+
18
+ - id: agent-default-model
19
+ config:
20
+ provider: deepseek-official
21
+ model: deepseek-flash
22
+
23
+ - insert:
24
+ - id: notesoup-engine
25
+ name: 'notesoup/dsh/engine'
26
+ config:
27
+ auto: true
28
+ thresholdRatio: 0.7
29
+ headroomTokens: 32768
30
+ reminderMarginTokens: 24576
31
+ agentName: dsh
32
+ # notesHome: /absolute/path/to/notes
33
+ - id: notesoup
34
+ name: 'notesoup/dsh'
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.43.0",
3
+ "version": "0.45.0",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"