humemory 0.2.7 → 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 +8 -4
- package/CHANGELOG.md +6 -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 +2 -0
- package/dist/agent/maintenance-queue.js +36 -61
- package/dist/agent/maintenance-runner.d.ts +17 -4
- package/dist/agent/maintenance-runner.js +45 -10
- 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 +96 -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
package/public/app/index.html
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
<meta charset="utf-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
6
|
<title>humemory — Boucles ouvertes</title>
|
|
7
|
-
<link rel="stylesheet" crossorigin href="./index-kv9v6ty0.css"><script type="module" crossorigin src="./index-
|
|
7
|
+
<link rel="stylesheet" crossorigin href="./index-kv9v6ty0.css"><script type="module" crossorigin src="./index-n2qg9hyr.js"></script></head>
|
|
8
8
|
<body>
|
|
9
9
|
<div id="root"></div>
|
|
10
10
|
|
package/scripts/consolidate.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
#!/usr/bin/env
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
2
|
/**
|
|
3
3
|
* humemory automatic consolidation script.
|
|
4
4
|
* Meant to run from cron, nightly.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import {
|
|
7
|
+
import { execFileSync } from 'child_process';
|
|
8
8
|
import { fileURLToPath } from 'url';
|
|
9
9
|
import { dirname, join } from 'path';
|
|
10
10
|
|
|
@@ -21,7 +21,7 @@ console.log();
|
|
|
21
21
|
try {
|
|
22
22
|
// Run the decay sweep
|
|
23
23
|
console.log('Updating consolidation...');
|
|
24
|
-
const decayOutput =
|
|
24
|
+
const decayOutput = execFileSync(process.execPath, [join(HUMEMORY_DIR, 'bin/humemory.js'), 'decay'], {
|
|
25
25
|
cwd: HUMEMORY_DIR,
|
|
26
26
|
encoding: 'utf-8',
|
|
27
27
|
});
|
|
@@ -29,7 +29,7 @@ try {
|
|
|
29
29
|
|
|
30
30
|
// State of the memory palace
|
|
31
31
|
console.log('humemory state:');
|
|
32
|
-
const statusOutput =
|
|
32
|
+
const statusOutput = execFileSync(process.execPath, [join(HUMEMORY_DIR, 'bin/humemory.js'), 'status'], {
|
|
33
33
|
cwd: HUMEMORY_DIR,
|
|
34
34
|
encoding: 'utf-8',
|
|
35
35
|
});
|
|
@@ -17,12 +17,13 @@
|
|
|
17
17
|
import { join, dirname } from 'path';
|
|
18
18
|
import { fileURLToPath } from 'url';
|
|
19
19
|
import { SQLiteStore } from '../src/store/sqlite.js';
|
|
20
|
+
import { databasePath } from '../src/core/paths.js';
|
|
20
21
|
import { applyCommitToLoops, renderCommitReport, type CommitInfo } from '../src/agent/commit-closer.js';
|
|
21
22
|
|
|
22
23
|
const __filename = fileURLToPath(import.meta.url);
|
|
23
24
|
const __dirname = dirname(__filename);
|
|
24
25
|
|
|
25
|
-
const DB_PATH =
|
|
26
|
+
const DB_PATH = databasePath();
|
|
26
27
|
|
|
27
28
|
/** Runs a git command, returning stdout or null when it fails. */
|
|
28
29
|
async function git(args: string[]): Promise<string | null> {
|
|
@@ -24,13 +24,14 @@
|
|
|
24
24
|
import { join, dirname } from 'path';
|
|
25
25
|
import { fileURLToPath } from 'url';
|
|
26
26
|
import { SQLiteStore } from '../src/store/sqlite.js';
|
|
27
|
+
import { databasePath } from '../src/core/paths.js';
|
|
27
28
|
import { SqliteCueResolver } from '../src/core/cues.js';
|
|
28
29
|
import { buildSessionContext, DEFAULT_SESSION_BUDGET, DEFAULT_SAILLANCE_THRESHOLD } from '../src/agent/session-context.js';
|
|
29
30
|
|
|
30
31
|
const __filename = fileURLToPath(import.meta.url);
|
|
31
32
|
const __dirname = dirname(__filename);
|
|
32
33
|
|
|
33
|
-
const DB_PATH =
|
|
34
|
+
const DB_PATH = databasePath();
|
|
34
35
|
const DIRECTORY = process.env.HUMEMORY_DIR ?? process.cwd();
|
|
35
36
|
const VERBOSE = process.env.HUMEMORY_VERBOSE === '1';
|
|
36
37
|
|
package/scripts/hook-session.ts
CHANGED
|
@@ -18,11 +18,12 @@
|
|
|
18
18
|
import { join, dirname } from 'path';
|
|
19
19
|
import { fileURLToPath } from 'url';
|
|
20
20
|
import { enqueueSession } from '../src/agent/maintenance-queue.js';
|
|
21
|
+
import { queueDirectory } from '../src/core/paths.js';
|
|
21
22
|
|
|
22
23
|
const __filename = fileURLToPath(import.meta.url);
|
|
23
24
|
const __dirname = dirname(__filename);
|
|
24
25
|
|
|
25
|
-
const QUEUE_DIR =
|
|
26
|
+
const QUEUE_DIR = queueDirectory();
|
|
26
27
|
const DIRECTORY = process.env.HUMEMORY_DIR ?? process.cwd();
|
|
27
28
|
const MAX_LEARNINGS = parseInt(process.env.HUMEMORY_MAX ?? '5');
|
|
28
29
|
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { SQLiteStore } from '../store/sqlite.js';
|
|
2
|
+
import { lastMessageTime, parseAgentSession, type ParsedSession } from './session-parser.js';
|
|
3
|
+
import { extractLearnings, extractLearningsDeterministic } from './learning-extractor.js';
|
|
4
|
+
import type { LLMClient } from '../core/llm-generator.js';
|
|
5
|
+
import type { TraceSource } from '../core/types.js';
|
|
6
|
+
|
|
7
|
+
export interface HookOptions {
|
|
8
|
+
dbPath: string;
|
|
9
|
+
directory?: string;
|
|
10
|
+
maxLearnings?: number;
|
|
11
|
+
client?: LLMClient;
|
|
12
|
+
llmTimeoutMs?: number;
|
|
13
|
+
source?: TraceSource;
|
|
14
|
+
agent?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Number of leading transcript messages already encoded for this session.
|
|
17
|
+
* `Stop` fires once per turn and resends the whole transcript, so without a
|
|
18
|
+
* checkpoint every pass would re-encode the entire history as new memories.
|
|
19
|
+
*/
|
|
20
|
+
sinceMessage?: number;
|
|
21
|
+
verbose?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface HookResult {
|
|
25
|
+
sessionId: string;
|
|
26
|
+
directory: string;
|
|
27
|
+
memoriesStored: number;
|
|
28
|
+
learnings: string[];
|
|
29
|
+
extractionMode: 'llm' | 'deterministic';
|
|
30
|
+
/** Total messages in the transcript — the checkpoint to persist after success. */
|
|
31
|
+
messagesSeen: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
|
|
35
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
36
|
+
try {
|
|
37
|
+
return await Promise.race([
|
|
38
|
+
promise,
|
|
39
|
+
new Promise<T>((_, reject) => {
|
|
40
|
+
timer = setTimeout(() => reject(new Error(`maintenance model timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
41
|
+
}),
|
|
42
|
+
]);
|
|
43
|
+
} finally {
|
|
44
|
+
if (timer) clearTimeout(timer);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function processSession(
|
|
49
|
+
rawTranscript: string,
|
|
50
|
+
options: HookOptions
|
|
51
|
+
): Promise<HookResult> {
|
|
52
|
+
const directory = options.directory ?? process.cwd();
|
|
53
|
+
const session = parseAgentSession(rawTranscript, directory);
|
|
54
|
+
const maxLearnings = options.maxLearnings ?? 5;
|
|
55
|
+
const messagesSeen = session.messages.length;
|
|
56
|
+
|
|
57
|
+
// Only the messages added since the last successful pass are candidates.
|
|
58
|
+
const since = Math.max(0, Math.min(options.sinceMessage ?? 0, messagesSeen));
|
|
59
|
+
const pending = session.messages.slice(since);
|
|
60
|
+
if (pending.length === 0) {
|
|
61
|
+
return {
|
|
62
|
+
sessionId: session.sessionId, directory: session.directory,
|
|
63
|
+
memoriesStored: 0, learnings: [], extractionMode: 'deterministic', messagesSeen,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const scoped: ParsedSession = {
|
|
67
|
+
...session,
|
|
68
|
+
messages: pending,
|
|
69
|
+
rawText: pending.map((m) => `${m.role}: ${m.content}`).join('\n\n'),
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
let extractionMode: HookResult['extractionMode'] = 'deterministic';
|
|
73
|
+
let learnings = extractLearningsDeterministic(scoped, maxLearnings);
|
|
74
|
+
if (options.client) {
|
|
75
|
+
try {
|
|
76
|
+
learnings = await withTimeout(
|
|
77
|
+
extractLearnings(scoped, options.client, maxLearnings),
|
|
78
|
+
options.llmTimeoutMs ?? 8_000,
|
|
79
|
+
);
|
|
80
|
+
extractionMode = 'llm';
|
|
81
|
+
} catch {
|
|
82
|
+
// Quota, network, timeout: the deterministic path already produced a result.
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (learnings.length === 0) {
|
|
87
|
+
return { sessionId: session.sessionId, directory: session.directory, memoriesStored: 0, learnings: [], extractionMode, messagesSeen };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// What is encoded belongs to the day the session ran, not the day it was
|
|
91
|
+
// read: a rollout sweep runs long after the fact, and dating every trace on
|
|
92
|
+
// the sweep collapses the timeline into a single import day.
|
|
93
|
+
const occurredAt = lastMessageTime(pending) ?? session.occurredAt ?? new Date();
|
|
94
|
+
|
|
95
|
+
const store = new SQLiteStore(options.dbPath);
|
|
96
|
+
const stored: string[] = [];
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
for (const learning of learnings) {
|
|
100
|
+
await store.add({
|
|
101
|
+
content: learning.content,
|
|
102
|
+
directory: session.directory,
|
|
103
|
+
day: occurredAt.toISOString().split('T')[0],
|
|
104
|
+
createdAt: occurredAt,
|
|
105
|
+
keywords: learning.keywords,
|
|
106
|
+
sessionId: session.sessionId,
|
|
107
|
+
memoryType: learning.memoryType,
|
|
108
|
+
level3Keywords: learning.level3Keywords,
|
|
109
|
+
source: options.source ?? 'agent',
|
|
110
|
+
agent: options.agent ?? 'unknown',
|
|
111
|
+
});
|
|
112
|
+
stored.push(learning.content.slice(0, 80));
|
|
113
|
+
}
|
|
114
|
+
} finally {
|
|
115
|
+
store.close();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
sessionId: session.sessionId,
|
|
120
|
+
directory: session.directory,
|
|
121
|
+
memoriesStored: stored.length,
|
|
122
|
+
learnings: stored,
|
|
123
|
+
extractionMode,
|
|
124
|
+
messagesSeen,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Imports Codex CLI rollouts into the maintenance queue.
|
|
3
|
+
*
|
|
4
|
+
* Acquisition stays outside the cognitive core: this only decides *which files
|
|
5
|
+
* are candidate sessions* and hands their raw bytes to `enqueueSession`. What
|
|
6
|
+
* becomes a trace, how it decays and when it resurfaces is still the store's
|
|
7
|
+
* business, decided later by the worker — the same path a Claude `Stop` hook
|
|
8
|
+
* feeds.
|
|
9
|
+
*
|
|
10
|
+
* Re-importing is safe: a queue job is keyed on `source + sessionId`, and the
|
|
11
|
+
* worker keeps a per-session checkpoint, so a rollout that grew since the last
|
|
12
|
+
* pass contributes only its new messages.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { readdir, readFile, stat } from 'fs/promises';
|
|
16
|
+
import { homedir } from 'os';
|
|
17
|
+
import { join } from 'path';
|
|
18
|
+
import { enqueueSession } from './maintenance-queue.js';
|
|
19
|
+
import { isSubagentThread, parseCodexRollout, readCodexRolloutMeta } from './codex-rollout-parser.js';
|
|
20
|
+
|
|
21
|
+
/** Marks these jobs as coming from a rollout sweep rather than a live hook. */
|
|
22
|
+
export const CODEX_SOURCE = 'codex-rollout';
|
|
23
|
+
|
|
24
|
+
export interface CodexImportOptions {
|
|
25
|
+
queueDir: string;
|
|
26
|
+
/** Defaults to `$CODEX_HOME/sessions`, else `~/.codex/sessions`. */
|
|
27
|
+
sessionsDir?: string;
|
|
28
|
+
/** Only rollouts modified at or after this instant. */
|
|
29
|
+
since?: Date;
|
|
30
|
+
/** Stop after this many *queued* sessions. */
|
|
31
|
+
limit?: number;
|
|
32
|
+
/** Threads Codex spawned for itself (judges, reviews) are excluded by default. */
|
|
33
|
+
includeSubagents?: boolean;
|
|
34
|
+
/** Scan and report without writing to the queue. */
|
|
35
|
+
dryRun?: boolean;
|
|
36
|
+
maxLearnings?: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface CodexImportResult {
|
|
40
|
+
scanned: number;
|
|
41
|
+
queued: number;
|
|
42
|
+
created: number;
|
|
43
|
+
skippedSubagent: number;
|
|
44
|
+
skippedEmpty: number;
|
|
45
|
+
skippedOld: number;
|
|
46
|
+
unreadable: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function defaultCodexSessionsDir(): string {
|
|
50
|
+
const home = process.env.CODEX_HOME ?? join(homedir(), '.codex');
|
|
51
|
+
return join(home, 'sessions');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Rollout files, depth-first through the YYYY/MM/DD tree. */
|
|
55
|
+
async function findRollouts(dir: string): Promise<string[]> {
|
|
56
|
+
let entries;
|
|
57
|
+
try {
|
|
58
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
59
|
+
} catch {
|
|
60
|
+
return []; // No codex on this machine, or no session ever recorded.
|
|
61
|
+
}
|
|
62
|
+
const found: string[] = [];
|
|
63
|
+
for (const entry of entries) {
|
|
64
|
+
const path = join(dir, entry.name);
|
|
65
|
+
if (entry.isDirectory()) found.push(...(await findRollouts(path)));
|
|
66
|
+
else if (entry.name.startsWith('rollout-') && entry.name.endsWith('.jsonl')) found.push(path);
|
|
67
|
+
}
|
|
68
|
+
return found;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function importCodexRollouts(options: CodexImportOptions): Promise<CodexImportResult> {
|
|
72
|
+
const sessionsDir = options.sessionsDir ?? defaultCodexSessionsDir();
|
|
73
|
+
const result: CodexImportResult = {
|
|
74
|
+
scanned: 0, queued: 0, created: 0,
|
|
75
|
+
skippedSubagent: 0, skippedEmpty: 0, skippedOld: 0, unreadable: 0,
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const files = (await findRollouts(sessionsDir)).sort();
|
|
79
|
+
|
|
80
|
+
for (const file of files) {
|
|
81
|
+
if (options.limit !== undefined && result.queued >= options.limit) break;
|
|
82
|
+
result.scanned += 1;
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
if (options.since) {
|
|
86
|
+
const { mtime } = await stat(file);
|
|
87
|
+
if (mtime < options.since) {
|
|
88
|
+
result.skippedOld += 1;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const raw = await readFile(file, 'utf-8');
|
|
94
|
+
const meta = readCodexRolloutMeta(raw);
|
|
95
|
+
if (!options.includeSubagents && isSubagentThread(meta)) {
|
|
96
|
+
result.skippedSubagent += 1;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// A rollout with no human turn and no answer holds nothing to learn from:
|
|
101
|
+
// an aborted start, or a thread that only ran tools.
|
|
102
|
+
const parsed = parseCodexRollout(raw, meta?.directory ?? sessionsDir);
|
|
103
|
+
if (parsed.messages.length === 0) {
|
|
104
|
+
result.skippedEmpty += 1;
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (options.dryRun) {
|
|
109
|
+
result.queued += 1;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const { created } = await enqueueSession(raw, {
|
|
114
|
+
queueDir: options.queueDir,
|
|
115
|
+
directory: parsed.directory,
|
|
116
|
+
source: CODEX_SOURCE,
|
|
117
|
+
agent: 'codex',
|
|
118
|
+
maxLearnings: options.maxLearnings,
|
|
119
|
+
});
|
|
120
|
+
result.queued += 1;
|
|
121
|
+
if (created) result.created += 1;
|
|
122
|
+
} catch {
|
|
123
|
+
// A rollout being written to, or one this user cannot read: never fatal.
|
|
124
|
+
result.unreadable += 1;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses a Codex CLI rollout into the same `ParsedSession` the Claude hook produces.
|
|
3
|
+
*
|
|
4
|
+
* Codex persists one JSONL file per thread under
|
|
5
|
+
* `~/.codex/sessions/YYYY/MM/DD/rollout-<ts>-<id>.jsonl`. Every line is an
|
|
6
|
+
* envelope `{ timestamp, type, payload }`; only two types carry a conversation:
|
|
7
|
+
*
|
|
8
|
+
* session_meta — first line: session id, cwd, and the thread's provenance
|
|
9
|
+
* response_item — the turns, of which only `payload.type === 'message'` is one
|
|
10
|
+
*
|
|
11
|
+
* `reasoning`, `custom_tool_call` and `custom_tool_call_output` items are
|
|
12
|
+
* dropped: the first is model-internal, the others are tool plumbing. The
|
|
13
|
+
* Claude parser drops `tool_result` for the same reason — a learning comes from
|
|
14
|
+
* what was decided, not from the mechanics of getting there.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { lastMessageTime, type ParsedSession, type SessionMessage } from './session-parser.js';
|
|
18
|
+
|
|
19
|
+
export interface CodexRolloutMeta {
|
|
20
|
+
sessionId: string;
|
|
21
|
+
directory?: string;
|
|
22
|
+
/** `user` for a thread you typed into, `subagent` for one Codex spawned itself. */
|
|
23
|
+
threadSource?: string;
|
|
24
|
+
timestamp?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Turns Codex injects into the user side of the transcript: they are context,
|
|
29
|
+
* not something a human said, and encoding them would fill the memory with
|
|
30
|
+
* plugin catalogues and environment dumps.
|
|
31
|
+
*/
|
|
32
|
+
const INJECTED_USER_BLOCK = /^<(environment_context|recommended_plugins|user_instructions|instructions|skills?_context)>/;
|
|
33
|
+
|
|
34
|
+
function textOf(content: unknown): string {
|
|
35
|
+
if (typeof content === 'string') return content;
|
|
36
|
+
if (!Array.isArray(content)) return '';
|
|
37
|
+
return content
|
|
38
|
+
.map((block: any) => (block?.type === 'input_text' || block?.type === 'output_text' ? (block.text ?? '') : ''))
|
|
39
|
+
.filter(Boolean)
|
|
40
|
+
.join('\n');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function lines(raw: string): any[] {
|
|
44
|
+
const parsed: any[] = [];
|
|
45
|
+
for (const line of raw.split('\n')) {
|
|
46
|
+
if (!line.trim()) continue;
|
|
47
|
+
try {
|
|
48
|
+
parsed.push(JSON.parse(line));
|
|
49
|
+
} catch {
|
|
50
|
+
// A rollout being written to is legitimately truncated on its last line.
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return parsed;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Reads the provenance header without walking the whole transcript. */
|
|
57
|
+
export function readCodexRolloutMeta(raw: string): CodexRolloutMeta | null {
|
|
58
|
+
for (const entry of lines(raw)) {
|
|
59
|
+
if (entry?.type !== 'session_meta') continue;
|
|
60
|
+
const payload = entry.payload ?? {};
|
|
61
|
+
return {
|
|
62
|
+
sessionId: payload.session_id ?? payload.id ?? '',
|
|
63
|
+
directory: typeof payload.cwd === 'string' ? payload.cwd : undefined,
|
|
64
|
+
threadSource: payload.thread_source,
|
|
65
|
+
timestamp: payload.timestamp ?? entry.timestamp,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** True when this text is a Codex rollout rather than a Claude hook payload. */
|
|
72
|
+
export function isCodexRollout(raw: string): boolean {
|
|
73
|
+
const first = raw.split('\n').find((line) => line.trim());
|
|
74
|
+
if (!first) return false;
|
|
75
|
+
try {
|
|
76
|
+
const entry = JSON.parse(first);
|
|
77
|
+
return entry?.type === 'session_meta' || entry?.type === 'response_item';
|
|
78
|
+
} catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A thread Codex spawned for itself — judge passes, reviews — is not a lived session. */
|
|
84
|
+
export function isSubagentThread(meta: CodexRolloutMeta | null): boolean {
|
|
85
|
+
return meta?.threadSource === 'subagent';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function parseCodexRollout(raw: string, directory: string): ParsedSession {
|
|
89
|
+
const entries = lines(raw);
|
|
90
|
+
const meta = readCodexRolloutMeta(raw);
|
|
91
|
+
const messages: SessionMessage[] = [];
|
|
92
|
+
|
|
93
|
+
for (const entry of entries) {
|
|
94
|
+
if (entry?.type !== 'response_item') continue;
|
|
95
|
+
const payload = entry.payload ?? {};
|
|
96
|
+
if (payload.type !== 'message') continue;
|
|
97
|
+
// `developer` carries the base instructions, not a turn.
|
|
98
|
+
if (payload.role !== 'user' && payload.role !== 'assistant') continue;
|
|
99
|
+
|
|
100
|
+
const content = textOf(payload.content).trim();
|
|
101
|
+
if (!content) continue;
|
|
102
|
+
if (payload.role === 'user' && INJECTED_USER_BLOCK.test(content)) continue;
|
|
103
|
+
|
|
104
|
+
messages.push({ role: payload.role, content, timestamp: entry.timestamp });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// A sweep can read a rollout weeks after the thread ran: the transcript's own
|
|
108
|
+
// clock is what the trace must be dated by, not the moment of the sweep.
|
|
109
|
+
const metaTime = meta?.timestamp ? new Date(meta.timestamp) : undefined;
|
|
110
|
+
const occurredAt =
|
|
111
|
+
lastMessageTime(messages) ??
|
|
112
|
+
(metaTime && !Number.isNaN(metaTime.getTime()) ? metaTime : undefined);
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
sessionId: meta?.sessionId || `codex-${Date.now()}`,
|
|
116
|
+
directory: meta?.directory || directory,
|
|
117
|
+
messages,
|
|
118
|
+
occurredAt,
|
|
119
|
+
rawText: messages.map((m) => `${m.role}: ${m.content}`).join('\n\n'),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
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
|
+
|
|
16
|
+
import type { Intention, IntentionStore } from '../core/types.js';
|
|
17
|
+
import { extractLoopIds, matchIntentionByShortId, loopId } from '../core/cues.js';
|
|
18
|
+
|
|
19
|
+
export interface CommitInfo {
|
|
20
|
+
sha: string;
|
|
21
|
+
message: string;
|
|
22
|
+
files: string[];
|
|
23
|
+
/** Mental place of the repository — bounds the heuristic to the current project. */
|
|
24
|
+
directory: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface CloseSuggestion {
|
|
28
|
+
intention: Intention;
|
|
29
|
+
score: number;
|
|
30
|
+
/** Tokens shared between the commit's files and the loop's content. */
|
|
31
|
+
matched: string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface CommitCloseResult {
|
|
35
|
+
closed: Intention[];
|
|
36
|
+
suggestions: CloseSuggestion[];
|
|
37
|
+
/** Ids mentioned in the message but unknown or ambiguous. */
|
|
38
|
+
unresolved: string[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Suggestion threshold: at least one meaningful shared token. */
|
|
42
|
+
export const SUGGESTION_THRESHOLD = 1;
|
|
43
|
+
|
|
44
|
+
/** Maximum suggestions shown — beyond that it is noise. */
|
|
45
|
+
export const MAX_SUGGESTIONS = 3;
|
|
46
|
+
|
|
47
|
+
// Words too common to signal anything.
|
|
48
|
+
const STOPWORDS = new Set([
|
|
49
|
+
'dans', 'pour', 'avec', 'sans', 'cette', 'leur', 'plus', 'mais', 'donc',
|
|
50
|
+
'index', 'test', 'tests', 'src', 'lib', 'main', 'temp', 'utils', 'util', 'core',
|
|
51
|
+
'the', 'and', 'for', 'with', 'from', 'that', 'this', 'into',
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
/** Splits a text into meaningful tokens, without accents or case. */
|
|
55
|
+
export function tokenize(text: string): string[] {
|
|
56
|
+
return text
|
|
57
|
+
.normalize('NFD')
|
|
58
|
+
.replace(/[̀-ͯ]/g, '')
|
|
59
|
+
.toLowerCase()
|
|
60
|
+
.split(/[^a-z0-9]+/)
|
|
61
|
+
.filter((t) => t.length >= 4 && !STOPWORDS.has(t));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Tokens drawn from a file path: directory segments plus the name without its extension. */
|
|
65
|
+
export function tokenizePath(path: string): string[] {
|
|
66
|
+
const normalized = path.replace(/\\/g, '/');
|
|
67
|
+
const withoutExt = normalized.replace(/\.[a-z0-9]+$/i, '');
|
|
68
|
+
return [...new Set(tokenize(withoutExt))];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Overlap between a commit's files and a loop's content.
|
|
73
|
+
*
|
|
74
|
+
* Deliberately crude: this score closes nothing, it only ranks suggestions put
|
|
75
|
+
* to a human.
|
|
76
|
+
*/
|
|
77
|
+
export function scoreOverlap(intention: Intention, files: string[]): CloseSuggestion['matched'] {
|
|
78
|
+
const contentTokens = new Set(tokenize(intention.content));
|
|
79
|
+
const matched = new Set<string>();
|
|
80
|
+
|
|
81
|
+
for (const file of files) {
|
|
82
|
+
for (const token of tokenizePath(file)) {
|
|
83
|
+
if (contentTokens.has(token)) matched.add(token);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return [...matched];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Applies a commit to the open loops.
|
|
92
|
+
*
|
|
93
|
+
* Closes the ones named explicitly (and cancels their remaining cues — a cue
|
|
94
|
+
* outliving its loop is a ghost wake-up). For the rest, it only suggests.
|
|
95
|
+
*/
|
|
96
|
+
export async function applyCommitToLoops(
|
|
97
|
+
store: IntentionStore,
|
|
98
|
+
commit: CommitInfo,
|
|
99
|
+
memories?: { verify(id: string, by?: string): Promise<unknown> }
|
|
100
|
+
): Promise<CommitCloseResult> {
|
|
101
|
+
const armed = await store.listIntentions({ status: 'armed', limit: 500 });
|
|
102
|
+
|
|
103
|
+
const closed: Intention[] = [];
|
|
104
|
+
const unresolved: string[] = [];
|
|
105
|
+
const closedIds = new Set<string>();
|
|
106
|
+
|
|
107
|
+
// 1. Explicit markers. Deliberately not bound to the directory: if someone
|
|
108
|
+
// types the id by hand, they know what they are closing.
|
|
109
|
+
for (const shortId of extractLoopIds(commit.message)) {
|
|
110
|
+
const target = matchIntentionByShortId(armed, shortId);
|
|
111
|
+
if (!target) {
|
|
112
|
+
unresolved.push(shortId);
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const intention = await store.updateIntentionStatus(target.id, 'closed', {
|
|
117
|
+
closedByCommit: commit.sha,
|
|
118
|
+
});
|
|
119
|
+
for (const cue of await store.listCues({ intentionId: target.id, status: 'armed' })) {
|
|
120
|
+
await store.updateCueStatus(cue.id, 'cancelled');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Phase 6.0.1 — `grounded` verification: an explicitly-closed loop vouches
|
|
124
|
+
// for the trace it points to. Only this path counts (Claude R1): the fuzzy
|
|
125
|
+
// file-overlap path below only *suggests* and must never become evidence.
|
|
126
|
+
if (intention.relatedMemoryId && memories) {
|
|
127
|
+
await memories.verify(intention.relatedMemoryId, 'grounded');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
closed.push(intention);
|
|
131
|
+
closedIds.add(target.id);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// 2. Heuristic, bounded to the current project and never applied on its own.
|
|
135
|
+
const suggestions = armed
|
|
136
|
+
.filter((i) => !closedIds.has(i.id) && i.directory === commit.directory)
|
|
137
|
+
.map((intention) => ({ intention, matched: scoreOverlap(intention, commit.files) }))
|
|
138
|
+
.map((s) => ({ ...s, score: s.matched.length }))
|
|
139
|
+
.filter((s) => s.score >= SUGGESTION_THRESHOLD)
|
|
140
|
+
.sort((a, b) => b.score - a.score)
|
|
141
|
+
.slice(0, MAX_SUGGESTIONS);
|
|
142
|
+
|
|
143
|
+
return { closed, suggestions, unresolved };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Renders the report printed after a commit. Empty string when there is nothing to say. */
|
|
147
|
+
export function renderCommitReport(result: CommitCloseResult): string {
|
|
148
|
+
const { closed, suggestions, unresolved } = result;
|
|
149
|
+
if (!closed.length && !suggestions.length && !unresolved.length) return '';
|
|
150
|
+
|
|
151
|
+
const lines: string[] = [];
|
|
152
|
+
|
|
153
|
+
for (const i of closed) {
|
|
154
|
+
lines.push(`✅ ${loopId(i.id)} closed — ${i.content}`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
for (const shortId of unresolved) {
|
|
158
|
+
lines.push(`⚠️ loop-${shortId}: no single open loop under that id`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (suggestions.length) {
|
|
162
|
+
lines.push('');
|
|
163
|
+
lines.push('💡 Loops this commit may have touched:');
|
|
164
|
+
for (const { intention, matched } of suggestions) {
|
|
165
|
+
lines.push(` ${loopId(intention.id)} — ${intention.content}`);
|
|
166
|
+
lines.push(` overlaps: ${matched.join(', ')}`);
|
|
167
|
+
}
|
|
168
|
+
lines.push('');
|
|
169
|
+
lines.push(` To close: pnpm cli intent close ${loopId(suggestions[0].intention.id)}`);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return `${lines.join('\n')}\n`;
|
|
173
|
+
}
|