humemory 0.2.6 → 0.2.8
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/AGENTS.md +49 -4
- package/CHANGELOG.md +12 -0
- package/README.md +22 -10
- package/dist/agent/kimi-import.d.ts +19 -0
- package/dist/agent/kimi-import.js +111 -0
- package/dist/agent/kimi-session-parser.d.ts +3 -0
- package/dist/agent/kimi-session-parser.js +102 -0
- package/dist/agent/maintenance-queue.d.ts +89 -0
- package/dist/agent/maintenance-queue.js +245 -87
- package/dist/agent/maintenance-runner.d.ts +17 -4
- package/dist/agent/maintenance-runner.js +68 -17
- package/dist/agent/maintenance-state.d.ts +4 -0
- package/dist/agent/mcp-client-setup.d.ts +16 -0
- package/dist/agent/mcp-client-setup.js +108 -0
- package/dist/agent/opencode-import.d.ts +22 -0
- package/dist/agent/opencode-import.js +71 -0
- package/dist/agent/opencode-session-parser.d.ts +3 -0
- package/dist/agent/opencode-session-parser.js +35 -0
- package/dist/agent/session-parser.d.ts +8 -0
- package/dist/agent/session-parser.js +18 -0
- package/dist/agent/source-registry.js +1 -1
- package/dist/api/server.js +3 -2
- package/dist/cli/index.js +164 -4
- package/dist/core/cues.d.ts +1 -0
- package/dist/core/cues.js +19 -7
- package/dist/core/embeddings.d.ts +0 -10
- package/dist/core/embeddings.js +2 -1
- package/dist/core/llm-generator.d.ts +2 -10
- package/dist/core/paths.d.ts +5 -0
- package/dist/core/paths.js +27 -0
- package/dist/core/project-path.d.ts +3 -0
- package/dist/core/project-path.js +14 -0
- package/dist/core/search.d.ts +1 -1
- package/dist/core/search.js +7 -9
- package/dist/core/types.d.ts +13 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/store/sqlite.d.ts +37 -0
- package/dist/store/sqlite.js +94 -42
- package/package.json +4 -3
- package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
- package/public/app/index.html +1 -1
- package/scripts/consolidate.js +4 -4
- package/scripts/hook-post-commit.ts +2 -1
- package/scripts/hook-session-start.ts +2 -1
- package/scripts/hook-session.ts +2 -1
- package/src/agent/claude-hook.ts +126 -0
- package/src/agent/codex-import.ts +129 -0
- package/src/agent/codex-rollout-parser.ts +121 -0
- package/src/agent/commit-closer.ts +173 -0
- package/src/agent/kimi-import.ts +128 -0
- package/src/agent/kimi-session-parser.ts +127 -0
- package/src/agent/learning-extractor.ts +128 -0
- package/src/agent/maintenance-queue.ts +546 -0
- package/src/agent/maintenance-runner.ts +322 -0
- package/src/agent/maintenance-state.ts +168 -0
- package/src/agent/mcp-client-setup.ts +125 -0
- package/src/agent/opencode-import.ts +96 -0
- package/src/agent/opencode-session-parser.ts +53 -0
- package/src/agent/session-context.ts +302 -0
- package/src/agent/session-parser.ts +155 -0
- package/src/agent/source-registry.ts +135 -0
- package/src/api/cors.ts +42 -0
- package/src/api/dream-routes.ts +46 -0
- package/src/api/errors.ts +45 -0
- package/src/api/intentions-routes.ts +348 -0
- package/src/api/limits.ts +90 -0
- package/src/api/maintenance-routes.ts +73 -0
- package/src/api/memory-routes.ts +391 -0
- package/src/api/scripts-routes.ts +176 -0
- package/src/api/security-headers.ts +54 -0
- package/src/api/server.ts +292 -0
- package/src/cli/index.ts +1175 -0
- package/src/core/clock.ts +64 -0
- package/src/core/cue-arg.ts +79 -0
- package/src/core/cues.ts +511 -0
- package/src/core/decay.ts +198 -0
- package/src/core/dreamer.ts +494 -0
- package/src/core/embeddings.ts +157 -0
- package/src/core/event-bus.ts +100 -0
- package/src/core/hybrid.ts +78 -0
- package/src/core/llm-cli-client.ts +118 -0
- package/src/core/llm-generator.ts +90 -0
- package/src/core/paths.ts +28 -0
- package/src/core/project-path.ts +14 -0
- package/src/core/sanitize.ts +116 -0
- package/src/core/scripts.ts +112 -0
- package/src/core/search.ts +189 -0
- package/src/core/trust.ts +67 -0
- package/src/core/types.ts +393 -0
- package/src/core/vector-clusterer.ts +131 -0
- package/src/index.ts +40 -0
- package/src/mcp/HTTP_TRANSPORT.md +359 -0
- package/src/mcp/server.ts +202 -0
- package/src/store/sqlite.ts +1958 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/** Import OpenCode's public session exports into the maintenance queue. */
|
|
2
|
+
import { execFile } from 'child_process';
|
|
3
|
+
import { promisify } from 'util';
|
|
4
|
+
import { enqueueSession } from './maintenance-queue.js';
|
|
5
|
+
import { parseOpenCodeExport } from './opencode-session-parser.js';
|
|
6
|
+
import { serializeAgentSession } from './session-parser.js';
|
|
7
|
+
|
|
8
|
+
const execFileAsync = promisify(execFile);
|
|
9
|
+
export const OPENCODE_SOURCE = 'opencode-session';
|
|
10
|
+
|
|
11
|
+
export type OpenCodeCommandRunner = (args: string[]) => Promise<string>;
|
|
12
|
+
|
|
13
|
+
export interface OpenCodeImportOptions {
|
|
14
|
+
queueDir: string;
|
|
15
|
+
since?: Date;
|
|
16
|
+
limit?: number;
|
|
17
|
+
includeSubagents?: boolean;
|
|
18
|
+
dryRun?: boolean;
|
|
19
|
+
maxLearnings?: number;
|
|
20
|
+
command?: string;
|
|
21
|
+
run?: OpenCodeCommandRunner;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface OpenCodeImportResult {
|
|
25
|
+
scanned: number;
|
|
26
|
+
queued: number;
|
|
27
|
+
created: number;
|
|
28
|
+
skippedEmpty: number;
|
|
29
|
+
unreadable: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface OpenCodeSessionRow {
|
|
33
|
+
id?: string;
|
|
34
|
+
directory?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function defaultOpenCodeCommand(): string {
|
|
38
|
+
return process.env.HUMEMORY_OPENCODE_COMMAND ?? (process.platform === 'win32' ? 'opencode.cmd' : 'opencode');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function createOpenCodeRunner(command = defaultOpenCodeCommand()): OpenCodeCommandRunner {
|
|
42
|
+
return async (args) => {
|
|
43
|
+
const { stdout } = await execFileAsync(command, args, {
|
|
44
|
+
encoding: 'utf8',
|
|
45
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
46
|
+
windowsHide: true,
|
|
47
|
+
});
|
|
48
|
+
return stdout;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function importOpenCodeSessions(options: OpenCodeImportOptions): Promise<OpenCodeImportResult> {
|
|
53
|
+
const run = options.run ?? createOpenCodeRunner(options.command);
|
|
54
|
+
const conditions: string[] = [];
|
|
55
|
+
if (options.since) conditions.push(`time_updated >= ${options.since.getTime()}`);
|
|
56
|
+
if (!options.includeSubagents) conditions.push('parent_id IS NULL');
|
|
57
|
+
const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
|
|
58
|
+
const sql = `SELECT id, directory FROM session${where} ORDER BY time_updated ASC`;
|
|
59
|
+
const rows = JSON.parse(await run(['db', sql, '--format', 'json'])) as OpenCodeSessionRow[];
|
|
60
|
+
const result: OpenCodeImportResult = {
|
|
61
|
+
scanned: rows.length,
|
|
62
|
+
queued: 0,
|
|
63
|
+
created: 0,
|
|
64
|
+
skippedEmpty: 0,
|
|
65
|
+
unreadable: 0,
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
for (const row of rows) {
|
|
69
|
+
if (options.limit !== undefined && result.queued >= options.limit) break;
|
|
70
|
+
if (!row.id) {
|
|
71
|
+
result.unreadable += 1;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
const parsed = parseOpenCodeExport(await run(['export', row.id]), row.directory ?? process.cwd());
|
|
76
|
+
if (!parsed.messages.some((message) => message.role === 'user') ||
|
|
77
|
+
!parsed.messages.some((message) => message.role === 'assistant')) {
|
|
78
|
+
result.skippedEmpty += 1;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
result.queued += 1;
|
|
82
|
+
if (options.dryRun) continue;
|
|
83
|
+
const queued = await enqueueSession(serializeAgentSession(parsed), {
|
|
84
|
+
queueDir: options.queueDir,
|
|
85
|
+
directory: parsed.directory,
|
|
86
|
+
source: OPENCODE_SOURCE,
|
|
87
|
+
agent: 'opencode',
|
|
88
|
+
maxLearnings: options.maxLearnings,
|
|
89
|
+
});
|
|
90
|
+
if (queued.created) result.created += 1;
|
|
91
|
+
} catch {
|
|
92
|
+
result.unreadable += 1;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { ParsedSession, SessionMessage } from './session-parser.js';
|
|
2
|
+
|
|
3
|
+
interface OpenCodeExport {
|
|
4
|
+
info?: {
|
|
5
|
+
id?: string;
|
|
6
|
+
directory?: string;
|
|
7
|
+
path?: string;
|
|
8
|
+
};
|
|
9
|
+
messages?: Array<{
|
|
10
|
+
info?: {
|
|
11
|
+
role?: string;
|
|
12
|
+
time?: { created?: number | string };
|
|
13
|
+
};
|
|
14
|
+
parts?: Array<{ type?: string; text?: string }>;
|
|
15
|
+
}>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function timestamp(value: number | string | undefined): string | undefined {
|
|
19
|
+
if (value === undefined) return undefined;
|
|
20
|
+
const date = typeof value === 'number' ? new Date(value) : new Date(value);
|
|
21
|
+
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Parse the public `opencode export` JSON shape, excluding tools and reasoning. */
|
|
25
|
+
export function parseOpenCodeExport(raw: string, fallbackDirectory: string): ParsedSession {
|
|
26
|
+
const payload = JSON.parse(raw) as OpenCodeExport;
|
|
27
|
+
const messages: SessionMessage[] = [];
|
|
28
|
+
|
|
29
|
+
for (const entry of payload.messages ?? []) {
|
|
30
|
+
const role = entry.info?.role;
|
|
31
|
+
if (role !== 'user' && role !== 'assistant') continue;
|
|
32
|
+
const content = (entry.parts ?? [])
|
|
33
|
+
.filter((part) => part.type === 'text' && typeof part.text === 'string')
|
|
34
|
+
.map((part) => part.text!.trim())
|
|
35
|
+
.filter(Boolean)
|
|
36
|
+
.join('\n');
|
|
37
|
+
if (!content) continue;
|
|
38
|
+
messages.push({ role, content, timestamp: timestamp(entry.info?.time?.created) });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const occurredAt = [...messages]
|
|
42
|
+
.reverse()
|
|
43
|
+
.map((message) => message.timestamp ? new Date(message.timestamp) : undefined)
|
|
44
|
+
.find((date) => date && !Number.isNaN(date.getTime()));
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
sessionId: payload.info?.id ?? 'opencode-unknown-session',
|
|
48
|
+
directory: payload.info?.directory ?? payload.info?.path ?? fallbackDirectory,
|
|
49
|
+
messages,
|
|
50
|
+
rawText: messages.map((message) => `${message.role}: ${message.content}`).join('\n\n'),
|
|
51
|
+
occurredAt,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,302 @@
|
|
|
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
|
+
|
|
13
|
+
import type { Intention, Memory, MemoryStore, IntentionStore, DecayLevel, Script } from '../core/types.js';
|
|
14
|
+
import type { CueResolver } from '../core/cues.js';
|
|
15
|
+
import { loopId, intentionSaillance } from '../core/cues.js';
|
|
16
|
+
import { scriptEffectiveSaillance } from '../core/scripts.js';
|
|
17
|
+
import { systemClock, type Clock } from '../core/clock.js';
|
|
18
|
+
import {
|
|
19
|
+
sanitizeTrace,
|
|
20
|
+
wrapUntrusted,
|
|
21
|
+
RECALLED_NOTES_PREFACE,
|
|
22
|
+
DEFAULT_TRACE_CAP,
|
|
23
|
+
} from '../core/sanitize.js';
|
|
24
|
+
|
|
25
|
+
/** Default budget: maximum number of items listed per section. */
|
|
26
|
+
export const DEFAULT_SESSION_BUDGET = 10;
|
|
27
|
+
|
|
28
|
+
/** A trace is only recalled if it stayed salient despite its decay. */
|
|
29
|
+
export const DEFAULT_SAILLANCE_THRESHOLD = 60;
|
|
30
|
+
|
|
31
|
+
/** Levels that are "degraded but still useful": the detail is gone, the meaning remains. */
|
|
32
|
+
export const RELEVANT_LEVELS: DecayLevel[] = [2, 3];
|
|
33
|
+
|
|
34
|
+
/** Max drill steps rendered in one block — the block goes into a prompt. */
|
|
35
|
+
export const SCRIPT_STEP_CAP = 8;
|
|
36
|
+
|
|
37
|
+
export interface SessionContextOptions {
|
|
38
|
+
store: MemoryStore & IntentionStore;
|
|
39
|
+
directory: string;
|
|
40
|
+
/** Current git branch — shown in the header, gives the agent its bearings. */
|
|
41
|
+
branch?: string;
|
|
42
|
+
/** Resolver: when provided, due cues are fired before composing. */
|
|
43
|
+
resolver?: CueResolver;
|
|
44
|
+
budget?: number;
|
|
45
|
+
saillanceThreshold?: number;
|
|
46
|
+
clock?: Clock;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface SessionContext {
|
|
50
|
+
markdown: string;
|
|
51
|
+
openLoops: Intention[];
|
|
52
|
+
traces: Memory[];
|
|
53
|
+
/** Loops woken by a time cue during this composition. */
|
|
54
|
+
firedNow: Intention[];
|
|
55
|
+
/** Drills woken during this composition (Phase 8.2) — at most one renders. */
|
|
56
|
+
firedScripts: Script[];
|
|
57
|
+
/**
|
|
58
|
+
* Marker-escape attempts neutralized while rendering (6.0.3). Non-zero is a
|
|
59
|
+
* security signal — log the event, never the payload (Claude R3/B11).
|
|
60
|
+
*/
|
|
61
|
+
escapeAttempts: { memoryId: string; count: number }[];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Renders a duration in short form: "2d ago", "3h ago". */
|
|
65
|
+
export function humanizeAge(from: Date, now: Date): string {
|
|
66
|
+
const ms = Math.max(0, now.getTime() - from.getTime());
|
|
67
|
+
const minutes = Math.floor(ms / 60_000);
|
|
68
|
+
if (minutes < 60) return minutes <= 1 ? 'just now' : `${minutes}min ago`;
|
|
69
|
+
const hours = Math.floor(minutes / 60);
|
|
70
|
+
if (hours < 24) return `${hours}h ago`;
|
|
71
|
+
const days = Math.floor(hours / 24);
|
|
72
|
+
if (days < 30) return `${days}d ago`;
|
|
73
|
+
const months = Math.floor(days / 30);
|
|
74
|
+
return `${months} months ago`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The most relevant content of a trace, given how far it has decayed. */
|
|
78
|
+
function traceText(memory: Memory): string {
|
|
79
|
+
switch (memory.currentLevel) {
|
|
80
|
+
case 0:
|
|
81
|
+
return memory.content;
|
|
82
|
+
case 1:
|
|
83
|
+
return memory.level1Summary ?? memory.content;
|
|
84
|
+
case 2:
|
|
85
|
+
return memory.level2Essential ?? memory.level1Summary ?? memory.content;
|
|
86
|
+
case 3:
|
|
87
|
+
return memory.level3Keywords ?? memory.level2Essential ?? memory.content;
|
|
88
|
+
default:
|
|
89
|
+
return memory.level3Keywords ?? memory.content;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Flattens text onto one line — the block goes into a prompt, not a document. */
|
|
94
|
+
function oneLine(text: string, max = 220): string {
|
|
95
|
+
const flat = text.replace(/\s+/g, ' ').trim();
|
|
96
|
+
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Composes the mnemonic context of the current directory.
|
|
101
|
+
*
|
|
102
|
+
* Side effects, deliberately: overdue intentions are expired and due time cues
|
|
103
|
+
* are fired. The start of a session is exactly when that housekeeping should
|
|
104
|
+
* happen — otherwise nobody ever does it.
|
|
105
|
+
*/
|
|
106
|
+
export async function buildSessionContext(options: SessionContextOptions): Promise<SessionContext> {
|
|
107
|
+
const {
|
|
108
|
+
store,
|
|
109
|
+
directory,
|
|
110
|
+
branch,
|
|
111
|
+
resolver,
|
|
112
|
+
budget = DEFAULT_SESSION_BUDGET,
|
|
113
|
+
saillanceThreshold = DEFAULT_SAILLANCE_THRESHOLD,
|
|
114
|
+
clock = systemClock,
|
|
115
|
+
} = options;
|
|
116
|
+
|
|
117
|
+
const now = clock.now();
|
|
118
|
+
const firedNow: Intention[] = [];
|
|
119
|
+
const firedScripts: Script[] = [];
|
|
120
|
+
|
|
121
|
+
if (resolver) {
|
|
122
|
+
await resolver.expireStale(now);
|
|
123
|
+
// Time cues first — dispatch by target kind (8.1): a script cue fired
|
|
124
|
+
// through resolver.fire() would throw by design.
|
|
125
|
+
for (const cue of await resolver.resolveTimeCues(now)) {
|
|
126
|
+
const fired = await resolver.fireAny(cue.id);
|
|
127
|
+
if (fired.kind === 'script') {
|
|
128
|
+
if (fired.script.directory === directory) firedScripts.push(fired.script);
|
|
129
|
+
} else if (fired.intention.directory === directory) {
|
|
130
|
+
firedNow.push(fired.intention);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// A session opening on a branch is a branch_switch from the drill's point
|
|
134
|
+
// of view (8.2): script cues armed on it fire. Intention behaviour is
|
|
135
|
+
// unchanged — their event cues wake through the bus, not here.
|
|
136
|
+
if (branch) {
|
|
137
|
+
const matched = await resolver.resolveEventCues({
|
|
138
|
+
type: 'branch_switch',
|
|
139
|
+
branch,
|
|
140
|
+
directory,
|
|
141
|
+
} as any);
|
|
142
|
+
for (const cue of matched) {
|
|
143
|
+
if (cue.targetKind !== 'script') continue;
|
|
144
|
+
const script = await resolver.fireScript(cue.id);
|
|
145
|
+
if (script.directory === directory) firedScripts.push(script);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const openLoops = (await store.listIntentions({ status: 'armed', directory, limit: budget })).sort(
|
|
151
|
+
(a, b) => a.createdAt.getTime() - b.createdAt.getTime()
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
const traces = (
|
|
155
|
+
await store.list({
|
|
156
|
+
directory,
|
|
157
|
+
levels: RELEVANT_LEVELS,
|
|
158
|
+
minSaillance: saillanceThreshold,
|
|
159
|
+
limit: budget,
|
|
160
|
+
})
|
|
161
|
+
).sort((a, b) => b.saillance - a.saillance);
|
|
162
|
+
|
|
163
|
+
// Phase 6.0.2 — a trace that loses an active contradiction leaves the block
|
|
164
|
+
// (it stays searchable). Cycle: a trace that is both winner and loser stays,
|
|
165
|
+
// flagged `disputed` — last write wins, nothing is inferred.
|
|
166
|
+
const disputedIds = new Set<string>();
|
|
167
|
+
let visibleTraces = traces;
|
|
168
|
+
if (store.listContradictions) {
|
|
169
|
+
const active = await store.listContradictions({ status: 'active' });
|
|
170
|
+
const losers = new Set(active.map((ct) => ct.loserId));
|
|
171
|
+
const winners = new Set(active.map((ct) => ct.winnerId));
|
|
172
|
+
for (const id of losers) if (winners.has(id)) disputedIds.add(id);
|
|
173
|
+
visibleTraces = traces.filter((m) => !losers.has(m.id) || disputedIds.has(m.id));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const rendered = renderMarkdown({ openLoops, traces: visibleTraces, firedNow, firedScripts, branch, now, disputedIds });
|
|
177
|
+
return {
|
|
178
|
+
markdown: rendered.markdown,
|
|
179
|
+
openLoops,
|
|
180
|
+
traces: visibleTraces,
|
|
181
|
+
firedNow,
|
|
182
|
+
firedScripts,
|
|
183
|
+
escapeAttempts: rendered.escapeAttempts,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function renderMarkdown(input: {
|
|
188
|
+
openLoops: Intention[];
|
|
189
|
+
traces: Memory[];
|
|
190
|
+
firedNow: Intention[];
|
|
191
|
+
firedScripts?: Script[];
|
|
192
|
+
branch?: string;
|
|
193
|
+
now: Date;
|
|
194
|
+
disputedIds?: Set<string>;
|
|
195
|
+
}): { markdown: string; escapeAttempts: { memoryId: string; count: number }[] } {
|
|
196
|
+
const { openLoops, traces, firedNow, branch, now, disputedIds } = input;
|
|
197
|
+
const escapeAttempts: { memoryId: string; count: number }[] = [];
|
|
198
|
+
|
|
199
|
+
// One drill per context block (Q1 conservative default): two scripts firing
|
|
200
|
+
// in the same session is a smell — the sharper one wins, the rest is noise.
|
|
201
|
+
// Sharpness = effective saillance (8.4 disuse included), not the raw bump.
|
|
202
|
+
const script = (input.firedScripts ?? []).sort(
|
|
203
|
+
(a, b) => scriptEffectiveSaillance(b, now) - scriptEffectiveSaillance(a, now)
|
|
204
|
+
)[0];
|
|
205
|
+
|
|
206
|
+
// Nothing to say: write nothing rather than inject an empty block into the prompt.
|
|
207
|
+
if (!openLoops.length && !traces.length && !firedNow.length && !script) return { markdown: '', escapeAttempts };
|
|
208
|
+
|
|
209
|
+
const lines: string[] = ['## 🧠 Mnemonic context (humemory)'];
|
|
210
|
+
if (branch) lines.push('', `_Current branch: \`${branch}\`_`);
|
|
211
|
+
|
|
212
|
+
if (script) {
|
|
213
|
+
const lastFired = script.lastFiredAt ? humanizeAge(script.lastFiredAt, now) : 'never';
|
|
214
|
+
lines.push('', `### 📋 Script: ${script.name} (fired ${script.fireCount}×, last ${lastFired})`);
|
|
215
|
+
const desc = sanitizeTrace(script.description);
|
|
216
|
+
// Escape-attempt telemetry (6.0.3/R3-B11) was missing for scripts —
|
|
217
|
+
// flagged twice in PHASE8_DIALOG.md, closed here: same accounting as
|
|
218
|
+
// the trace loop below, keyed on the script id since a script has no
|
|
219
|
+
// per-step id of its own.
|
|
220
|
+
if (desc.escapedMarkers > 0) escapeAttempts.push({ memoryId: script.id, count: desc.escapedMarkers });
|
|
221
|
+
// Same injection rules as traces (6.0.3): human-authored renders bare,
|
|
222
|
+
// agent/dreamer-authored stays wrapped. The description used to render
|
|
223
|
+
// bare unconditionally while the steps below were correctly gated
|
|
224
|
+
// (SECURITY_AUDIT.md H-03) — both now share the same `bare` check.
|
|
225
|
+
const bare = script.source === 'human';
|
|
226
|
+
lines.push(
|
|
227
|
+
`> ${bare ? oneLine(desc.text) : wrapUntrusted(oneLine(desc.text), { source: script.source, agent: script.agent, id: script.id })}`
|
|
228
|
+
);
|
|
229
|
+
script.steps.slice(0, SCRIPT_STEP_CAP).forEach((step, i) => {
|
|
230
|
+
const s = sanitizeTrace(step);
|
|
231
|
+
if (s.escapedMarkers > 0) escapeAttempts.push({ memoryId: script.id, count: s.escapedMarkers });
|
|
232
|
+
const body = bare
|
|
233
|
+
? oneLine(s.text)
|
|
234
|
+
: wrapUntrusted(oneLine(s.text), { source: script.source, agent: script.agent, id: script.id });
|
|
235
|
+
lines.push(`${i + 1}. ${body}`);
|
|
236
|
+
});
|
|
237
|
+
if (script.steps.length > SCRIPT_STEP_CAP) {
|
|
238
|
+
lines.push(`_… ${script.steps.length - SCRIPT_STEP_CAP} more steps — \`pnpm cli script fire ${script.id.slice(0, 8)}\` for the full drill._`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Intentions carry the same provenance shape as memories (6.0.1) but used to
|
|
243
|
+
// render bare unconditionally regardless of it (SECURITY_AUDIT.md H-03).
|
|
244
|
+
// Only a human-verified loop skips the untrusted wrapper now.
|
|
245
|
+
const renderIntentionBody = (i: Intention, s: { text: string }): string => {
|
|
246
|
+
const bare = i.verified === true && i.verificationReason === 'human';
|
|
247
|
+
return bare
|
|
248
|
+
? oneLine(s.text)
|
|
249
|
+
: wrapUntrusted(oneLine(s.text), { source: i.source, agent: i.agent, verified: i.verified, id: i.id });
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
if (firedNow.length) {
|
|
253
|
+
lines.push('', '### ⏰ Deadlines reached', RECALLED_NOTES_PREFACE);
|
|
254
|
+
for (const i of firedNow) {
|
|
255
|
+
const s = sanitizeTrace(i.content);
|
|
256
|
+
// Same reporting as scripts and traces: the content was already
|
|
257
|
+
// neutralised, but a swallowed count hides the attempt from the operator.
|
|
258
|
+
if (s.escapedMarkers > 0) escapeAttempts.push({ memoryId: i.id, count: s.escapedMarkers });
|
|
259
|
+
lines.push(`- **[${loopId(i.id)}]** ${renderIntentionBody(i, s)}`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (openLoops.length) {
|
|
264
|
+
lines.push('', '### Open loops (Zeigarnik)', RECALLED_NOTES_PREFACE);
|
|
265
|
+
for (const i of openLoops) {
|
|
266
|
+
const age = humanizeAge(i.createdAt, now);
|
|
267
|
+
const deadline =
|
|
268
|
+
i.expiresAt && i.expiresAt.getTime() > now.getTime()
|
|
269
|
+
? ` — due in ${humanizeAge(now, i.expiresAt).replace(' ago', '')}`
|
|
270
|
+
: '';
|
|
271
|
+
const s = sanitizeTrace(i.content);
|
|
272
|
+
if (s.escapedMarkers > 0) escapeAttempts.push({ memoryId: i.id, count: s.escapedMarkers });
|
|
273
|
+
lines.push(`- **[${loopId(i.id)}]** ${renderIntentionBody(i, s)} (armed ${age}${deadline})`);
|
|
274
|
+
}
|
|
275
|
+
lines.push('', `_To close a loop: mention \`Closes ${loopId(openLoops[0].id)}\` in a commit message._`);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (traces.length) {
|
|
279
|
+
lines.push('', '### Relevant decayed traces', RECALLED_NOTES_PREFACE);
|
|
280
|
+
for (const m of traces) {
|
|
281
|
+
const s = sanitizeTrace(traceText(m), DEFAULT_TRACE_CAP);
|
|
282
|
+
if (s.escapedMarkers > 0) escapeAttempts.push({ memoryId: m.id, count: s.escapedMarkers });
|
|
283
|
+
// Only traces verified by a human render bare; earned verification
|
|
284
|
+
// (corroborated/reused/grounded) never unwraps content (6.0.3).
|
|
285
|
+
const bare = m.verified === true && m.verificationReason === 'human';
|
|
286
|
+
const body = bare
|
|
287
|
+
? s.text
|
|
288
|
+
: wrapUntrusted(s.text, {
|
|
289
|
+
source: m.source,
|
|
290
|
+
agent: m.agent,
|
|
291
|
+
verified: m.verified,
|
|
292
|
+
id: m.id,
|
|
293
|
+
});
|
|
294
|
+
lines.push(`- [L${m.currentLevel}]${disputedIds?.has(m.id) ? ' ⚔️ *disputed*' : ''} ${body}`);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
return { markdown: `${lines.join('\n')}\n`, escapeAttempts };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Current salience of a loop — re-exported for consumers of the context. */
|
|
302
|
+
export { intentionSaillance };
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { isCodexRollout, parseCodexRollout } from './codex-rollout-parser.js';
|
|
2
|
+
|
|
3
|
+
export interface SessionMessage {
|
|
4
|
+
role: 'user' | 'assistant' | 'system';
|
|
5
|
+
content: string;
|
|
6
|
+
timestamp?: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface ParsedSession {
|
|
10
|
+
sessionId: string;
|
|
11
|
+
directory: string;
|
|
12
|
+
messages: SessionMessage[];
|
|
13
|
+
rawText: string;
|
|
14
|
+
/**
|
|
15
|
+
* When the session was *lived*, not when it was read. A rollout swept weeks
|
|
16
|
+
* after the fact must encode as a trace of that day, otherwise every import
|
|
17
|
+
* lands on the import date and the memory loses its timeline — and, with it,
|
|
18
|
+
* the age decay works from.
|
|
19
|
+
*/
|
|
20
|
+
occurredAt?: Date;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Canonical acquisition envelope consumed by the maintenance queue.
|
|
25
|
+
*
|
|
26
|
+
* Source-specific importers normalize their private formats once, then reuse
|
|
27
|
+
* the same parser/checkpoint path as the live Claude hook. Keeping the envelope
|
|
28
|
+
* here prevents every importer from inventing a subtly different transcript.
|
|
29
|
+
*/
|
|
30
|
+
export function serializeAgentSession(session: ParsedSession): string {
|
|
31
|
+
return JSON.stringify({
|
|
32
|
+
session_id: session.sessionId,
|
|
33
|
+
cwd: session.directory,
|
|
34
|
+
transcript: session.messages.map((message) => ({
|
|
35
|
+
role: message.role,
|
|
36
|
+
content: message.content,
|
|
37
|
+
timestamp: message.timestamp,
|
|
38
|
+
})),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The instant a transcript line carries, when it carries a usable one. */
|
|
43
|
+
export function messageTime(message: SessionMessage | undefined): Date | undefined {
|
|
44
|
+
if (!message?.timestamp) return undefined;
|
|
45
|
+
const at = new Date(message.timestamp);
|
|
46
|
+
return Number.isNaN(at.getTime()) ? undefined : at;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The last usable instant in a run of messages — the session's own clock. */
|
|
50
|
+
export function lastMessageTime(messages: SessionMessage[]): Date | undefined {
|
|
51
|
+
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
|
52
|
+
const at = messageTime(messages[i]);
|
|
53
|
+
if (at) return at;
|
|
54
|
+
}
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function extractText(content: unknown): string {
|
|
59
|
+
if (typeof content === 'string') return content;
|
|
60
|
+
if (Array.isArray(content)) {
|
|
61
|
+
return content
|
|
62
|
+
.map((block: any) => {
|
|
63
|
+
if (typeof block === 'string') return block;
|
|
64
|
+
if (block?.type === 'text') return block.text ?? '';
|
|
65
|
+
if (block?.type === 'tool_result') return '';
|
|
66
|
+
return '';
|
|
67
|
+
})
|
|
68
|
+
.filter(Boolean)
|
|
69
|
+
.join('\n');
|
|
70
|
+
}
|
|
71
|
+
return String(content ?? '');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Parse Claude Code hook stdin payload (JSON with transcript array)
|
|
75
|
+
export function parseClaudeHookPayload(raw: string, directory: string): ParsedSession {
|
|
76
|
+
try {
|
|
77
|
+
const payload = JSON.parse(raw);
|
|
78
|
+
|
|
79
|
+
// Format: { session_id, transcript: [{role, content}] }
|
|
80
|
+
if (payload.transcript && Array.isArray(payload.transcript)) {
|
|
81
|
+
const messages: SessionMessage[] = payload.transcript.map((m: any) => ({
|
|
82
|
+
role: m.role ?? 'assistant',
|
|
83
|
+
content: extractText(m.content),
|
|
84
|
+
timestamp: m.timestamp,
|
|
85
|
+
}));
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
sessionId: payload.session_id ?? `session-${Date.now()}`,
|
|
89
|
+
directory: payload.cwd ?? directory,
|
|
90
|
+
messages,
|
|
91
|
+
rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
|
|
92
|
+
occurredAt: lastMessageTime(messages),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Format: array of messages directly
|
|
97
|
+
if (Array.isArray(payload)) {
|
|
98
|
+
const messages: SessionMessage[] = payload.map((m: any) => ({
|
|
99
|
+
role: m.role ?? 'assistant',
|
|
100
|
+
content: extractText(m.content),
|
|
101
|
+
timestamp: m.timestamp,
|
|
102
|
+
}));
|
|
103
|
+
return {
|
|
104
|
+
sessionId: `session-${Date.now()}`,
|
|
105
|
+
directory,
|
|
106
|
+
messages,
|
|
107
|
+
rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
|
|
108
|
+
occurredAt: lastMessageTime(messages),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
} catch {
|
|
112
|
+
// Not JSON — treat as raw text transcript
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// JSONL: each line is a message
|
|
116
|
+
const lines = raw.split('\n').filter(Boolean);
|
|
117
|
+
const messages: SessionMessage[] = [];
|
|
118
|
+
for (const line of lines) {
|
|
119
|
+
try {
|
|
120
|
+
const obj = JSON.parse(line);
|
|
121
|
+
if (obj.role && obj.content !== undefined) {
|
|
122
|
+
messages.push({ role: obj.role, content: extractText(obj.content) });
|
|
123
|
+
}
|
|
124
|
+
} catch {
|
|
125
|
+
// Not JSONL line, skip
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (messages.length > 0) {
|
|
130
|
+
return {
|
|
131
|
+
sessionId: `session-${Date.now()}`,
|
|
132
|
+
directory,
|
|
133
|
+
messages,
|
|
134
|
+
rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
|
|
135
|
+
occurredAt: lastMessageTime(messages),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Fallback: plain text
|
|
140
|
+
return {
|
|
141
|
+
sessionId: `session-${Date.now()}`,
|
|
142
|
+
directory,
|
|
143
|
+
messages: [{ role: 'assistant', content: raw }],
|
|
144
|
+
rawText: raw,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Entry point for any local agent transcript: detects the producer and hands
|
|
150
|
+
* off. Claude hook payloads and Codex rollouts are both JSON on stdin, so the
|
|
151
|
+
* dispatch is on shape, not on a flag the caller has to remember to pass.
|
|
152
|
+
*/
|
|
153
|
+
export function parseAgentSession(raw: string, directory: string): ParsedSession {
|
|
154
|
+
return isCodexRollout(raw) ? parseCodexRollout(raw, directory) : parseClaudeHookPayload(raw, directory);
|
|
155
|
+
}
|