humemory 0.2.4 → 0.2.6

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/dist/cli/index.js CHANGED
@@ -12,6 +12,8 @@ const __dirname = dirname(__filename);
12
12
  // Shared store. HUMEMORY_DB points at another database — same convention as the
13
13
  // hooks, and required to exercise the CLI without touching production.
14
14
  const DB_PATH = process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
15
+ // Same inbox the agent hooks write to — the CLI only ever queues, never encodes.
16
+ const QUEUE_DIR = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
15
17
  let store;
16
18
  function getStore() {
17
19
  if (!store) {
@@ -790,10 +792,96 @@ for (const verb of ['approve', 'reject']) {
790
792
  }
791
793
  });
792
794
  }
795
+ // === MAINTENANCE ===
796
+ const maintenance = program
797
+ .command('maintenance')
798
+ .description('Health of the consolidation loop, and a way to force a pass');
799
+ maintenance
800
+ .command('status', { isDefault: true })
801
+ .description('Is consolidation still running, and when did it last succeed?')
802
+ .option('--json', 'Machine-readable output')
803
+ .option('--stale-after <minutes>', 'Staleness budget before the loop is called overdue', '60')
804
+ .action(async (options) => {
805
+ const { readMaintenanceState, assessMaintenance, defaultStatePath } = await import('../agent/maintenance-state.js');
806
+ const staleAfterMs = Math.max(1, Number(options.staleAfter)) * 60_000;
807
+ const health = assessMaintenance(await readMaintenanceState(defaultStatePath(QUEUE_DIR)), { staleAfterMs });
808
+ if (options.json) {
809
+ console.log(JSON.stringify(health, null, 2));
810
+ }
811
+ else {
812
+ console.log(`\n${health.stale ? '✗' : '✓'} ${health.summary}`);
813
+ if (health.lastRunAt)
814
+ console.log(` last attempt ${health.lastRunAt}`);
815
+ if (health.lastSuccessAt)
816
+ console.log(` last success ${health.lastSuccessAt}`);
817
+ if (health.lastError)
818
+ console.log(` last error ${health.lastError}`);
819
+ if (health.lastResult) {
820
+ const r = health.lastResult;
821
+ console.log(` last counts ${r.processed}/${r.discovered} jobs, ${r.memoriesStored} memories, ${r.failed} failed, ${r.deadLettered} dead-lettered`);
822
+ }
823
+ console.log();
824
+ if (health.stale) {
825
+ console.log('The loop lives in the API process — check that it is running, then `humemory maintenance run`.\n');
826
+ }
827
+ }
828
+ // Non-zero on staleness so a checker can act on it without parsing text.
829
+ if (health.stale)
830
+ process.exitCode = 1;
831
+ });
832
+ maintenance
833
+ .command('run')
834
+ .description('Force one consolidation pass here and now, in this process')
835
+ .option('--skip-codex', 'Do not import codex rollouts first')
836
+ .action(async (options) => {
837
+ const { runMaintenancePass, resolveMaintenanceClient } = await import('../agent/maintenance-runner.js');
838
+ const client = await resolveMaintenanceClient();
839
+ const { worker } = await runMaintenancePass({
840
+ client,
841
+ codexSinceDays: options.skipCodex ? false : undefined,
842
+ runner: 'cli',
843
+ });
844
+ console.log(`✓ ${worker.processed}/${worker.discovered} jobs, ${worker.memoriesStored} memories, ` +
845
+ `${worker.failed} failed, ${worker.deadLettered} dead-lettered${worker.busy ? ' (another worker held the lock)' : ''}`);
846
+ });
793
847
  // === LOCAL AGENT SOURCES ===
794
848
  const sources = program
795
849
  .command('sources')
796
850
  .description('Discover local AI agent runtimes without reading their sessions');
851
+ sources
852
+ .command('import-codex')
853
+ .description('Queue Codex CLI rollouts for maintenance (nothing is encoded until the worker runs)')
854
+ .option('--since <days>', 'Only rollouts touched in the last N days', '7')
855
+ .option('--all', 'Every rollout ever recorded, ignoring --since')
856
+ .option('--limit <n>', 'Stop after N queued sessions')
857
+ .option('--include-subagents', 'Also import threads codex spawned for itself')
858
+ .option('--dry-run', 'Report what would be queued, write nothing')
859
+ .option('--sessions-dir <dir>', 'Override $CODEX_HOME/sessions')
860
+ .action(async (options) => {
861
+ const { importCodexRollouts, defaultCodexSessionsDir } = await import('../agent/codex-import.js');
862
+ const sessionsDir = options.sessionsDir ? resolve(options.sessionsDir) : defaultCodexSessionsDir();
863
+ const days = Number(options.since);
864
+ const since = options.all || !Number.isFinite(days)
865
+ ? undefined
866
+ : new Date(Date.now() - days * 24 * 60 * 60 * 1000);
867
+ console.log(`⏳ Scanning ${sessionsDir}${since ? ` (last ${days} day(s))` : ' (all)'}...`);
868
+ const result = await importCodexRollouts({
869
+ queueDir: QUEUE_DIR,
870
+ sessionsDir,
871
+ since,
872
+ limit: options.limit ? parseInt(options.limit) : undefined,
873
+ includeSubagents: options.includeSubagents,
874
+ dryRun: options.dryRun,
875
+ });
876
+ console.log(`\n${options.dryRun ? 'Would queue' : '✓ Queued'} ${result.queued} session(s)` +
877
+ `${options.dryRun ? '' : ` (${result.created} new)`} out of ${result.scanned} scanned.`);
878
+ console.log(` skipped — ${result.skippedOld} older than the window, ` +
879
+ `${result.skippedSubagent} subagent thread(s), ${result.skippedEmpty} without a turn, ` +
880
+ `${result.unreadable} unreadable`);
881
+ if (!options.dryRun && result.queued > 0) {
882
+ console.log('\nRun `pnpm maintenance` to encode them (or wait for the scheduled pass).');
883
+ }
884
+ });
797
885
  sources
798
886
  .command('discover', { isDefault: true })
799
887
  .description('Show known runtimes and the local evidence found for each one')
@@ -0,0 +1,43 @@
1
+ /**
2
+ * `LLMClient` backed by a local agent CLI instead of a hosted API key.
3
+ *
4
+ * humemory's consolidation path is deterministic and network-free by default;
5
+ * this adapter exists for machines that have no `ANTHROPIC_API_KEY` but do have
6
+ * a logged-in coding agent on the PATH. It is opt-in
7
+ * (`HUMEMORY_MAINTENANCE_LLM=codex`) and every failure falls back to the
8
+ * deterministic extractor upstream, so a missing binary is never fatal.
9
+ *
10
+ * Three flags matter and none of them are cosmetic:
11
+ * --ephemeral no rollout is written under ~/.codex/sessions. Without
12
+ * it, each consolidation leaves a session that humemory
13
+ * would later ingest as a trace — memory eating itself.
14
+ * --ignore-user-config skips the user's skills, plugins and hooks. Cheaper
15
+ * (~2k fewer tokens per call, half the latency) and it
16
+ * stops a humemory Stop hook wired into codex from
17
+ * re-entering humemory while maintenance is running.
18
+ * -s read-only consolidation summarises text; it never needs a write.
19
+ */
20
+ import type { LLMClient } from './llm-generator.js';
21
+ /** Runs one non-interactive agent turn and resolves with its final message. */
22
+ export type CliRunner = (prompt: string, opts: {
23
+ timeoutMs: number;
24
+ }) => Promise<string>;
25
+ export interface CodexClientOptions {
26
+ /** Model id. Unset means the CLI's own default — mini models are rejected on ChatGPT accounts. */
27
+ model?: string;
28
+ /** Wall-clock budget for one turn. Agent start-up alone is several seconds. */
29
+ timeoutMs?: number;
30
+ /** Injected in tests; the default spawns the real `codex` binary. */
31
+ runner?: CliRunner;
32
+ }
33
+ /** Strips the ```json fences a chat-tuned model wraps around structured output. */
34
+ export declare function unfence(text: string): string;
35
+ /** Flattens an Anthropic-shaped request into one prompt string for a CLI turn. */
36
+ export declare function flattenPrompt(params: any): string;
37
+ export declare function codexArgs(outputPath: string, model?: string): string[];
38
+ /**
39
+ * Wraps a coding-agent CLI in the `LLMClient` shape the consolidation path expects.
40
+ * Only the fields `generateMemoryLevels` reads are honoured — this is a duck, not
41
+ * an SDK: no streaming, no tools, no token accounting.
42
+ */
43
+ export declare function createCodexClient(options?: CodexClientOptions): LLMClient;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * `LLMClient` backed by a local agent CLI instead of a hosted API key.
3
+ *
4
+ * humemory's consolidation path is deterministic and network-free by default;
5
+ * this adapter exists for machines that have no `ANTHROPIC_API_KEY` but do have
6
+ * a logged-in coding agent on the PATH. It is opt-in
7
+ * (`HUMEMORY_MAINTENANCE_LLM=codex`) and every failure falls back to the
8
+ * deterministic extractor upstream, so a missing binary is never fatal.
9
+ *
10
+ * Three flags matter and none of them are cosmetic:
11
+ * --ephemeral no rollout is written under ~/.codex/sessions. Without
12
+ * it, each consolidation leaves a session that humemory
13
+ * would later ingest as a trace — memory eating itself.
14
+ * --ignore-user-config skips the user's skills, plugins and hooks. Cheaper
15
+ * (~2k fewer tokens per call, half the latency) and it
16
+ * stops a humemory Stop hook wired into codex from
17
+ * re-entering humemory while maintenance is running.
18
+ * -s read-only consolidation summarises text; it never needs a write.
19
+ */
20
+ import { mkdtempSync, readFileSync, rmSync } from 'fs';
21
+ import { tmpdir } from 'os';
22
+ import { join } from 'path';
23
+ /** Strips the ```json fences a chat-tuned model wraps around structured output. */
24
+ export function unfence(text) {
25
+ const fenced = text.trim().match(/^```(?:json)?\s*\n([\s\S]*?)\n?```$/);
26
+ return (fenced ? fenced[1] : text).trim();
27
+ }
28
+ /** Flattens an Anthropic-shaped request into one prompt string for a CLI turn. */
29
+ export function flattenPrompt(params) {
30
+ const blocks = [];
31
+ const system = params?.system;
32
+ if (typeof system === 'string')
33
+ blocks.push(system);
34
+ else if (Array.isArray(system)) {
35
+ for (const part of system)
36
+ if (typeof part?.text === 'string')
37
+ blocks.push(part.text);
38
+ }
39
+ for (const message of params?.messages ?? []) {
40
+ const content = message?.content;
41
+ if (typeof content === 'string')
42
+ blocks.push(content);
43
+ else if (Array.isArray(content)) {
44
+ for (const part of content)
45
+ if (typeof part?.text === 'string')
46
+ blocks.push(part.text);
47
+ }
48
+ }
49
+ return blocks.join('\n\n');
50
+ }
51
+ export function codexArgs(outputPath, model) {
52
+ return [
53
+ 'exec',
54
+ '--ephemeral',
55
+ '--ignore-user-config',
56
+ '--ignore-rules',
57
+ '--skip-git-repo-check',
58
+ '-s', 'read-only',
59
+ '-c', 'model_reasoning_effort="low"',
60
+ '-c', 'model_verbosity="low"',
61
+ ...(model ? ['-m', model] : []),
62
+ '--color', 'never',
63
+ '-o', outputPath,
64
+ '-',
65
+ ];
66
+ }
67
+ const spawnCodex = async (prompt, { timeoutMs }) => {
68
+ const dir = mkdtempSync(join(tmpdir(), 'humemory-codex-'));
69
+ const outputPath = join(dir, 'last-message.txt');
70
+ try {
71
+ const proc = Bun.spawn(['codex', ...codexArgs(outputPath, process.env.HUMEMORY_LLM_MODEL)], {
72
+ stdin: new TextEncoder().encode(prompt),
73
+ stdout: 'ignore',
74
+ stderr: 'pipe',
75
+ });
76
+ const timer = setTimeout(() => proc.kill(), timeoutMs);
77
+ let code;
78
+ try {
79
+ code = await proc.exited;
80
+ }
81
+ finally {
82
+ clearTimeout(timer);
83
+ }
84
+ if (code !== 0)
85
+ throw new Error(`codex exec exited ${code}: ${(await new Response(proc.stderr).text()).slice(0, 200)}`);
86
+ return readFileSync(outputPath, 'utf-8');
87
+ }
88
+ finally {
89
+ rmSync(dir, { recursive: true, force: true });
90
+ }
91
+ };
92
+ /**
93
+ * Wraps a coding-agent CLI in the `LLMClient` shape the consolidation path expects.
94
+ * Only the fields `generateMemoryLevels` reads are honoured — this is a duck, not
95
+ * an SDK: no streaming, no tools, no token accounting.
96
+ */
97
+ export function createCodexClient(options = {}) {
98
+ const runner = options.runner ?? spawnCodex;
99
+ const timeoutMs = options.timeoutMs ?? 60_000;
100
+ return {
101
+ messages: {
102
+ create: async (params) => {
103
+ const text = await runner(flattenPrompt(params), { timeoutMs });
104
+ return { content: [{ type: 'text', text: unfence(text) }] };
105
+ },
106
+ },
107
+ };
108
+ }
@@ -45,7 +45,15 @@ export declare class SQLiteStore implements MemoryStore, IntentionStore, ScriptS
45
45
  private loadIntoMemory;
46
46
  private rowToMemory;
47
47
  private memoryToRow;
48
- add(memory: Omit<Memory, 'id' | 'createdAt' | 'recallCount' | 'decayRate' | 'currentLevel' | 'saillance'>, options?: {
48
+ /**
49
+ * `createdAt` defaults to now, but a caller encoding an *older* session — a
50
+ * rollout swept days later — passes the instant it was lived. Age is what
51
+ * decay runs on, so a backdated trace arrives already degraded, exactly as if
52
+ * it had been encoded on the day.
53
+ */
54
+ add(memory: Omit<Memory, 'id' | 'createdAt' | 'recallCount' | 'decayRate' | 'currentLevel' | 'saillance'> & {
55
+ createdAt?: Date;
56
+ }, options?: {
49
57
  autoGenerate?: boolean;
50
58
  }): Promise<Memory>;
51
59
  getById(id: string): Promise<Memory | null>;
@@ -493,9 +493,16 @@ export class SQLiteStore {
493
493
  $refuted_count: memory.refutedCount ?? 0,
494
494
  };
495
495
  }
496
+ /**
497
+ * `createdAt` defaults to now, but a caller encoding an *older* session — a
498
+ * rollout swept days later — passes the instant it was lived. Age is what
499
+ * decay runs on, so a backdated trace arrives already degraded, exactly as if
500
+ * it had been encoded on the day.
501
+ */
496
502
  async add(memory, options = {}) {
497
503
  const id = crypto.randomUUID();
498
504
  const now = this.clock.now();
505
+ const createdAt = memory.createdAt ?? now;
499
506
  let generatedLevels = {};
500
507
  if (options.autoGenerate && !memory.level1Summary) {
501
508
  const memType = (memory.memoryType || 'semantic');
@@ -506,11 +513,11 @@ export class SQLiteStore {
506
513
  ...memory,
507
514
  ...generatedLevels,
508
515
  id,
509
- createdAt: now,
516
+ createdAt,
510
517
  recallCount: 0,
511
518
  decayRate: calculateDecayRate(memory.content, memory.keywords),
512
519
  currentLevel: 0,
513
- saillance: calculateSaillance({ ...memory, id, createdAt: now, recallCount: 0, decayRate: 0.5 }, now),
520
+ saillance: calculateSaillance({ ...memory, id, createdAt, recallCount: 0, decayRate: 0.5 }, now),
514
521
  // Phase 6.0.1 — provenance defaults
515
522
  source: memory.source ?? 'agent',
516
523
  verified: memory.verified ?? false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Memory for AI agents that forgets like a human — decaying traces, inverse search, and prospective loops that resurface on a cue",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -88,6 +88,8 @@
88
88
  "cli": "bun run src/cli/index.ts",
89
89
  "consolidate": "bun run scripts/consolidate.js",
90
90
  "maintenance": "bun run scripts/maintenance-worker.ts",
91
+ "maintenance:status": "bun run src/cli/index.ts maintenance status",
92
+ "win:install": "pwsh -File scripts/windows/install.ps1",
91
93
  "dream": "bun run src/cli/index.ts dream",
92
94
  "mcp": "bun run src/mcp/server.ts",
93
95
  "build:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\" && bun build web/index.html --outdir public/app --production --splitting",
@@ -1,29 +1,23 @@
1
1
  #!/usr/bin/env bun
2
- /** One non-blocking maintenance pass over sessions queued by local agent hooks. */
2
+ /**
3
+ * One non-blocking maintenance pass over sessions queued by local agent hooks.
4
+ *
5
+ * The pass itself lives in src/agent/maintenance-runner.ts, shared with the API
6
+ * process, which runs it on a timer. This script stays for manual runs
7
+ * (`pnpm maintenance`) and for a machine that does not keep the API resident.
8
+ */
3
9
 
4
- import Anthropic from '@anthropic-ai/sdk';
5
- import { dirname, join } from 'path';
6
- import { fileURLToPath } from 'url';
7
- import type { LLMClient } from '../src/core/llm-generator.js';
8
- import { processMaintenanceQueue } from '../src/agent/maintenance-queue.js';
10
+ import { runMaintenancePass, resolveMaintenanceClient, defaultLlmTimeoutMs } from '../src/agent/maintenance-runner.js';
9
11
 
10
- const __dirname = dirname(fileURLToPath(import.meta.url));
11
- const queueDir = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../data/maintenance-queue');
12
- const dbPath = process.env.HUMEMORY_DB ?? join(__dirname, '../data/humemory.db');
13
- const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? 'none';
12
+ const llmTimeoutMs = defaultLlmTimeoutMs();
13
+ const client = await resolveMaintenanceClient(llmTimeoutMs);
14
14
 
15
- let client: LLMClient | undefined;
16
- if (provider === 'anthropic' && process.env.ANTHROPIC_API_KEY) {
17
- client = new Anthropic() as unknown as LLMClient;
18
- }
15
+ // --skip-codex for a machine where the rollouts are imported some other way.
16
+ const codexSinceDays = process.argv.includes('--skip-codex')
17
+ ? false as const
18
+ : Number(process.env.HUMEMORY_MAINTENANCE_CODEX_DAYS ?? 1);
19
19
 
20
- const result = await processMaintenanceQueue({
21
- queueDir,
22
- dbPath,
23
- client,
24
- llmTimeoutMs: Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000),
25
- maxJobs: Number(process.env.HUMEMORY_MAINTENANCE_BATCH ?? 20),
26
- });
20
+ const { worker: result } = await runMaintenancePass({ client, llmTimeoutMs, codexSinceDays });
27
21
 
28
22
  if (result.busy) {
29
23
  if (process.env.HUMEMORY_VERBOSE === '1') console.error('[humemory] maintenance: another worker is active');