@hyperwindmill/caretaker-cli 0.22.0 → 0.24.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 (61) hide show
  1. package/dist/cli/web/scheduler/locks.d.ts +3 -3
  2. package/dist/cli/web/scheduler/memory_extract.d.ts +55 -0
  3. package/dist/cli/web/scheduler/memory_extract.d.ts.map +1 -0
  4. package/dist/cli/web/scheduler/memory_extract.js +112 -0
  5. package/dist/cli/web/scheduler/memory_sweep.d.ts +68 -0
  6. package/dist/cli/web/scheduler/memory_sweep.d.ts.map +1 -0
  7. package/dist/cli/web/scheduler/memory_sweep.js +329 -0
  8. package/dist/cli/web/scheduler/task_review.d.ts +3 -0
  9. package/dist/cli/web/scheduler/task_review.d.ts.map +1 -1
  10. package/dist/cli/web/scheduler/task_review.js +1 -0
  11. package/dist/cli/web/scheduler/task_roles.js +1 -1
  12. package/dist/cli/web/scheduler/task_strategy.d.ts.map +1 -1
  13. package/dist/cli/web/scheduler/task_strategy.js +8 -4
  14. package/dist/cli/web/scheduler.d.ts.map +1 -1
  15. package/dist/cli/web/scheduler.js +5 -0
  16. package/dist/cli/web/server.d.ts.map +1 -1
  17. package/dist/cli/web/server.js +67 -27
  18. package/dist/harness/claude_code_runner.d.ts.map +1 -1
  19. package/dist/harness/claude_code_runner.js +5 -0
  20. package/dist/harness/loop.d.ts +9 -0
  21. package/dist/harness/loop.d.ts.map +1 -1
  22. package/dist/harness/loop.js +10 -0
  23. package/dist/harness/memory_recall.d.ts +23 -0
  24. package/dist/harness/memory_recall.d.ts.map +1 -0
  25. package/dist/harness/memory_recall.js +70 -0
  26. package/dist/harness/tools/builtin/index.d.ts +2 -1
  27. package/dist/harness/tools/builtin/index.d.ts.map +1 -1
  28. package/dist/harness/tools/builtin/index.js +4 -1
  29. package/dist/harness/tools/builtin/memory_tools.d.ts +3 -0
  30. package/dist/harness/tools/builtin/memory_tools.d.ts.map +1 -0
  31. package/dist/harness/tools/builtin/memory_tools.js +60 -0
  32. package/dist/harness/tools/builtin/task_tools.js +37 -37
  33. package/dist/harness/tools/resolve.d.ts.map +1 -1
  34. package/dist/harness/tools/resolve.js +15 -0
  35. package/dist/harness/tools/types.d.ts +6 -0
  36. package/dist/harness/tools/types.d.ts.map +1 -1
  37. package/dist/lib/docker.d.ts +1 -1
  38. package/dist/lib/docker.d.ts.map +1 -1
  39. package/dist/lib/docker.js +2 -2
  40. package/dist/lib/project_resolve.d.ts +5 -0
  41. package/dist/lib/project_resolve.d.ts.map +1 -0
  42. package/dist/lib/project_resolve.js +23 -0
  43. package/dist/lib/project_slug.d.ts +29 -0
  44. package/dist/lib/project_slug.d.ts.map +1 -0
  45. package/dist/lib/project_slug.js +41 -0
  46. package/dist/lib/task_git.d.ts +5 -5
  47. package/dist/lib/task_git.d.ts.map +1 -1
  48. package/dist/lib/task_git.js +8 -6
  49. package/dist/mcp/builtin_server.d.ts +1 -0
  50. package/dist/mcp/builtin_server.d.ts.map +1 -1
  51. package/dist/mcp/builtin_server.js +6 -5
  52. package/dist/store/db.d.ts +78 -7
  53. package/dist/store/db.d.ts.map +1 -1
  54. package/dist/store/db.js +127 -15
  55. package/dist/store/json.d.ts +1 -0
  56. package/dist/store/json.d.ts.map +1 -1
  57. package/dist/store/json.js +6 -1
  58. package/dist/tui/agents.js +5 -2
  59. package/dist/webview/standalone.js +602 -434
  60. package/dist/webview/standalone.js.map +4 -4
  61. package/package.json +3 -3
@@ -11,13 +11,13 @@ export declare const runningTasks: Set<string>;
11
11
  * for the current cycle to burn through its turns — the whole point of Pause
12
12
  * when an agent has gone off the rails.
13
13
  */
14
- export declare const runningTaskControllers: Map<number, AbortController>;
14
+ export declare const runningTaskControllers: Map<string, AbortController>;
15
15
  /** Abort the in-flight run for a task, if one is registered. Returns whether it fired. */
16
- export declare function abortRunningTask(taskId: number): boolean;
16
+ export declare function abortRunningTask(taskId: string): boolean;
17
17
  /**
18
18
  * Project ids with a repository sync (clone/pull) in flight — shared between
19
19
  * the heartbeat's pre-worktree sync and POST /api/projects/:id/sync so the
20
20
  * two can never race a clone. Derived state only; never persisted.
21
21
  */
22
- export declare const syncingProjects: Set<number>;
22
+ export declare const syncingProjects: Set<string>;
23
23
  //# sourceMappingURL=locks.d.ts.map
@@ -0,0 +1,55 @@
1
+ import type { AgentConfig, ProjectConfig } from '../../../types.js';
2
+ export declare const MAX_DEDUP_CHARS = 4000;
3
+ export declare const MAX_MEMORIES_PER_CALL = 5;
4
+ export declare const MAX_MEMORY_TITLE_CHARS = 200;
5
+ export declare const MAX_MEMORY_BODY_CHARS = 2000;
6
+ export declare const MAX_MEMORY_KEYWORDS = 10;
7
+ /** One validated memory candidate out of the model. `level` is the model's
8
+ * only scope verb — the host maps it to a concrete projectId. */
9
+ export interface ExtractedMemory {
10
+ level: 'project' | 'global';
11
+ kind: 'fact' | 'episode';
12
+ importance: 'low' | 'normal' | 'high';
13
+ title: string;
14
+ body: string;
15
+ keywords: string[];
16
+ }
17
+ export interface CombinedResult {
18
+ summary: string;
19
+ memories: ExtractedMemory[];
20
+ }
21
+ /** Everything the combined call needs; assembled by the sweep per chunk. */
22
+ export interface SummarizeContext {
23
+ prevSummary: string;
24
+ chunkText: string;
25
+ /** Preformatted "existing memories" lines (formatDedupBlock), '' when none. */
26
+ dedupBlock: string;
27
+ /** Whether a project is resolved for this session — gates the level choice. */
28
+ hasProject: boolean;
29
+ }
30
+ export declare function buildCombinedPrompt(ctx: SummarizeContext): string;
31
+ /** Outermost-braces JSON extraction (also strips fences/prose for free).
32
+ * null = failed chunk: the caller leaves the cursor, next sweep retries.
33
+ * Deliberately NO raw-text-as-summary fallback — it would poison the digest. */
34
+ export declare function parseCombinedResponse(text: string): {
35
+ summary: string;
36
+ memories: unknown;
37
+ } | null;
38
+ /** Host-side gate on model output: drop entries without title/body, coerce
39
+ * invalid enums to fact/normal, degrade project→global when no project is
40
+ * in scope, cap count and field sizes. Extraction is best-effort — a bad
41
+ * entry is dropped, never a failed chunk. */
42
+ export declare function validateMemories(raw: unknown, hasProject: boolean): ExtractedMemory[];
43
+ /** One line per existing memory (newest first — caller sorts), stopping
44
+ * before MAX_DEDUP_CHARS. Titles + keywords only, never bodies. */
45
+ export declare function formatDedupBlock(entries: Array<{
46
+ title: string;
47
+ keywords: string[];
48
+ }>): string;
49
+ /** Host-side project resolution (scope ids are never chosen by a model):
50
+ * the session agent's workingDir prefix-matched, path-aware, against the
51
+ * configured projects' workingDir. Longest match wins (nested projects).
52
+ * '' = no project in scope → global-only extraction.
53
+ * Delegates to lib/project_resolve.ts — shared with the read path. */
54
+ export declare function resolveProjectId(sessionAgentId: string, agents: AgentConfig[], projects: ProjectConfig[]): string;
55
+ //# sourceMappingURL=memory_extract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory_extract.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/memory_extract.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEpE,eAAO,MAAM,eAAe,OAAO,CAAC;AACpC,eAAO,MAAM,qBAAqB,IAAI,CAAC;AACvC,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAC1C,eAAO,MAAM,qBAAqB,OAAO,CAAC;AAC1C,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAEtC;kEACkE;AAClE,MAAM,WAAW,eAAe;IAC9B,KAAK,EAAE,SAAS,GAAG,QAAQ,CAAC;IAC5B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,UAAU,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IACtC,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,eAAe,EAAE,CAAC;CAC7B;AAED,4EAA4E;AAC5E,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,+EAA+E;IAC/E,UAAU,EAAE,MAAM,CAAC;IACnB,+EAA+E;IAC/E,UAAU,EAAE,OAAO,CAAC;CACrB;AAMD,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,gBAAgB,GAAG,MAAM,CAwBjE;AAED;;iFAEiF;AACjF,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CAAE,GAAG,IAAI,CAYjG;AAED;;;8CAG8C;AAC9C,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,GAAG,eAAe,EAAE,CAuBrF;AAED;oEACoE;AACpE,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,KAAK,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,GAAG,MAAM,CAU9F;AAED;;;;uEAIuE;AACvE,wBAAgB,gBAAgB,CAC9B,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,WAAW,EAAE,EACrB,QAAQ,EAAE,aAAa,EAAE,GACxB,MAAM,CAGR"}
@@ -0,0 +1,112 @@
1
+ // Pure helpers for the sweep's combined summarize+extract call: prompt
2
+ // assembly, defensive JSON parsing, entry validation, dedup-block formatting,
3
+ // and host-side project resolution. No harness or store imports (types only)
4
+ // so everything here is unit-testable without CARETAKER_HOME.
5
+ // See docs/superpowers/specs/2026-08-24-memory-daemon-step2-extraction-design.md
6
+ import { resolveProjectIdForDir } from '../../../lib/project_resolve.js';
7
+ export const MAX_DEDUP_CHARS = 4000;
8
+ export const MAX_MEMORIES_PER_CALL = 5;
9
+ export const MAX_MEMORY_TITLE_CHARS = 200;
10
+ export const MAX_MEMORY_BODY_CHARS = 2000;
11
+ export const MAX_MEMORY_KEYWORDS = 10;
12
+ const LEVEL_PROJECT = '"level": "project" for facts about this specific project, "global" for facts about the user or their machine/environment that hold everywhere.';
13
+ const LEVEL_GLOBAL_ONLY = '"level": always "global" (no project is in scope).';
14
+ export function buildCombinedPrompt(ctx) {
15
+ return [
16
+ 'You maintain a rolling summary of a conversation between a user and an AI agent, and you extract durable memories from it.',
17
+ '',
18
+ 'Reply with ONLY a JSON object, no code fences, in this exact shape:',
19
+ '{"summary": "<updated rolling summary>", "memories": [{"level": "...", "kind": "...", "importance": "...", "title": "...", "body": "...", "keywords": ["..."]}]}',
20
+ '',
21
+ 'SUMMARY: integrate the NEW MESSAGES into the PREVIOUS SUMMARY and rewrite it as one standalone plain-text summary, at most 300 words. Keep durable facts, decisions, preferences, constraints, and open threads; drop pleasantries and dead ends.',
22
+ '',
23
+ `MEMORIES: at most ${MAX_MEMORIES_PER_CALL} facts worth remembering beyond this conversation, using the summary as context. Only NEW information — never re-emit anything under EXISTING MEMORIES. Most chunks contain nothing durable: an empty array is the normal answer. Fields:`,
24
+ `- ${ctx.hasProject ? LEVEL_PROJECT : LEVEL_GLOBAL_ONLY}`,
25
+ '- "kind": "fact" (timeless knowledge: conventions, preferences, constraints, decisions) or "episode" (a dated event: something that happened).',
26
+ '- "importance": judge it from the TONE of the conversation. "high" only when the user marked it explicitly ("remember this", "never again"), was emphatic or frustrated, or corrected a mistake; "normal" for ordinary facts and decisions; "low" for incidental context.',
27
+ `- "title": short and searchable. "body": the fact itself, self-contained markdown. "keywords": up to ${MAX_MEMORY_KEYWORDS} lowercase search words.`,
28
+ '',
29
+ 'EXISTING MEMORIES (do not re-emit):',
30
+ ctx.dedupBlock || '(none)',
31
+ '',
32
+ 'PREVIOUS SUMMARY:',
33
+ ctx.prevSummary.trim() || '(none)',
34
+ '',
35
+ 'NEW MESSAGES:',
36
+ ctx.chunkText,
37
+ ].join('\n');
38
+ }
39
+ /** Outermost-braces JSON extraction (also strips fences/prose for free).
40
+ * null = failed chunk: the caller leaves the cursor, next sweep retries.
41
+ * Deliberately NO raw-text-as-summary fallback — it would poison the digest. */
42
+ export function parseCombinedResponse(text) {
43
+ const start = text.indexOf('{');
44
+ const end = text.lastIndexOf('}');
45
+ if (start === -1 || end <= start)
46
+ return null;
47
+ let obj;
48
+ try {
49
+ obj = JSON.parse(text.slice(start, end + 1));
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ if (typeof obj?.summary !== 'string' || !obj.summary.trim())
55
+ return null;
56
+ return { summary: obj.summary.trim(), memories: obj.memories };
57
+ }
58
+ /** Host-side gate on model output: drop entries without title/body, coerce
59
+ * invalid enums to fact/normal, degrade project→global when no project is
60
+ * in scope, cap count and field sizes. Extraction is best-effort — a bad
61
+ * entry is dropped, never a failed chunk. */
62
+ export function validateMemories(raw, hasProject) {
63
+ if (!Array.isArray(raw))
64
+ return [];
65
+ const out = [];
66
+ for (const e of raw) {
67
+ if (out.length >= MAX_MEMORIES_PER_CALL)
68
+ break;
69
+ if (typeof e?.title !== 'string' || !e.title.trim())
70
+ continue;
71
+ if (typeof e?.body !== 'string' || !e.body.trim())
72
+ continue;
73
+ const keywords = Array.isArray(e.keywords)
74
+ ? e.keywords
75
+ .filter((k) => typeof k === 'string' && k.trim() !== '')
76
+ .map((k) => k.trim())
77
+ .slice(0, MAX_MEMORY_KEYWORDS)
78
+ : [];
79
+ out.push({
80
+ level: e.level === 'project' && hasProject ? 'project' : 'global',
81
+ kind: e.kind === 'episode' ? 'episode' : 'fact',
82
+ importance: e.importance === 'low' || e.importance === 'high' ? e.importance : 'normal',
83
+ title: e.title.trim().slice(0, MAX_MEMORY_TITLE_CHARS),
84
+ body: e.body.trim().slice(0, MAX_MEMORY_BODY_CHARS),
85
+ keywords,
86
+ });
87
+ }
88
+ return out;
89
+ }
90
+ /** One line per existing memory (newest first — caller sorts), stopping
91
+ * before MAX_DEDUP_CHARS. Titles + keywords only, never bodies. */
92
+ export function formatDedupBlock(entries) {
93
+ const lines = [];
94
+ let len = 0;
95
+ for (const e of entries) {
96
+ const line = e.keywords.length ? `- ${e.title} [${e.keywords.join(', ')}]` : `- ${e.title}`;
97
+ if (len + line.length + 1 > MAX_DEDUP_CHARS)
98
+ break;
99
+ lines.push(line);
100
+ len += line.length + 1;
101
+ }
102
+ return lines.join('\n');
103
+ }
104
+ /** Host-side project resolution (scope ids are never chosen by a model):
105
+ * the session agent's workingDir prefix-matched, path-aware, against the
106
+ * configured projects' workingDir. Longest match wins (nested projects).
107
+ * '' = no project in scope → global-only extraction.
108
+ * Delegates to lib/project_resolve.ts — shared with the read path. */
109
+ export function resolveProjectId(sessionAgentId, agents, projects) {
110
+ const dir = agents.find((a) => a.id === sessionAgentId)?.workingDir;
111
+ return dir ? resolveProjectIdForDir(dir, projects) : '';
112
+ }
@@ -0,0 +1,68 @@
1
+ import type { AgentConfig, CaretakerConfig, ProjectConfig, ProviderConfig } from '../../../types.js';
2
+ import type { MessageRecord } from '../../../session/types.js';
3
+ import { type CombinedResult, type SummarizeContext } from './memory_extract.js';
4
+ export declare const DEFAULT_SWEEP_MINUTES = 5;
5
+ export declare const DEFAULT_MIN_NEW_MESSAGES = 4;
6
+ export declare const MAX_CALLS_PER_SWEEP = 10;
7
+ export declare const MAX_CHUNK_CHARS = 20000;
8
+ export declare const MAX_TOOL_RESULT_CHARS = 500;
9
+ export declare const MAX_SUMMARY_CHARS = 4000;
10
+ export declare const SUMMARIZE_TIMEOUT_MS = 120000;
11
+ export interface ResolvedMemoryConfig {
12
+ agent: AgentConfig;
13
+ provider: ProviderConfig;
14
+ sweepMinutes: number;
15
+ minNewMessages: number;
16
+ /** Full lists, for per-session project resolution (the session's agent is
17
+ * a different agent than the memory agent). */
18
+ agents: AgentConfig[];
19
+ projects: ProjectConfig[];
20
+ }
21
+ /** null = subsystem off (unset config, deleted agent, or the agent's provider
22
+ * no longer exists). Any provider type works — the summarize call launches
23
+ * through the harness loop, which already dispatches claude-code. */
24
+ export declare function resolveMemoryConfig(config: CaretakerConfig, agents: AgentConfig[]): ResolvedMemoryConfig | null;
25
+ /** One role-labelled line per message. Thinking parts are dropped (never fed
26
+ * to the memory model); tool results are hard-truncated — they are the
27
+ * largest strings in a session and carry the least durable meaning. */
28
+ export declare function formatMessage(m: MessageRecord): string;
29
+ /** Index of the cursor message; -1 when lastMessageId is '' or not found
30
+ * (both mean: process from the beginning). */
31
+ export declare function locateCursor(messages: MessageRecord[], lastMessageId: string): number;
32
+ /** Consecutive chunks whose formatted text stays under MAX_CHUNK_CHARS. A
33
+ * single oversized message becomes its own chunk with its text truncated —
34
+ * the cursor must always be able to advance past it. */
35
+ export declare function chunkMessages(messages: MessageRecord[]): Array<{
36
+ messages: MessageRecord[];
37
+ text: string;
38
+ }>;
39
+ /** null = failure (network, non-OK, empty or non-JSON response). The caller
40
+ * leaves the cursor where it was; the next sweep retries. Best-effort, the
41
+ * same contract as titling (harness/title.ts). */
42
+ export type SummarizeFn = (ctx: SummarizeContext) => Promise<CombinedResult | null>;
43
+ /** The summarize call launches through the harness loop with the memory
44
+ * agent's identity: every provider type works (claude-code spawns a one-shot
45
+ * `claude -p`, no session persisted), and the agent's systemPrompt shapes
46
+ * the summaries. Always a fresh conversation — never the agent's sessions.
47
+ * `tools: []` plus `dontAsk` (auto-denies every claude-side tool call) keep
48
+ * it pure text generation; workingDir is pinned to CARETAKER_HOME so the
49
+ * project AGENTS.md walk stays out of the prompt. */
50
+ export declare function makeSummarizer(resolved: ResolvedMemoryConfig): SummarizeFn;
51
+ export interface SweepResult {
52
+ scanned: number;
53
+ summarized: number;
54
+ memories: number;
55
+ calls: number;
56
+ budgetSkipped: number;
57
+ }
58
+ /** One full pass over every session on disk. Sessions written by any surface
59
+ * are picked up — the sweep reads shared state, it is not wired per surface.
60
+ * Failures are per-session and best-effort: warn, skip, retry next sweep. */
61
+ export declare function sweepMemory(resolved: ResolvedMemoryConfig, summarize: SummarizeFn): Promise<SweepResult>;
62
+ /** The scheduler-facing entry: called every 15 s tick, does work at most once
63
+ * per sweepMinutes, never overlapping. `summarizeOverride` is test-only. */
64
+ export declare function runMemorySweepTick(now: Date, summarizeOverride?: SummarizeFn): Promise<void>;
65
+ export declare const __memorySweepTesting: {
66
+ reset(): void;
67
+ };
68
+ //# sourceMappingURL=memory_sweep.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory_sweep.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/memory_sweep.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACrG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAa/D,OAAO,EAML,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACtB,MAAM,qBAAqB,CAAC;AAE7B,eAAO,MAAM,qBAAqB,IAAI,CAAC;AACvC,eAAO,MAAM,wBAAwB,IAAI,CAAC;AAC1C,eAAO,MAAM,mBAAmB,KAAK,CAAC;AACtC,eAAO,MAAM,eAAe,QAAS,CAAC;AACtC,eAAO,MAAM,qBAAqB,MAAM,CAAC;AACzC,eAAO,MAAM,iBAAiB,OAAQ,CAAC;AACvC,eAAO,MAAM,oBAAoB,SAAU,CAAC;AAE5C,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,WAAW,CAAC;IACnB,QAAQ,EAAE,cAAc,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB;oDACgD;IAChD,MAAM,EAAE,WAAW,EAAE,CAAC;IACtB,QAAQ,EAAE,aAAa,EAAE,CAAC;CAC3B;AAED;;sEAEsE;AACtE,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,WAAW,EAAE,GACpB,oBAAoB,GAAG,IAAI,CAe7B;AAED;;wEAEwE;AACxE,wBAAgB,aAAa,CAAC,CAAC,EAAE,aAAa,GAAG,MAAM,CAiBtD;AAED;+CAC+C;AAC/C,wBAAgB,YAAY,CAAC,QAAQ,EAAE,aAAa,EAAE,EAAE,aAAa,EAAE,MAAM,GAAG,MAAM,CAGrF;AAED;;yDAEyD;AACzD,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,aAAa,EAAE,GACxB,KAAK,CAAC;IAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAoBpD;AAED;;mDAEmD;AACnD,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;AAEpF;;;;;;sDAMsD;AACtD,wBAAgB,cAAc,CAAC,QAAQ,EAAE,oBAAoB,GAAG,WAAW,CA6B1E;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;CACvB;AAED;;8EAE8E;AAC9E,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,oBAAoB,EAC9B,SAAS,EAAE,WAAW,GACrB,OAAO,CAAC,WAAW,CAAC,CAqJtB;AAMD;6EAC6E;AAC7E,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,IAAI,EACT,iBAAiB,CAAC,EAAE,WAAW,GAC9B,OAAO,CAAC,IAAI,CAAC,CA8Bf;AAED,eAAO,MAAM,oBAAoB;aACtB,IAAI;CAKd,CAAC"}
@@ -0,0 +1,329 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readdir, stat } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { sessionsRoot, readSession, dataDir } from '../../../session/store.js';
5
+ import { loadConfig, loadAgents } from '../../../store/json.js';
6
+ import { run } from '../../../harness/loop.js';
7
+ import { deleteSessionDigest, listMemories, listSessionDigests, saveMemory, saveSessionDigest, } from '../../../store/db.js';
8
+ import { buildCombinedPrompt, formatDedupBlock, parseCombinedResponse, resolveProjectId, validateMemories, } from './memory_extract.js';
9
+ export const DEFAULT_SWEEP_MINUTES = 5;
10
+ export const DEFAULT_MIN_NEW_MESSAGES = 4;
11
+ export const MAX_CALLS_PER_SWEEP = 10;
12
+ export const MAX_CHUNK_CHARS = 20_000;
13
+ export const MAX_TOOL_RESULT_CHARS = 500;
14
+ export const MAX_SUMMARY_CHARS = 4_000;
15
+ export const SUMMARIZE_TIMEOUT_MS = 120_000;
16
+ /** null = subsystem off (unset config, deleted agent, or the agent's provider
17
+ * no longer exists). Any provider type works — the summarize call launches
18
+ * through the harness loop, which already dispatches claude-code. */
19
+ export function resolveMemoryConfig(config, agents) {
20
+ const m = config.memory;
21
+ if (!m?.agentId)
22
+ return null;
23
+ const agent = agents.find((a) => a.id === m.agentId);
24
+ if (!agent)
25
+ return null;
26
+ const provider = (config.providers || []).find((p) => p.name === agent.provider);
27
+ if (!provider)
28
+ return null;
29
+ return {
30
+ agent,
31
+ provider,
32
+ sweepMinutes: m.sweepMinutes ?? DEFAULT_SWEEP_MINUTES,
33
+ minNewMessages: m.minNewMessages ?? DEFAULT_MIN_NEW_MESSAGES,
34
+ agents,
35
+ projects: config.projects ?? [],
36
+ };
37
+ }
38
+ /** One role-labelled line per message. Thinking parts are dropped (never fed
39
+ * to the memory model); tool results are hard-truncated — they are the
40
+ * largest strings in a session and carry the least durable meaning. */
41
+ export function formatMessage(m) {
42
+ if (m.role === 'tool') {
43
+ const body = m.content.length > MAX_TOOL_RESULT_CHARS
44
+ ? m.content.slice(0, MAX_TOOL_RESULT_CHARS) + '…'
45
+ : m.content;
46
+ return `[tool result] ${body}`;
47
+ }
48
+ if (m.role === 'assistant' && m.parts?.length) {
49
+ const parts = [];
50
+ for (const p of m.parts) {
51
+ if (p.type === 'text' && p.text.trim())
52
+ parts.push(p.text);
53
+ else if (p.type === 'tool_use')
54
+ parts.push(`[calls tool: ${p.name}]`);
55
+ }
56
+ return `assistant: ${parts.join('\n')}`;
57
+ }
58
+ return `${m.role}: ${m.content}`;
59
+ }
60
+ /** Index of the cursor message; -1 when lastMessageId is '' or not found
61
+ * (both mean: process from the beginning). */
62
+ export function locateCursor(messages, lastMessageId) {
63
+ if (!lastMessageId)
64
+ return -1;
65
+ return messages.findIndex((m) => m.id === lastMessageId);
66
+ }
67
+ /** Consecutive chunks whose formatted text stays under MAX_CHUNK_CHARS. A
68
+ * single oversized message becomes its own chunk with its text truncated —
69
+ * the cursor must always be able to advance past it. */
70
+ export function chunkMessages(messages) {
71
+ const chunks = [];
72
+ let cur = [];
73
+ let curTexts = [];
74
+ let curLen = 0;
75
+ for (const m of messages) {
76
+ let t = formatMessage(m);
77
+ if (t.length > MAX_CHUNK_CHARS)
78
+ t = t.slice(0, MAX_CHUNK_CHARS) + '…';
79
+ if (curLen + t.length > MAX_CHUNK_CHARS && cur.length > 0) {
80
+ chunks.push({ messages: cur, text: curTexts.join('\n') });
81
+ cur = [];
82
+ curTexts = [];
83
+ curLen = 0;
84
+ }
85
+ cur.push(m);
86
+ curTexts.push(t);
87
+ curLen += t.length + 1;
88
+ }
89
+ if (cur.length > 0)
90
+ chunks.push({ messages: cur, text: curTexts.join('\n') });
91
+ return chunks;
92
+ }
93
+ /** The summarize call launches through the harness loop with the memory
94
+ * agent's identity: every provider type works (claude-code spawns a one-shot
95
+ * `claude -p`, no session persisted), and the agent's systemPrompt shapes
96
+ * the summaries. Always a fresh conversation — never the agent's sessions.
97
+ * `tools: []` plus `dontAsk` (auto-denies every claude-side tool call) keep
98
+ * it pure text generation; workingDir is pinned to CARETAKER_HOME so the
99
+ * project AGENTS.md walk stays out of the prompt. */
100
+ export function makeSummarizer(resolved) {
101
+ return async (ctx) => {
102
+ const ac = new AbortController();
103
+ const timer = setTimeout(() => ac.abort(), SUMMARIZE_TIMEOUT_MS);
104
+ try {
105
+ const result = await run({
106
+ agent: resolved.agent,
107
+ provider: resolved.provider,
108
+ tools: [],
109
+ prompt: buildCombinedPrompt(ctx),
110
+ signal: ac.signal,
111
+ workingDir: dataDir(),
112
+ claudeCode: { permissionMode: 'dontAsk' },
113
+ skipMemoryRecall: true,
114
+ });
115
+ if (result.stop !== 'done')
116
+ return null;
117
+ const parsed = parseCombinedResponse(result.text);
118
+ if (!parsed)
119
+ return null;
120
+ const summary = parsed.summary.length > MAX_SUMMARY_CHARS
121
+ ? parsed.summary.slice(0, MAX_SUMMARY_CHARS) + '…'
122
+ : parsed.summary;
123
+ return { summary, memories: validateMemories(parsed.memories, ctx.hasProject) };
124
+ }
125
+ catch {
126
+ return null;
127
+ }
128
+ finally {
129
+ clearTimeout(timer);
130
+ }
131
+ };
132
+ }
133
+ /** One full pass over every session on disk. Sessions written by any surface
134
+ * are picked up — the sweep reads shared state, it is not wired per surface.
135
+ * Failures are per-session and best-effort: warn, skip, retry next sweep. */
136
+ export async function sweepMemory(resolved, summarize) {
137
+ const result = { scanned: 0, summarized: 0, memories: 0, calls: 0, budgetSkipped: 0 };
138
+ const root = sessionsRoot();
139
+ let agentIds = [];
140
+ try {
141
+ agentIds = await readdir(root);
142
+ }
143
+ catch {
144
+ return result; // no sessions dir yet — nothing to do
145
+ }
146
+ const digests = new Map((await listSessionDigests()).map((d) => [d.id, d]));
147
+ const seen = new Set();
148
+ for (const agentId of agentIds) {
149
+ let files = [];
150
+ try {
151
+ files = (await readdir(join(root, agentId))).filter((f) => f.endsWith('.jsonl'));
152
+ }
153
+ catch {
154
+ continue; // stray non-directory entry
155
+ }
156
+ for (const file of files) {
157
+ const sessionId = file.slice(0, -'.jsonl'.length);
158
+ seen.add(sessionId);
159
+ const digest = digests.get(sessionId) ?? null;
160
+ const path = join(root, agentId, file);
161
+ // The whole per-session body is guarded: a digest save that throws (a
162
+ // hand-copied file whose name fails safeId, a store write error) must
163
+ // cost only that session this sweep — never the sessions after it.
164
+ try {
165
+ // mtime gate: scannedAt is only ever written when the digest was fully
166
+ // caught up (see invariant below), so mtime < scannedAt ⇒ nothing new.
167
+ try {
168
+ const st = await stat(path);
169
+ if (digest && st.mtime.getTime() < new Date(digest.scannedAt).getTime())
170
+ continue;
171
+ }
172
+ catch {
173
+ continue; // vanished between readdir and stat; cleanup pass handles the digest
174
+ }
175
+ // Captured BEFORE the read: an append racing the read keeps
176
+ // mtime ≥ scannedAt, so the session is re-read next sweep.
177
+ const scannedAt = new Date().toISOString();
178
+ let session;
179
+ try {
180
+ session = await readSession(agentId, sessionId);
181
+ }
182
+ catch (err) {
183
+ console.warn(`[memory] failed to read session ${sessionId}:`, err);
184
+ continue;
185
+ }
186
+ result.scanned++;
187
+ let record = digest ?? {
188
+ id: sessionId,
189
+ agentId,
190
+ lastMessageId: '',
191
+ messageCount: 0,
192
+ summary: '',
193
+ model: '',
194
+ scannedAt: '',
195
+ updatedAt: '',
196
+ };
197
+ const idx = locateCursor(session.messages, record.lastMessageId);
198
+ if (record.lastMessageId && idx === -1) {
199
+ // Cursor lost (rewritten/truncated file): restart from message zero.
200
+ record = { ...record, lastMessageId: '', messageCount: 0, summary: '', model: '' };
201
+ }
202
+ const fresh = session.messages.slice(idx + 1);
203
+ if (fresh.length < resolved.minNewMessages) {
204
+ // Debounce: arm the mtime gate and wait for the next append.
205
+ await saveSessionDigest({ ...record, agentId, scannedAt });
206
+ continue;
207
+ }
208
+ // Scope + dedup context, once per session. `dedup` is mutated as new
209
+ // memories are saved so the NEXT chunk of this session sees them too;
210
+ // across sessions the fresh listMemories() covers it.
211
+ const projectId = resolveProjectId(agentId, resolved.agents, resolved.projects);
212
+ const dedup = (await listMemories())
213
+ .filter((m) => m.projectId === '' || m.projectId === projectId)
214
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
215
+ // INVARIANT: per-chunk saves keep the OLD scannedAt. The new one is
216
+ // only persisted when every chunk succeeded — a budget stop or model
217
+ // failure must leave the session mtime-gate-open for the next sweep.
218
+ let caughtUp = true;
219
+ for (const chunk of chunkMessages(fresh)) {
220
+ if (result.calls >= MAX_CALLS_PER_SWEEP) {
221
+ result.budgetSkipped++;
222
+ caughtUp = false;
223
+ break;
224
+ }
225
+ result.calls++;
226
+ const res = await summarize({
227
+ prevSummary: record.summary,
228
+ chunkText: chunk.text,
229
+ dedupBlock: formatDedupBlock(dedup),
230
+ hasProject: projectId !== '',
231
+ });
232
+ if (res === null) {
233
+ caughtUp = false;
234
+ break; // cursor stays; next sweep retries
235
+ }
236
+ // Memories BEFORE the digest record: a crash between the two
237
+ // re-extracts this chunk next sweep, but the titles just saved are
238
+ // then in the dedup block, so the model omits them — duplicates
239
+ // with a dedup guard beat silent loss.
240
+ for (const em of res.memories) {
241
+ const memory = {
242
+ id: randomUUID(),
243
+ projectId: em.level === 'project' && projectId ? projectId : '',
244
+ kind: em.kind,
245
+ importance: em.importance,
246
+ title: em.title,
247
+ body: em.body,
248
+ keywords: em.keywords,
249
+ sourceSessionId: sessionId,
250
+ sourceAgentId: agentId,
251
+ model: resolved.agent.model,
252
+ createdAt: new Date().toISOString(),
253
+ };
254
+ await saveMemory(memory);
255
+ result.memories++;
256
+ dedup.unshift({ title: memory.title, keywords: memory.keywords });
257
+ }
258
+ const last = chunk.messages[chunk.messages.length - 1];
259
+ record = {
260
+ ...record,
261
+ agentId,
262
+ lastMessageId: last.id,
263
+ messageCount: record.messageCount + chunk.messages.length,
264
+ summary: res.summary,
265
+ model: resolved.agent.model,
266
+ };
267
+ await saveSessionDigest(record); // crash loses at most one chunk
268
+ result.summarized++;
269
+ }
270
+ if (caughtUp) {
271
+ await saveSessionDigest({ ...record, agentId, scannedAt });
272
+ }
273
+ }
274
+ catch (err) {
275
+ console.warn(`[memory] sweep of session ${sessionId} failed:`, err);
276
+ }
277
+ }
278
+ }
279
+ // Regenerable-cache hygiene: drop digests whose session no longer exists.
280
+ for (const [id] of digests) {
281
+ if (!seen.has(id))
282
+ await deleteSessionDigest(id);
283
+ }
284
+ return result;
285
+ }
286
+ let lastSweepStartedAt = 0;
287
+ let sweepInFlight = false;
288
+ let warnedUnusable = false;
289
+ /** The scheduler-facing entry: called every 15 s tick, does work at most once
290
+ * per sweepMinutes, never overlapping. `summarizeOverride` is test-only. */
291
+ export async function runMemorySweepTick(now, summarizeOverride) {
292
+ const config = await loadConfig();
293
+ if (!config.memory)
294
+ return; // subsystem off — zero cost
295
+ const resolved = resolveMemoryConfig(config, await loadAgents());
296
+ if (!resolved) {
297
+ if (!warnedUnusable) {
298
+ warnedUnusable = true;
299
+ console.warn("[memory] memory config is set but unusable (deleted agent, or the agent's provider no longer exists) — sweeps disabled until fixed");
300
+ }
301
+ return;
302
+ }
303
+ warnedUnusable = false;
304
+ if (sweepInFlight)
305
+ return;
306
+ if (now.getTime() - lastSweepStartedAt < resolved.sweepMinutes * 60_000)
307
+ return;
308
+ lastSweepStartedAt = now.getTime();
309
+ sweepInFlight = true;
310
+ try {
311
+ const res = await sweepMemory(resolved, summarizeOverride ?? makeSummarizer(resolved));
312
+ if (res.calls > 0 || res.budgetSkipped > 0) {
313
+ console.log(`[memory] sweep: scanned=${res.scanned} calls=${res.calls} summarized=${res.summarized} memories=${res.memories} budget-skipped=${res.budgetSkipped}`);
314
+ }
315
+ }
316
+ catch (err) {
317
+ console.error('[memory] sweep failed:', err);
318
+ }
319
+ finally {
320
+ sweepInFlight = false;
321
+ }
322
+ }
323
+ export const __memorySweepTesting = {
324
+ reset() {
325
+ lastSweepStartedAt = 0;
326
+ sweepInFlight = false;
327
+ warnedUnusable = false;
328
+ },
329
+ };
@@ -10,6 +10,9 @@ export declare function runDoneReview(opts: {
10
10
  objective: string;
11
11
  branch: string;
12
12
  workingDir: string;
13
+ /** The task's project — explicit memory-recall scope (the worktree the
14
+ * review runs in never prefix-matches the project's workingDir). */
15
+ projectId?: string;
13
16
  round: number;
14
17
  signal?: AbortSignal;
15
18
  /** Wall-clock budget (seconds) for the review run. Defaults to the claude-code default. */
@@ -1 +1 @@
1
- {"version":3,"file":"task_review.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/task_review.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iCAAiC,CAAC;AAI5D,eAAO,MAAM,iBAAiB,IAAI,CAAC;AAEnC,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CA2BrF;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMnE;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE;IACxC,KAAK,EAAE,WAAW,CAAC;IACnB,QAAQ,EAAE,cAAc,CAAC;IACzB,KAAK,EAAE,IAAI,EAAE,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,2FAA2F;IAC3F,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;wDAEoD;IACpD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,2EAA2E;IAC3E,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,GAAG,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAqDzD"}
1
+ {"version":3,"file":"task_review.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/task_review.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iCAAiC,CAAC;AAI5D,eAAO,MAAM,iBAAiB,IAAI,CAAC;AAEnC,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CA2BrF;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMnE;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE;IACxC,KAAK,EAAE,WAAW,CAAC;IACnB,QAAQ,EAAE,cAAc,CAAC;IACzB,KAAK,EAAE,IAAI,EAAE,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB;yEACqE;IACrE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,2FAA2F;IAC3F,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;wDAEoD;IACpD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,2EAA2E;IAC3E,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,GAAG,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAsDzD"}
@@ -78,6 +78,7 @@ export async function runDoneReview(opts) {
78
78
  prompt,
79
79
  history: [],
80
80
  workingDir: opts.workingDir,
81
+ memoryProjectId: opts.projectId,
81
82
  signal,
82
83
  dockerContainer: opts.dockerContainer,
83
84
  ...(claudeCode ? { claudeCode } : {}),
@@ -51,7 +51,7 @@ export function resolveSddEnabled(task, project) {
51
51
  export async function activationStatus(task, project) {
52
52
  if (!resolvePlanningEnabled(task, project))
53
53
  return 'active';
54
- const messages = (await runQuery(`SELECT * FROM task_messages WHERE taskId = ${task.id}`));
54
+ const messages = (await runQuery(`SELECT * FROM task_messages WHERE taskId = '${task.id}'`));
55
55
  return messages.some((m) => m.messageType === 'plan') ? 'active' : 'planning';
56
56
  }
57
57
  /** Builtins the planner must not have: everything that mutates the workspace.
@@ -1 +1 @@
1
- {"version":3,"file":"task_strategy.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/task_strategy.ts"],"names":[],"mappings":"AAyHA,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAodnE"}
1
+ {"version":3,"file":"task_strategy.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/task_strategy.ts"],"names":[],"mappings":"AAyHA,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAudnE"}