humemory 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/.githooks/post-commit +22 -0
  2. package/AGENTS.md +328 -0
  3. package/CHANGELOG.md +198 -0
  4. package/LICENSE +21 -0
  5. package/README.md +488 -0
  6. package/bin/humemory.js +19 -0
  7. package/dist/agent/claude-hook.d.ts +15 -0
  8. package/dist/agent/claude-hook.js +38 -0
  9. package/dist/agent/commit-closer.d.ts +60 -0
  10. package/dist/agent/commit-closer.js +125 -0
  11. package/dist/agent/learning-extractor.d.ts +10 -0
  12. package/dist/agent/learning-extractor.js +75 -0
  13. package/dist/agent/session-context.d.ts +63 -0
  14. package/dist/agent/session-context.js +216 -0
  15. package/dist/agent/session-parser.d.ts +12 -0
  16. package/dist/agent/session-parser.js +85 -0
  17. package/dist/api/dream-routes.d.ts +7 -0
  18. package/dist/api/dream-routes.js +40 -0
  19. package/dist/api/intentions-routes.d.ts +23 -0
  20. package/dist/api/intentions-routes.js +252 -0
  21. package/dist/api/memory-routes.d.ts +10 -0
  22. package/dist/api/memory-routes.js +277 -0
  23. package/dist/api/scripts-routes.d.ts +13 -0
  24. package/dist/api/scripts-routes.js +129 -0
  25. package/dist/api/server.d.ts +33 -0
  26. package/dist/api/server.js +157 -0
  27. package/dist/cli/index.d.ts +2 -0
  28. package/dist/cli/index.js +798 -0
  29. package/dist/core/clock.d.ts +38 -0
  30. package/dist/core/clock.js +52 -0
  31. package/dist/core/cue-arg.d.ts +19 -0
  32. package/dist/core/cue-arg.js +72 -0
  33. package/dist/core/cues.d.ts +138 -0
  34. package/dist/core/cues.js +372 -0
  35. package/dist/core/decay.d.ts +49 -0
  36. package/dist/core/decay.js +157 -0
  37. package/dist/core/dreamer.d.ts +114 -0
  38. package/dist/core/dreamer.js +427 -0
  39. package/dist/core/embeddings.d.ts +79 -0
  40. package/dist/core/embeddings.js +133 -0
  41. package/dist/core/event-bus.d.ts +71 -0
  42. package/dist/core/event-bus.js +67 -0
  43. package/dist/core/hybrid.d.ts +33 -0
  44. package/dist/core/hybrid.js +63 -0
  45. package/dist/core/llm-generator.d.ts +18 -0
  46. package/dist/core/llm-generator.js +69 -0
  47. package/dist/core/sanitize.d.ts +57 -0
  48. package/dist/core/sanitize.js +87 -0
  49. package/dist/core/scripts.d.ts +55 -0
  50. package/dist/core/scripts.js +96 -0
  51. package/dist/core/search.d.ts +42 -0
  52. package/dist/core/search.js +173 -0
  53. package/dist/core/trust.d.ts +48 -0
  54. package/dist/core/trust.js +57 -0
  55. package/dist/core/types.d.ts +333 -0
  56. package/dist/core/types.js +1 -0
  57. package/dist/core/vector-clusterer.d.ts +53 -0
  58. package/dist/core/vector-clusterer.js +113 -0
  59. package/dist/index.d.ts +28 -0
  60. package/dist/index.js +18 -0
  61. package/dist/mcp/server.d.ts +22 -0
  62. package/dist/mcp/server.js +158 -0
  63. package/dist/store/sqlite.d.ts +240 -0
  64. package/dist/store/sqlite.js +1653 -0
  65. package/docs/TESTING.md +244 -0
  66. package/package.json +95 -0
  67. package/public/app/galaxy-f42190mq.js +10 -0
  68. package/public/app/index-2cf31xxn.css +1 -0
  69. package/public/app/index-epqg22cp.js +1 -0
  70. package/public/app/index-f9h80bzq.js +12 -0
  71. package/public/app/index-gbfwa9vq.js +2 -0
  72. package/public/app/index-kvhc17mz.js +2 -0
  73. package/public/app/index-pbd5t4dj.js +2 -0
  74. package/public/app/index.html +12 -0
  75. package/public/app/promenade-cnzzpm73.js +4111 -0
  76. package/public/app/river-tyawhh8w.js +13 -0
  77. package/public/session.html +659 -0
  78. package/scripts/consolidate.js +46 -0
  79. package/scripts/hook-post-commit.ts +80 -0
  80. package/scripts/hook-session-start.ts +92 -0
  81. package/scripts/hook-session.ts +60 -0
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Closing loops from commits — Phase 5.3.2.
3
+ *
4
+ * The gesture that purges an open loop is the commit. Two paths:
5
+ *
6
+ * 1. **Explicit** — `Closes loop-a1b2c3d4` in the message. The author's
7
+ * intention, unambiguous: close it.
8
+ * 2. **Heuristic** — overlap between the files touched and the loop's text. This
9
+ * **never** closes anything automatically: it suggests. Closing the wrong loop
10
+ * costs more than leaving one open.
11
+ *
12
+ * The logic lives here so it stays testable; `scripts/hook-post-commit.ts` only
13
+ * queries git and prints.
14
+ */
15
+ import { extractLoopIds, matchIntentionByShortId, loopId } from '../core/cues.js';
16
+ /** Suggestion threshold: at least one meaningful shared token. */
17
+ export const SUGGESTION_THRESHOLD = 1;
18
+ /** Maximum suggestions shown — beyond that it is noise. */
19
+ export const MAX_SUGGESTIONS = 3;
20
+ // Words too common to signal anything.
21
+ const STOPWORDS = new Set([
22
+ 'dans', 'pour', 'avec', 'sans', 'cette', 'leur', 'plus', 'mais', 'donc',
23
+ 'index', 'test', 'tests', 'src', 'lib', 'main', 'temp', 'utils', 'util', 'core',
24
+ 'the', 'and', 'for', 'with', 'from', 'that', 'this', 'into',
25
+ ]);
26
+ /** Splits a text into meaningful tokens, without accents or case. */
27
+ export function tokenize(text) {
28
+ return text
29
+ .normalize('NFD')
30
+ .replace(/[̀-ͯ]/g, '')
31
+ .toLowerCase()
32
+ .split(/[^a-z0-9]+/)
33
+ .filter((t) => t.length >= 4 && !STOPWORDS.has(t));
34
+ }
35
+ /** Tokens drawn from a file path: directory segments plus the name without its extension. */
36
+ export function tokenizePath(path) {
37
+ const normalized = path.replace(/\\/g, '/');
38
+ const withoutExt = normalized.replace(/\.[a-z0-9]+$/i, '');
39
+ return [...new Set(tokenize(withoutExt))];
40
+ }
41
+ /**
42
+ * Overlap between a commit's files and a loop's content.
43
+ *
44
+ * Deliberately crude: this score closes nothing, it only ranks suggestions put
45
+ * to a human.
46
+ */
47
+ export function scoreOverlap(intention, files) {
48
+ const contentTokens = new Set(tokenize(intention.content));
49
+ const matched = new Set();
50
+ for (const file of files) {
51
+ for (const token of tokenizePath(file)) {
52
+ if (contentTokens.has(token))
53
+ matched.add(token);
54
+ }
55
+ }
56
+ return [...matched];
57
+ }
58
+ /**
59
+ * Applies a commit to the open loops.
60
+ *
61
+ * Closes the ones named explicitly (and cancels their remaining cues — a cue
62
+ * outliving its loop is a ghost wake-up). For the rest, it only suggests.
63
+ */
64
+ export async function applyCommitToLoops(store, commit, memories) {
65
+ const armed = await store.listIntentions({ status: 'armed', limit: 500 });
66
+ const closed = [];
67
+ const unresolved = [];
68
+ const closedIds = new Set();
69
+ // 1. Explicit markers. Deliberately not bound to the directory: if someone
70
+ // types the id by hand, they know what they are closing.
71
+ for (const shortId of extractLoopIds(commit.message)) {
72
+ const target = matchIntentionByShortId(armed, shortId);
73
+ if (!target) {
74
+ unresolved.push(shortId);
75
+ continue;
76
+ }
77
+ const intention = await store.updateIntentionStatus(target.id, 'closed', {
78
+ closedByCommit: commit.sha,
79
+ });
80
+ for (const cue of await store.listCues({ intentionId: target.id, status: 'armed' })) {
81
+ await store.updateCueStatus(cue.id, 'cancelled');
82
+ }
83
+ // Phase 6.0.1 — `grounded` verification: an explicitly-closed loop vouches
84
+ // for the trace it points to. Only this path counts (Claude R1): the fuzzy
85
+ // file-overlap path below only *suggests* and must never become evidence.
86
+ if (intention.relatedMemoryId && memories) {
87
+ await memories.verify(intention.relatedMemoryId, 'grounded');
88
+ }
89
+ closed.push(intention);
90
+ closedIds.add(target.id);
91
+ }
92
+ // 2. Heuristic, bounded to the current project and never applied on its own.
93
+ const suggestions = armed
94
+ .filter((i) => !closedIds.has(i.id) && i.directory === commit.directory)
95
+ .map((intention) => ({ intention, matched: scoreOverlap(intention, commit.files) }))
96
+ .map((s) => ({ ...s, score: s.matched.length }))
97
+ .filter((s) => s.score >= SUGGESTION_THRESHOLD)
98
+ .sort((a, b) => b.score - a.score)
99
+ .slice(0, MAX_SUGGESTIONS);
100
+ return { closed, suggestions, unresolved };
101
+ }
102
+ /** Renders the report printed after a commit. Empty string when there is nothing to say. */
103
+ export function renderCommitReport(result) {
104
+ const { closed, suggestions, unresolved } = result;
105
+ if (!closed.length && !suggestions.length && !unresolved.length)
106
+ return '';
107
+ const lines = [];
108
+ for (const i of closed) {
109
+ lines.push(`✅ ${loopId(i.id)} closed — ${i.content}`);
110
+ }
111
+ for (const shortId of unresolved) {
112
+ lines.push(`⚠️ loop-${shortId}: no single open loop under that id`);
113
+ }
114
+ if (suggestions.length) {
115
+ lines.push('');
116
+ lines.push('💡 Loops this commit may have touched:');
117
+ for (const { intention, matched } of suggestions) {
118
+ lines.push(` ${loopId(intention.id)} — ${intention.content}`);
119
+ lines.push(` overlaps: ${matched.join(', ')}`);
120
+ }
121
+ lines.push('');
122
+ lines.push(` To close: pnpm cli intent close ${loopId(suggestions[0].intention.id)}`);
123
+ }
124
+ return `${lines.join('\n')}\n`;
125
+ }
@@ -0,0 +1,10 @@
1
+ import type { LLMClient } from '../core/llm-generator.js';
2
+ import type { MemoryType } from '../core/types.js';
3
+ import type { ParsedSession } from './session-parser.js';
4
+ export interface ExtractedLearning {
5
+ content: string;
6
+ memoryType: MemoryType;
7
+ keywords: string[];
8
+ level3Keywords: string;
9
+ }
10
+ export declare function extractLearnings(session: ParsedSession, client: LLMClient, maxLearnings?: number): Promise<ExtractedLearning[]>;
@@ -0,0 +1,75 @@
1
+ const SYSTEM_PROMPT = `You are a system that extracts mnemonic learnings.
2
+ Analyse the session and extract the key learnings worth remembering.
3
+ Write them in the same language as the session itself.
4
+ Answer with a JSON array ONLY — no markdown.`;
5
+ export async function extractLearnings(session, client, maxLearnings = 5) {
6
+ // Truncate to avoid token limits — keep last ~3000 chars which has recent context
7
+ const transcript = session.rawText.slice(-3000);
8
+ const response = await client.messages.create({
9
+ model: 'claude-haiku-4-5-20251001',
10
+ max_tokens: 1024,
11
+ system: [
12
+ {
13
+ type: 'text',
14
+ text: SYSTEM_PROMPT,
15
+ cache_control: { type: 'ephemeral' },
16
+ },
17
+ ],
18
+ messages: [
19
+ {
20
+ role: 'user',
21
+ content: `Projet: ${session.directory}
22
+ Session: ${session.sessionId}
23
+
24
+ Transcript:
25
+ """
26
+ ${transcript}
27
+ """
28
+
29
+ Extract up to ${maxLearnings} key learnings (technical decisions, bugs solved, patterns discovered, important facts).
30
+ Skip trivial exchanges and repetitions.
31
+
32
+ Format JSON requis:
33
+ [
34
+ {
35
+ "content": "full description of the learning",
36
+ "memoryType": "episodic|semantic|procedural",
37
+ "keywords": ["mot1", "mot2"],
38
+ "level3Keywords": "BM25 keywords separated by spaces"
39
+ }
40
+ ]`,
41
+ },
42
+ ],
43
+ });
44
+ const text = response.content[0]?.type === 'text' ? (response.content[0].text ?? '') : '';
45
+ try {
46
+ const parsed = JSON.parse(text.trim());
47
+ if (!Array.isArray(parsed))
48
+ throw new Error('Expected array');
49
+ return parsed
50
+ .filter((item) => item.content && item.memoryType)
51
+ .map((item) => ({
52
+ content: String(item.content),
53
+ memoryType: (['episodic', 'semantic', 'procedural'].includes(item.memoryType)
54
+ ? item.memoryType
55
+ : 'semantic'),
56
+ keywords: Array.isArray(item.keywords) ? item.keywords.map(String) : [],
57
+ level3Keywords: String(item.level3Keywords || item.keywords?.join(' ') || ''),
58
+ }))
59
+ .slice(0, maxLearnings);
60
+ }
61
+ catch {
62
+ // Fallback: store the last assistant message as single episodic memory
63
+ const lastAssistant = session.messages.filter(m => m.role === 'assistant').pop();
64
+ if (!lastAssistant)
65
+ return [];
66
+ return [
67
+ {
68
+ content: lastAssistant.content.slice(0, 500),
69
+ memoryType: 'episodic',
70
+ keywords: [],
71
+ level3Keywords: '',
72
+ },
73
+ ];
74
+ }
75
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Session-start mnemonic context — Phase 5.3.1.
3
+ *
4
+ * When a Claude Code session begins, the agent has no idea what it left
5
+ * unfinished. This module composes the markdown block that reminds it: the open
6
+ * loops of the current project first (prospective memory), then the decayed but
7
+ * still relevant traces (retrospective memory).
8
+ *
9
+ * The logic lives here so it stays testable; `scripts/hook-session-start.ts` is
10
+ * only a shell that reads the environment and writes to stdout.
11
+ */
12
+ import type { Intention, Memory, MemoryStore, IntentionStore, DecayLevel, Script } from '../core/types.js';
13
+ import type { CueResolver } from '../core/cues.js';
14
+ import { intentionSaillance } from '../core/cues.js';
15
+ import { type Clock } from '../core/clock.js';
16
+ /** Default budget: maximum number of items listed per section. */
17
+ export declare const DEFAULT_SESSION_BUDGET = 10;
18
+ /** A trace is only recalled if it stayed salient despite its decay. */
19
+ export declare const DEFAULT_SAILLANCE_THRESHOLD = 60;
20
+ /** Levels that are "degraded but still useful": the detail is gone, the meaning remains. */
21
+ export declare const RELEVANT_LEVELS: DecayLevel[];
22
+ /** Max drill steps rendered in one block — the block goes into a prompt. */
23
+ export declare const SCRIPT_STEP_CAP = 8;
24
+ export interface SessionContextOptions {
25
+ store: MemoryStore & IntentionStore;
26
+ directory: string;
27
+ /** Current git branch — shown in the header, gives the agent its bearings. */
28
+ branch?: string;
29
+ /** Resolver: when provided, due cues are fired before composing. */
30
+ resolver?: CueResolver;
31
+ budget?: number;
32
+ saillanceThreshold?: number;
33
+ clock?: Clock;
34
+ }
35
+ export interface SessionContext {
36
+ markdown: string;
37
+ openLoops: Intention[];
38
+ traces: Memory[];
39
+ /** Loops woken by a time cue during this composition. */
40
+ firedNow: Intention[];
41
+ /** Drills woken during this composition (Phase 8.2) — at most one renders. */
42
+ firedScripts: Script[];
43
+ /**
44
+ * Marker-escape attempts neutralized while rendering (6.0.3). Non-zero is a
45
+ * security signal — log the event, never the payload (Claude R3/B11).
46
+ */
47
+ escapeAttempts: {
48
+ memoryId: string;
49
+ count: number;
50
+ }[];
51
+ }
52
+ /** Renders a duration in short form: "2d ago", "3h ago". */
53
+ export declare function humanizeAge(from: Date, now: Date): string;
54
+ /**
55
+ * Composes the mnemonic context of the current directory.
56
+ *
57
+ * Side effects, deliberately: overdue intentions are expired and due time cues
58
+ * are fired. The start of a session is exactly when that housekeeping should
59
+ * happen — otherwise nobody ever does it.
60
+ */
61
+ export declare function buildSessionContext(options: SessionContextOptions): Promise<SessionContext>;
62
+ /** Current salience of a loop — re-exported for consumers of the context. */
63
+ export { intentionSaillance };
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Session-start mnemonic context — Phase 5.3.1.
3
+ *
4
+ * When a Claude Code session begins, the agent has no idea what it left
5
+ * unfinished. This module composes the markdown block that reminds it: the open
6
+ * loops of the current project first (prospective memory), then the decayed but
7
+ * still relevant traces (retrospective memory).
8
+ *
9
+ * The logic lives here so it stays testable; `scripts/hook-session-start.ts` is
10
+ * only a shell that reads the environment and writes to stdout.
11
+ */
12
+ import { loopId, intentionSaillance } from '../core/cues.js';
13
+ import { scriptEffectiveSaillance } from '../core/scripts.js';
14
+ import { systemClock } from '../core/clock.js';
15
+ import { sanitizeTrace, wrapUntrusted, RECALLED_NOTES_PREFACE, DEFAULT_TRACE_CAP, } from '../core/sanitize.js';
16
+ /** Default budget: maximum number of items listed per section. */
17
+ export const DEFAULT_SESSION_BUDGET = 10;
18
+ /** A trace is only recalled if it stayed salient despite its decay. */
19
+ export const DEFAULT_SAILLANCE_THRESHOLD = 60;
20
+ /** Levels that are "degraded but still useful": the detail is gone, the meaning remains. */
21
+ export const RELEVANT_LEVELS = [2, 3];
22
+ /** Max drill steps rendered in one block — the block goes into a prompt. */
23
+ export const SCRIPT_STEP_CAP = 8;
24
+ /** Renders a duration in short form: "2d ago", "3h ago". */
25
+ export function humanizeAge(from, now) {
26
+ const ms = Math.max(0, now.getTime() - from.getTime());
27
+ const minutes = Math.floor(ms / 60_000);
28
+ if (minutes < 60)
29
+ return minutes <= 1 ? 'just now' : `${minutes}min ago`;
30
+ const hours = Math.floor(minutes / 60);
31
+ if (hours < 24)
32
+ return `${hours}h ago`;
33
+ const days = Math.floor(hours / 24);
34
+ if (days < 30)
35
+ return `${days}d ago`;
36
+ const months = Math.floor(days / 30);
37
+ return `${months} months ago`;
38
+ }
39
+ /** The most relevant content of a trace, given how far it has decayed. */
40
+ function traceText(memory) {
41
+ switch (memory.currentLevel) {
42
+ case 0:
43
+ return memory.content;
44
+ case 1:
45
+ return memory.level1Summary ?? memory.content;
46
+ case 2:
47
+ return memory.level2Essential ?? memory.level1Summary ?? memory.content;
48
+ case 3:
49
+ return memory.level3Keywords ?? memory.level2Essential ?? memory.content;
50
+ default:
51
+ return memory.level3Keywords ?? memory.content;
52
+ }
53
+ }
54
+ /** Flattens text onto one line — the block goes into a prompt, not a document. */
55
+ function oneLine(text, max = 220) {
56
+ const flat = text.replace(/\s+/g, ' ').trim();
57
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
58
+ }
59
+ /**
60
+ * Composes the mnemonic context of the current directory.
61
+ *
62
+ * Side effects, deliberately: overdue intentions are expired and due time cues
63
+ * are fired. The start of a session is exactly when that housekeeping should
64
+ * happen — otherwise nobody ever does it.
65
+ */
66
+ export async function buildSessionContext(options) {
67
+ const { store, directory, branch, resolver, budget = DEFAULT_SESSION_BUDGET, saillanceThreshold = DEFAULT_SAILLANCE_THRESHOLD, clock = systemClock, } = options;
68
+ const now = clock.now();
69
+ const firedNow = [];
70
+ const firedScripts = [];
71
+ if (resolver) {
72
+ await resolver.expireStale(now);
73
+ // Time cues first — dispatch by target kind (8.1): a script cue fired
74
+ // through resolver.fire() would throw by design.
75
+ for (const cue of await resolver.resolveTimeCues(now)) {
76
+ const fired = await resolver.fireAny(cue.id);
77
+ if (fired.kind === 'script') {
78
+ if (fired.script.directory === directory)
79
+ firedScripts.push(fired.script);
80
+ }
81
+ else if (fired.intention.directory === directory) {
82
+ firedNow.push(fired.intention);
83
+ }
84
+ }
85
+ // A session opening on a branch is a branch_switch from the drill's point
86
+ // of view (8.2): script cues armed on it fire. Intention behaviour is
87
+ // unchanged — their event cues wake through the bus, not here.
88
+ if (branch) {
89
+ const matched = await resolver.resolveEventCues({
90
+ type: 'branch_switch',
91
+ branch,
92
+ directory,
93
+ });
94
+ for (const cue of matched) {
95
+ if (cue.targetKind !== 'script')
96
+ continue;
97
+ const script = await resolver.fireScript(cue.id);
98
+ if (script.directory === directory)
99
+ firedScripts.push(script);
100
+ }
101
+ }
102
+ }
103
+ const openLoops = (await store.listIntentions({ status: 'armed', directory, limit: budget })).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
104
+ const traces = (await store.list({
105
+ directory,
106
+ levels: RELEVANT_LEVELS,
107
+ minSaillance: saillanceThreshold,
108
+ limit: budget,
109
+ })).sort((a, b) => b.saillance - a.saillance);
110
+ // Phase 6.0.2 — a trace that loses an active contradiction leaves the block
111
+ // (it stays searchable). Cycle: a trace that is both winner and loser stays,
112
+ // flagged `disputed` — last write wins, nothing is inferred.
113
+ const disputedIds = new Set();
114
+ let visibleTraces = traces;
115
+ if (store.listContradictions) {
116
+ const active = await store.listContradictions({ status: 'active' });
117
+ const losers = new Set(active.map((ct) => ct.loserId));
118
+ const winners = new Set(active.map((ct) => ct.winnerId));
119
+ for (const id of losers)
120
+ if (winners.has(id))
121
+ disputedIds.add(id);
122
+ visibleTraces = traces.filter((m) => !losers.has(m.id) || disputedIds.has(m.id));
123
+ }
124
+ const rendered = renderMarkdown({ openLoops, traces: visibleTraces, firedNow, firedScripts, branch, now, disputedIds });
125
+ return {
126
+ markdown: rendered.markdown,
127
+ openLoops,
128
+ traces: visibleTraces,
129
+ firedNow,
130
+ firedScripts,
131
+ escapeAttempts: rendered.escapeAttempts,
132
+ };
133
+ }
134
+ function renderMarkdown(input) {
135
+ const { openLoops, traces, firedNow, branch, now, disputedIds } = input;
136
+ const escapeAttempts = [];
137
+ // One drill per context block (Q1 conservative default): two scripts firing
138
+ // in the same session is a smell — the sharper one wins, the rest is noise.
139
+ // Sharpness = effective saillance (8.4 disuse included), not the raw bump.
140
+ const script = (input.firedScripts ?? []).sort((a, b) => scriptEffectiveSaillance(b, now) - scriptEffectiveSaillance(a, now))[0];
141
+ // Nothing to say: write nothing rather than inject an empty block into the prompt.
142
+ if (!openLoops.length && !traces.length && !firedNow.length && !script)
143
+ return { markdown: '', escapeAttempts };
144
+ const lines = ['## 🧠 Mnemonic context (humemory)'];
145
+ if (branch)
146
+ lines.push('', `_Current branch: \`${branch}\`_`);
147
+ if (script) {
148
+ const lastFired = script.lastFiredAt ? humanizeAge(script.lastFiredAt, now) : 'never';
149
+ lines.push('', `### 📋 Script: ${script.name} (fired ${script.fireCount}×, last ${lastFired})`);
150
+ const desc = sanitizeTrace(script.description);
151
+ // Escape-attempt telemetry (6.0.3/R3-B11) was missing for scripts —
152
+ // flagged twice in PHASE8_DIALOG.md, closed here: same accounting as
153
+ // the trace loop below, keyed on the script id since a script has no
154
+ // per-step id of its own.
155
+ if (desc.escapedMarkers > 0)
156
+ escapeAttempts.push({ memoryId: script.id, count: desc.escapedMarkers });
157
+ lines.push(`> ${oneLine(desc.text)}`);
158
+ // Same injection rules as traces (6.0.3): human-authored renders bare,
159
+ // agent/dreamer-authored stays wrapped.
160
+ const bare = script.source === 'human';
161
+ script.steps.slice(0, SCRIPT_STEP_CAP).forEach((step, i) => {
162
+ const s = sanitizeTrace(step);
163
+ if (s.escapedMarkers > 0)
164
+ escapeAttempts.push({ memoryId: script.id, count: s.escapedMarkers });
165
+ const body = bare
166
+ ? oneLine(s.text)
167
+ : wrapUntrusted(oneLine(s.text), { source: script.source, agent: script.agent, id: script.id });
168
+ lines.push(`${i + 1}. ${body}`);
169
+ });
170
+ if (script.steps.length > SCRIPT_STEP_CAP) {
171
+ lines.push(`_… ${script.steps.length - SCRIPT_STEP_CAP} more steps — \`pnpm cli script fire ${script.id.slice(0, 8)}\` for the full drill._`);
172
+ }
173
+ }
174
+ if (firedNow.length) {
175
+ lines.push('', '### ⏰ Deadlines reached', RECALLED_NOTES_PREFACE);
176
+ for (const i of firedNow) {
177
+ const s = sanitizeTrace(i.content);
178
+ lines.push(`- **[${loopId(i.id)}]** ${oneLine(s.text)}`);
179
+ }
180
+ }
181
+ if (openLoops.length) {
182
+ lines.push('', '### Open loops (Zeigarnik)', RECALLED_NOTES_PREFACE);
183
+ for (const i of openLoops) {
184
+ const age = humanizeAge(i.createdAt, now);
185
+ const deadline = i.expiresAt && i.expiresAt.getTime() > now.getTime()
186
+ ? ` — due in ${humanizeAge(now, i.expiresAt).replace(' ago', '')}`
187
+ : '';
188
+ const s = sanitizeTrace(i.content);
189
+ lines.push(`- **[${loopId(i.id)}]** ${oneLine(s.text)} (armed ${age}${deadline})`);
190
+ }
191
+ lines.push('', `_To close a loop: mention \`Closes ${loopId(openLoops[0].id)}\` in a commit message._`);
192
+ }
193
+ if (traces.length) {
194
+ lines.push('', '### Relevant decayed traces', RECALLED_NOTES_PREFACE);
195
+ for (const m of traces) {
196
+ const s = sanitizeTrace(traceText(m), DEFAULT_TRACE_CAP);
197
+ if (s.escapedMarkers > 0)
198
+ escapeAttempts.push({ memoryId: m.id, count: s.escapedMarkers });
199
+ // Only traces verified by a human render bare; earned verification
200
+ // (corroborated/reused/grounded) never unwraps content (6.0.3).
201
+ const bare = m.verified === true && m.verificationReason === 'human';
202
+ const body = bare
203
+ ? s.text
204
+ : wrapUntrusted(s.text, {
205
+ source: m.source,
206
+ agent: m.agent,
207
+ verified: m.verified,
208
+ id: m.id,
209
+ });
210
+ lines.push(`- [L${m.currentLevel}]${disputedIds?.has(m.id) ? ' ⚔️ *disputed*' : ''} ${body}`);
211
+ }
212
+ }
213
+ return { markdown: `${lines.join('\n')}\n`, escapeAttempts };
214
+ }
215
+ /** Current salience of a loop — re-exported for consumers of the context. */
216
+ export { intentionSaillance };
@@ -0,0 +1,12 @@
1
+ export interface SessionMessage {
2
+ role: 'user' | 'assistant' | 'system';
3
+ content: string;
4
+ timestamp?: string;
5
+ }
6
+ export interface ParsedSession {
7
+ sessionId: string;
8
+ directory: string;
9
+ messages: SessionMessage[];
10
+ rawText: string;
11
+ }
12
+ export declare function parseClaudeHookPayload(raw: string, directory: string): ParsedSession;
@@ -0,0 +1,85 @@
1
+ function extractText(content) {
2
+ if (typeof content === 'string')
3
+ return content;
4
+ if (Array.isArray(content)) {
5
+ return content
6
+ .map((block) => {
7
+ if (typeof block === 'string')
8
+ return block;
9
+ if (block?.type === 'text')
10
+ return block.text ?? '';
11
+ if (block?.type === 'tool_result')
12
+ return '';
13
+ return '';
14
+ })
15
+ .filter(Boolean)
16
+ .join('\n');
17
+ }
18
+ return String(content ?? '');
19
+ }
20
+ // Parse Claude Code hook stdin payload (JSON with transcript array)
21
+ export function parseClaudeHookPayload(raw, directory) {
22
+ try {
23
+ const payload = JSON.parse(raw);
24
+ // Format: { session_id, transcript: [{role, content}] }
25
+ if (payload.transcript && Array.isArray(payload.transcript)) {
26
+ const messages = payload.transcript.map((m) => ({
27
+ role: m.role ?? 'assistant',
28
+ content: extractText(m.content),
29
+ timestamp: m.timestamp,
30
+ }));
31
+ return {
32
+ sessionId: payload.session_id ?? `session-${Date.now()}`,
33
+ directory: payload.cwd ?? directory,
34
+ messages,
35
+ rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
36
+ };
37
+ }
38
+ // Format: array of messages directly
39
+ if (Array.isArray(payload)) {
40
+ const messages = payload.map((m) => ({
41
+ role: m.role ?? 'assistant',
42
+ content: extractText(m.content),
43
+ timestamp: m.timestamp,
44
+ }));
45
+ return {
46
+ sessionId: `session-${Date.now()}`,
47
+ directory,
48
+ messages,
49
+ rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
50
+ };
51
+ }
52
+ }
53
+ catch {
54
+ // Not JSON — treat as raw text transcript
55
+ }
56
+ // JSONL: each line is a message
57
+ const lines = raw.split('\n').filter(Boolean);
58
+ const messages = [];
59
+ for (const line of lines) {
60
+ try {
61
+ const obj = JSON.parse(line);
62
+ if (obj.role && obj.content !== undefined) {
63
+ messages.push({ role: obj.role, content: extractText(obj.content) });
64
+ }
65
+ }
66
+ catch {
67
+ // Not JSONL line, skip
68
+ }
69
+ }
70
+ if (messages.length > 0) {
71
+ return {
72
+ sessionId: `session-${Date.now()}`,
73
+ directory,
74
+ messages,
75
+ rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
76
+ };
77
+ }
78
+ // Fallback: plain text
79
+ return {
80
+ sessionId: `session-${Date.now()}`,
81
+ directory,
82
+ messages: [{ role: 'assistant', content: raw }],
83
+ rawText: raw,
84
+ };
85
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * HTTP routes for dreaming (Phase 6.1). Same testable-sub-router pattern as
3
+ * memory-routes.ts: the store is a parameter, no production DB in tests.
4
+ */
5
+ import { Hono } from 'hono';
6
+ import type { SQLiteStore } from '../store/sqlite.js';
7
+ export declare function createDreamRoutes(store: SQLiteStore): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * HTTP routes for dreaming (Phase 6.1). Same testable-sub-router pattern as
3
+ * memory-routes.ts: the store is a parameter, no production DB in tests.
4
+ */
5
+ import { Hono } from 'hono';
6
+ import { runDreamer, applyDreamProposal } from '../core/dreamer.js';
7
+ export function createDreamRoutes(store) {
8
+ const app = new Hono();
9
+ app.get('/dreams', async (c) => {
10
+ const status = c.req.query('status') ?? 'pending';
11
+ const proposals = await store.listDreamProposals({ status: status });
12
+ return c.json({ success: true, proposals });
13
+ });
14
+ app.post('/dreams/run', async (c) => {
15
+ const report = await runDreamer({ store });
16
+ return c.json({ success: true, report });
17
+ });
18
+ for (const verb of ['approve', 'reject']) {
19
+ app.post(`/dreams/:id/${verb}`, async (c) => {
20
+ try {
21
+ const id = c.req.param('id');
22
+ if (verb === 'approve') {
23
+ const pending = await store.listDreamProposals({ status: 'pending', includeExpired: true });
24
+ const target = pending.find((p) => p.id === id);
25
+ if (!target)
26
+ return c.json({ success: false, error: 'Not found or not pending' }, 404);
27
+ const effect = await applyDreamProposal(store, target);
28
+ const proposal = await store.resolveDreamProposal(id, 'approved');
29
+ return c.json({ success: true, proposal, effect });
30
+ }
31
+ const proposal = await store.resolveDreamProposal(id, 'rejected');
32
+ return c.json({ success: true, proposal });
33
+ }
34
+ catch (error) {
35
+ return c.json({ success: false, error: String(error) }, 500);
36
+ }
37
+ });
38
+ }
39
+ return app;
40
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * HTTP routes for prospective memory — Phase 5.4.
3
+ *
4
+ * Sub-router mounted by `src/api/server.ts`. It takes its store as a parameter
5
+ * rather than opening one at module load: that is what makes it testable without
6
+ * touching the production database (see docs/TESTING.md).
7
+ */
8
+ import { Hono } from 'hono';
9
+ import type { SQLiteStore } from '../store/sqlite.js';
10
+ import type { AppEvent } from '../core/event-bus.js';
11
+ import type { TriggerSpec } from '../core/types.js';
12
+ import type { Clock } from '../core/clock.js';
13
+ /**
14
+ * Validates a trigger coming off the network. Incoming JSON is not trusted: a
15
+ * malformed `triggerSpec` would be stored as is and would never wake anything.
16
+ */
17
+ export declare function validateTriggerSpec(raw: unknown): TriggerSpec;
18
+ /** Validates an event pushed to `POST /events`. */
19
+ export declare function validateAppEvent(raw: unknown): AppEvent;
20
+ export interface IntentionRoutesOptions {
21
+ clock?: Clock;
22
+ }
23
+ export declare function createIntentionRoutes(store: SQLiteStore, options?: IntentionRoutesOptions): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;