notesoup 0.52.4 → 0.52.6

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.
package/README.md CHANGED
@@ -53,15 +53,29 @@ pi -e npm:notesoup
53
53
 
54
54
  ## Configuration
55
55
 
56
- The reminder threshold is Pi's compaction reserve plus a margin, configured under the top-level `notesoup` key in `~/.pi/agent/settings.json` or `<cwd>/.pi/settings.json` (project values win per key):
56
+ Pi budget settings live under the top-level `notesoup` key in `~/.pi/agent/settings.json` or `<cwd>/.pi/settings.json`. Trusted project values win **per key**: a project override of `reserveTokens` still inherits a global `warningRunwayTokens`. Each value must be a positive safe integer (numeric strings are also accepted). An absent value uses its fallback; an invalid value emits a warning and uses that same fallback, not a lower-precedence global value.
57
+
58
+ | Setting | Meaning | Fallback |
59
+ | --- | --- | --- |
60
+ | `notesoup.reserveTokens` | Remaining tokens at the hard-reserve wipe. Also subtracted by `get_context_remaining`. | The active Pi compaction reserve, including provider/model overrides. |
61
+ | `notesoup.warningRunwayTokens` | Room between the final warning and the hard-reserve wipe. Warning fires at remaining tokens ≤ reserve + runway. | Shared default: `16384`. |
62
+ | `notesoup.reminderMarginTokens` | Early reminder margin above the resolved notesoup reserve. | `24576`. |
63
+
64
+ For example, explicitly configure an `8192` hard reserve and a `16384` warning runway:
57
65
 
58
66
  ```json
59
67
  {
60
- "compaction": { "reserveTokens": 16384 },
61
- "notesoup": { "reminderMarginTokens": 24576 }
68
+ "notesoup": {
69
+ "reserveTokens": 8192,
70
+ "warningRunwayTokens": 16384
71
+ }
62
72
  }
63
73
  ```
64
74
 
75
+ This warns at **24576 remaining tokens** and hard-wipes at **8192**; `get_context_remaining` reports `16384` at the warning line. These are example settings, not changed defaults. Without overrides, the reserve still inherits Pi's active compaction reserve, and the warning runway remains `16384`. The early reminder uses reserve + reminder margin; if usage crosses both reminder and warning, the final warning takes precedence.
76
+
77
+ These settings only change notesoup's budget thresholds. They do not modify Pi's native `compaction` settings or enable automatic resets when Pi's compaction is disabled (or notesoup is off). Other hosts retain their existing host-specific settings.
78
+
65
79
  Environment variables:
66
80
 
67
81
  - `NOTESOUP_DISABLED` — presence-style kill switch: any value but an explicit no (`0`, `false`, `no`, `off`) turns notesoup off. On Pi the extension registers nothing at all; on Claude the mod passes every event through and native compaction behaves as if the mod were absent.
@@ -1,7 +1,7 @@
1
1
  import { type ResolvedThresholds } from "../../src/budget/policy.js";
2
2
  import { SettingsManager, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  /**
4
- * Read the active compaction reserve, enablement, and notesoup margin settings. This
4
+ * Read the active compaction reserve, enablement, and notesoup budget settings. This
5
5
  * function deliberately has no cache: the budget owner supplies the invocation-scoped
6
6
  * cache so two live notesoup instances cannot share mutable policy state.
7
7
  */
@@ -4,13 +4,11 @@ export type ResolvedThresholds = {
4
4
  warning: number;
5
5
  };
6
6
  /**
7
- * Pure derivation of the thresholds from the host's reserve: the reminder fires at reserve
8
- * plus the notesoup margin, the warning steer at reserve plus WARNING_RUNWAY_TOKENS.
9
- * An invalid margin degrades to the default and reports one warning. Automatic
10
- * threshold/overflow handling is represented by reset lifecycle boundary drafts;
11
- * no compaction summary is generated.
7
+ * Derive notesoup thresholds from the host reserve and optional notesoup overrides.
8
+ * Invalid settings fall back independently and report one warning per offending key.
9
+ * No host compaction settings are changed and no compaction summary is generated.
12
10
  */
13
- export declare function deriveThresholds(reserveTokens: number, margins: Record<string, unknown>): {
11
+ export declare function deriveThresholds(reserveTokens: number, settings: Record<string, unknown>): {
14
12
  thresholds: ResolvedThresholds;
15
13
  warnings: string[];
16
14
  };
@@ -2,28 +2,25 @@ import { DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "./constan
2
2
  import { positiveInteger } from "./parse.js";
3
3
  import { NOTESOUP_SETTINGS_KEY } from "../settings.js";
4
4
  /**
5
- * Pure derivation of the thresholds from the host's reserve: the reminder fires at reserve
6
- * plus the notesoup margin, the warning steer at reserve plus WARNING_RUNWAY_TOKENS.
7
- * An invalid margin degrades to the default and reports one warning. Automatic
8
- * threshold/overflow handling is represented by reset lifecycle boundary drafts;
9
- * no compaction summary is generated.
5
+ * Derive notesoup thresholds from the host reserve and optional notesoup overrides.
6
+ * Invalid settings fall back independently and report one warning per offending key.
7
+ * No host compaction settings are changed and no compaction summary is generated.
10
8
  */
11
- export function deriveThresholds(reserveTokens, margins) {
9
+ export function deriveThresholds(reserveTokens, settings) {
12
10
  const warnings = [];
13
- const reminderKey = `${NOTESOUP_SETTINGS_KEY}.reminderMarginTokens`;
14
- let reminderMargin;
15
- if (margins.reminderMarginTokens === undefined)
16
- reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
17
- else {
18
- const parsed = positiveInteger(margins.reminderMarginTokens);
19
- if (parsed === undefined) {
20
- warnings.push(`🥣 ${reminderKey} must be a positive integer · using the default`);
21
- reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
22
- }
23
- else
24
- reminderMargin = parsed;
25
- }
26
- return { thresholds: { reminder: reserveTokens + reminderMargin, reserve: reserveTokens, warning: reserveTokens + WARNING_RUNWAY_TOKENS }, warnings };
11
+ const resolve = (key, fallback) => {
12
+ if (settings[key] === undefined)
13
+ return fallback;
14
+ const parsed = positiveInteger(settings[key]);
15
+ if (parsed !== undefined)
16
+ return parsed;
17
+ warnings.push(`🥣 ${NOTESOUP_SETTINGS_KEY}.${key} must be a positive integer · using the default`);
18
+ return fallback;
19
+ };
20
+ const reserve = resolve("reserveTokens", reserveTokens);
21
+ const reminderMargin = resolve("reminderMarginTokens", DEFAULT_REMINDER_MARGIN_TOKENS);
22
+ const warningRunway = resolve("warningRunwayTokens", WARNING_RUNWAY_TOKENS);
23
+ return { thresholds: { reminder: reserve + reminderMargin, reserve, warning: reserve + warningRunway }, warnings };
27
24
  }
28
25
  /** Room before the hard-reserve wipe; unknown usage stays unknown. */
29
26
  export function remainingBudget(remaining, reserve) {
@@ -44,10 +44,12 @@ export type NotesQuery = {
44
44
  crumpled?: boolean;
45
45
  };
46
46
  /** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
47
+ /** `accessedBefore` is the last access before this read, so a read never hides how long a note sat unread. */
47
48
  export type NoteReadResult = {
48
49
  meta: NoteMeta;
49
50
  body: string;
50
51
  resolvedScope: Scope;
52
+ accessedBefore: number;
51
53
  };
52
54
  export type NoteWriteResult = {
53
55
  meta: NoteMeta;
@@ -297,11 +297,11 @@ export function createNotesStore(input) {
297
297
  const parsed = parseNote(raw, now);
298
298
  // Named homes, and every read during a dream, leave no access stamp.
299
299
  if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined))
300
- return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
300
+ return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope, accessedBefore: parsed.meta.lastAccessed };
301
301
  // A read records its own access, exactly as a write records an edit.
302
302
  const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
303
303
  await atomicWrite(path, serializeNote(meta, parsed.body));
304
- return { meta, body: parsed.body, resolvedScope: scope };
304
+ return { meta, body: parsed.body, resolvedScope: scope, accessedBefore: parsed.meta.lastAccessed };
305
305
  });
306
306
  }
307
307
  async function update(address, edits, options = {}) {
@@ -20,6 +20,7 @@ export declare const DreamBeginDataSchema: Type.TObject<{
20
20
  homes_unavailable: Type.TArray<Type.TString>;
21
21
  files: Type.TArray<Type.TObject<{
22
22
  updated_at: Type.TString;
23
+ last_accessed: Type.TString;
23
24
  crumpled_at: Type.TOptional<Type.TString>;
24
25
  project_root: Type.TOptional<Type.TString>;
25
26
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -45,6 +46,7 @@ export declare const dreamBegin: {
45
46
  homes_unavailable: Type.TArray<Type.TString>;
46
47
  files: Type.TArray<Type.TObject<{
47
48
  updated_at: Type.TString;
49
+ last_accessed: Type.TString;
48
50
  crumpled_at: Type.TOptional<Type.TString>;
49
51
  project_root: Type.TOptional<Type.TString>;
50
52
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -11,6 +11,7 @@ export declare const NoteMetadataSchema: Type.TObject<{
11
11
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
12
12
  created_at: Type.TString;
13
13
  updated_at: Type.TString;
14
+ last_accessed: Type.TString;
14
15
  crumpled_at: Type.TOptional<Type.TString>;
15
16
  project: Type.TOptional<Type.TString>;
16
17
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
@@ -38,6 +39,7 @@ export declare const NotesReadDataSchema: Type.TObject<{
38
39
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
39
40
  created_at: Type.TString;
40
41
  updated_at: Type.TString;
42
+ last_accessed: Type.TString;
41
43
  crumpled_at: Type.TOptional<Type.TString>;
42
44
  project: Type.TOptional<Type.TString>;
43
45
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
@@ -56,6 +58,7 @@ export declare const NotesListDataSchema: Type.TObject<{
56
58
  homes_unavailable: Type.TArray<Type.TString>;
57
59
  files: Type.TArray<Type.TObject<{
58
60
  updated_at: Type.TString;
61
+ last_accessed: Type.TString;
59
62
  crumpled_at: Type.TOptional<Type.TString>;
60
63
  project_root: Type.TOptional<Type.TString>;
61
64
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -77,6 +80,7 @@ export declare const NotesSearchDataSchema: Type.TObject<{
77
80
  offset_chars: Type.TInteger;
78
81
  }>>;
79
82
  updated_at: Type.TString;
83
+ last_accessed: Type.TString;
80
84
  crumpled_at: Type.TOptional<Type.TString>;
81
85
  project_root: Type.TOptional<Type.TString>;
82
86
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -187,6 +191,7 @@ export declare const notesRead: {
187
191
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
188
192
  created_at: Type.TString;
189
193
  updated_at: Type.TString;
194
+ last_accessed: Type.TString;
190
195
  crumpled_at: Type.TOptional<Type.TString>;
191
196
  project: Type.TOptional<Type.TString>;
192
197
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
@@ -225,6 +230,7 @@ export declare const notesList: {
225
230
  homes_unavailable: Type.TArray<Type.TString>;
226
231
  files: Type.TArray<Type.TObject<{
227
232
  updated_at: Type.TString;
233
+ last_accessed: Type.TString;
228
234
  crumpled_at: Type.TOptional<Type.TString>;
229
235
  project_root: Type.TOptional<Type.TString>;
230
236
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -271,6 +277,7 @@ export declare const notesSearch: {
271
277
  offset_chars: Type.TInteger;
272
278
  }>>;
273
279
  updated_at: Type.TString;
280
+ last_accessed: Type.TString;
274
281
  crumpled_at: Type.TOptional<Type.TString>;
275
282
  project_root: Type.TOptional<Type.TString>;
276
283
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -40,6 +40,7 @@ export const NoteMetadataSchema = Type.Object({
40
40
  origin: Type.Union([...ORIGIN_VALUES]),
41
41
  created_at: Type.String(),
42
42
  updated_at: Type.String(),
43
+ last_accessed: Type.String(),
43
44
  crumpled_at: Type.Optional(Type.String()),
44
45
  project: Type.Optional(Type.String()),
45
46
  extra: Type.Record(Type.String(), Type.Unknown()),
@@ -71,6 +72,7 @@ function noteMetadata(meta) {
71
72
  origin: meta.origin,
72
73
  created_at: localIso(meta.createdAt),
73
74
  updated_at: localIso(meta.updatedAt),
75
+ last_accessed: localIso(meta.lastAccessed),
74
76
  ...(typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {}),
75
77
  ...(typeof meta.project === "string" ? { project: meta.project } : {}),
76
78
  extra,
@@ -81,6 +83,7 @@ function renderMetadata(metadata) {
81
83
  `origin ${metadata.origin}`,
82
84
  `created ${metadata.created_at}`,
83
85
  `updated ${metadata.updated_at}`,
86
+ `accessed ${metadata.last_accessed}`,
84
87
  ...(metadata.crumpled_at === undefined ? [] : [`crumpled ${metadata.crumpled_at}`]),
85
88
  ...(metadata.project === undefined ? [] : [`project ${metadata.project}`]),
86
89
  ];
@@ -107,6 +110,7 @@ const ListedFileSchema = Type.Object({
107
110
  project_key: Type.Optional(Type.String()),
108
111
  ...ProjectReceiptSchema,
109
112
  updated_at: Type.String(),
113
+ last_accessed: Type.String(),
110
114
  crumpled_at: Type.Optional(Type.String()),
111
115
  }, { additionalProperties: false });
112
116
  const MatchSchema = Type.Object({
@@ -173,7 +177,7 @@ export function snapshot(rows, limit, status, renderData, shrink) {
173
177
  return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
174
178
  }
175
179
  export function listedFile(row, identity) {
176
- return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
180
+ return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), last_accessed: localIso(row.meta.lastAccessed), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
177
181
  }
178
182
  export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
179
183
  function renderWriteData(data) {
@@ -265,7 +269,8 @@ export const notesRead = {
265
269
  const totalChars = Array.from(note.body).length;
266
270
  if (params.offset_chars !== undefined && params.offset_chars > totalChars)
267
271
  return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
268
- const metadata = noteMetadata(note.meta);
272
+ // Report the access before this one: the read itself must not make a long-unread note look fresh.
273
+ const metadata = noteMetadata({ ...note.meta, lastAccessed: note.accessedBefore });
269
274
  return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
270
275
  }
271
276
  catch (error) {
@@ -278,7 +283,7 @@ export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FI
278
283
  export function renderListData(data) {
279
284
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
280
285
  for (const file of data.files) {
281
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
286
+ lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | accessed ${file.last_accessed}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
282
287
  }
283
288
  if (data.more > 0)
284
289
  lines.push(`${data.more} more matching notes omitted; narrow with glob`);
@@ -1,11 +1,81 @@
1
1
  import assert from "node:assert/strict";
2
+ import { join } from "node:path";
2
3
  import test from "node:test";
4
+ import { SettingsManager } from "@earendil-works/pi-coding-agent";
3
5
  import { DEFAULT_REMINDER_MARGIN_TOKENS, DEFAULT_RESERVE_TOKENS } from "../src/budget/constants.js";
4
- import { GUIDANCE_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
6
+ import { GUIDANCE_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
7
+ import { deriveThresholds } from "../src/budget/policy.js";
8
+ import { readThresholdSettings } from "../plugins/pi/thresholds.js";
5
9
  import { NOTESOUP_SETTINGS_KEY } from "../src/settings.js";
6
- import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultJson, runContextHook, runHandlers, sentOf, settingsFixture, } from "./helpers/extension.js";
10
+ import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultJson, runContextHook, runHandlers, sentOf, settingsFixture, writeJson, } from "./helpers/extension.js";
7
11
  import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
8
12
  const testEnvironment = installExtensionTestHooks("notesoup-integration");
13
+ test("budget derivation preserves defaults and validates overrides independently", () => {
14
+ assert.deepEqual(deriveThresholds(32_768, {}), {
15
+ thresholds: { reserve: 32_768, reminder: 57_344, warning: 49_152 }, warnings: [],
16
+ });
17
+ assert.deepEqual(deriveThresholds(32_768, { reserveTokens: 8192, warningRunwayTokens: "16384" }), {
18
+ thresholds: { reserve: 8192, reminder: 32_768, warning: 24_576 }, warnings: [],
19
+ });
20
+ const invalid = deriveThresholds(32_768, { reserveTokens: 0, warningRunwayTokens: 1.5, reminderMarginTokens: -1 });
21
+ assert.deepEqual(invalid.thresholds, deriveThresholds(32_768, {}).thresholds);
22
+ assert.equal(invalid.warnings.length, 3);
23
+ for (const key of ["reserveTokens", "warningRunwayTokens", "reminderMarginTokens"]) {
24
+ assert.equal(invalid.warnings.filter((warning) => warning.includes(`notesoup.${key} must be a positive integer · using the default`)).length, 1);
25
+ }
26
+ assert.deepEqual(deriveThresholds(32_768, { reserveTokens: 8192, warningRunwayTokens: null }).thresholds, { reserve: 8192, reminder: 32_768, warning: 24_576 }, "an invalid runway does not discard a valid reserve");
27
+ });
28
+ test("Pi budget settings merge per key without changing native compaction settings or enablement", async () => {
29
+ const fixture = settingsFixture({
30
+ reserveTokens: 32_768,
31
+ global: { notesoup: { reserveTokens: 12_000, warningRunwayTokens: 20_000 } },
32
+ project: { notesoup: { reserveTokens: 8192 } },
33
+ });
34
+ const sm = manager();
35
+ const ctx = context(sm, undefined, undefined, true, fixture.cwd);
36
+ const sdk = SettingsManager.create(fixture.cwd, fixture.agentDir, { projectTrusted: true });
37
+ const native = sdk.getCompactionSettings();
38
+ assert.deepEqual(readThresholdSettings(ctx, sdk), {
39
+ thresholds: { reserve: 8192, reminder: 32_768, warning: 28_192 }, automatic: true, warnings: [],
40
+ });
41
+ assert.deepEqual(sdk.getCompactionSettings(), native, "notesoup reserve does not mutate Pi's reserve or other compaction settings");
42
+ writeJson(join(fixture.cwd, ".pi", "settings.json"), { notesoup: { warningRunwayTokens: 4096, reserveTokens: 0 } });
43
+ const reloaded = SettingsManager.create(fixture.cwd, fixture.agentDir, { projectTrusted: true });
44
+ const invalid = readThresholdSettings(ctx, reloaded);
45
+ assert.deepEqual(invalid.thresholds, { reserve: 32_768, reminder: 57_344, warning: 36_864 }, "invalid project reserve falls back to native, not the global notesoup reserve; project runway wins");
46
+ assert.equal(invalid.warnings.length, 1);
47
+ assert.match(invalid.warnings[0], /notesoup.reserveTokens/);
48
+ const disabledSettings = { compaction: { enabled: false, reserveTokens: 32_768 }, notesoup: { reserveTokens: 8192, warningRunwayTokens: 16_384 } };
49
+ const disabled = SettingsManager.inMemory(disabledSettings);
50
+ const captured = makeExtension(sm, disabled);
51
+ const full = context(sm, undefined, { tokens: 199_999, percent: 99.9, contextWindow: 200_000 });
52
+ assert.equal(readThresholdSettings(full, disabled).automatic, false);
53
+ assert.equal(await runContextHook(captured, full), undefined, "new knobs do not enable warning injection when native compaction is off");
54
+ const boundary = await commitTurnEndBoundary(captured, sm, full);
55
+ assert.equal(boundary.entries.some((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE), false, "new knobs do not enable a hard wipe when native compaction is off");
56
+ assert.equal(disabled.getCompactionSettings().enabled, false);
57
+ });
58
+ test("Pi warning, reported room, and hard wipe use the notesoup reserve override", async () => {
59
+ const fixture = settingsFixture({ reserveTokens: 32_768, global: { notesoup: { reserveTokens: 8192, warningRunwayTokens: 16_384 } } });
60
+ const sm = manager();
61
+ appendText(sm, "user", "ongoing work");
62
+ const captured = makeExtension(sm);
63
+ await runHandlers(captured, "session_tree", {}, context(sm, undefined, undefined, true, fixture.cwd));
64
+ const at = (remaining) => context(sm, undefined, { tokens: 200_000 - remaining, percent: 0, contextWindow: 200_000 }, true, fixture.cwd);
65
+ const early = await runContextHook(captured, at(24_577));
66
+ assert.equal(early?.messages[0]?.customType, GUIDANCE_TYPE, "no warning above reserve + runway");
67
+ assert.match(String(early?.messages[0]?.content), /About 16385 tokens of room left\./, "guidance subtracts the overridden reserve");
68
+ const warning = await runContextHook(captured, at(24_576));
69
+ assert.equal(warning?.messages[0]?.customType, WARNING_TYPE, "warn at 8192 + 16384, not native reserve + runway");
70
+ const room = async (remaining) => resultJson(await call(captured, "get_context_remaining", {}, at(remaining))).remaining_tokens;
71
+ assert.equal(await room(24_576), 16_384);
72
+ assert.equal(await room(8193), 1);
73
+ const before = await commitTurnEndBoundary(captured, sm, at(8193));
74
+ assert.equal(before.entries.some((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE), false, "no wipe above the overridden reserve, even below Pi's reserve");
75
+ assert.equal(await room(8192), 0);
76
+ const hard = await commitTurnEndBoundary(captured, sm, at(8192));
77
+ assert.equal(hard.entries.filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE).length, 1, "hard wipe at the overridden reserve");
78
+ });
9
79
  test("low-budget guidance and warning persist at turn_end, once per active window", async () => {
10
80
  const sessionManager = manager();
11
81
  const captured = makeExtension(sessionManager);
@@ -38,6 +38,11 @@ test("dream skill is publicly discoverable and resolves the shared playbook", ()
38
38
  assert.equal(skillPlaybook, packagePlaybook);
39
39
  const playbook = readFileSync(packagePlaybook, "utf8");
40
40
  assert.equal(readFileSync(skillPlaybook, "utf8"), playbook);
41
+ const instructions = readFileSync(join(skill.baseDir, "SKILL.md"), "utf8");
42
+ for (const name of ["dream_begin", "dream_forget", "dream_end"])
43
+ assert.ok(instructions.includes(name));
44
+ assert.match(instructions, /missing from the current tool list, search for them/);
45
+ assert.doesNotMatch(instructions, /tool_search|searchTools|codemode/);
41
46
  });
42
47
  test("npm tarball keeps the skill's relative playbook path portable after extraction", () => {
43
48
  const root = packageRoot();
@@ -36,6 +36,8 @@ test("a dream opens one other project, writes its notes, deletes only crumpled o
36
36
  const begun = await dreamBegin.execute({ project: "beta" }, me, state);
37
37
  assert.ok(begun.ok);
38
38
  assert.deepEqual(begun.data.files.map(f => f.address).sort(), ["@projects/beta/rule.md", "@sessions/b1/checkpoint.md", "@sessions/b2/trash.md"]);
39
+ assert.ok(begun.data.files.every(f => typeof f.last_accessed === "string"), "the dream's list shows each note's last access");
40
+ assert.match(dreamBegin.render(begun), /\| accessed /);
39
41
  assert.equal((await dreamBegin.execute({}, me, state)).ok, false, "only one dream at a time");
40
42
  assert.ok(existsSync(join(home, ".dream.lock.beta")), "the project lock is held");
41
43
  assert.equal((await dreamBegin.execute({ project: "beta" }, as("other", "alpha"), {})).ok, false, "another session can't dream the same project");
@@ -59,6 +61,19 @@ test("a dream opens one other project, writes its notes, deletes only crumpled o
59
61
  assert.equal((await notesWrite.execute({ address: "@projects/beta/rule", content: "x" }, ident())).ok, false, "closed again");
60
62
  assert.equal((await dreamEnd.execute({}, me, state)).ok, false);
61
63
  });
64
+ test("notes_read reports the access before itself, so reading never makes an unread note look fresh", async (t) => {
65
+ const { home, as } = fixture(t);
66
+ const me = as("s", "alpha");
67
+ const old = "2026-01-01T08:00:00.000+08:00";
68
+ mkdirSync(join(home, "human"), { recursive: true });
69
+ writeFileSync(join(home, "human", "stale.md"), `---\norigin: self\ncreatedAt: ${old}\nupdatedAt: ${old}\nlastAccessed: ${old}\naccessCount: 0\n---\n\nbody`);
70
+ const first = await notesRead.execute({ address: "@human/stale" }, me);
71
+ assert.ok(first.ok);
72
+ assert.equal(Date.parse(first.data.metadata.last_accessed), Date.parse(old), "the first read shows the old access");
73
+ const second = await notesRead.execute({ address: "@human/stale" }, me);
74
+ assert.ok(second.ok);
75
+ assert.ok(Date.parse(second.data.metadata.last_accessed) > Date.parse(old), "the first read still counted as an access");
76
+ });
62
77
  test("dream_begin refuses an unknown project", async (t) => {
63
78
  const { as } = fixture(t);
64
79
  const state = {};
@@ -139,7 +139,7 @@ test("search offsets address the body and never move when access metadata grows"
139
139
  assert.equal(frontBody, "needle later");
140
140
  assert.equal(frontMatch.offsetChars, 0, "frontmatter length is not part of the body offset");
141
141
  assert.equal(Array.from(frontBody).slice(frontMatch.offsetChars).join(""), "needle later");
142
- assert.deepEqual(Object.keys((await notes.read("counted.md"))).sort(), ["body", "meta", "resolvedScope"], "a read exposes metadata and the body, never a serialized rendering");
142
+ assert.deepEqual(Object.keys((await notes.read("counted.md"))).sort(), ["accessedBefore", "body", "meta", "resolvedScope"], "a read exposes metadata and the body, never a serialized rendering");
143
143
  });
144
144
  test("invalid addressing and failed edits leave stored bytes untouched without poisoning the queue", async (t) => {
145
145
  const { home, context, notes } = fixture(t);
@@ -403,7 +403,7 @@ test("list and search merge scopes and carry addresses; the path jail rejects es
403
403
  const listed = resultData(await call(captured, "notes_list", {}, ctx));
404
404
  assert.deepEqual([...listed.files].map((file) => file.address).sort(), ["@human/three.md", "@project/two.md", "one.md"], "every merged row carries its full address");
405
405
  for (const row of listed.files) {
406
- assert.deepEqual(Object.keys(row).sort(), ["address", "updated_at", ...(row.address.startsWith("@project/") ? ["project_key"] : [])].sort());
406
+ assert.deepEqual(Object.keys(row).sort(), ["address", "updated_at", "last_accessed", ...(row.address.startsWith("@project/") ? ["project_key"] : [])].sort());
407
407
  }
408
408
  const scoped = resultData(await call(captured, "notes_list", { glob: "@human/**" }, ctx));
409
409
  assert.deepEqual(scoped.files.map((file) => file.address), ["@human/three.md"], "an address glob filter narrows the set");
@@ -51,12 +51,12 @@ test("notes_update unchanged keeps quiet", () => {
51
51
  assert.equal(lines(component), "unchanged a.md");
52
52
  });
53
53
  test("notes_read collapsed: size and a peek at the first line", () => {
54
- const result = toolResult(success({ address: "@project/MAP.md", metadata: { origin: "self", created_at: "x", updated_at: "y", extra: {} }, text: "# MAP\n\nbody", total_chars: 11, next_offset_chars: null }));
54
+ const result = toolResult(success({ address: "@project/MAP.md", metadata: { origin: "self", created_at: "x", updated_at: "y", last_accessed: "z", extra: {} }, text: "# MAP\n\nbody", total_chars: 11, next_offset_chars: null }));
55
55
  const component = notesReadRenderers.renderResult(result, { expanded: false }, flatTheme);
56
56
  assert.equal(lines(component), "read @project/MAP.md · 11 chars — # MAP");
57
57
  });
58
58
  test("notes_read expanded: truncation points at the next offset", () => {
59
- const result = toolResult(success({ address: "a.md", metadata: { origin: "self", created_at: "x", updated_at: "y", extra: {} }, text: "part", total_chars: 10, next_offset_chars: 4 }));
59
+ const result = toolResult(success({ address: "a.md", metadata: { origin: "self", created_at: "x", updated_at: "y", last_accessed: "z", extra: {} }, text: "part", total_chars: 10, next_offset_chars: 4 }));
60
60
  const component = notesReadRenderers.renderResult(result, { expanded: true }, flatTheme);
61
61
  assert.equal(lines(component), "read a.md · 10 chars · truncated — part\n\npart\n… continue at offset_chars=4");
62
62
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.52.4",
3
+ "version": "0.52.6",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
package/playbook.md CHANGED
@@ -4,31 +4,42 @@ I am reviewing my notes: keeping what is useful, connecting what belongs togethe
4
4
 
5
5
  ## Scope
6
6
 
7
- Work within the readable sources and writable homes established for this run. Do not broaden that scope while exploring. If a boundary is unclear, ask before crossing it.
8
-
9
- A project dream draws from that project's material, project notes, and session notes identified as belonging to the project; it organizes only that project's notes. A store-wide dream may inspect across homes, but authorship and write permissions still apply. Unknown ownership is a coverage gap to report, not a reason to guess or repair ownership.
7
+ A dream covers one project: its `@project` notes and the session notes born in it. `@human`, `@self`, and `@model` are not part of a dream unless the human asks for them or the dream runs from inside the notes home itself. Do not broaden that scope while exploring; if a boundary is unclear, ask before crossing it. Unknown ownership is a coverage gap to report, not a reason to guess or repair ownership.
10
8
 
11
9
  The homes serve different readers:
12
10
 
13
- - Session notes (`<path>`, no `@`) are a trip's working record. Read them as sources where permitted; never edit them, even after promoting a useful finding.
11
+ - Session notes (`<path>`, no `@`) are a trip's working record. Read them as sources; do not rewrite them. Only the wastebasket rule below may remove another session's notes.
14
12
  - `@project` notes hold knowledge for whoever next works on that project.
15
13
  - `@human` notes hold the human's cross-project preferences and standing rules. Do not turn project facts or your own conclusions into rules in the human's voice.
16
14
  - `@self` notes belong to their author: private if the author has a name, one shared notebook for everyone nameless. Other named authors' notes are read-only unless the human authorizes revision.
17
15
  - `@model` notes describe the substrate's behavior. Other models' notes are read-only unless the human authorizes revision.
18
16
 
17
+ ## What a durable note holds
18
+
19
+ Durable notes hold decisions, constraints, and lessons that stay true after the current work ends. They are not diaries: commit hashes, test counts, dates, and the story of how something was reached belong to git and history. A session finding is worth promoting only when it meets this bar.
20
+
19
21
  ## Review and consolidate
20
22
 
21
- 1. **Leave stable notes alone.** Change a note to incorporate new evidence, resolve a verified error, merge a genuine duplicate, or split an oversized file, not merely to shorten or rephrase it. No change is a valid outcome.
22
- 2. **Verify only what the proposed change depends on.** Before correcting or promoting a conclusion, check the relevant evidence as needed. Do not revalidate every stable note or turn dream into a source-code audit. An unavailable referent is unverified, not proof that it is dead; do not promote an unsupported claim as current fact.
23
- 3. **Merge only genuine duplicates.** Supersede a note only when both notes have the same topic and kind (checkpoint, design, log), and the survivor is strictly newer or more specific. Name the shared topic in the survivor. Otherwise keep both and record any unresolved conflict.
24
- 4. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper home, migrate it: copy it there preserving frontmatter with a one-line provenance note, crumple the original, and update both homes' maps. Crumple keeps the original readable by address, so relocation is reversible: do it, don't propose it. Propose only when the destination home itself is unclear.
25
- 5. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
26
- 6. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links. Checkpoints may exceed the budget: trim prose, never facts.
27
- 7. **Keep maps useful.** Each writable home's MAP.md may include a Cheatsheet of rules that apply in every window; keep it short, about 5 lines. The rest stays the note index: durable notes' addresses and short gists, for lookup. Preserve standing rules, add promoted notes, and drop entries that no longer hold. Maps follow the same size budget.
28
- 8. **Preserve the record.** Never physically delete a live note; after merging, crumple the absorbed note only if it is writable. The wastebasket is the one exception: physically delete a crumpled note when its home is writable and it has been crumpled and untouched for more than 7 days. With raw frontmatter, judge by `lastAccessed`, falling back to `crumpledAt`. With only `notes_*` tools, judge by `crumpled_at`. If no date is readable, keep the note and report it. Never read a raw note through `notes_read` to get the date: it refreshes `lastAccessed`. A venue that cannot delete files lists the doomed addresses in its report instead of blanking them. Preserve existing metadata and provenance.
23
+ 1. **Leave stable notes alone.** Change a note to incorporate new evidence, fix a verified error, retire a stale claim, merge a genuine duplicate, trim diary content, or split an oversized file, not merely to shorten or rephrase it. No change is a valid outcome.
24
+ 2. **Verify only what the proposed change depends on.** Before correcting, retiring, or promoting a conclusion, check the relevant evidence as needed. Do not revalidate every stable note or turn dream into a source-code audit. An unavailable referent is unverified, not proof that it is dead.
25
+ 3. **Retire what is no longer true.** When evidence shows a durable note is stale, correct it in place; if nothing true remains, crumple it. Remove or fix its MAP line either way. A note's last access is a hint, not evidence: long-unread notes are candidates to check, not to crumple on sight. A read reports the access before itself, so reviewing a note does not make it look fresh.
26
+ 4. **Merge only genuine duplicates.** Merge two notes only when they share a topic and kind (checkpoint, design, log). First carry every fact, condition, and exception unique to the absorbed note into the survivor, then crumple the absorbed note. Otherwise keep both and record any unresolved conflict.
27
+ 5. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper home, move it there, preserving its metadata, and update both homes' maps. Do it, don't propose it. Propose only when the destination home itself is unclear.
28
+ 6. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
29
+ 7. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links.
30
+ 8. **Keep maps useful.** Each writable home's MAP.md may include a Cheatsheet of rules that apply in every window; keep it short, about 5 lines. The rest stays the note index: durable notes' addresses and short gists, for lookup. Preserve standing rules, add promoted notes, and drop entries that no longer hold. Maps follow the same size budget.
31
+
32
+ ## Deleting
33
+
34
+ Never physically delete a live note; crumple it first. Two cases allow deleting a crumpled note:
35
+
36
+ - **Your own session's notes** may be deleted once crumpled.
37
+ - **The wastebasket:** any note within the dream's reach that was crumpled more than 7 days ago may be deleted, whatever its home or session. Judge by its crumpled date; if none is readable, keep it and report it.
38
+
39
+ Where notes cannot be deleted, list the doomed addresses in the report instead of blanking them.
29
40
 
30
41
  ## Report
31
42
 
32
- Give a concise report grouped by home: what you inspected, changed, promoted, deleted, and left unresolved. Mention coverage gaps and partial failures. If no notes changed, say so. Distinguish actual note changes from execution or audit artifacts; do not claim success for an incomplete run.
43
+ Give a concise report grouped by home: what you inspected, changed, retired, promoted, deleted, and left unresolved. Mention coverage gaps and partial failures. If no notes changed, say so. Distinguish actual note changes from execution or audit artifacts; do not claim success for an incomplete run.
33
44
 
34
45
  Put skill ideas and unresolved questions in the final message as proposals for the human, not new skill files.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.52.4",
3
+ "version": "0.52.6",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -8569,10 +8569,10 @@ function createNotesStore(input) {
8569
8569
  if (raw === void 0) return void 0;
8570
8570
  const now = Date.now();
8571
8571
  const parsed = parseNote(raw, now);
8572
- if (identity2.dreaming !== void 0 || (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, accessedBefore: parsed.meta.lastAccessed };
8573
8573
  const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
8574
8574
  await atomicWrite(path, serializeNote(meta, parsed.body));
8575
- return { meta, body: parsed.body, resolvedScope: scope };
8575
+ return { meta, body: parsed.body, resolvedScope: scope, accessedBefore: parsed.meta.lastAccessed };
8576
8576
  });
8577
8577
  }
8578
8578
  async function update(address, edits, options = {}) {
@@ -9053,6 +9053,7 @@ var NoteMetadataSchema = typebox_exports.Object({
9053
9053
  origin: typebox_exports.Union([...ORIGIN_VALUES]),
9054
9054
  created_at: typebox_exports.String(),
9055
9055
  updated_at: typebox_exports.String(),
9056
+ last_accessed: typebox_exports.String(),
9056
9057
  crumpled_at: typebox_exports.Optional(typebox_exports.String()),
9057
9058
  project: typebox_exports.Optional(typebox_exports.String()),
9058
9059
  extra: typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())
@@ -9078,6 +9079,7 @@ function noteMetadata(meta) {
9078
9079
  origin: meta.origin,
9079
9080
  created_at: localIso(meta.createdAt),
9080
9081
  updated_at: localIso(meta.updatedAt),
9082
+ last_accessed: localIso(meta.lastAccessed),
9081
9083
  ...typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {},
9082
9084
  ...typeof meta.project === "string" ? { project: meta.project } : {},
9083
9085
  extra
@@ -9088,6 +9090,7 @@ function renderMetadata(metadata) {
9088
9090
  `origin ${metadata.origin}`,
9089
9091
  `created ${metadata.created_at}`,
9090
9092
  `updated ${metadata.updated_at}`,
9093
+ `accessed ${metadata.last_accessed}`,
9091
9094
  ...metadata.crumpled_at === void 0 ? [] : [`crumpled ${metadata.crumpled_at}`],
9092
9095
  ...metadata.project === void 0 ? [] : [`project ${metadata.project}`]
9093
9096
  ];
@@ -9111,6 +9114,7 @@ var ListedFileSchema = typebox_exports.Object({
9111
9114
  project_key: typebox_exports.Optional(typebox_exports.String()),
9112
9115
  ...ProjectReceiptSchema,
9113
9116
  updated_at: typebox_exports.String(),
9117
+ last_accessed: typebox_exports.String(),
9114
9118
  crumpled_at: typebox_exports.Optional(typebox_exports.String())
9115
9119
  }, { additionalProperties: false });
9116
9120
  var MatchSchema = typebox_exports.Object({
@@ -9174,7 +9178,7 @@ function snapshot(rows, limit, status, renderData, shrink) {
9174
9178
  return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
9175
9179
  }
9176
9180
  function listedFile(row, identity2) {
9177
- return { ...noteIdentity(identity2, row.address), updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
9181
+ return { ...noteIdentity(identity2, row.address), updated_at: localIso(row.meta.updatedAt), last_accessed: localIso(row.meta.lastAccessed), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
9178
9182
  }
9179
9183
  var notesWriteParameters = typebox_exports.Object({ address: typebox_exports.String(), content: typebox_exports.String(), origin: ORIGIN }, { additionalProperties: false });
9180
9184
  function renderWriteData(data) {
@@ -9267,7 +9271,7 @@ var notesRead = {
9267
9271
  if (!note) return failure("not_found", `No note at ${resolved.address}.`);
9268
9272
  const totalChars = Array.from(note.body).length;
9269
9273
  if (params.offset_chars !== void 0 && params.offset_chars > totalChars) return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
9270
- const metadata = noteMetadata(note.meta);
9274
+ const metadata = noteMetadata({ ...note.meta, lastAccessed: note.accessedBefore });
9271
9275
  return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
9272
9276
  } catch (error) {
9273
9277
  return failureOf(error);
@@ -9279,7 +9283,7 @@ var notesListParameters = typebox_exports.Object({ glob: GLOB_PARAMETER, limit:
9279
9283
  function renderListData(data) {
9280
9284
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
9281
9285
  for (const file of data.files) {
9282
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === void 0 ? "" : ` | crumpled ${file.crumpled_at}`}`);
9286
+ lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | accessed ${file.last_accessed}${file.crumpled_at === void 0 ? "" : ` | crumpled ${file.crumpled_at}`}`);
9283
9287
  }
9284
9288
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
9285
9289
  for (const home of data.homes_unavailable) lines.push(`${home} could not be read`);
@@ -4,31 +4,42 @@ I am reviewing my notes: keeping what is useful, connecting what belongs togethe
4
4
 
5
5
  ## Scope
6
6
 
7
- Work within the readable sources and writable homes established for this run. Do not broaden that scope while exploring. If a boundary is unclear, ask before crossing it.
8
-
9
- A project dream draws from that project's material, project notes, and session notes identified as belonging to the project; it organizes only that project's notes. A store-wide dream may inspect across homes, but authorship and write permissions still apply. Unknown ownership is a coverage gap to report, not a reason to guess or repair ownership.
7
+ A dream covers one project: its `@project` notes and the session notes born in it. `@human`, `@self`, and `@model` are not part of a dream unless the human asks for them or the dream runs from inside the notes home itself. Do not broaden that scope while exploring; if a boundary is unclear, ask before crossing it. Unknown ownership is a coverage gap to report, not a reason to guess or repair ownership.
10
8
 
11
9
  The homes serve different readers:
12
10
 
13
- - Session notes (`<path>`, no `@`) are a trip's working record. Read them as sources where permitted; never edit them, even after promoting a useful finding.
11
+ - Session notes (`<path>`, no `@`) are a trip's working record. Read them as sources; do not rewrite them. Only the wastebasket rule below may remove another session's notes.
14
12
  - `@project` notes hold knowledge for whoever next works on that project.
15
13
  - `@human` notes hold the human's cross-project preferences and standing rules. Do not turn project facts or your own conclusions into rules in the human's voice.
16
14
  - `@self` notes belong to their author: private if the author has a name, one shared notebook for everyone nameless. Other named authors' notes are read-only unless the human authorizes revision.
17
15
  - `@model` notes describe the substrate's behavior. Other models' notes are read-only unless the human authorizes revision.
18
16
 
17
+ ## What a durable note holds
18
+
19
+ Durable notes hold decisions, constraints, and lessons that stay true after the current work ends. They are not diaries: commit hashes, test counts, dates, and the story of how something was reached belong to git and history. A session finding is worth promoting only when it meets this bar.
20
+
19
21
  ## Review and consolidate
20
22
 
21
- 1. **Leave stable notes alone.** Change a note to incorporate new evidence, resolve a verified error, merge a genuine duplicate, or split an oversized file, not merely to shorten or rephrase it. No change is a valid outcome.
22
- 2. **Verify only what the proposed change depends on.** Before correcting or promoting a conclusion, check the relevant evidence as needed. Do not revalidate every stable note or turn dream into a source-code audit. An unavailable referent is unverified, not proof that it is dead; do not promote an unsupported claim as current fact.
23
- 3. **Merge only genuine duplicates.** Supersede a note only when both notes have the same topic and kind (checkpoint, design, log), and the survivor is strictly newer or more specific. Name the shared topic in the survivor. Otherwise keep both and record any unresolved conflict.
24
- 4. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper home, migrate it: copy it there preserving frontmatter with a one-line provenance note, crumple the original, and update both homes' maps. Crumple keeps the original readable by address, so relocation is reversible: do it, don't propose it. Propose only when the destination home itself is unclear.
25
- 5. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
26
- 6. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links. Checkpoints may exceed the budget: trim prose, never facts.
27
- 7. **Keep maps useful.** Each writable home's MAP.md may include a Cheatsheet of rules that apply in every window; keep it short, about 5 lines. The rest stays the note index: durable notes' addresses and short gists, for lookup. Preserve standing rules, add promoted notes, and drop entries that no longer hold. Maps follow the same size budget.
28
- 8. **Preserve the record.** Never physically delete a live note; after merging, crumple the absorbed note only if it is writable. The wastebasket is the one exception: physically delete a crumpled note when its home is writable and it has been crumpled and untouched for more than 7 days. With raw frontmatter, judge by `lastAccessed`, falling back to `crumpledAt`. With only `notes_*` tools, judge by `crumpled_at`. If no date is readable, keep the note and report it. Never read a raw note through `notes_read` to get the date: it refreshes `lastAccessed`. A venue that cannot delete files lists the doomed addresses in its report instead of blanking them. Preserve existing metadata and provenance.
23
+ 1. **Leave stable notes alone.** Change a note to incorporate new evidence, fix a verified error, retire a stale claim, merge a genuine duplicate, trim diary content, or split an oversized file, not merely to shorten or rephrase it. No change is a valid outcome.
24
+ 2. **Verify only what the proposed change depends on.** Before correcting, retiring, or promoting a conclusion, check the relevant evidence as needed. Do not revalidate every stable note or turn dream into a source-code audit. An unavailable referent is unverified, not proof that it is dead.
25
+ 3. **Retire what is no longer true.** When evidence shows a durable note is stale, correct it in place; if nothing true remains, crumple it. Remove or fix its MAP line either way. A note's last access is a hint, not evidence: long-unread notes are candidates to check, not to crumple on sight. A read reports the access before itself, so reviewing a note does not make it look fresh.
26
+ 4. **Merge only genuine duplicates.** Merge two notes only when they share a topic and kind (checkpoint, design, log). First carry every fact, condition, and exception unique to the absorbed note into the survivor, then crumple the absorbed note. Otherwise keep both and record any unresolved conflict.
27
+ 5. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper home, move it there, preserving its metadata, and update both homes' maps. Do it, don't propose it. Propose only when the destination home itself is unclear.
28
+ 6. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
29
+ 7. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links.
30
+ 8. **Keep maps useful.** Each writable home's MAP.md may include a Cheatsheet of rules that apply in every window; keep it short, about 5 lines. The rest stays the note index: durable notes' addresses and short gists, for lookup. Preserve standing rules, add promoted notes, and drop entries that no longer hold. Maps follow the same size budget.
31
+
32
+ ## Deleting
33
+
34
+ Never physically delete a live note; crumple it first. Two cases allow deleting a crumpled note:
35
+
36
+ - **Your own session's notes** may be deleted once crumpled.
37
+ - **The wastebasket:** any note within the dream's reach that was crumpled more than 7 days ago may be deleted, whatever its home or session. Judge by its crumpled date; if none is readable, keep it and report it.
38
+
39
+ Where notes cannot be deleted, list the doomed addresses in the report instead of blanking them.
29
40
 
30
41
  ## Report
31
42
 
32
- Give a concise report grouped by home: what you inspected, changed, promoted, deleted, and left unresolved. Mention coverage gaps and partial failures. If no notes changed, say so. Distinguish actual note changes from execution or audit artifacts; do not claim success for an incomplete run.
43
+ Give a concise report grouped by home: what you inspected, changed, retired, promoted, deleted, and left unresolved. Mention coverage gaps and partial failures. If no notes changed, say so. Distinguish actual note changes from execution or audit artifacts; do not claim success for an incomplete run.
33
44
 
34
45
  Put skill ideas and unresolved questions in the final message as proposals for the human, not new skill files.
@@ -10,3 +10,11 @@ Read `../../playbook.md` completely, resolving the path from this skill's direct
10
10
  Dream in this agent's current session. Do not start another agent or model unless the human asks.
11
11
 
12
12
  Work within the supplied readable and writable scope. If the scope or permission to write has not been established, ask rather than inventing it or setting up execution machinery yourself.
13
+
14
+ ## Tools
15
+
16
+ Use `dream_begin`, `dream_forget`, and `dream_end` for the dream lifecycle. If any are missing from the current tool list, search for them before proceeding. If they remain unavailable, report that limitation rather than inventing a replacement backend.
17
+
18
+ - Every dream starts with `dream_begin`, before reading or editing any notes.
19
+ - Use `notes_*` to read and organize notes within the established scope. `dream_forget` permanently deletes a crumpled note when the playbook permits it; never delete a live note.
20
+ - `dream_end` closes the open dream. Close it when finished, and report any partial failures.
@@ -5,7 +5,7 @@ import { mergeNotesoupSettings } from "../../src/settings.js";
5
5
  import { errorMessage } from "../../src/error-message.js";
6
6
 
7
7
  /**
8
- * Read the active compaction reserve, enablement, and notesoup margin settings. This
8
+ * Read the active compaction reserve, enablement, and notesoup budget settings. This
9
9
  * function deliberately has no cache: the budget owner supplies the invocation-scoped
10
10
  * cache so two live notesoup instances cannot share mutable policy state.
11
11
  */
@@ -10,3 +10,11 @@ Read `../../playbook.md` completely, resolving the path from this skill's direct
10
10
  Dream in this agent's current session. Do not start another agent or model unless the human asks.
11
11
 
12
12
  Work within the supplied readable and writable scope. If the scope or permission to write has not been established, ask rather than inventing it or setting up execution machinery yourself.
13
+
14
+ ## Tools
15
+
16
+ Use `dream_begin`, `dream_forget`, and `dream_end` for the dream lifecycle. If any are missing from the current tool list, search for them before proceeding. If they remain unavailable, report that limitation rather than inventing a replacement backend.
17
+
18
+ - Every dream starts with `dream_begin`, before reading or editing any notes.
19
+ - Use `notes_*` to read and organize notes within the established scope. `dream_forget` permanently deletes a crumpled note when the playbook permits it; never delete a live note.
20
+ - `dream_end` closes the open dream. Close it when finished, and report any partial failures.
@@ -5,25 +5,23 @@ import { NOTESOUP_SETTINGS_KEY } from "../settings.js";
5
5
  export type ResolvedThresholds = { reminder: number; reserve: number; warning: number };
6
6
 
7
7
  /**
8
- * Pure derivation of the thresholds from the host's reserve: the reminder fires at reserve
9
- * plus the notesoup margin, the warning steer at reserve plus WARNING_RUNWAY_TOKENS.
10
- * An invalid margin degrades to the default and reports one warning. Automatic
11
- * threshold/overflow handling is represented by reset lifecycle boundary drafts;
12
- * no compaction summary is generated.
8
+ * Derive notesoup thresholds from the host reserve and optional notesoup overrides.
9
+ * Invalid settings fall back independently and report one warning per offending key.
10
+ * No host compaction settings are changed and no compaction summary is generated.
13
11
  */
14
- export function deriveThresholds(reserveTokens: number, margins: Record<string, unknown>): { thresholds: ResolvedThresholds; warnings: string[] } {
12
+ export function deriveThresholds(reserveTokens: number, settings: Record<string, unknown>): { thresholds: ResolvedThresholds; warnings: string[] } {
15
13
  const warnings: string[] = [];
16
- const reminderKey = `${NOTESOUP_SETTINGS_KEY}.reminderMarginTokens`;
17
- let reminderMargin: number;
18
- if (margins.reminderMarginTokens === undefined) reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
19
- else {
20
- const parsed = positiveInteger(margins.reminderMarginTokens);
21
- if (parsed === undefined) {
22
- warnings.push(`🥣 ${reminderKey} must be a positive integer · using the default`);
23
- reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
24
- } else reminderMargin = parsed;
25
- }
26
- return { thresholds: { reminder: reserveTokens + reminderMargin, reserve: reserveTokens, warning: reserveTokens + WARNING_RUNWAY_TOKENS }, warnings };
14
+ const resolve = (key: string, fallback: number): number => {
15
+ if (settings[key] === undefined) return fallback;
16
+ const parsed = positiveInteger(settings[key]);
17
+ if (parsed !== undefined) return parsed;
18
+ warnings.push(`🥣 ${NOTESOUP_SETTINGS_KEY}.${key} must be a positive integer · using the default`);
19
+ return fallback;
20
+ };
21
+ const reserve = resolve("reserveTokens", reserveTokens);
22
+ const reminderMargin = resolve("reminderMarginTokens", DEFAULT_REMINDER_MARGIN_TOKENS);
23
+ const warningRunway = resolve("warningRunwayTokens", WARNING_RUNWAY_TOKENS);
24
+ return { thresholds: { reminder: reserve + reminderMargin, reserve, warning: reserve + warningRunway }, warnings };
27
25
  }
28
26
 
29
27
  /** Room before the hard-reserve wipe; unknown usage stays unknown. */
@@ -33,7 +33,8 @@ export type EditOptions = { origin?: Origin; crumpled?: boolean; replaceAll?: bo
33
33
  */
34
34
  export type NotesQuery = { glob?: string | null; crumpled?: boolean };
35
35
  /** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
36
- export type NoteReadResult = { meta: NoteMeta; body: string; resolvedScope: Scope };
36
+ /** `accessedBefore` is the last access before this read, so a read never hides how long a note sat unread. */
37
+ export type NoteReadResult = { meta: NoteMeta; body: string; resolvedScope: Scope; accessedBefore: number };
37
38
  export type NoteWriteResult = { meta: NoteMeta; outcome: "created" | "overwrote" | "uncrumpled" };
38
39
  export type NoteChange =
39
40
  | { kind: "none"; before: ""; after: "" }
@@ -328,11 +329,11 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
328
329
  const now = Date.now();
329
330
  const parsed = parseNote(raw, now);
330
331
  // Named homes, and every read during a dream, leave no access stamp.
331
- if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined)) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
332
+ if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined)) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope, accessedBefore: parsed.meta.lastAccessed };
332
333
  // A read records its own access, exactly as a write records an edit.
333
334
  const meta: NoteMeta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
334
335
  await atomicWrite(path, serializeNote(meta, parsed.body));
335
- return { meta, body: parsed.body, resolvedScope: scope };
336
+ return { meta, body: parsed.body, resolvedScope: scope, accessedBefore: parsed.meta.lastAccessed };
336
337
  });
337
338
  }
338
339
 
@@ -42,6 +42,7 @@ export const NoteMetadataSchema = Type.Object({
42
42
  origin: Type.Union([...ORIGIN_VALUES]),
43
43
  created_at: Type.String(),
44
44
  updated_at: Type.String(),
45
+ last_accessed: Type.String(),
45
46
  crumpled_at: Type.Optional(Type.String()),
46
47
  project: Type.Optional(Type.String()),
47
48
  extra: Type.Record(Type.String(), Type.Unknown()),
@@ -73,6 +74,7 @@ function noteMetadata(meta: NoteMeta): NoteMetadata {
73
74
  origin: meta.origin,
74
75
  created_at: localIso(meta.createdAt),
75
76
  updated_at: localIso(meta.updatedAt),
77
+ last_accessed: localIso(meta.lastAccessed),
76
78
  ...(typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {}),
77
79
  ...(typeof meta.project === "string" ? { project: meta.project } : {}),
78
80
  extra,
@@ -84,6 +86,7 @@ function renderMetadata(metadata: NoteMetadata): string {
84
86
  `origin ${metadata.origin}`,
85
87
  `created ${metadata.created_at}`,
86
88
  `updated ${metadata.updated_at}`,
89
+ `accessed ${metadata.last_accessed}`,
87
90
  ...(metadata.crumpled_at === undefined ? [] : [`crumpled ${metadata.crumpled_at}`]),
88
91
  ...(metadata.project === undefined ? [] : [`project ${metadata.project}`]),
89
92
  ];
@@ -110,6 +113,7 @@ const ListedFileSchema = Type.Object({
110
113
  project_key: Type.Optional(Type.String()),
111
114
  ...ProjectReceiptSchema,
112
115
  updated_at: Type.String(),
116
+ last_accessed: Type.String(),
113
117
  crumpled_at: Type.Optional(Type.String()),
114
118
  }, { additionalProperties: false });
115
119
 
@@ -197,7 +201,7 @@ export function snapshot<T extends { address: string }>(
197
201
  }
198
202
 
199
203
  export function listedFile(row: Pick<NoteRow, "address" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
200
- return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
204
+ return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), last_accessed: localIso(row.meta.lastAccessed), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
201
205
  }
202
206
 
203
207
  export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
@@ -291,7 +295,8 @@ export const notesRead = {
291
295
  if (!note) return failure("not_found", `No note at ${resolved.address}.`);
292
296
  const totalChars = Array.from(note.body).length;
293
297
  if (params.offset_chars !== undefined && params.offset_chars > totalChars) return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
294
- const metadata = noteMetadata(note.meta);
298
+ // Report the access before this one: the read itself must not make a long-unread note look fresh.
299
+ const metadata = noteMetadata({ ...note.meta, lastAccessed: note.accessedBefore });
295
300
  return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
296
301
  } catch (error) { return failureOf(error); }
297
302
  },
@@ -303,7 +308,7 @@ export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FI
303
308
  export function renderListData(data: NotesListData): string {
304
309
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
305
310
  for (const file of data.files) {
306
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
311
+ lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | accessed ${file.last_accessed}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
307
312
  }
308
313
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
309
314
  for (const home of data.homes_unavailable) lines.push(`${home} could not be read`);