diff --git a/CHANGELOG.md b/CHANGELOG.md index 376bb64..7ad707f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,18 @@ follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Changed + +- Context injection now loads the two most recent daily logs instead of + today's and yesterday's by calendar date. Days without a log are skipped, so + the first session after a weekend or time off still sees the last working + days instead of no daily log at all. + +### Added + +- `PI_MEMORY_DAILY_LOGS` sets how many recent daily logs are injected + (default `2`, `0` disables daily-log injection). + ## [0.4.2] — 2026-08-10 ### Added diff --git a/README.md b/README.md index cca8286..1326c02 100644 --- a/README.md +++ b/README.md @@ -117,9 +117,11 @@ If the first search doesn't find what you need, try rephrasing or switching mode Before every agent turn, the following are injected into the system prompt (in priority order): 1. **Open scratchpad items** (up to 2K chars) -2. **Today's daily log** (up to 3K chars, tail) +2. **Most recent daily log** (up to 3K chars, tail): today's, or the last day that has a log 3. **MEMORY.md** (up to 4K chars, middle-truncated) -4. **Yesterday's daily log** (up to 3K chars, tail — lowest priority, trimmed first) +4. **Earlier daily logs** (up to 3K chars each, tail — lowest priority, trimmed first) + +Daily logs are picked by recency, not by calendar day: days without a log (weekends, time off) are skipped, so the first session after a break still sees the last working days. `PI_MEMORY_DAILY_LOGS` sets how many logs are injected (default 2). Total injection is capped at 16K chars. @@ -188,6 +190,7 @@ This ensures in-progress context survives compaction and is visible in the next | Variable | Values | Default | Description | |----------|--------|---------|-------------| | `PI_MEMORY_DIR` | path | `~/.pi/agent/memory` | Override the memory storage directory | +| `PI_MEMORY_DAILY_LOGS` | non-negative integer | `2` | Number of most recent daily logs injected into context. Days without a log are skipped. `0` disables daily-log injection | | `PI_MEMORY_SNAPSHOT` | `stable`, `refresh`, `per-turn` | `stable` | `stable` snapshots once at session start and never re-renders it (deletions append a correction); `refresh` also re-renders on long-term writes and day rollover; `per-turn` rebuilds every turn (legacy behavior) | | `PI_MEMORY_QMD_UPDATE` | `background`, `manual`, `off` | `background` | Controls automatic `qmd update` + `qmd embed` after writes | | `PI_MEMORY_QMD_SEARCH_TIMEOUT_MS` | positive integer (milliseconds) | `60000` | Sets the timeout for explicit `memory_search` qmd queries | diff --git a/index.ts b/index.ts index 2f27901..6ace2db 100644 --- a/index.ts +++ b/index.ts @@ -8,7 +8,7 @@ * Layout (under ~/.pi/agent/memory/): * MEMORY.md — curated long-term memory (decisions, preferences, durable facts) * SCRATCHPAD.md — checklist of things to keep in mind / fix later - * daily/YYYY-MM-DD.md — daily append-only log (today + yesterday loaded at session start) + * daily/YYYY-MM-DD.md — daily append-only log (two most recent logs loaded at session start) * recovery/*.json — durable records for restoring memory_forget deletions * * Tools: @@ -20,7 +20,7 @@ * memory_search — search across all memory files via qmd (keyword, semantic, or deep) * * Context injection: - * - MEMORY.md + SCRATCHPAD.md + today's + yesterday's daily logs injected into every turn + * - MEMORY.md + SCRATCHPAD.md + the most recent daily logs (PI_MEMORY_DAILY_LOGS, default 2) injected into every turn */ import { type ExecFileOptions, execFile } from "node:child_process"; @@ -154,6 +154,13 @@ const CONTEXT_SCRATCHPAD_MAX_CHARS = 2_000; const CONTEXT_SCRATCHPAD_MAX_LINES = 120; const CONTEXT_DAILY_MAX_CHARS = 3_000; const CONTEXT_DAILY_MAX_LINES = 120; +const DEFAULT_DAILY_LOG_COUNT = 2; + +/** How many of the most recent daily logs to inject (`PI_MEMORY_DAILY_LOGS`, 0 disables). */ +export function getDailyLogCount(env: NodeJS.ProcessEnv = process.env): number { + const value = (env.PI_MEMORY_DAILY_LOGS ?? "").trim(); + return /^\d+$/.test(value) ? Number(value) : DEFAULT_DAILY_LOG_COUNT; +} const CONTEXT_SEARCH_MAX_CHARS = 2_500; const CONTEXT_SEARCH_MAX_LINES = 80; const CONTEXT_MAX_CHARS = 16_000; @@ -796,9 +803,49 @@ function readRecoveryRecord(recoveryId: string): { record: RecoveryRecord; fileP // Context builder // --------------------------------------------------------------------------- +/** + * The `count` most recent non-empty daily logs up to today, newest first. + * Days without a log are skipped, so a weekend or a break does not leave the + * context without the last working day. + */ +function recentDailyLogs(count: number): { date: string; content: string }[] { + if (count <= 0) return []; + const today = todayStr(); + let names: string[]; + try { + names = fs.readdirSync(DAILY_DIR); + } catch { + return []; + } + const dates = names + .filter((name) => name.endsWith(".md")) + .map((name) => name.slice(0, -3)) + .filter((date) => isValidDailyDate(date) && date <= today) + .sort() + .reverse(); + const logs: { date: string; content: string }[] = []; + for (const date of dates) { + const content = readFileSafe(dailyPath(date)); + if (content?.trim()) logs.push({ date, content }); + if (logs.length === count) break; + } + return logs; +} + +function formatDailySection(date: string, content: string): string | null { + const label = date === todayStr() ? " (today)" : date === yesterdayStr() ? " (yesterday)" : ""; + return formatContextSection( + `## Daily log: ${date}${label}`, + content, + "end", + CONTEXT_DAILY_MAX_LINES, + CONTEXT_DAILY_MAX_CHARS, + ); +} + export function buildMemoryContext(searchResults?: string): string { ensureDirs(); - // Priority order: scratchpad > today's daily > search results > MEMORY.md > yesterday's daily + // Priority order: scratchpad > latest daily > search results > MEMORY.md > earlier dailies const sections: string[] = []; const scratchpad = readFileSafe(SCRATCHPAD_FILE); @@ -817,18 +864,9 @@ export function buildMemoryContext(searchResults?: string): string { } } - const today = todayStr(); - const yesterday = yesterdayStr(); - - const todayContent = readFileSafe(dailyPath(today)); - if (todayContent?.trim()) { - const section = formatContextSection( - `## Daily log: ${today} (today)`, - todayContent, - "end", - CONTEXT_DAILY_MAX_LINES, - CONTEXT_DAILY_MAX_CHARS, - ); + const [latestDaily, ...earlierDailies] = recentDailyLogs(getDailyLogCount()); + if (latestDaily) { + const section = formatDailySection(latestDaily.date, latestDaily.content); if (section) sections.push(section); } @@ -855,15 +893,8 @@ export function buildMemoryContext(searchResults?: string): string { if (section) sections.push(section); } - const yesterdayContent = readFileSafe(dailyPath(yesterday)); - if (yesterdayContent?.trim()) { - const section = formatContextSection( - `## Daily log: ${yesterday} (yesterday)`, - yesterdayContent, - "end", - CONTEXT_DAILY_MAX_LINES, - CONTEXT_DAILY_MAX_CHARS, - ); + for (const { date, content } of earlierDailies) { + const section = formatDailySection(date, content); if (section) sections.push(section); } @@ -2468,6 +2499,7 @@ export default function (pi: ExtensionAPI) { `- PI_MEMORY_QMD_SEARCH_TIMEOUT_MS: ${getQmdSearchTimeoutMs()}`, `- PI_MEMORY_EMBED_PROBE_TIMEOUT_MS: ${getEmbedProbeTimeoutMs()}`, `- PI_MEMORY_DIR: ${process.env.PI_MEMORY_DIR ? "set" : "default"}`, + `- PI_MEMORY_DAILY_LOGS: ${getDailyLogCount()}`, `- PI_MEMORY_EXIT_SUMMARY: ${isExitSummaryEnabled() ? "enabled" : "disabled"}`, `- PI_MEMORY_EXIT_SUMMARY_MODEL: ${process.env.PI_MEMORY_EXIT_SUMMARY_MODEL?.trim() || "session model"}`, `- PI_MEMORY_EXIT_SUMMARY_REASONING_EFFORT: ${getExitSummaryReasoningEffort() ?? "off"}`, diff --git a/test/unit.test.ts b/test/unit.test.ts index 5d7725b..e63e9ea 100644 --- a/test/unit.test.ts +++ b/test/unit.test.ts @@ -31,6 +31,7 @@ import { ensureDirs, ensureQmdEmbed, forgetBlocks, + getDailyLogCount, getEmbedProbeTimeoutMs, getExitSummaryReasoningEffort, getExitSummaryTimeoutMs, @@ -603,6 +604,77 @@ describe("buildMemoryContext", () => { expect(ctx).toContain("Yesterday's work"); }); + describe("recent daily logs", () => { + const daysAgo = (n: number) => { + const d = new Date(); + d.setDate(d.getDate() - n); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; + }; + const writeDaily = (date: string, content: string) => + fs.writeFileSync(path.join(tmpDir, "daily", `${date}.md`), content, "utf-8"); + let saved: string | undefined; + beforeEach(() => { + saved = process.env.PI_MEMORY_DAILY_LOGS; + delete process.env.PI_MEMORY_DAILY_LOGS; + ensureDirs(); + }); + afterEach(() => { + if (saved === undefined) delete process.env.PI_MEMORY_DAILY_LOGS; + else process.env.PI_MEMORY_DAILY_LOGS = saved; + }); + + test("injects the last two logs across a gap with no log for yesterday", () => { + writeDaily(daysAgo(3), "Friday work"); + writeDaily(daysAgo(4), "Thursday work"); + writeDaily(daysAgo(5), "Wednesday work"); + const ctx = buildMemoryContext(); + expect(ctx).toContain(`## Daily log: ${daysAgo(3)}`); + expect(ctx).toContain("Friday work"); + expect(ctx).toContain("Thursday work"); + expect(ctx).not.toContain("Wednesday work"); + expect(ctx).not.toContain("(yesterday)"); + }); + + test("pairs today with the most recent earlier log", () => { + writeDaily(todayStr(), "Monday work"); + writeDaily(daysAgo(3), "Friday work"); + writeDaily(daysAgo(4), "Thursday work"); + const ctx = buildMemoryContext(); + expect(ctx).toContain(`## Daily log: ${todayStr()} (today)`); + expect(ctx).toContain("Friday work"); + expect(ctx).not.toContain("Thursday work"); + }); + + test("puts older logs after MEMORY.md, newest first", () => { + process.env.PI_MEMORY_DAILY_LOGS = "3"; + writeDaily(daysAgo(1), "Newest"); + writeDaily(daysAgo(2), "Middle"); + writeDaily(daysAgo(6), "Oldest"); + fs.writeFileSync(path.join(tmpDir, "MEMORY.md"), "Long-term fact", "utf-8"); + const ctx = buildMemoryContext(); + const order = ["Newest", "Long-term fact", "Middle", "Oldest"].map((s) => ctx.indexOf(s)); + expect(order.every((i) => i >= 0)).toBe(true); + expect([...order].sort((a, b) => a - b)).toEqual(order); + }); + + test("PI_MEMORY_DAILY_LOGS=0 disables daily injection", () => { + process.env.PI_MEMORY_DAILY_LOGS = "0"; + writeDaily(todayStr(), "Today's work"); + expect(buildMemoryContext()).toBe(""); + }); + + test("skips empty, future-dated, and non-date files", () => { + writeDaily(daysAgo(-1), "Future work"); + writeDaily(daysAgo(1), " \n"); + writeDaily(daysAgo(2), "Real work"); + fs.writeFileSync(path.join(tmpDir, "daily", "notes.md"), "Stray file", "utf-8"); + const ctx = buildMemoryContext(); + expect(ctx).toContain("Real work"); + expect(ctx).not.toContain("Future work"); + expect(ctx).not.toContain("Stray file"); + }); + }); + test("combines all sections with separators", () => { ensureDirs(); fs.writeFileSync(path.join(tmpDir, "MEMORY.md"), "Memory content", "utf-8"); @@ -1254,6 +1326,18 @@ describe("runQmdSearch qmd diagnostics", () => { }); }); +describe("getDailyLogCount", () => { + test("defaults to 2 and accepts non-negative integers", () => { + expect(getDailyLogCount({})).toBe(2); + expect(getDailyLogCount({ PI_MEMORY_DAILY_LOGS: "5" })).toBe(5); + expect(getDailyLogCount({ PI_MEMORY_DAILY_LOGS: " 0 " })).toBe(0); + expect(getDailyLogCount({ PI_MEMORY_DAILY_LOGS: "" })).toBe(2); + expect(getDailyLogCount({ PI_MEMORY_DAILY_LOGS: "-1" })).toBe(2); + expect(getDailyLogCount({ PI_MEMORY_DAILY_LOGS: "1.5" })).toBe(2); + expect(getDailyLogCount({ PI_MEMORY_DAILY_LOGS: "abc" })).toBe(2); + }); +}); + describe("getQmdSearchTimeoutMs", () => { test("accepts positive integer milliseconds and defaults invalid values", () => { expect(getQmdSearchTimeoutMs({ PI_MEMORY_QMD_SEARCH_TIMEOUT_MS: "90000" })).toBe(90_000);