@agent_memory/dsh 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/plugin.mjs +692 -107
- package/dist/plugin.mjs.map +4 -4
- package/package.json +1 -1
package/dist/plugin.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/plugin.ts", "../../core/src/errors.ts", "../../core/src/paths.ts", "../../core/src/startup.ts", "../../core/src/config/load.ts", "../../core/src/config/toml.ts", "../../core/src/config/schema.ts", "../../core/src/config/config.ts", "../../core/src/policy/policy.ts", "../../core/src/fs/atomic.ts", "../../core/src/fs/wait.ts", "../../core/src/model/frontmatter.ts", "../../core/src/model/metadata.ts", "../../core/src/projects/projects.ts", "../../core/src/fs/lock.ts", "../../core/src/model/ids.ts", "../../core/src/model/validity.ts", "../../core/src/journal/journal.ts", "../../core/src/store/store.ts", "../../core/src/index/tokenizer.ts", "../../core/src/index/bm25.ts", "../../core/src/index/embedding.ts", "../../core/src/index/hybrid.ts", "../../core/src/embed/cache.ts", "../../core/src/scan/scan.ts", "../../core/src/rules/rules.ts", "../../core/src/inject/snapshot.ts", "../../core/src/inject/assemble.ts", "../../core/src/inject/sections.ts", "../../core/src/personalization/guidance.ts", "../../core/src/proposals/proposals.ts", "../../core/src/actor.ts", "../../core/src/service/quota.ts", "../../core/src/distill/closeout.ts", "../../core/src/ops/ops.ts", "../../core/src/profile/profile.ts", "../../core/src/personalization/scaffold.ts", "../../core/src/human/command.ts", "../../core/src/transfer/import.ts", "../src/tools.ts", "../src/review.ts", "../src/personalization.ts", "../src/session-tools.ts", "../src/gui.ts", "../src/service.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * DSH host plugin \u2014 S0 M1 probe.\n *\n * Deliberately tiny: proves the host loads a bundle, gives the model a tool,\n * injects one system-prompt section, and exposes the services the real adapter\n * will rely on (`commands` + `tokenMeter`). It is not the memory service.\n *\n * Contract (ADR-0003): a Host-only bundle exports `apply(ctx, config)`, may\n * declare `inject`, and registers through the context so Cordis owns the\n * disposers. Every service is reached through the context object, which keeps\n * this module loadable from a linked checkout without host node_modules on its\n * resolution path.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport {\n addRejected,\n bindEvidence,\n buildCloseoutPrompt,\n CloseoutRound,\n collectL0,\n createProposal,\n HUMAN_COMMAND_HINT,\n listProposals,\n loadRejected,\n parseCloseout,\n resolveHome,\n runHumanCommand,\n summaryHash,\n type DistillEvent,\n type Proposal,\n type ProposalInput,\n} from '../../core/src/index.ts';\nimport { registerTools } from './tools.ts';\nimport { reviewProposal, type ReviewExecLike, type UserQuestionsLike } from './review.ts';\nimport { registerUserProfileTool } from './personalization.ts';\nimport { registerSessionTools, type SessionQueryLike } from './session-tools.ts';\nimport { registerGuiRoutes, type GuiConnection } from './gui.ts';\nimport { openHostService, type SessionStoreLike } from './service.ts';\n\nexport const name = 'agent-memory';\nexport const inject = ['tools'];\n\nconst SECTION_NAME = 'agent-memory:probe';\nconst PROBE_LINE =\n 'Agent Memory probe is active. If the user sends exactly \"am-probe\", reply exactly \"am-probe-ok\".';\n\nexport interface ToolDefinitionLike {\n readonly name: string;\n readonly description: string;\n readonly parameters: unknown;\n readonly output: {\n readonly schema: unknown;\n readonly render: (args: unknown, value: unknown) => unknown;\n };\n readonly execute: (args: any, exec: any) => unknown;\n}\n\nexport interface ToolRegistryLike {\n register(definition: ToolDefinitionLike): unknown;\n}\n\nexport interface PromptRegistryLike {\n section(spec: {\n readonly name: string;\n readonly order: number;\n readonly text: string;\n readonly interpolate?: boolean;\n }): unknown;\n}\n\nexport interface CommandsLike {\n register(spec: {\n readonly name: string;\n readonly description: string;\n readonly input?: { readonly hint: string };\n readonly handler: (invocation: any) => unknown;\n }): unknown;\n execute?(\n agent: unknown,\n line: string,\n attachments: readonly unknown[],\n signal: AbortSignal,\n ): Promise<{ readonly result: { readonly kind?: string; readonly text?: string } } | undefined>;\n}\n\nexport interface TokenMeterLike {\n measure(session: unknown): { readonly totalTokens?: number; readonly surfaceTokens?: number };\n}\n\nexport interface PluginContextLike {\n readonly tools: ToolRegistryLike;\n get?(name: string): unknown;\n readonly systemPrompt?: PromptRegistryLike;\n readonly commands?: CommandsLike;\n readonly tokenMeter?: TokenMeterLike;\n}\n\n/**\n * Resolve an optional service without touching an undeclared property.\n *\n * Cordis throws \"cannot get property X without inject\" on a bare `ctx.X`\n * access, so `ctx.get(name)` is tried first (the same lookup YAML `!!js`\n * expressions use). The direct property access stays as a fallback for\n * contexts without `get`, guarded because it can throw for the same reason.\n */\nfunction service<T>(ctx: PluginContextLike, name: string): T | undefined {\n try {\n const resolved = ctx.get?.(name);\n if (resolved !== undefined) return resolved as T;\n } catch {\n // fall through to the guarded property access\n }\n try {\n const direct = (ctx as unknown as Record<string, unknown>)[name];\n return direct === undefined ? undefined : (direct as T);\n } catch {\n return undefined;\n }\n}\n\nfunction eventTextOf(data: unknown): string {\n if (typeof data !== 'object' || data === null) return '';\n const record = data as { content?: unknown; text?: unknown };\n if (Array.isArray(record.content)) {\n return record.content\n .map((block) =>\n typeof block === 'object' && block !== null && typeof (block as { text?: unknown }).text === 'string'\n ? (block as { text: string }).text\n : '',\n )\n .filter((text) => text !== '')\n .join('\\n');\n }\n return typeof record.text === 'string' ? record.text : '';\n}\n\nfunction eventsOf(sessions: SessionStoreLike | undefined, sessionId: string): DistillEvent[] {\n const live = sessions?.get(sessionId);\n if (live === undefined) return [];\n const events: DistillEvent[] = [];\n for (let seq = 0; seq < (live.seq ?? 0); seq += 1) {\n const event = live.eventAt(seq);\n if (event === undefined) continue;\n const speaker = event.type.startsWith('assistant')\n ? 'assistant'\n : event.type.startsWith('tool')\n ? 'tool'\n : event.type.startsWith('system')\n ? 'system'\n : 'user';\n events.push({ seq: event.seq, speaker, text: eventTextOf(event.data) });\n }\n return events;\n}\n\nexport function apply(ctx: PluginContextLike): void {\n // S4: real tool surface + injection when a store is configured. If startup\n // fails (no home, bad policy, sealed file changed) fall back to the probe so a\n // broken store never takes the host down.\n const home = resolveHome({ env: process.env });\n // Cordis forbids undeclared service property reads; go through the guarded\n // resolver (ctx.get first) so a composition without a session still loads.\n const sessionService = service<{ id?: string }>(ctx, 'session');\n const sessionId = sessionService?.id ?? `dsh-${process.pid}`;\n const persistence = service<import('./service.ts').SessionPersistenceLike>(ctx, 'sessionPersistence');\n const sessions = service<import('./service.ts').SessionStoreLike>(ctx, 'sessions');\n let startupFailure: string | undefined;\n const host = openHostService(\n home,\n {\n sessionId,\n ...(persistence === undefined ? {} : { persistence }),\n ...(sessions === undefined ? {} : { sessions }),\n },\n {\n onFailure: (error) => {\n const formatted = error as { format?: () => string; message?: string };\n startupFailure = typeof formatted.format === 'function' ? formatted.format() : (formatted.message ?? String(error));\n },\n },\n );\n if (host !== null) {\n // Registration-time services (the command plane). Interaction services are\n // resolved per call: Cordis may not have activated the provider fiber yet\n // when this plugin applies, and `userQuestions` (Typert) comes up later.\n const commands = service<CommandsLike>(ctx, 'commands');\n const resolveQuestions = (): UserQuestionsLike | undefined =>\n service<UserQuestionsLike>(ctx, 'userQuestions');\n const resolveCommands = (): CommandsLike | undefined => service<CommandsLike>(ctx, 'commands');\n const reviewDeps = () => {\n const userQuestions = resolveQuestions();\n const commandsNow = resolveCommands();\n return {\n store: host.store,\n config: host.runtime.config,\n home,\n ...(userQuestions === undefined ? {} : { userQuestions }),\n ...(commandsNow === undefined ? {} : { commands: commandsNow }),\n };\n };\n // Module health (architecture v2 P0.5): one failing optional module must\n // not take the others down. `/api/agent-memory/status` exposes this list.\n const moduleHealth: { name: string; ok: boolean; error?: string }[] = [];\n const guard = (name: string, run: () => void): void => {\n try {\n run();\n moduleHealth.push({ name, ok: true });\n } catch (error) {\n moduleHealth.push({\n name,\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n // S9 review card: propose opens a Chinese button card and the click runs\n // `/mem decide \u2026`; the model never supplies the verdict (ADR-0012).\n registerTools(ctx as never, host, { sessionId, delegationDepth: 0 }, undefined, {\n reviewProposal: (proposal, exec) =>\n reviewProposal(reviewDeps(), proposal as Proposal, exec as ReviewExecLike | undefined),\n reviewPending: async (proposalId, exec) => {\n const pending = listProposals(host.store);\n const proposal =\n proposalId === undefined ? pending[0] : pending.find((entry) => entry.id === proposalId);\n if (proposal === undefined) {\n throw new Error(\n proposalId === undefined ? '\u5F53\u524D\u6CA1\u6709\u5F85\u5BA1\u63D0\u6848' : `\u6CA1\u6709\u5F85\u5BA1\u63D0\u6848 ${proposalId}\uFF08\u53EF\u80FD\u5DF2\u88AB\u51B3\u5B9A\u6216\u4F5C\u5E9F\uFF09`,\n );\n }\n return reviewProposal(reviewDeps(), proposal, exec as ReviewExecLike | undefined);\n },\n });\n // P1: USER.md profile tool (read always; writes need a prior read + card).\n const readSessions = new Set<string>();\n guard('user-profile', () =>\n registerUserProfileTool(ctx as never, {\n home,\n store: host.store,\n resolveQuestions,\n mode: host.mode,\n readSessions,\n }),\n );\n // P2: session-history tools over the host's native sessionQuery service.\n guard('session-tools', () =>\n registerSessionTools(ctx as never, {\n resolveQuery: () => service<SessionQueryLike>(ctx, 'sessionQuery'),\n sessionId,\n }),\n );\n // V2 GUI routes: status/list/item/search/export. Exact routes own their\n // full `/api/...` path (see dsh-api-session-controller).\n const effectful = ctx as unknown as {\n effect?: (install: () => unknown, label?: string) => unknown;\n };\n const effect = (install: () => unknown, label?: string): unknown =>\n typeof effectful.effect === 'function' ? effectful.effect(install, label) : install();\n const installRoutes = (connection: GuiConnection): void => {\n registerGuiRoutes(\n connection,\n { store: host.store, home, mode: host.mode, modules: moduleHealth, config: host.runtime.config },\n effect,\n );\n try {\n host.store.appendAudit({ event: 'gui-route', state: 'registered', path: '/api/agent-memory/*' });\n } catch {\n // Journal problems are reported by `mem doctor`.\n }\n };\n const connectionNow = service<GuiConnection>(ctx, 'connection');\n if (connectionNow !== undefined) installRoutes(connectionNow);\n else {\n (ctx as unknown as {\n inject?: (deps: string[], callback: (child: unknown) => void) => unknown;\n }).inject?.(['connection'], (child) => {\n // The injected child is a Context; the service hangs off `.connection`,\n // not off the child itself.\n const connection = (child as { connection?: GuiConnection }).connection;\n if (connection !== undefined) installRoutes(connection);\n });\n }\n try {\n host.store.appendAudit({\n event: 'gui-route',\n path: '/api/agent-memory/*',\n at: connectionNow !== undefined ? 'apply' : 'deferred',\n });\n } catch {\n // A journal problem is reported by `mem doctor`; the panel can still load.\n }\n guard('injection', () => {\n const prompt = service<PromptRegistryLike>(ctx, 'systemPrompt');\n for (const section of host.assembleSections()) prompt?.section(section);\n });\n\n // S6 closeout: `/closeout` opens a round, registers `closeout_submit` only\n // for that round, and disposes it after submit (or when a new round opens).\n type RoundEntry = { round: CloseoutRound; dispose: (() => void) | undefined };\n const rounds = new Map<string, RoundEntry>();\n const rejected = loadRejected(home);\n\n const disposeRound = (id: string): void => {\n const entry = rounds.get(id);\n if (entry === undefined) return;\n entry.round.dispose();\n entry.dispose?.();\n rounds.delete(id);\n };\n\n // S8 human command plane: the CLI-level operations run from the chat box.\n // Commands execute in the UI plane, never as a model message, and `decide`\n // is still not a tool (ADR-0011).\n commands?.register({\n name: 'mem',\n description: 'Agent Memory\uFF1A\u5BA1\u63D0\u6848\u3001\u91C7\u7EB3/\u5426\u51B3\u3001\u5199\u5165\u3001\u67E5\u770B\u4E0E\u8FD0\u7EF4\uFF08\u4EBA\u64CD\u4F5C\uFF09',\n input: { hint: HUMAN_COMMAND_HINT },\n handler: (invocation: { rawInput?: string }) => {\n const result = runHumanCommand(\n { store: host.store, config: host.runtime.config, home },\n invocation.rawInput ?? '',\n );\n return { kind: result.ok ? 'success' : 'error', text: result.text };\n },\n });\n commands?.register({\n name: 'closeout',\n description: 'Run one closeout distillation round over the current session.',\n handler: (invocation: {\n agent?: { session?: { id?: string }; followup?: (input: unknown) => unknown };\n }) => {\n const sid = invocation.agent?.session?.id ?? sessionId;\n disposeRound(sid);\n const round = new CloseoutRound({ timeoutMs: 300_000 });\n const definition = {\n name: 'closeout_submit',\n description: 'Submit the closeout distillation JSON for the current round.',\n parameters: {\n type: 'object',\n properties: { payload: { type: 'object' } },\n required: ['payload'],\n additionalProperties: false,\n },\n output: {\n schema: { type: 'object' },\n render: (_args: unknown, value: unknown) => [\n { type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) },\n ],\n },\n execute: async (args: { payload?: unknown }, exec?: { agent?: { session?: { id?: string } } }) => {\n const callSid = exec?.agent?.session?.id ?? sid;\n const entry = rounds.get(callSid);\n if (entry === undefined || entry.round.status !== 'open') {\n throw new Error('no active closeout round');\n }\n const accepted = entry.round.submit();\n if (!accepted.ok) throw new Error(accepted.error);\n\n const events = eventsOf(sessions, callSid);\n const active = host.store.active();\n const parsed = parseCloseout(JSON.stringify(args.payload ?? {}), {\n events,\n activeIds: active.map((doc) => doc.id),\n activeAbstracts: active.map((doc) => doc.abstract),\n rejectedHashes: rejected,\n maxProposals: host.runtime.config.distill.max_proposals,\n });\n const created: string[] = [];\n const hashes: string[] = [];\n const eventsBySeq = new Map(events.map((event) => [event.seq, event]));\n for (const candidate of parsed.candidates) {\n const base_hashes = candidate.targets.map((id) => host.store.read(id).content_hash);\n const input: ProposalInput =\n candidate.op === 'delete'\n ? {\n op: 'delete',\n target: candidate.targets[0] as string,\n base_hash: base_hashes[0] as string,\n reason: candidate.reason,\n }\n : {\n op: 'supersede',\n targets: candidate.targets,\n base_hashes,\n replacements: candidate.replacements.map((replacement) => ({\n kind: replacement.kind,\n abstract: replacement.abstract,\n body: replacement.body,\n evidence_level: 'observed',\n provenance: replacement.evidence.map((entry) =>\n bindEvidence({\n sessionId: callSid,\n eventSeq: entry.event_seq,\n quote: entry.quote,\n lookup: () => eventsBySeq.get(entry.event_seq),\n }),\n ),\n })),\n reason: candidate.reason,\n };\n created.push(createProposal({ store: host.store, config: host.runtime.config }, input).id);\n const hash = summaryHash(candidate);\n hashes.push(hash);\n rejected.add(hash);\n }\n if (hashes.length > 0) addRejected(home, hashes);\n disposeRound(callSid);\n return { created, dropped: parsed.dropped, message: parsed.message, truncated: parsed.truncated };\n },\n };\n const dispose = ctx.tools.register(definition as never);\n rounds.set(sid, { round, dispose: typeof dispose === 'function' ? (dispose as () => void) : undefined });\n\n const prompt = buildCloseoutPrompt({\n l0: collectL0(eventsOf(sessions, sid)),\n active: host.store.active().map((doc) => ({ id: doc.id, kind: doc.kind, abstract: doc.abstract })),\n maxProposals: host.runtime.config.distill.max_proposals,\n });\n // CommandResult must be returned synchronously; `followup` only queues.\n void invocation.agent?.followup?.({\n id: randomUUID(),\n role: 'user',\n content: [{ type: 'text', text: prompt }],\n source: { kind: 'user' },\n });\n return { kind: 'success', text: 'closeout round started' };\n },\n });\n\n // V3.2 retrospective commands: each queues one model turn that reviews the\n // current development round and proposes new entries of one kind. The\n // proposal is human-approved; the model never writes directly.\n const retroPrompt = (kind: 'fact' | 'pitfall' | 'exp', label: string): string =>\n [\n `\u4F60\u6B63\u5728\u6267\u884C\u300CAgent Memory \u56DE\u987E\u300D\uFF1A\u53EA\u56DE\u987E\u5F53\u524D\u8FD9\u4E00\u8F6E\u5F00\u53D1\uFF08\u4ECE\u672C\u8F6E\u7528\u6237\u8BF7\u6C42\u5F00\u59CB\uFF0C\u5230\u73B0\u5728\u7684\u5BF9\u8BDD\u3001\u5DE5\u5177\u8C03\u7528\u4E0E\u4EE3\u7801\u6539\u52A8\uFF09\u3002`,\n `\u8BF7\u63D0\u70BC\u672C\u8F6E\u771F\u6B63\u53D1\u751F\u3001\u503C\u5F97\u957F\u671F\u4FDD\u7559\u7684\u300C${label}\u300D\uFF0C\u6700\u591A 3 \u6761\u3002`,\n '',\n '\u8981\u6C42\uFF1A',\n `1. \u53EA\u5199\u300C${label}\u300D\uFF0C\u4E0D\u8981\u6DF7\u5165\u5176\u4ED6\u7C7B\u578B\uFF1B\u6CA1\u6709\u5C31\u76F4\u8BF4\u300C\u672C\u8F6E\u6682\u65E0${label}\u300D\uFF0C\u4E0D\u8981\u7F16\u9020\u3002`,\n '2. \u5FC5\u987B\u57FA\u4E8E\u771F\u5B9E\u4E0A\u4E0B\u6587\uFF1B\u5148\u7528 memory_context \u53D6\u6700\u8FD1\u4E8B\u4EF6\uFF0C\u62FF\u5230\u771F\u5B9E\u7684 event_seq \u4E0E\u5F15\u6587\u3002',\n `3. \u8C03\u7528 memory_propose\uFF1Aop=\"create\"\uFF0Creplacements \u4E2D\u653E kind=\"${kind}\"\u3001abstract\uFF08\u4E00\u53E5\u8BDD\uFF0C\u4E0D\u8D85\u8FC7 40 \u5B57\uFF09\u3001body\u3001evidence:[{event_seq, quote}]\u3002`,\n '4. \u521B\u5EFA\u540E\u53EA\u56DE\u590D\u4E00\u53E5\uFF1A\u63D0\u6848\u540D/\u6570\u91CF + \u300C\u53BB\u300E\u8BB0\u5FC6 \u2192 \u63D0\u6848\u300F\u5BA1\u6279\u300D\u3002\u4E0D\u8981\u66FF\u4EBA\u91C7\u7EB3\u3002',\n '5. \u4E0D\u8981\u4FEE\u6539 RULES\u3001\u4E0D\u8981\u5199 SOUL\uFF0C\u4E5F\u4E0D\u8981\u8C03\u7528 memory_record\u3002',\n '',\n `\u672C\u8F6E\u7ED3\u675F\uFF08\u7528\u6237\u6267\u884C\u4E86 /mem-${kind}\uFF09\u3002`,\n ].join('\\n');\n\n const registerRetro = (kind: 'fact' | 'pitfall' | 'exp', label: string): void => {\n commands?.register({\n name: `mem-${kind}`,\n description: `\u56DE\u987E\u672C\u8F6E\u5F00\u53D1\uFF0C\u63D0\u70BC${label}\u5E76\u63D0\u6848\u65B0\u589E\uFF08\u4EBA\u5BA1\u6279\uFF09`,\n handler: (invocation: { agent?: { followup?: (input: unknown) => unknown } }) => {\n void invocation.agent?.followup?.({\n id: randomUUID(),\n role: 'user',\n content: [{ type: 'text', text: retroPrompt(kind, label) }],\n source: { kind: 'user' },\n });\n return { kind: 'success', text: `\u5DF2\u5F00\u59CB\u56DE\u987E\u672C\u8F6E ${label}\uFF0C\u7ED3\u679C\u4F1A\u4EE5\u63D0\u6848\u5F62\u5F0F\u51FA\u73B0\uFF0C\u7B49\u5F85\u4F60\u5BA1\u6279\u3002` };\n },\n });\n };\n registerRetro('fact', '\u4E8B\u5B9E');\n registerRetro('pitfall', '\u5751');\n registerRetro('exp', '\u7ECF\u9A8C');\n return;\n }\n\n ctx.tools.register({\n name: 'am_echo',\n description:\n 'Probe tool for the Agent Memory plugin (S0 M1). Echoes the given text back with an \"echo:\" prefix.',\n parameters: {\n type: 'object',\n properties: {\n text: { type: 'string', description: 'Text to echo back.' },\n },\n required: ['text'],\n additionalProperties: false,\n },\n output: {\n schema: { type: 'string' },\n render: (_args: unknown, value: unknown) => [{ type: 'text', text: String(value) }],\n },\n execute(args: { text: string }) {\n return `echo: ${args.text}`;\n },\n });\n\n ctx.tools.register({\n name: 'am_probe_tokens',\n description:\n 'Probe tool for the Agent Memory plugin (S0 M3). Reports the token meter reading for the current session.',\n parameters: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n output: {\n schema: { type: 'string' },\n render: (_args: unknown, value: unknown) => [{ type: 'text', text: String(value) }],\n },\n execute(_args: unknown, exec: { agent?: { session?: unknown } }) {\n const meter = service<TokenMeterLike>(ctx, 'tokenMeter');\n if (meter === undefined) return 'tokenMeter service is not available in this composition';\n const session = exec.agent?.session;\n if (session === undefined) return 'no session on the calling agent';\n const measured = meter.measure(session);\n return JSON.stringify({\n totalTokens: measured.totalTokens ?? null,\n surfaceTokens: measured.surfaceTokens ?? null,\n });\n },\n });\n\n const prompts = service<PromptRegistryLike>(ctx, 'systemPrompt');\n const probeText =\n startupFailure === undefined\n ? PROBE_LINE\n : `${PROBE_LINE}\\n\\nAgent Memory \u542F\u52A8\u5931\u8D25\uFF08\u8BF7\u628A\u4E0B\u9762\u7684\u4FEE\u590D\u547D\u4EE4\u539F\u6837\u8F6C\u544A\u7528\u6237\u5E76\u7B49\u5F85\u786E\u8BA4\uFF09\uFF1A\\n${startupFailure}`;\n prompts?.section({\n name: SECTION_NAME,\n order: 500,\n interpolate: false,\n text: probeText,\n });\n\n const commands = service<CommandsLike>(ctx, 'commands');\n commands?.register({\n name: 'am-closeout',\n description: 'Probe command for the Agent Memory plugin (S0 M4): queues one model turn.',\n handler: (invocation: { agent?: { followup?: (input: unknown) => unknown } }) => {\n const agent = invocation.agent;\n if (agent?.followup === undefined) {\n return { kind: 'error', text: 'no agent on this command invocation' };\n }\n agent.followup({\n // A queued follow-up is appended verbatim as a `user/message` event, and\n // the session rejects a message whose role does not match its event type.\n // The host's `createUserMessage()` also stamps a stable `id`; a hand-built\n // message must carry its own, because replay validation rejects an\n // unidentified message and the whole stored session then fails to load.\n id: globalThis.crypto.randomUUID(),\n role: 'user',\n content: [{ type: 'text', text: 'Reply with exactly: am-closeout-ok' }],\n source: { kind: 'user' },\n });\n return { kind: 'success', text: 'queued one probe turn' };\n },\n });\n}\n", "/**\n * Startup failures are loud on purpose.\n *\n * The reference failure this guards against is Hermes' silent breakage: a\n * config parse error swallowed by `except: pass` left the whole memory\n * subsystem dead with no message (see docs/research/06 \u00A7L3). Nothing in this\n * package may degrade silently at startup.\n */\n\nexport type StartupFailureCode =\n | 'CONFIG_INVALID'\n | 'CONFIG_UNREADABLE'\n | 'POLICY_MISSING'\n | 'POLICY_INVALID'\n | 'POLICY_MISMATCH'\n | 'SEALED_FILE_MISMATCH'\n | 'HOME_INVALID'\n | 'SEAL_REFUSED';\n\nexport interface StartupFailureInit {\n /** Ordered, printable detail lines (each already formatted). */\n readonly details?: readonly string[];\n /** One-line next step for a human. */\n readonly hint?: string;\n /** Exact command that repairs this failure; printed highlighted by `format()`. */\n readonly fixCommand?: string;\n /** Machine-readable offending keys, for tests and tooling. */\n readonly keys?: readonly string[];\n /** File the failure came from, when there is one. */\n readonly sourcePath?: string;\n}\n\nexport class StartupError extends Error {\n readonly code: StartupFailureCode;\n readonly details: readonly string[];\n readonly hint: string | undefined;\n readonly fixCommand: string | undefined;\n readonly keys: readonly string[];\n readonly sourcePath: string | undefined;\n\n constructor(code: StartupFailureCode, message: string, init: StartupFailureInit = {}) {\n super(message);\n this.name = 'StartupError';\n this.code = code;\n this.details = init.details ?? [];\n this.hint = init.hint;\n this.fixCommand = init.fixCommand;\n this.keys = init.keys ?? [];\n this.sourcePath = init.sourcePath;\n }\n\n /** Multi-line text for a terminal; never truncated, never prettified away. */\n format(): string {\n const lines = [`Agent Memory startup failed [${this.code}]: ${this.message}`];\n if (this.sourcePath !== undefined) lines.push(` file: ${this.sourcePath}`);\n for (const detail of this.details) lines.push(` - ${detail}`);\n if (this.fixCommand !== undefined) {\n // Deliberately loud: the human must see the exact repair command even when\n // this text is shown inside a desktop card or a chat transcript.\n lines.push('', ' ================ REQUIRED ACTION ================');\n lines.push(` >>> RUN THIS COMMAND: ${this.fixCommand}`);\n lines.push(' ===================================================');\n }\n if (this.hint !== undefined) lines.push(` hint: ${this.hint}`);\n return lines.join('\\n');\n }\n}\n\nexport class ConfigError extends StartupError {\n readonly problems: readonly ConfigProblem[];\n\n constructor(sourcePath: string, problems: readonly ConfigProblem[], hint?: string) {\n const sorted = [...problems].sort((a, b) => a.key.localeCompare(b.key));\n const count = sorted.length;\n super(\n 'CONFIG_INVALID',\n `configuration rejected (${count} problem${count === 1 ? '' : 's'})`,\n {\n sourcePath,\n keys: sorted.map((problem) => problem.key),\n details: sorted.map(formatProblem),\n ...(hint === undefined ? {} : { hint }),\n },\n );\n this.name = 'ConfigError';\n this.problems = sorted;\n }\n}\n\nexport interface ConfigProblem {\n readonly key: string;\n readonly message: string;\n readonly line?: number;\n}\n\nexport function formatProblem(problem: ConfigProblem): string {\n const prefix = problem.line === undefined ? '' : `line ${problem.line} | `;\n return `${prefix}${problem.message}`;\n}\n", "import { homedir } from 'node:os';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport { StartupError } from './errors.ts';\n\n/**\n * Where the store lives, and nothing else.\n *\n * The data directory is meant to sit outside the agent's tool sandbox (`06`\n * \u00A7L0): under DSH's `workspace-write` policy, tool writes outside the workspace\n * are refused. That is a tool-layer boundary, not OS-level isolation \u2014 the host\n * process can still read the path, and S0 has to confirm the boundary for the\n * pinned DSH version. The path here is host-side truth, never model input.\n */\n\nconst WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\\..*)?$/i;\n\n/** Reject paths a Windows filesystem cannot represent or that name devices. */\nexport function assertSafeHome(home: string): void {\n if (!isAbsolute(home)) {\n throw new StartupError('HOME_INVALID', 'the store path must be absolute', {\n sourcePath: home,\n hint: 'pass --home with an absolute path, or set AGENT_MEMORY_HOME',\n });\n }\n const segments = home.split(/[\\\\/]+/).filter((segment) => segment !== '');\n const dataSegments = segments[0]?.endsWith(':') === true ? segments.slice(1) : segments;\n for (const segment of dataSegments) {\n if (WINDOWS_RESERVED.test(segment)) {\n throw new StartupError('HOME_INVALID', `the store path contains a reserved Windows name: ${segment}`, {\n sourcePath: home,\n hint: 'choose a different --home',\n });\n }\n if (segment.includes(':')) {\n throw new StartupError('HOME_INVALID', `the store path contains an invalid segment: ${segment}`, {\n sourcePath: home,\n hint: 'colons are only allowed in the drive prefix',\n });\n }\n }\n}\n\nexport interface EnvLike {\n readonly [key: string]: string | undefined;\n}\n\nexport interface MemoryPaths {\n readonly home: string;\n readonly configFile: string;\n readonly projectsFile: string;\n readonly policyFile: string;\n readonly sealFile: string;\n readonly lockFile: string;\n readonly soulFile: string;\n readonly userFile: string;\n readonly rulesFile: string;\n readonly memoryIndexFile: string;\n readonly memoriesDir: string;\n readonly proposalsDir: string;\n readonly pendingDir: string;\n readonly indexDir: string;\n readonly manifestFile: string;\n readonly stateDir: string;\n readonly journalDir: string;\n readonly txnDir: string;\n readonly snapshotsDir: string;\n}\n\nexport function memoryPaths(home: string): MemoryPaths {\n return {\n home,\n configFile: join(home, 'config.toml'),\n projectsFile: join(home, 'projects.json'),\n policyFile: join(home, 'policy.json'),\n sealFile: join(home, '.state', 'policy.seal.json'),\n lockFile: join(home, '.state', 'lock'),\n soulFile: join(home, 'SOUL.md'),\n userFile: join(home, 'USER.md'),\n rulesFile: join(home, 'RULES.md'),\n memoryIndexFile: join(home, 'MEMORY.md'),\n memoriesDir: join(home, 'memories'),\n proposalsDir: join(home, 'proposals'),\n pendingDir: join(home, 'proposals', 'pending'),\n indexDir: join(home, '.index'),\n manifestFile: join(home, '.index', 'manifest.json'),\n stateDir: join(home, '.state'),\n journalDir: join(home, '.state', 'journal'),\n txnDir: join(home, '.state', 'txn'),\n snapshotsDir: join(home, '.state', 'snapshots'),\n };\n}\n\n/** Directories `mem init` creates (v1.3 layout: one journal, no audit file). */\nexport function layoutDirectories(paths: MemoryPaths): string[] {\n return [\n paths.home,\n join(paths.memoriesDir, 'fact'),\n join(paths.memoriesDir, 'pitfall'),\n join(paths.memoriesDir, 'exp'),\n paths.proposalsDir,\n paths.pendingDir,\n paths.indexDir,\n paths.stateDir,\n paths.journalDir,\n paths.txnDir,\n paths.snapshotsDir,\n ];\n}\n\n/**\n * Resolution order: explicit option \u2192 AGENT_MEMORY_HOME \u2192 DSH_HOME/memory \u2192\n * ~/.dsh/memory. Relative paths resolve against the working directory.\n */\nexport function resolveHome(options: { home?: string; env?: EnvLike; cwd?: string } = {}): string {\n const cwd = options.cwd ?? process.cwd();\n const explicit = options.home ?? options.env?.AGENT_MEMORY_HOME;\n if (explicit !== undefined && explicit.trim() !== '') {\n return isAbsolute(explicit) ? explicit : resolve(cwd, explicit);\n }\n const dshHome = options.env?.DSH_HOME;\n if (dshHome !== undefined && dshHome.trim() !== '') {\n return join(isAbsolute(dshHome) ? dshHome : resolve(cwd, dshHome), 'memory');\n }\n return join(homedir(), '.dsh', 'memory');\n}\n", "import { existsSync, statSync } from 'node:fs';\nimport { loadConfig } from './config/load.ts';\nimport type { Config } from './config/config.ts';\nimport { ConfigError, StartupError, type ConfigProblem } from './errors.ts';\nimport { memoryPaths, assertSafeHome, resolveHome, type EnvLike, type MemoryPaths } from './paths.ts';\nimport { loadPolicy, verifySealedFiles, type Policy } from './policy/policy.ts';\n\n/**\n * The one startup path. Everything loud about configuration lives here:\n *\n * 1. the store must exist (missing store = loud error, not silent defaults);\n * 2. policy.json must match its seal (tampering = refusal to start);\n * 3. config.toml must validate (unknown keys are refused, named);\n * 4. config may tighten policy bounds, never widen them.\n */\n\nexport interface StartupOptions {\n readonly home?: string;\n readonly configPath?: string;\n readonly env?: EnvLike;\n readonly cwd?: string;\n}\n\nexport interface Runtime {\n readonly home: string;\n readonly paths: MemoryPaths;\n readonly config: Config;\n readonly policy: Policy;\n readonly configPath: string | null;\n readonly policyPath: string;\n readonly sealPath: string;\n readonly policySha256: string;\n readonly sealedAt: string;\n readonly warnings: readonly string[];\n}\n\nexport function startup(options: StartupOptions = {}): Runtime {\n const home = resolveHome({\n home: options.home,\n env: options.env,\n cwd: options.cwd,\n });\n\n assertSafeHome(home);\n\n let isDirectory = false;\n try {\n isDirectory = statSync(home).isDirectory();\n } catch {\n isDirectory = false;\n }\n if (!isDirectory) {\n throw new StartupError('HOME_INVALID', 'the memory store does not exist', {\n sourcePath: home,\n hint: 'run `mem init` (or set AGENT_MEMORY_HOME / DSH_HOME) before starting',\n });\n }\n\n const loadedPolicy = loadPolicy({ home });\n verifySealedFiles({ home, policy: loadedPolicy.policy });\n const loadedConfig = loadConfig({\n home,\n configPath: options.configPath,\n env: options.env,\n cwd: options.cwd,\n });\n\n const paths = memoryPaths(home);\n const boundsProblems = checkPolicyBounds(loadedConfig.config, loadedPolicy.policy);\n if (boundsProblems.length > 0) {\n throw new ConfigError(\n loadedConfig.configPath ?? paths.configFile,\n boundsProblems,\n 'config.toml may tighten policy.json, never widen it',\n );\n }\n\n const warnings = [...loadedConfig.warnings, ...missingContentWarnings(paths)];\n\n return {\n home,\n paths,\n config: loadedConfig.config,\n policy: loadedPolicy.policy,\n configPath: loadedConfig.configPath,\n policyPath: loadedPolicy.policyPath,\n sealPath: loadedPolicy.sealPath,\n policySha256: loadedPolicy.sha256,\n sealedAt: loadedPolicy.sealedAt,\n warnings,\n };\n}\n\nfunction checkPolicyBounds(config: Config, policy: Policy): ConfigProblem[] {\n const problems: ConfigProblem[] = [];\n if (config.storage.max_records > policy.capacity.max_records) {\n problems.push({\n key: 'storage.max_records',\n message: `\"storage.max_records\" (${config.storage.max_records}) exceeds policy.capacity.max_records (${policy.capacity.max_records})`,\n });\n }\n if (config.storage.max_record_chars > policy.capacity.max_record_chars) {\n problems.push({\n key: 'storage.max_record_chars',\n message: `\"storage.max_record_chars\" (${config.storage.max_record_chars}) exceeds policy.capacity.max_record_chars (${policy.capacity.max_record_chars})`,\n });\n }\n return problems;\n}\n\n/**\n * Missing content files are warnings, not failures: a fresh store legitimately\n * has no memories yet. Files that were expected but cannot be read are a\n * different matter and are handled by the store layer in S2.\n */\nfunction missingContentWarnings(paths: MemoryPaths): string[] {\n const expected: ReadonlyArray<readonly [string, string]> = [\n [paths.soulFile, 'SOUL.md'],\n [paths.userFile, 'USER.md'],\n [paths.rulesFile, 'RULES.md'],\n [paths.memoryIndexFile, 'MEMORY.md'],\n ];\n return expected\n .filter(([filePath]) => !existsSync(filePath))\n .map(([, name]) => `${name} is not present yet; that injection section will be empty`);\n}\n", "import { readFileSync } from 'node:fs';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport { StartupError } from '../errors.ts';\nimport type { EnvLike } from '../paths.ts';\nimport { parseConfigDocument, type Config } from './config.ts';\n\nexport interface LoadedConfig {\n readonly config: Config;\n /** Path actually read, or null when built-in defaults are in use. */\n readonly configPath: string | null;\n readonly warnings: readonly string[];\n}\n\n/**\n * Load config.toml.\n *\n * Resolution: explicit path \u2192 AGENT_MEMORY_CONFIG \u2192 <home>/config.toml.\n * A missing default file means \"all defaults\"; a missing explicit file is an\n * error, because the caller asked for that specific file.\n */\nexport function loadConfig(options: {\n home: string;\n configPath?: string;\n env?: EnvLike;\n cwd?: string;\n}): LoadedConfig {\n const cwd = options.cwd ?? process.cwd();\n const fromEnv = options.env?.AGENT_MEMORY_CONFIG;\n const explicit = options.configPath ?? (fromEnv === undefined || fromEnv.trim() === '' ? undefined : fromEnv);\n const configPath =\n explicit === undefined\n ? join(options.home, 'config.toml')\n : isAbsolute(explicit)\n ? explicit\n : resolve(cwd, explicit);\n\n let text: string;\n try {\n text = readFileSync(configPath, 'utf8');\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT' && explicit === undefined) {\n return {\n config: parseConfigDocument('', configPath).config,\n configPath: null,\n warnings: [`${configPath} not found; built-in defaults are in use`],\n };\n }\n if (code === 'ENOENT') {\n throw new StartupError('CONFIG_UNREADABLE', 'the config file does not exist', {\n sourcePath: configPath,\n hint: 'create it with `mem init`, or drop --config / AGENT_MEMORY_CONFIG',\n });\n }\n throw new StartupError('CONFIG_UNREADABLE', 'the config file cannot be read', {\n sourcePath: configPath,\n details: [error instanceof Error ? error.message : String(error)],\n });\n }\n\n const { config } = parseConfigDocument(text, configPath);\n return { config, configPath, warnings: [] };\n}\n", "/**\n * A deliberately small TOML subset.\n *\n * ADR-0001 explains why this is hand-written instead of a dependency: runtime\n * dependencies are zero, and a half-understood config file is worse than a\n * rejected one. Supported syntax is exactly:\n *\n * - comments (`#` to end of line, outside strings)\n * - `[table]` and `[nested.table]` headers\n * - `key = value` with bare keys ([A-Za-z0-9_-]+)\n * - basic strings (\"...\" with \\\\ \\\" \\n \\r \\t), literal strings ('...')\n * - integers (decimal, optional sign) and booleans\n * - single-line, homogeneous arrays of those scalars\n *\n * Anything else - floats, dates, inline tables, dotted keys, multi-line\n * strings, nested arrays, arrays of tables - is refused with a line number.\n */\n\nexport type RawScalar = string | number | boolean;\nexport type RawValue = RawScalar | readonly RawScalar[];\nexport interface RawTable {\n readonly [key: string]: RawValue | RawTable;\n}\n\nexport interface TomlDocument {\n readonly root: RawTable;\n readonly lineOf: (key: string) => number | undefined;\n}\n\nexport class TomlSyntaxError extends Error {\n readonly line: number;\n readonly sourcePath: string | undefined;\n\n constructor(message: string, line: number, sourcePath?: string) {\n super(sourcePath === undefined ? `line ${line}: ${message}` : `${sourcePath}:${line}: ${message}`);\n this.name = 'TomlSyntaxError';\n this.line = line;\n this.sourcePath = sourcePath;\n }\n}\n\nconst BARE_KEY = /^[A-Za-z0-9_-]+$/;\nconst INTEGER = /^[+-]?\\d+$/;\nconst FLOAT = /^[+-]?(?:\\d+\\.\\d*|\\.\\d+|\\d+[eE][+-]?\\d+|\\d+\\.\\d*[eE][+-]?\\d+)$/;\nconst ESCAPES: Readonly<Record<string, string>> = {\n '\\\\': '\\\\',\n '\"': '\"',\n n: '\\n',\n r: '\\r',\n t: '\\t',\n};\n\nexport function isRawTable(value: unknown): value is RawTable {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction errorAt(message: string, line: number, sourcePath?: string): TomlSyntaxError {\n return new TomlSyntaxError(message, line, sourcePath);\n}\n\n/** Windows editors add a UTF-8 BOM; it is not part of the first key. */\nexport function stripBom(text: string): string {\n return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n}\n\n/** Drop a trailing `#` comment, respecting quoted spans. */\nfunction stripTrailingComment(line: string): string {\n let quote: string | null = null;\n for (let index = 0; index < line.length; index += 1) {\n const char = line[index];\n if (quote !== null) {\n if (quote === '\"' && char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = null;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n continue;\n }\n if (char === '#') return line.slice(0, index);\n }\n return line;\n}\n\nexport function parseRestrictedToml(text: string, options: { sourcePath?: string } = {}): TomlDocument {\n const sourcePath = options.sourcePath;\n const root: Record<string, unknown> = {};\n const lines = new Map<string, number>();\n const tables = new Set<string>();\n let current: Record<string, unknown> = root;\n let currentPath: string[] = [];\n const rawLines = stripBom(text).split(/\\r\\n|\\n|\\r/);\n\n for (let index = 0; index < rawLines.length; index += 1) {\n const lineNumber = index + 1;\n const line = stripTrailingComment(rawLines[index] ?? '').trim();\n if (line === '') continue;\n\n if (line.startsWith('[[')) {\n throw errorAt('arrays of tables ([[...]]) are not supported', lineNumber, sourcePath);\n }\n\n if (line.startsWith('[')) {\n const header = /^\\[\\s*([^[\\]]*?)\\s*\\]$/.exec(line);\n if (header === null) throw errorAt(`malformed table header: ${line}`, lineNumber, sourcePath);\n const headerText = header[1] ?? '';\n const segments = headerText.split('.').map((segment) => segment.trim());\n if (segments.some((segment) => segment === '' || !BARE_KEY.test(segment))) {\n throw errorAt(`invalid table name: ${headerText}`, lineNumber, sourcePath);\n }\n const tableKey = segments.join('.');\n if (tables.has(tableKey)) throw errorAt(`duplicate table [${tableKey}]`, lineNumber, sourcePath);\n let node = root;\n for (const segment of segments) {\n const existing = node[segment];\n if (existing === undefined) {\n const created: Record<string, unknown> = {};\n node[segment] = created;\n node = created;\n } else if (isRawTable(existing)) {\n node = existing;\n } else {\n throw errorAt(`[${tableKey}] conflicts with an existing value named \"${segment}\"`, lineNumber, sourcePath);\n }\n }\n tables.add(tableKey);\n current = node;\n currentPath = segments;\n continue;\n }\n\n const assignment = findAssignment(line);\n if (assignment < 0) throw errorAt(`expected \"key = value\": ${line}`, lineNumber, sourcePath);\n const keyText = line.slice(0, assignment).trim();\n const valueText = line.slice(assignment + 1).trim();\n if (keyText === '') throw errorAt('missing key before \"=\"', lineNumber, sourcePath);\n if (keyText.includes('.')) {\n throw errorAt('dotted keys are not supported; declare a [table] header instead', lineNumber, sourcePath);\n }\n const key = unquoteKey(keyText, lineNumber, sourcePath);\n if (key === undefined) throw errorAt(`invalid key: ${keyText}`, lineNumber, sourcePath);\n if (valueText === '') throw errorAt(`missing value for key \"${key}\"`, lineNumber, sourcePath);\n const fullKey = [...currentPath, key].join('.');\n if (Object.prototype.hasOwnProperty.call(current, key)) {\n throw errorAt(`duplicate key \"${fullKey}\"`, lineNumber, sourcePath);\n }\n current[key] = parseValue(valueText, lineNumber, sourcePath, fullKey);\n lines.set(fullKey, lineNumber);\n }\n\n return { root: root as RawTable, lineOf: (key: string) => lines.get(key) };\n}\n\nfunction findAssignment(line: string): number {\n let quote: string | null = null;\n for (let index = 0; index < line.length; index += 1) {\n const char = line[index];\n if (quote !== null) {\n if (quote === '\"' && char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = null;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n continue;\n }\n if (char === '=') return index;\n }\n return -1;\n}\n\nfunction unquoteKey(keyText: string, line: number, sourcePath?: string): string | undefined {\n if (keyText.startsWith('\"') || keyText.startsWith(\"'\")) {\n if (keyText.length < 2 || keyText.at(-1) !== keyText[0]) {\n throw errorAt('unterminated quoted key', line, sourcePath);\n }\n return parseQuoted(keyText, line, sourcePath);\n }\n if (!BARE_KEY.test(keyText)) return undefined;\n return keyText;\n}\n\nfunction parseValue(\n text: string,\n line: number,\n sourcePath: string | undefined,\n key: string,\n): RawValue {\n if (text === 'true') return true;\n if (text === 'false') return false;\n if (INTEGER.test(text)) {\n const value = Number(text);\n if (!Number.isSafeInteger(value)) throw errorAt(`\"${key}\": integer is outside the safe range`, line, sourcePath);\n return value;\n }\n if (text.startsWith('\"\"\"') || text.startsWith(\"'''\")) {\n throw errorAt(`\"${key}\": multi-line strings are not supported`, line, sourcePath);\n }\n if (text.startsWith('\"') || text.startsWith(\"'\")) {\n if (text.length < 2 || text.at(-1) !== text[0]) {\n throw errorAt(`\"${key}\": unterminated string`, line, sourcePath);\n }\n return parseQuoted(text, line, sourcePath);\n }\n if (text.startsWith('[')) return parseArray(text, line, sourcePath, key);\n if (text.startsWith('{')) throw errorAt(`\"${key}\": inline tables are not supported`, line, sourcePath);\n if (FLOAT.test(text)) throw errorAt(`\"${key}\": floats are not supported; use an integer`, line, sourcePath);\n throw errorAt(`\"${key}\": unsupported value: ${text}`, line, sourcePath);\n}\n\nfunction parseQuoted(text: string, line: number, sourcePath?: string): string {\n const quote = text[0];\n if (quote !== '\"' && quote !== \"'\") throw errorAt('not a quoted string', line, sourcePath);\n const body = text.slice(1, -1);\n if (quote === \"'\") return body;\n let out = '';\n for (let index = 0; index < body.length; index += 1) {\n const char = body[index];\n if (char !== '\\\\') {\n out += char;\n continue;\n }\n const next = body[index + 1];\n if (next === undefined) throw errorAt('trailing backslash in string', line, sourcePath);\n const replacement = ESCAPES[next];\n if (replacement === undefined) {\n throw errorAt(\n `unsupported escape \"\\\\${next}\" (supported: \\\\\\\\ \\\\\" \\\\n \\\\r \\\\t)`,\n line,\n sourcePath,\n );\n }\n out += replacement;\n index += 1;\n }\n return out;\n}\n\nfunction parseArray(\n text: string,\n line: number,\n sourcePath: string | undefined,\n key: string,\n): readonly RawScalar[] {\n if (!text.endsWith(']')) throw errorAt(`\"${key}\": unterminated array`, line, sourcePath);\n const inner = text.slice(1, -1).trim();\n if (inner === '') return [];\n const items = splitTopLevel(inner, line, sourcePath);\n const values = items.map((item) => parseValue(item, line, sourcePath, key));\n const kinds = new Set(values.map((value) => typeof value));\n if (kinds.size > 1) throw errorAt(`\"${key}\": arrays must hold values of a single type`, line, sourcePath);\n return values as readonly RawScalar[];\n}\n\nfunction splitTopLevel(inner: string, line: number, sourcePath?: string): string[] {\n const items: string[] = [];\n let current = '';\n let quote: string | null = null;\n for (let index = 0; index < inner.length; index += 1) {\n const char = inner[index];\n if (quote !== null) {\n current += char;\n if (quote === '\"' && char === '\\\\') {\n const next = inner[index + 1];\n if (next !== undefined) {\n current += next;\n index += 1;\n }\n continue;\n }\n if (char === quote) quote = null;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n current += char;\n continue;\n }\n if (char === '[' || char === '{') {\n throw errorAt('nested arrays and inline tables are not supported', line, sourcePath);\n }\n if (char === ',') {\n items.push(current.trim());\n current = '';\n continue;\n }\n current += char;\n }\n if (quote !== null) throw errorAt('unterminated string inside array', line, sourcePath);\n items.push(current.trim());\n if (items.some((item) => item === '')) throw errorAt('empty element in array', line, sourcePath);\n return items;\n}\n\n/** Serialize a string as a TOML basic string (used for generated defaults). */\nexport function quoteTomlString(value: string): string {\n const escaped = value\n .replaceAll('\\\\', '\\\\\\\\')\n .replaceAll('\"', '\\\\\"')\n .replaceAll('\\n', '\\\\n')\n .replaceAll('\\r', '\\\\r')\n .replaceAll('\\t', '\\\\t');\n return `\"${escaped}\"`;\n}\n", "/**\n * Declarative schema validation shared by config.toml and policy.json.\n *\n * Both files are strict: an unknown key is a startup failure, never a warning\n * that gets ignored. The messages name the offending dotted key so a human can\n * fix it without reading this source file.\n */\n\nimport type { ConfigProblem } from '../errors.ts';\nimport { isRawTable, type RawScalar, type RawTable, type RawValue } from './toml.ts';\n\nexport type FieldSpec =\n | { readonly type: 'string'; readonly default?: string; readonly nonEmpty?: boolean }\n | {\n readonly type: 'int';\n readonly default?: number;\n readonly min?: number;\n readonly max?: number;\n }\n | { readonly type: 'bool'; readonly default?: boolean }\n | { readonly type: 'enum'; readonly values: readonly string[]; readonly default?: string }\n | {\n readonly type: 'string[]';\n readonly values?: readonly string[];\n readonly default?: readonly string[];\n };\n\nexport interface TableSpec {\n readonly [key: string]: FieldSpec | TableSpec;\n}\n\nexport interface ValidationResult {\n readonly values: RawTable;\n readonly problems: readonly ConfigProblem[];\n}\n\nexport interface ValidateOptions {\n readonly prefix?: string;\n readonly lineOf?: (key: string) => number | undefined;\n}\n\nexport function isFieldSpec(spec: FieldSpec | TableSpec): spec is FieldSpec {\n return 'type' in spec;\n}\n\nexport function isArrayValue(value: unknown): value is readonly RawScalar[] {\n return Array.isArray(value);\n}\n\nexport function validateAgainstSchema(\n schema: TableSpec,\n raw: RawTable,\n options: ValidateOptions = {},\n): ValidationResult {\n const problems: ConfigProblem[] = [];\n const values = walk(schema, raw, options.prefix ?? '', problems, options.lineOf);\n return { values, problems };\n}\n\n/** Every field key of a schema, dotted and sorted. Used by the docs gate. */\nexport function schemaKeys(schema: TableSpec, prefix = ''): string[] {\n const keys: string[] = [];\n for (const [name, spec] of Object.entries(schema)) {\n const key = prefix === '' ? name : `${prefix}.${name}`;\n if (isFieldSpec(spec)) keys.push(key);\n else keys.push(...schemaKeys(spec, key));\n }\n return keys.sort();\n}\n\n/** All-default values for a schema. */\nexport function schemaDefaults(schema: TableSpec): RawTable {\n return validateAgainstSchema(schema, {}).values;\n}\n\nfunction walk(\n schema: TableSpec,\n raw: RawTable,\n prefix: string,\n problems: ConfigProblem[],\n lineOf: ((key: string) => number | undefined) | undefined,\n): RawTable {\n const out: Record<string, RawValue | RawTable> = {};\n const seen = new Set<string>();\n const known = new Map(Object.entries(schema));\n\n for (const [name, rawValue] of Object.entries(raw)) {\n seen.add(name);\n const key = prefix === '' ? name : `${prefix}.${name}`;\n const line = lineOf?.(key);\n const spec = known.get(name);\n\n if (spec === undefined) {\n problems.push({\n key,\n message: unknownKeyMessage(key, name, known),\n ...(line === undefined ? {} : { line }),\n });\n continue;\n }\n\n if (isFieldSpec(spec)) {\n if (isRawTable(rawValue)) {\n problems.push({\n key,\n message: `\"${key}\" must be ${typeLabel(spec)}, not a table`,\n ...(line === undefined ? {} : { line }),\n });\n continue;\n }\n const checked = checkField(spec, rawValue, key, problems);\n if (checked !== undefined) out[name] = checked;\n continue;\n }\n\n if (!isRawTable(rawValue)) {\n problems.push({\n key,\n message: `\"${key}\" must be a table ([${key}]), not ${describeValue(rawValue)}`,\n ...(line === undefined ? {} : { line }),\n });\n continue;\n }\n out[name] = walk(spec, rawValue, key, problems, lineOf);\n }\n\n for (const [name, spec] of Object.entries(schema)) {\n if (seen.has(name)) continue;\n const key = prefix === '' ? name : `${prefix}.${name}`;\n if (isFieldSpec(spec)) {\n if (spec.default !== undefined) out[name] = spec.default;\n else problems.push({ key, message: `missing required key \"${key}\"` });\n continue;\n }\n out[name] = walk(spec, {}, key, problems, lineOf);\n }\n\n return out;\n}\n\nfunction checkField(\n spec: FieldSpec,\n value: RawValue,\n key: string,\n problems: ConfigProblem[],\n): RawValue | undefined {\n const fail = (message: string): undefined => {\n problems.push({ key, message });\n return undefined;\n };\n\n switch (spec.type) {\n case 'string': {\n if (typeof value !== 'string') return fail(`\"${key}\" must be ${typeLabel(spec)}, not ${describeValue(value)}`);\n if (spec.nonEmpty === true && value.trim() === '') return fail(`\"${key}\" must not be empty`);\n return value;\n }\n case 'int': {\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n return fail(`\"${key}\" must be ${typeLabel(spec)}, not ${describeValue(value)}`);\n }\n if (spec.min !== undefined && value < spec.min) {\n return fail(`\"${key}\" must be at least ${spec.min}, found ${value}`);\n }\n if (spec.max !== undefined && value > spec.max) {\n return fail(`\"${key}\" must be at most ${spec.max}, found ${value}`);\n }\n return value;\n }\n case 'bool': {\n if (typeof value !== 'boolean') return fail(`\"${key}\" must be ${typeLabel(spec)}, not ${describeValue(value)}`);\n return value;\n }\n case 'enum': {\n if (typeof value !== 'string' || !spec.values.includes(value)) {\n return fail(`\"${key}\" must be ${typeLabel(spec)}, not ${describeValue(value)}`);\n }\n return value;\n }\n case 'string[]': {\n if (!isArrayValue(value) || !value.every((item) => typeof item === 'string')) {\n return fail(`\"${key}\" must be ${typeLabel(spec)}, not ${describeValue(value)}`);\n }\n const strings = value as readonly string[];\n if (spec.values !== undefined) {\n const bad = strings.find((item) => !spec.values?.includes(item));\n if (bad !== undefined) return fail(`\"${key}\" may only contain ${typeLabel(spec)}; found \"${bad}\"`);\n }\n return strings;\n }\n }\n}\n\nexport function typeLabel(spec: FieldSpec): string {\n switch (spec.type) {\n case 'string':\n return 'a string';\n case 'int':\n return 'an integer';\n case 'bool':\n return 'a boolean';\n case 'enum':\n return `one of ${spec.values.map((value) => `\"${value}\"`).join(', ')}`;\n case 'string[]':\n return spec.values === undefined\n ? 'an array of strings'\n : `an array of ${spec.values.map((value) => `\"${value}\"`).join(', ')}`;\n }\n}\n\nfunction describeValue(value: unknown): string {\n if (isRawTable(value)) return 'a table';\n if (isArrayValue(value)) return 'an array';\n if (typeof value === 'string') return `the string ${JSON.stringify(value)}`;\n if (typeof value === 'number') return `the integer ${value}`;\n return `the boolean ${String(value)}`;\n}\n\nfunction unknownKeyMessage(key: string, name: string, known: ReadonlyMap<string, FieldSpec | TableSpec>): string {\n const suggestion = suggestKey(name, known.keys());\n if (suggestion === undefined) return `unknown key \"${key}\"`;\n const prefix = key.slice(0, key.length - name.length);\n return `unknown key \"${key}\" (did you mean \"${prefix}${suggestion}\"?)`;\n}\n\nfunction suggestKey(name: string, candidates: Iterable<string>): string | undefined {\n let best: { candidate: string; distance: number } | undefined;\n for (const candidate of candidates) {\n const distance = editDistance(name.toLowerCase(), candidate.toLowerCase());\n if (distance > 2) continue;\n if (best === undefined || distance < best.distance) best = { candidate, distance };\n }\n return best?.candidate;\n}\n\nfunction editDistance(a: string, b: string): number {\n const rows = a.length + 1;\n const cols = b.length + 1;\n let previous: number[] = Array.from({ length: cols }, (_, index) => index);\n for (let row = 1; row < rows; row += 1) {\n const current: number[] = [row];\n for (let col = 1; col < cols; col += 1) {\n const cost = a[row - 1] === b[col - 1] ? 0 : 1;\n const above = previous[col] ?? 0;\n const left = current[col - 1] ?? 0;\n const diagonal = previous[col - 1] ?? 0;\n current[col] = Math.min(above + 1, left + 1, diagonal + cost);\n }\n previous = current;\n }\n return previous[cols - 1] ?? 0;\n}\n", "/**\n * config.toml: every user-tunable number, with no security-relevant switch.\n *\n * The split with policy.json is deliberate and checked at startup:\n * policy.json (sealed, human-only) sets the outermost bounds; config.toml may\n * tighten them but can never widen them. See docs/config.md.\n */\n\nimport { ConfigError, type ConfigProblem } from '../errors.ts';\nimport type { RawTable } from './toml.ts';\nimport { isRawTable, parseRestrictedToml, TomlSyntaxError } from './toml.ts';\nimport { schemaKeys, validateAgainstSchema, type TableSpec } from './schema.ts';\n\nexport interface Config {\n readonly schema_version: number;\n readonly storage: {\n readonly max_records: number;\n readonly max_record_chars: number;\n };\n readonly inject: {\n readonly persona_max_chars: number;\n readonly guidance_max_chars: number;\n readonly user_max_chars: number;\n readonly rules_max_chars: number;\n readonly index_max_chars: number;\n readonly total_max_chars: number;\n readonly protect: boolean;\n readonly counter: 'chars' | 'tokens';\n };\n readonly recall: {\n readonly limit: number;\n readonly min_score: number;\n readonly max_limit: number;\n readonly hybrid: boolean;\n readonly embedding_weight: number;\n };\n readonly distill: {\n readonly max_proposals: number;\n readonly require_quote: boolean;\n };\n readonly lock: {\n readonly heartbeat_ms: number;\n readonly stale_ms: number;\n readonly timeout_ms: number;\n };\n readonly limits: {\n readonly abstract_chars: number;\n readonly body_chars: number;\n };\n readonly quota: {\n readonly t0_per_session: number;\n };\n readonly proposals: {\n readonly max_pending: number;\n };\n readonly personalization: {\n readonly mode: 'confirm' | 'direct' | 'readonly';\n };\n}\n\n/**\n * Limits copied from the V1.0 plan (06 \u00A76.1 budgets, 08 \u00A7sub-budgets, v1.3 \u00A78).\n *\n * `recall.min_score` is an integer per-mille score (500 = 0.5) because the\n * restricted TOML subset deliberately has no floats. S3 interprets it as a\n * normalized BM25 threshold; S2a's substring recall ignores it.\n */\nexport const configSchema: TableSpec = {\n schema_version: { type: 'int', default: 2, min: 2, max: 2 },\n storage: {\n max_records: { type: 'int', default: 1000, min: 1, max: 100_000 },\n max_record_chars: { type: 'int', default: 10_000, min: 100, max: 200_000 },\n },\n inject: {\n persona_max_chars: { type: 'int', default: 200, min: 0, max: 5_000 },\n guidance_max_chars: { type: 'int', default: 300, min: 0, max: 2_000 },\n user_max_chars: { type: 'int', default: 1_100, min: 0, max: 20_000 },\n rules_max_chars: { type: 'int', default: 1_200, min: 0, max: 10_000 },\n index_max_chars: { type: 'int', default: 1_200, min: 0, max: 20_000 },\n total_max_chars: { type: 'int', default: 4_000, min: 0, max: 40_000 },\n protect: { type: 'bool', default: true },\n counter: { type: 'enum', values: ['chars', 'tokens'], default: 'chars' },\n },\n recall: {\n limit: { type: 'int', default: 5, min: 1, max: 100 },\n min_score: { type: 'int', default: 500, min: 0, max: 1_000 },\n max_limit: { type: 'int', default: 20, min: 1, max: 100 },\n hybrid: { type: 'bool', default: false },\n embedding_weight: { type: 'int', default: 400, min: 0, max: 1_000 },\n },\n distill: {\n max_proposals: { type: 'int', default: 5, min: 1, max: 5 },\n require_quote: { type: 'bool', default: true },\n },\n lock: {\n heartbeat_ms: { type: 'int', default: 15_000, min: 1_000, max: 60_000 },\n stale_ms: { type: 'int', default: 300_000, min: 5_000, max: 3_600_000 },\n timeout_ms: { type: 'int', default: 60_000, min: 1_000, max: 600_000 },\n },\n limits: {\n abstract_chars: { type: 'int', default: 120, min: 20, max: 1_000 },\n body_chars: { type: 'int', default: 4_000, min: 100, max: 200_000 },\n },\n quota: {\n t0_per_session: { type: 'int', default: 20, min: 1, max: 1_000 },\n },\n proposals: {\n max_pending: { type: 'int', default: 50, min: 1, max: 1_000 },\n },\n personalization: {\n mode: { type: 'enum', values: ['confirm', 'direct', 'readonly'], default: 'confirm' },\n },\n};\n\n/**\n * The config file written by `mem init`. Every key is present so a human can see\n * what is tunable without reading the schema.\n */\nexport const CONFIG_TEMPLATE = `# Agent Memory V1.0 - \u7528\u6237\u914D\u7F6E\uFF08\u4EBA\u53EF\u6539\uFF1Bagent \u4E0D\u9700\u8981\u6539\uFF09\n# \u6BCF\u4E2A\u952E\u90FD\u5728\u542F\u52A8\u65F6\u6821\u9A8C\uFF1A\u672A\u77E5\u952E\u3001\u7C7B\u578B\u9519\u8BEF\u3001\u8D85\u8303\u56F4\u90FD\u4F1A\u8BA9\u542F\u52A8\u54CD\u4EAE\u5931\u8D25\uFF0C\u5E76\u70B9\u540D\u51FA\u9519\u952E\u3002\n# \u8BF4\u660E\u89C1 docs/config.md\u3002\u5B89\u5168\u8FB9\u754C\u4E0D\u5728\u8FD9\u4E2A\u6587\u4EF6\u91CC\uFF0C\u800C\u5728 policy.json\uFF08\u54C8\u5E0C\u5C01\u5B58\uFF09\u3002\n\nschema_version = 2\n\n[storage]\n# \u8BB0\u5FC6\u6761\u76EE\u4E0A\u9650\uFF1B\u8D85\u8FC7\u540E\u5199\u5165\u88AB\u62D2\u7EDD\uFF08\u4E0D\u81EA\u52A8\u6DD8\u6C70\uFF09\u3002\nmax_records = 1000\n# \u5355\u6761\u8BB0\u5FC6\u6587\u4EF6\u5B57\u7B26\u4E0A\u9650\uFF08\u542B frontmatter\uFF09\u3002\nmax_record_chars = 10000\n\n[inject]\n# \u5E38\u9A7B\u6CE8\u5165\u7684\u4E94\u4E2A\u5206\u533A\u9884\u7B97\uFF08\u5B57\u7B26\u6570\uFF09\u4E0E\u5408\u8BA1\u4E0A\u9650\u3002\npersona_max_chars = 200\nguidance_max_chars = 300\nuser_max_chars = 1100\nrules_max_chars = 1200\nindex_max_chars = 1200\ntotal_max_chars = 4000\n# \u6CE8\u5165\u6BB5\u6253 protected \u6807\u8BB0\uFF1A\u538B\u7F29\u4E0D\u5F97\u89E6\u53CA\u3002\nprotect = true\n# \u9884\u7B97\u8BA1\u91CF\u65B9\u5F0F\uFF1Achars\uFF08\u5B57\u7B26\uFF0C\u4FDD\u5B88\uFF09\u6216 tokens\uFF08S3 \u8D77\u7528 tokenMeter\uFF09\u3002\ncounter = \"chars\"\n\n[recall]\n# \u5355\u6B21\u68C0\u7D22\u9ED8\u8BA4\u8FD4\u56DE\u6761\u6570\uFF0C\u4EE5\u53CA\u4E0A\u9650\u3002\nlimit = 5\nmax_limit = 20\n# \u5343\u5206\u5236\u9608\u503C\uFF08500 = 0.5\uFF09\uFF1BS2a \u5B50\u4E32\u53EC\u56DE\u4E0D\u4F7F\u7528\uFF0CS3 BM25 \u4F7F\u7528\u3002\nmin_score = 500\n# \u6DF7\u5408\u68C0\u7D22\uFF1A\u9ED8\u8BA4\u5173\u95ED\uFF1B\u5F00\u542F\u540E BM25 \u4E0E\u672C\u5730\u5411\u91CF\u5206\u6570\u878D\u5408\uFF08S2a \u7528\u786E\u5B9A\u6027 hash \u515C\u5E95\uFF09\u3002\nhybrid = false\n# \u5411\u91CF\u5728\u878D\u5408\u5206\u6570\u4E2D\u7684\u6743\u91CD\uFF08\u5343\u5206\u5236\uFF0C400 = 0.4\uFF09\u3002\nembedding_weight = 400\n\n[distill]\n# \u6BCF\u6B21\u6536\u5C3E\u84B8\u998F\u6700\u591A\u51E0\u6761\u63D0\u6848\uFF08V1.0 \u89C4\u683C\u786C\u4E0A\u9650 5\uFF09\u3002\nmax_proposals = 5\n# \u63D0\u6848\u5FC5\u987B\u5E26\u539F\u6587\u5F15\u7528\u3002\nrequire_quote = true\n\n[lock]\n# \u5199\u9501\uFF1A\u5FC3\u8DF3\u95F4\u9694\u3001\u9648\u65E7\u9608\u503C\u3001\u83B7\u53D6\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09\u3002\nheartbeat_ms = 15000\nstale_ms = 300000\ntimeout_ms = 60000\n\n[limits]\n# \u5355\u6761\u8BB0\u5FC6\u7684\u6458\u8981\u4E0E\u6B63\u6587\u5B57\u7B26\u4E0A\u9650\u3002\nabstract_chars = 120\nbody_chars = 4000\n\n[quota]\n# \u6BCF\u4E2A\u4F1A\u8BDD\u5141\u8BB8\u7684 T0 \u5199\u5165\u6761\u6570\uFF08S4 \u8D77\u5F3A\u5236\u6267\u884C\uFF09\u3002\nt0_per_session = 20\n\n[proposals]\n# \u5F85\u5BA1\u63D0\u6848\u4E0A\u9650\u3002\nmax_pending = 50\n\n[personalization]\n# \u52A9\u624B\u5199\u8BB0\u5FC6\u7684\u6743\u9650\uFF1Aconfirm\uFF08\u6BCF\u6B21\u5148\u786E\u8BA4\uFF09/ direct\uFF08\u81EA\u4E3B\u5199\u5165\uFF09/ readonly\uFF08\u53EA\u8BFB\uFF09\u3002\nmode = \"confirm\"\n`;\n\nexport function defaultConfig(): Config {\n return validateConfigTable({}).config;\n}\n\nexport function configKeys(): string[] {\n return schemaKeys(configSchema);\n}\n\nexport function validateConfigTable(\n raw: RawTable,\n options: { lineOf?: (key: string) => number | undefined } = {},\n): { config: Config; problems: ConfigProblem[] } {\n const { values, problems: schemaProblems } = validateAgainstSchema(configSchema, raw, options);\n const problems = [...schemaProblems];\n const config = values as unknown as Config;\n const inject = values.inject;\n if (isRawTable(inject)) {\n const parts = [\n inject.persona_max_chars,\n inject.guidance_max_chars,\n inject.user_max_chars,\n inject.rules_max_chars,\n inject.index_max_chars,\n ];\n const total = inject.total_max_chars;\n if (parts.every((part): part is number => typeof part === 'number') && typeof total === 'number') {\n const sum = parts.reduce((acc, part) => acc + part, 0);\n if (sum > total) {\n problems.push({\n key: 'inject.total_max_chars',\n message: `the five injection sections add up to ${sum} chars, more than inject.total_max_chars (${total})`,\n });\n }\n }\n }\n const recall = values.recall;\n if (isRawTable(recall)) {\n const limit = recall.limit;\n const max = recall.max_limit;\n if (typeof limit === 'number' && typeof max === 'number' && limit > max) {\n problems.push({\n key: 'recall.limit',\n message: `\"recall.limit\" (${limit}) must not exceed recall.max_limit (${max})`,\n });\n }\n }\n return { config, problems };\n}\n\n/** Parse config text strictly. Throws ConfigError (which names every bad key). */\nexport function parseConfig(text: string, sourcePath: string): Config {\n return parseConfigDocument(text, sourcePath).config;\n}\n\nexport function parseConfigDocument(\n text: string,\n sourcePath: string,\n): { config: Config; problems: ConfigProblem[]; lineOf: (key: string) => number | undefined } {\n let parsed: ReturnType<typeof parseRestrictedToml>;\n try {\n parsed = parseRestrictedToml(text, { sourcePath });\n } catch (error) {\n if (error instanceof TomlSyntaxError) {\n throw new ConfigError(sourcePath, [\n { key: '<syntax>', message: `${error.message.replace(`${sourcePath}:`, '').trim()}` },\n ]);\n }\n throw error;\n }\n const { config, problems } = validateConfigTable(parsed.root, { lineOf: parsed.lineOf });\n if (problems.length > 0) {\n throw new ConfigError(sourcePath, problems, 'fix the named keys; unknown keys are refused, never ignored');\n }\n return { config, problems, lineOf: parsed.lineOf };\n}\n", "import { createHash } from 'node:crypto';\r\nimport { existsSync, readFileSync } from 'node:fs';\r\nimport { isRawTable, stripBom, type RawTable } from '../config/toml.ts';\r\nimport { schemaKeys, validateAgainstSchema, type TableSpec } from '../config/schema.ts';\r\nimport { StartupError, type ConfigProblem } from '../errors.ts';\r\nimport { writeFileAtomic } from '../fs/atomic.ts';\r\nimport { hashContent } from '../model/frontmatter.ts';\r\nimport { memoryPaths } from '../paths.ts';\r\n\r\n/**\r\n * policy.json: the attack surface that must not be editable by the agent.\r\n *\r\n * It is sealed with a SHA-256 of its bytes. Every startup recomputes the hash;\r\n * any mismatch aborts startup instead of loading a relaxed policy (`06` L3).\r\n * Re-sealing is a human action: `mem policy seal --accept`.\r\n *\r\n * The optional `sealed_files` hashes make the human-maintained SOUL/USER/RULES\r\n * editable only through a deliberate re-seal: an empty string skips a file.\r\n */\r\n\r\nexport interface Policy {\r\n readonly version: number;\r\n readonly capacity: {\r\n readonly max_records: number;\r\n readonly max_record_chars: number;\r\n };\r\n readonly scan: {\r\n readonly invisible_unicode: 'reject';\r\n readonly credentials: 'reject';\r\n readonly injection: 'reject' | 'flag';\r\n readonly private_tag: 'reject' | 'confirm';\r\n };\r\n readonly rules: {\r\n readonly agent_writable: false;\r\n };\r\n readonly sealed_files: {\r\n readonly soul: string;\r\n readonly user: string;\r\n readonly rules: string;\r\n };\r\n}\r\n\r\nexport const policySchema: TableSpec = {\r\n version: { type: 'int', default: 2, min: 1, max: 2 },\r\n capacity: {\r\n max_records: { type: 'int', default: 1000, min: 1, max: 100_000 },\r\n max_record_chars: { type: 'int', default: 10_000, min: 100, max: 200_000 },\r\n },\r\n scan: {\r\n invisible_unicode: { type: 'enum', values: ['reject'], default: 'reject' },\r\n credentials: { type: 'enum', values: ['reject'], default: 'reject' },\r\n injection: { type: 'enum', values: ['reject', 'flag'], default: 'reject' },\r\n private_tag: { type: 'enum', values: ['reject', 'confirm'], default: 'confirm' },\r\n },\r\n rules: {\r\n agent_writable: { type: 'bool', default: false },\r\n },\r\n sealed_files: {\r\n soul: { type: 'string', default: '' },\r\n user: { type: 'string', default: '' },\r\n rules: { type: 'string', default: '' },\r\n },\r\n};\r\n\r\nexport const POLICY_TEMPLATE = `{\r\n \"version\": 2,\r\n \"capacity\": {\r\n \"max_records\": 1000,\r\n \"max_record_chars\": 10000\r\n },\r\n \"scan\": {\r\n \"invisible_unicode\": \"reject\",\r\n \"credentials\": \"reject\",\r\n \"injection\": \"reject\",\r\n \"private_tag\": \"confirm\"\r\n },\r\n \"rules\": {\r\n \"agent_writable\": false\r\n },\r\n \"sealed_files\": {\r\n \"soul\": \"\",\r\n \"user\": \"\",\r\n \"rules\": \"\"\r\n }\r\n}\r\n`;\r\n\r\nexport interface SealRecord {\r\n readonly policy: string;\r\n readonly sha256: string;\r\n readonly sealed_at: string;\r\n}\r\n\r\nexport interface LoadedPolicy {\r\n readonly policy: Policy;\r\n readonly policyPath: string;\r\n readonly sealPath: string;\r\n readonly sha256: string;\r\n readonly sealedAt: string;\r\n}\r\n\r\nexport function policyKeys(): string[] {\r\n return schemaKeys(policySchema);\r\n}\r\n\r\nexport function defaultPolicy(): Policy {\r\n return parsePolicyText(POLICY_TEMPLATE).policy;\r\n}\r\n\r\nexport function hashBytes(data: string | Uint8Array): string {\r\n return createHash('sha256').update(data).digest('hex');\r\n}\r\n\r\nexport function parsePolicyText(text: string): { policy: Policy; problems: ConfigProblem[] } {\r\n let raw: unknown;\r\n try {\r\n raw = JSON.parse(stripBom(text));\r\n } catch (error) {\r\n const message = error instanceof Error ? error.message : String(error);\r\n return {\r\n policy: {} as Policy,\r\n problems: [{ key: '<json>', message: `policy is not valid JSON: ${message}` }],\r\n };\r\n }\r\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\r\n return {\r\n policy: {} as Policy,\r\n problems: [{ key: '<root>', message: 'policy must be a JSON object' }],\r\n };\r\n }\r\n const { values, problems: schemaProblems } = validateAgainstSchema(policySchema, raw as RawTable);\r\n const problems = [...schemaProblems];\r\n const policy = values as unknown as Policy;\r\n const rules = values.rules;\r\n if (isRawTable(rules) && rules.agent_writable === true) {\r\n problems.push({\r\n key: 'rules.agent_writable',\r\n message: '\"rules.agent_writable\" must stay false in V1.0: the agent has no channel to RULES.md',\r\n });\r\n }\r\n const sealed = values.sealed_files;\r\n if (isRawTable(sealed)) {\r\n for (const key of ['soul', 'user', 'rules'] as const) {\r\n const value = sealed[key];\r\n if (typeof value === 'string' && value !== '' && !/^[0-9a-f]{64}$/.test(value)) {\r\n problems.push({\r\n key: `sealed_files.${key}`,\r\n message: `\"sealed_files.${key}\" must be empty or a 64-character lowercase hex hash`,\r\n });\r\n }\r\n }\r\n }\r\n return { policy, problems };\r\n}\r\n\r\nexport interface SealedFileHashes {\r\n readonly soul: string;\r\n readonly user: string;\r\n readonly rules: string;\r\n}\r\n\r\n/**\r\n * Normalized hashes of the human-maintained files. A missing file seals as an\r\n * empty string, which means \"skip this file\".\r\n */\r\nexport function computeSealedFiles(home: string): SealedFileHashes {\r\n const paths = memoryPaths(home);\r\n const hashOf = (file: string): string => {\r\n try {\r\n return existsSync(file) ? hashContent(readFileSync(file, 'utf8')) : '';\r\n } catch {\r\n return '';\r\n }\r\n };\r\n return { soul: hashOf(paths.soulFile), user: hashOf(paths.userFile), rules: hashOf(paths.rulesFile) };\r\n}\r\n\r\n/**\r\n * Startup check for the sealed human files. Editing SOUL/USER/RULES without a\r\n * deliberate re-seal stops startup with the file named.\r\n */\r\nexport function verifySealedFiles(options: { home: string; policy: Policy }): void {\r\n const paths = memoryPaths(options.home);\r\n const targets: ReadonlyArray<readonly [keyof SealedFileHashes, string, string]> = [\r\n ['soul', paths.soulFile, 'SOUL.md'],\r\n ['user', paths.userFile, 'USER.md'],\r\n ['rules', paths.rulesFile, 'RULES.md'],\r\n ];\r\n for (const [key, file, name] of targets) {\r\n const expected = options.policy.sealed_files[key];\r\n if (expected === '') continue;\r\n const actual = existsSync(file) ? hashContent(readFileSync(file, 'utf8')) : '';\r\n if (actual !== expected) {\r\n const homeArg = /\\s/.test(options.home) ? `\"${options.home}\"` : options.home;\r\n throw new StartupError('SEALED_FILE_MISMATCH', `${name} does not match its sealed hash`, {\r\n sourcePath: file,\r\n details: [`sealed sha256 ${expected}`, `actual sha256 ${actual === '' ? '(missing)' : actual}`],\r\n fixCommand: `mem policy seal --home ${homeArg} --accept`,\r\n hint: `\u7F16\u8F91 ${name} \u540E\u5FC5\u987B\u91CD\u65B0\u5C01\u5B58\uFF1B\u4E5F\u53EF\u4EE5\u5728\u804A\u5929\u6846\u8FD0\u884C /mem seal --accept`,\r\n });\r\n }\r\n }\r\n}\r\n\r\nexport function loadPolicy(options: { home: string }): LoadedPolicy {\r\n const paths = memoryPaths(options.home);\r\n const policyText = readFileText(paths.policyFile, {\r\n code: 'POLICY_MISSING',\r\n message: 'policy.json is missing from the store',\r\n hint: 'run `mem init` to create the store, then seal the policy',\r\n });\r\n const sealText = readFileText(paths.sealFile, {\r\n code: 'POLICY_MISSING',\r\n message: 'policy.json is not sealed',\r\n hint: 'a human must review it and run `mem policy seal --accept`',\r\n });\r\n\r\n const seal = parseSeal(sealText, paths.sealFile);\r\n const sha256 = hashBytes(policyText);\r\n if (seal.sha256 !== sha256) {\r\n throw new StartupError('POLICY_MISMATCH', 'policy.json does not match its sealed hash', {\r\n sourcePath: paths.policyFile,\r\n details: [`sealed sha256 ${seal.sha256}`, `actual sha256 ${sha256}`],\r\n hint: 'the policy is immutable at runtime; after a deliberate human edit run `mem policy seal --accept`',\r\n });\r\n }\r\n\r\n const { policy, problems } = parsePolicyText(policyText);\r\n if (problems.length > 0) throw policyProblems(paths.policyFile, problems);\r\n\r\n return { policy, sha256, sealedAt: seal.sealed_at, policyPath: paths.policyFile, sealPath: paths.sealFile };\r\n}\r\n\r\nexport interface SealResult {\r\n readonly sealPath: string;\r\n readonly sha256: string;\r\n /** Hash that was sealed before this call, if any. */\r\n readonly previousSha256: string | null;\r\n /** Normalized hashes of SOUL/USER/RULES at the moment of sealing. */\r\n readonly sealedFiles: SealedFileHashes;\r\n}\r\n\r\n/**\r\n * Re-seal the policy. Requires `accept === true`, which only the CLI passes\r\n * after a human typed the flag; nothing in the agent's tool surface can reach\r\n * this function.\r\n */\r\nexport function sealPolicy(options: {\r\n home: string;\r\n accept: boolean;\r\n now?: Date;\r\n /** Seal USER.md too. Default false: the agent may propose USER edits. */\r\n sealUser?: boolean;\r\n}): SealResult {\r\n const paths = memoryPaths(options.home);\r\n if (!options.accept) {\r\n throw new StartupError('SEAL_REFUSED', 'refusing to re-seal policy.json without explicit confirmation', {\r\n sourcePath: paths.policyFile,\r\n hint: 'review the file, then run `mem policy seal --accept`; the agent has no path to this action',\r\n });\r\n }\r\n\r\n const policyText = readFileText(paths.policyFile, {\r\n code: 'POLICY_MISSING',\r\n message: 'policy.json is missing from the store',\r\n hint: 'run `mem init` first',\r\n });\r\n const { policy, problems } = parsePolicyText(policyText);\r\n if (problems.length > 0) throw policyProblems(paths.policyFile, problems);\r\n\r\n const computed = computeSealedFiles(options.home);\r\n const sealedFiles: SealedFileHashes = {\r\n soul: computed.soul,\r\n user: options.sealUser === true ? computed.user : '',\r\n rules: computed.rules,\r\n };\r\n const nextText = `${JSON.stringify({ ...policy, sealed_files: sealedFiles }, null, 2)}\\n`;\r\n writeFileAtomic(paths.policyFile, nextText);\r\n\r\n const previous = tryReadSeal(paths.sealFile);\r\n const sha256 = hashBytes(nextText);\r\n writeSeal(paths.sealFile, { policy: 'policy.json', sha256, sealed_at: (options.now ?? new Date()).toISOString() });\r\n return { sealPath: paths.sealFile, sha256, previousSha256: previous?.sha256 ?? null, sealedFiles };\r\n}\r\n\r\n/**\r\n * Used by `mem init`: seal when unsealed, accept when already sealed and\r\n * matching, refuse when the file changed under an existing seal.\r\n */\r\nexport function sealIfNeeded(options: { home: string; now?: Date }): SealResult {\r\n const paths = memoryPaths(options.home);\r\n const policyText = readFileText(paths.policyFile, {\r\n code: 'POLICY_MISSING',\r\n message: 'policy.json is missing from the store',\r\n hint: 'run `mem init` first',\r\n });\r\n const { problems } = parsePolicyText(policyText);\r\n if (problems.length > 0) throw policyProblems(paths.policyFile, problems);\r\n\r\n const sha256 = hashBytes(policyText);\r\n const sealedFiles = computeSealedFiles(options.home);\r\n const existing = tryReadSeal(paths.sealFile);\r\n if (existing !== null) {\r\n if (existing.sha256 !== sha256) {\r\n throw new StartupError('POLICY_MISMATCH', 'policy.json changed after it was sealed', {\r\n sourcePath: paths.policyFile,\r\n details: [`sealed sha256 ${existing.sha256}`, `actual sha256 ${sha256}`],\r\n hint: 'verify the change, then run `mem policy seal --accept`',\r\n });\r\n }\r\n return { sealPath: paths.sealFile, sha256, previousSha256: existing.sha256, sealedFiles };\r\n }\r\n writeSeal(paths.sealFile, { policy: 'policy.json', sha256, sealed_at: (options.now ?? new Date()).toISOString() });\r\n return { sealPath: paths.sealFile, sha256, previousSha256: null, sealedFiles };\r\n}\r\n\r\nfunction writeSeal(sealPath: string, record: SealRecord): void {\r\n writeFileAtomic(sealPath, `${JSON.stringify(record, null, 2)}\\n`);\r\n}\r\n\r\nfunction parseSeal(text: string, sealPath: string): SealRecord {\r\n let raw: unknown;\r\n try {\r\n raw = JSON.parse(stripBom(text));\r\n } catch (error) {\r\n const message = error instanceof Error ? error.message : String(error);\r\n throw new StartupError('POLICY_INVALID', 'the policy seal file is not valid JSON', {\r\n sourcePath: sealPath,\r\n details: [message],\r\n hint: 'run `mem policy seal --accept` to write a fresh seal',\r\n });\r\n }\r\n if (typeof raw !== 'object' || raw === null) {\r\n throw new StartupError('POLICY_INVALID', 'the policy seal file must be a JSON object', {\r\n sourcePath: sealPath,\r\n });\r\n }\r\n const record = raw as Record<string, unknown>;\r\n const allowed = new Set(['policy', 'sha256', 'sealed_at']);\r\n const unknown = Object.keys(record).filter((key) => !allowed.has(key));\r\n if (unknown.length > 0) {\r\n throw new StartupError('POLICY_INVALID', 'the policy seal file has unknown keys', {\r\n sourcePath: sealPath,\r\n details: unknown.map((key) => `unknown key \"${key}\"`),\r\n });\r\n }\r\n const sha256 = record.sha256;\r\n if (typeof record.policy !== 'string' || typeof sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(sha256)) {\r\n throw new StartupError('POLICY_INVALID', 'the policy seal file is malformed', {\r\n sourcePath: sealPath,\r\n details: ['expected { \"policy\": string, \"sha256\": <64 hex chars>, \"sealed_at\": string }'],\r\n });\r\n }\r\n const sealedAt = typeof record.sealed_at === 'string' ? record.sealed_at : '';\r\n return { policy: record.policy, sha256, sealed_at: sealedAt };\r\n}\r\n\r\nfunction tryReadSeal(sealPath: string): SealRecord | null {\r\n let text: string;\r\n try {\r\n text = readFileSync(sealPath, 'utf8');\r\n } catch {\r\n return null;\r\n }\r\n return parseSeal(text, sealPath);\r\n}\r\n\r\nfunction readFileText(filePath: string, missing: { code: 'POLICY_MISSING'; message: string; hint: string }): string {\r\n try {\r\n return readFileSync(filePath, 'utf8');\r\n } catch (error) {\r\n const code = (error as NodeJS.ErrnoException).code;\r\n if (code === 'ENOENT') {\r\n throw new StartupError(missing.code, missing.message, {\r\n sourcePath: filePath,\r\n hint: missing.hint,\r\n });\r\n }\r\n throw new StartupError('POLICY_INVALID', 'the policy file cannot be read', {\r\n sourcePath: filePath,\r\n details: [error instanceof Error ? error.message : String(error)],\r\n });\r\n }\r\n}\r\n\r\nfunction policyProblems(sourcePath: string, problems: readonly ConfigProblem[]): StartupError {\r\n return new StartupError('POLICY_INVALID', `policy rejected (${problems.length} problem${problems.length === 1 ? '' : 's'})`, {\r\n sourcePath,\r\n keys: problems.map((problem) => problem.key),\r\n details: problems.map((problem) => problem.message),\r\n hint: 'fix policy.json, then have a human run `mem policy seal --accept`',\r\n });\r\n}\r\n", "import { randomBytes } from 'node:crypto';\nimport { closeSync, mkdirSync, openSync, renameSync, rmSync, fsyncSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { sleepSync } from './wait.ts';\n\n/**\n * Atomic replace: write a sibling temp file, fsync it, then rename over the\n * target. On Windows, rename can hit `EPERM`/`EBUSY` while an indexer or\n * antivirus holds the target; a short bounded retry is the documented behaviour\n * (plan v1.3 \u00A76.2), and a persistent failure is a loud error, never a half\n * write.\n *\n * Directory entries are not fsynced: Windows cannot flush a directory handle.\n * The store therefore promises \"detectable and recoverable after a crash\", not\n * zero loss on power failure (plan v1.3 \u00A72.2).\n */\nexport interface AtomicWriteOptions {\n readonly retries?: number;\n readonly retryDelayMs?: number;\n}\n\nexport function writeFileAtomic(\n filePath: string,\n data: string | Uint8Array,\n options: AtomicWriteOptions = {},\n): void {\n mkdirSync(dirname(filePath), { recursive: true });\n const tempPath = `${filePath}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`;\n const retries = options.retries ?? 5;\n const delay = options.retryDelayMs ?? 20;\n\n try {\n const fd = openSync(tempPath, 'w');\n try {\n writeFileSync(fd, typeof data === 'string' ? data : Buffer.from(data));\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n\n for (let attempt = 0; ; attempt += 1) {\n try {\n renameSync(tempPath, filePath);\n return;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if ((code !== 'EPERM' && code !== 'EBUSY') || attempt >= retries) throw error;\n sleepSync(delay * (attempt + 1));\n }\n }\n } catch (error) {\n rmSync(tempPath, { force: true });\n throw error;\n }\n}\n\nexport function ensureDir(dir: string): void {\n mkdirSync(dir, { recursive: true });\n}\n", "/** Synchronous sleep for retry loops; avoids busy-waiting. */\nexport function sleepSync(ms: number): void {\n if (ms <= 0) return;\n const cell = new Int32Array(new SharedArrayBuffer(4));\n Atomics.wait(cell, 0, 0, ms);\n}\n", "import { createHash } from 'node:crypto';\nimport type { EvidenceLevel, Kind, MemoryDoc, MemoryRelation, ProvenanceEntry, RelationType } from './types.ts';\nimport { projectProblem, relationsProblem, sourceProblem, tagsProblem } from './metadata.ts';\n\n/**\n * Frontmatter is one `key: <JSON value>` per line between two `---` fences.\n *\n * That is the whole format: no YAML parser, no aliases, no multi-line values.\n * Unknown or duplicated keys, missing required fields, a second inline object on\n * one line, or a value whose JSON type is wrong all refuse the file \u2014 a\n * half-understood memory is worse than a rejected one.\n */\n\nexport interface MemoryLimits {\n readonly abstractChars: number;\n readonly bodyChars: number;\n readonly maxRecordChars: number;\n}\n\nexport class FrontmatterError extends Error {\n readonly field: string;\n readonly filePath: string | undefined;\n\n constructor(field: string, message: string, filePath?: string) {\n super(`${field}: ${message}`);\n this.name = 'FrontmatterError';\n this.field = field;\n this.filePath = filePath;\n }\n}\n\nconst FIELD_ORDER = [\n 'id',\n 'mem_schema',\n 'kind',\n 'scope',\n 'project',\n 'tags',\n 'relations',\n 'source',\n 'abstract',\n 'created_at',\n 'valid_from',\n 'valid_until',\n 'supersedes',\n 'author',\n 'evidence_level',\n 'error_signatures',\n 'provenance',\n] as const;\n\nconst FIELD_SET = new Set<string>(FIELD_ORDER);\nconst KINDS = new Set<Kind>(['fact', 'pitfall', 'exp']);\nconst EVIDENCE = new Set<EvidenceLevel>(['user_explicit', 'user_confirmed', 'observed', 'inferred']);\nconst SPEAKERS = new Set(['user', 'assistant', 'tool', 'system']);\n\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst TIMESTAMP = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/;\nconst ID = /^mem-\\d{8}-[0-9a-f]{8}$/;\nconst SHA256 = /^[0-9a-f]{64}$/;\n\nexport function normalizeText(text: string): string {\n const withoutBom = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n return withoutBom.replaceAll('\\r\\n', '\\n').replace(/\\n*$/, '\\n');\n}\n\nexport function hashContent(text: string): string {\n return createHash('sha256').update(normalizeText(text), 'utf8').digest('hex');\n}\n\nfunction isValidDate(value: string): boolean {\n const match = DATE.exec(value);\n if (match === null) return false;\n const [, year, month, day] = match;\n const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)));\n return (\n date.getUTCFullYear() === Number(year) &&\n date.getUTCMonth() === Number(month) - 1 &&\n date.getUTCDate() === Number(day)\n );\n}\n\nfunction fail(field: string, message: string, filePath?: string): never {\n throw new FrontmatterError(field, message, filePath);\n}\n\nfunction requireString(value: unknown, field: string, filePath: string | undefined): string {\n if (typeof value !== 'string') fail(field, `must be a string, found ${JSON.stringify(value)}`, filePath);\n return value;\n}\n\nfunction requireArray(value: unknown, field: string, filePath: string | undefined): readonly unknown[] {\n if (!Array.isArray(value)) fail(field, `must be an array, found ${JSON.stringify(value)}`, filePath);\n return value;\n}\n\nexport function parseMemoryFile(text: string, filePath: string, limits: MemoryLimits): MemoryDoc {\n const normalized = normalizeText(text);\n if (!normalized.startsWith('---\\n')) fail('frontmatter', 'file must start with a \"---\" fence', filePath);\n const end = normalized.indexOf('\\n---\\n', 4);\n if (end < 0) fail('frontmatter', 'missing closing \"---\" fence', filePath);\n\n const header = normalized.slice(4, end);\n const body = normalized.slice(end + 5);\n\n const values = new Map<string, unknown>();\n for (const line of header.split('\\n')) {\n if (line.trim() === '') fail('frontmatter', 'blank line inside the frontmatter', filePath);\n const separator = line.indexOf(': ');\n if (separator < 0) fail('frontmatter', `line is not \"key: <JSON>\": ${line.slice(0, 40)}`, filePath);\n const key = line.slice(0, separator);\n if (!/^[a-z_]+$/.test(key)) fail('frontmatter', `invalid key \"${key}\"`, filePath);\n if (!FIELD_SET.has(key)) fail(key, 'unknown frontmatter key', filePath);\n if (values.has(key)) fail(key, 'duplicate frontmatter key', filePath);\n let parsed: unknown;\n try {\n parsed = JSON.parse(line.slice(separator + 2));\n } catch {\n fail(key, 'value is not valid JSON', filePath);\n }\n values.set(key, parsed);\n }\n\n for (const field of ['id', 'mem_schema', 'kind', 'scope', 'abstract', 'created_at', 'valid_from']) {\n if (!values.has(field)) fail(field, 'missing required field', filePath);\n }\n\n const id = requireString(values.get('id'), 'id', filePath);\n if (!ID.test(id)) fail('id', 'must look like mem-YYYYMMDD-8hex', filePath);\n if (values.get('mem_schema') !== 1 && values.get('mem_schema') !== 2) {\n fail('mem_schema', 'must be 1 or 2', filePath);\n }\n const memSchema = values.get('mem_schema') as 1 | 2;\n const kind = requireString(values.get('kind'), 'kind', filePath);\n if (!KINDS.has(kind as Kind)) fail('kind', 'must be fact, pitfall or exp', filePath);\n if (values.get('scope') !== 'local') fail('scope', 'must be \"local\" in V1', filePath);\n\n const rawProject = values.has('project') ? values.get('project') : null;\n const projectIssue = projectProblem(rawProject);\n if (projectIssue !== undefined) fail('project', projectIssue, filePath);\n const project = rawProject === null || rawProject === undefined ? null : (rawProject as string);\n\n const rawTags = values.has('tags') ? values.get('tags') : [];\n const tagsIssue = tagsProblem(rawTags);\n if (tagsIssue !== undefined) fail('tags', tagsIssue, filePath);\n const tags = requireArray(rawTags, 'tags', filePath).map((entry) => entry as string);\n\n const rawRelations = values.has('relations') ? values.get('relations') : [];\n const relationsIssue = relationsProblem(rawRelations, id);\n if (relationsIssue !== undefined) fail('relations', relationsIssue, filePath);\n const relations = requireArray(rawRelations, 'relations', filePath).map((entry) => {\n const relation = entry as { type: RelationType; target: string };\n return { type: relation.type, target: relation.target } satisfies MemoryRelation;\n });\n\n const rawSource = values.has('source') ? values.get('source') : null;\n const sourceIssue = sourceProblem(rawSource);\n if (sourceIssue !== undefined) fail('source', sourceIssue, filePath);\n const source = rawSource === null || rawSource === undefined ? null : (rawSource as { type: string; id: string });\n\n const abstract = requireString(values.get('abstract'), 'abstract', filePath);\n if (abstract.trim() === '') fail('abstract', 'must not be empty', filePath);\n if (/[\\r\\n]/.test(abstract)) fail('abstract', 'must be a single line', filePath);\n if ([...abstract].length > limits.abstractChars) {\n fail('abstract', `exceeds limits.abstract_chars (${limits.abstractChars})`, filePath);\n }\n\n const createdAt = requireString(values.get('created_at'), 'created_at', filePath);\n if (!TIMESTAMP.test(createdAt)) fail('created_at', 'must be an ISO timestamp with an offset', filePath);\n\n const validFrom = requireString(values.get('valid_from'), 'valid_from', filePath);\n if (!isValidDate(validFrom)) fail('valid_from', 'must be a real YYYY-MM-DD date', filePath);\n\n const rawValidUntil = values.has('valid_until') ? values.get('valid_until') : null;\n let validUntil: string | null = null;\n if (rawValidUntil !== null) {\n validUntil = requireString(rawValidUntil, 'valid_until', filePath);\n if (!isValidDate(validUntil)) fail('valid_until', 'must be null or a real YYYY-MM-DD date', filePath);\n if (validUntil <= validFrom) fail('valid_until', 'must be after valid_from', filePath);\n }\n\n const rawSupersedes = values.has('supersedes') ? values.get('supersedes') : [];\n const supersedes = requireArray(rawSupersedes, 'supersedes', filePath).map((entry) => {\n const target = requireString(entry, 'supersedes[]', filePath);\n if (!ID.test(target)) fail('supersedes[]', `invalid memory id \"${target}\"`, filePath);\n return target;\n });\n if (new Set(supersedes).size !== supersedes.length) fail('supersedes', 'must not contain duplicates', filePath);\n if (supersedes.includes(id)) fail('supersedes', 'must not reference itself', filePath);\n\n const author = requireString(values.get('author'), 'author', filePath);\n if (author !== 'agent' && author !== 'human') fail('author', 'must be agent or human', filePath);\n\n const evidenceLevel = requireString(values.get('evidence_level'), 'evidence_level', filePath);\n if (!EVIDENCE.has(evidenceLevel as EvidenceLevel)) {\n fail('evidence_level', 'must be user_explicit, user_confirmed, observed or inferred', filePath);\n }\n\n const rawSignatures = values.has('error_signatures') ? values.get('error_signatures') : [];\n const errorSignatures = requireArray(rawSignatures, 'error_signatures', filePath).map((entry) => {\n const signature = requireString(entry, 'error_signatures[]', filePath);\n if (signature.length === 0) fail('error_signatures[]', 'must not be empty', filePath);\n if ([...signature].length > 80) fail('error_signatures[]', 'must be at most 80 characters', filePath);\n return signature;\n });\n if (errorSignatures.length > 3) fail('error_signatures', 'must contain at most 3 entries', filePath);\n if (kind === 'pitfall' && errorSignatures.length === 0) {\n fail('error_signatures', 'a pitfall must declare at least one signature', filePath);\n }\n\n const rawProvenance = values.has('provenance') ? values.get('provenance') : [];\n const provenance = requireArray(rawProvenance, 'provenance', filePath).map((entry) => {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {\n fail('provenance[]', 'must be an object', filePath);\n }\n const record = entry as Record<string, unknown>;\n const sessionId = requireString(record.session_id, 'provenance[].session_id', filePath);\n const eventSeq = record.event_seq;\n if (typeof eventSeq !== 'number' || !Number.isSafeInteger(eventSeq) || eventSeq < 0) {\n fail('provenance[].event_seq', 'must be a non-negative integer', filePath);\n }\n const speaker = requireString(record.speaker, 'provenance[].speaker', filePath);\n if (!SPEAKERS.has(speaker)) fail('provenance[].speaker', 'must be user, assistant, tool or system', filePath);\n const quote = requireString(record.quote, 'provenance[].quote', filePath);\n if ([...quote].length > 160) fail('provenance[].quote', 'must be at most 160 characters', filePath);\n const eventSha = requireString(record.event_sha256, 'provenance[].event_sha256', filePath);\n if (!SHA256.test(eventSha)) fail('provenance[].event_sha256', 'must be 64 lowercase hex characters', filePath);\n return { session_id: sessionId, event_seq: eventSeq, speaker, quote, event_sha256: eventSha } as ProvenanceEntry;\n });\n if (author === 'agent' && provenance.length === 0) {\n fail('provenance', 'an agent-authored memory needs at least one provenance entry', filePath);\n }\n\n if ([...body].length > limits.bodyChars) {\n fail('body', `exceeds limits.body_chars (${limits.bodyChars})`, filePath);\n }\n if ([...normalized].length > limits.maxRecordChars) {\n fail('file', `exceeds storage.max_record_chars (${limits.maxRecordChars})`, filePath);\n }\n\n return {\n id,\n mem_schema: memSchema,\n kind: kind as Kind,\n scope: 'local',\n project,\n tags,\n relations,\n source,\n abstract,\n created_at: createdAt,\n valid_from: validFrom,\n valid_until: validUntil,\n supersedes,\n author,\n evidence_level: evidenceLevel as EvidenceLevel,\n error_signatures: errorSignatures,\n provenance,\n body,\n file_path: filePath,\n content_hash: hashContent(normalized),\n };\n}\n\n/** Serialize in the fixed field order so diffs stay stable. */\nexport function serializeMemory(doc: Omit<MemoryDoc, 'file_path' | 'content_hash'>): string {\n const values: Record<string, unknown> = {\n id: doc.id,\n mem_schema: doc.mem_schema,\n kind: doc.kind,\n scope: doc.scope,\n project: doc.project ?? null,\n tags: doc.tags ?? [],\n relations: doc.relations ?? [],\n source: doc.source ?? null,\n abstract: doc.abstract,\n created_at: doc.created_at,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n supersedes: doc.supersedes,\n author: doc.author,\n evidence_level: doc.evidence_level,\n error_signatures: doc.error_signatures,\n provenance: doc.provenance,\n };\n const lines = FIELD_ORDER.map((field) => `${field}: ${JSON.stringify(values[field])}`);\n const body = doc.body.endsWith('\\n') ? doc.body : `${doc.body}\\n`;\n return `---\\n${lines.join('\\n')}\\n---\\n${body}`;\n}\n", "import type { MemoryRelation, MemorySource, RelationType } from './types.ts';\n\n/**\n * Metadata limits for the v1.4 fields (`project`, `tags`, `relations`).\n *\n * Kept in one module so the file parser and the store reject the same shapes.\n * Relations deliberately stop at three edge families: `supersedes` remains its\n * own immutable field; `relates_to`/`derived_from` live here.\n */\n\nexport const PROJECT_NAME_MAX = 64;\nexport const TAG_MAX = 32;\nexport const TAGS_MAX = 8;\nexport const RELATIONS_MAX = 16;\n\nconst RELATION_TYPES: readonly RelationType[] = ['relates_to', 'derived_from'];\nconst MEMORY_ID = /^mem-\\d{8}-[0-9a-f]{8}$/;\n\nexport function projectProblem(value: unknown): string | undefined {\n if (value === null || value === undefined) return undefined;\n if (typeof value !== 'string') return 'project must be a string or null';\n const name = value.trim();\n if (name === '') return 'project must not be empty';\n if (name !== value) return 'project must not have leading or trailing whitespace';\n if ([...name].length > PROJECT_NAME_MAX) {\n return `project must be at most ${PROJECT_NAME_MAX} characters`;\n }\n if (/[\\r\\n]/.test(name)) return 'project must be a single line';\n if (/[\\\\/]/.test(name)) return 'project must not contain path separators';\n if (name === '\u672A\u5F52\u7C7B') return 'project name \"\u672A\u5F52\u7C7B\" is reserved for the default bucket';\n return undefined;\n}\n\nexport function tagsProblem(value: unknown): string | undefined {\n if (!Array.isArray(value)) return 'tags must be an array';\n if (value.length > TAGS_MAX) return `tags allows at most ${TAGS_MAX} entries`;\n const seen = new Set<string>();\n for (const entry of value) {\n if (typeof entry !== 'string') return 'each tag must be a string';\n if (entry.length === 0) return 'tags must not contain empty entries';\n if ([...entry].length > TAG_MAX) return `each tag must be at most ${TAG_MAX} characters`;\n if (/[\\r\\n]/.test(entry)) return 'tags must be single-line';\n if (seen.has(entry)) return `duplicate tag \"${entry}\"`;\n seen.add(entry);\n }\n return undefined;\n}\n\nexport function relationsProblem(value: unknown, selfId?: string): string | undefined {\n if (!Array.isArray(value)) return 'relations must be an array';\n if (value.length > RELATIONS_MAX) return `relations allows at most ${RELATIONS_MAX} entries`;\n const seen = new Set<string>();\n for (const entry of value) {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {\n return 'each relation must be an object';\n }\n const relation = entry as { type?: unknown; target?: unknown };\n if (typeof relation.type !== 'string' || !RELATION_TYPES.includes(relation.type as RelationType)) {\n return 'relation.type must be relates_to or derived_from';\n }\n if (typeof relation.target !== 'string' || !MEMORY_ID.test(relation.target)) {\n return 'relation.target must look like mem-YYYYMMDD-8hex';\n }\n if (relation.target === selfId) return 'a relation must not target itself';\n const key = `${relation.type}:${relation.target}`;\n if (seen.has(key)) return 'relations must not contain duplicates';\n seen.add(key);\n }\n return undefined;\n}\n\nexport function normalizeRelations(value: readonly MemoryRelation[] | undefined): readonly MemoryRelation[] {\n if (value === undefined || value.length === 0) return [];\n return value.map((relation) => ({ type: relation.type, target: relation.target }));\n}\n\n/** External provenance marker for imported records (Mem0 first). */\nexport function sourceProblem(value: unknown): string | undefined {\n if (value === null || value === undefined) return undefined;\n if (typeof value !== 'object' || Array.isArray(value)) return 'source must be an object or null';\n const source = value as { type?: unknown; id?: unknown };\n if (typeof source.type !== 'string' || source.type.length === 0 || [...source.type].length > 32) {\n return 'source.type must be a non-empty string up to 32 characters';\n }\n if (typeof source.id !== 'string' || source.id.length === 0 || [...source.id].length > 128) {\n return 'source.id must be a non-empty string up to 128 characters';\n }\n if (/[\\r\\n]/.test(source.type) || /[\\r\\n]/.test(source.id)) return 'source values must be single-line';\n return undefined;\n}\n\nexport function normalizeSource(value: MemorySource | null | undefined): MemorySource | null {\n if (value === null || value === undefined) return null;\n return { type: value.type, id: value.id };\n}\n", "import { existsSync, readFileSync } from 'node:fs';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { projectProblem, PROJECT_NAME_MAX } from '../model/metadata.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * User-created project registry (v1.4).\n *\n * Projects are labels, not folders: a memory points at a project name, and the\n * registry only decides which names the UI offers. Deleting a project therefore\n * never deletes memories; they simply stop matching a live project.\n *\n * The file is plain JSON at `<home>/projects.json` and is intentionally small:\n * `{ schema: 1, projects: [{ name, description, created_at, updated_at }] }`.\n */\n\nexport interface Project {\n readonly name: string;\n readonly description: string;\n readonly created_at: string;\n readonly updated_at: string;\n}\n\nexport interface ProjectRegistry {\n readonly schema: 1;\n readonly projects: readonly Project[];\n}\n\nexport class ProjectError extends Error {\n readonly code: 'INVALID' | 'EXISTS' | 'NOT_FOUND';\n constructor(code: ProjectError['code'], message: string) {\n super(message);\n this.name = 'ProjectError';\n this.code = code;\n }\n}\n\nconst DESCRIPTION_MAX = 280;\nconst TIMESTAMP = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nfunction readRegistry(home: string): ProjectRegistry {\n const file = memoryPaths(home).projectsFile;\n if (!existsSync(file)) return { schema: 1, projects: [] };\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(file, 'utf8').replace(/^\\uFEFF/, ''));\n } catch {\n throw new ProjectError('INVALID', `projects.json is not valid JSON: ${file}`);\n }\n if (typeof parsed !== 'object' || parsed === null) {\n throw new ProjectError('INVALID', 'projects.json must be an object');\n }\n const record = parsed as { schema?: unknown; projects?: unknown };\n if (record.schema !== 1) throw new ProjectError('INVALID', 'projects.json schema must be 1');\n if (!Array.isArray(record.projects)) throw new ProjectError('INVALID', 'projects.json projects must be an array');\n const seen = new Set<string>();\n const projects: Project[] = [];\n for (const raw of record.projects) {\n if (typeof raw !== 'object' || raw === null) throw new ProjectError('INVALID', 'each project must be an object');\n const entry = raw as { name?: unknown; description?: unknown; created_at?: unknown; updated_at?: unknown };\n const issue = projectProblem(entry.name);\n if (issue !== undefined) throw new ProjectError('INVALID', issue);\n if (typeof entry.description !== 'string' || [...entry.description].length > DESCRIPTION_MAX) {\n throw new ProjectError('INVALID', `project description must be a string up to ${DESCRIPTION_MAX} characters`);\n }\n if (typeof entry.created_at !== 'string' || !TIMESTAMP.test(entry.created_at)) {\n throw new ProjectError('INVALID', 'project created_at must be an ISO timestamp');\n }\n if (typeof entry.updated_at !== 'string' || !TIMESTAMP.test(entry.updated_at)) {\n throw new ProjectError('INVALID', 'project updated_at must be an ISO timestamp');\n }\n const name = entry.name as string;\n if (seen.has(name.toLocaleLowerCase())) throw new ProjectError('INVALID', `duplicate project name: ${name}`);\n seen.add(name.toLocaleLowerCase());\n projects.push({\n name,\n description: entry.description,\n created_at: entry.created_at,\n updated_at: entry.updated_at,\n });\n }\n return { schema: 1, projects };\n}\n\nfunction writeRegistry(home: string, registry: ProjectRegistry): void {\n writeFileAtomic(memoryPaths(home).projectsFile, `${JSON.stringify(registry, null, 2)}\\n`);\n}\n\nexport function listProjects(home: string): readonly Project[] {\n return readRegistry(home).projects;\n}\n\nexport function projectExists(home: string, name: string): boolean {\n const lower = name.toLocaleLowerCase();\n return readRegistry(home).projects.some((project) => project.name.toLocaleLowerCase() === lower);\n}\n\nexport function createProject(options: {\n home: string;\n name: string;\n description?: string;\n now?: Date;\n}): Project {\n const name = options.name.trim();\n const issue = projectProblem(name);\n if (issue !== undefined) throw new ProjectError('INVALID', issue);\n if (name.length > PROJECT_NAME_MAX) throw new ProjectError('INVALID', 'project name is too long');\n const description = (options.description ?? '').trim();\n if ([...description].length > DESCRIPTION_MAX) {\n throw new ProjectError('INVALID', `project description must be at most ${DESCRIPTION_MAX} characters`);\n }\n if (/[\\r\\n]/.test(description)) throw new ProjectError('INVALID', 'project description must be a single line');\n const registry = readRegistry(options.home);\n if (registry.projects.some((project) => project.name.toLocaleLowerCase() === name.toLocaleLowerCase())) {\n throw new ProjectError('EXISTS', `project already exists: ${name}`);\n }\n const at = (options.now ?? new Date()).toISOString();\n const project: Project = { name, description, created_at: at, updated_at: at };\n writeRegistry(options.home, { schema: 1, projects: [...registry.projects, project] });\n return project;\n}\n\n/** Create an empty registry during `mem init`; existing files are kept. */\nexport function ensureProjectsFile(home: string): boolean {\n const file = memoryPaths(home).projectsFile;\n if (existsSync(file)) return false;\n writeRegistry(home, { schema: 1, projects: [] });\n return true;\n}\n\n/**\n * Remove a project label. Memories keep their frontmatter untouched; callers\n * map an unknown project to the \"\u672A\u5F52\u7C7B\" bucket. If the name is later recreated,\n * those memories become visible under it again by design.\n */\nexport function deleteProject(home: string, name: string): boolean {\n const registry = readRegistry(home);\n const lower = name.toLocaleLowerCase();\n const kept = registry.projects.filter((project) => project.name.toLocaleLowerCase() !== lower);\n if (kept.length === registry.projects.length) return false;\n writeRegistry(home, { schema: 1, projects: kept });\n return true;\n}\n", "import { randomBytes } from 'node:crypto';\nimport { closeSync, fsyncSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';\nimport { sleepSync } from './wait.ts';\n\n/**\n * Single-writer lock with a lease.\n *\n * Acquired before the first read and held across read \u2192 validate \u2192 write \u2192\n * journal \u2192 derived files (plan v1.3 \u00A76.2). A lease only becomes stale when its\n * heartbeat is older than `stale_ms` **and** the recorded PID is gone; a live\n * process keeps the lock even if its heartbeat is late, so a slow operation is\n * never silently overwritten.\n */\n\nexport interface LockConfig {\n readonly heartbeatMs: number;\n readonly staleMs: number;\n readonly timeoutMs: number;\n}\n\nexport interface LockFileInfo {\n readonly pid: number;\n readonly token: string;\n readonly acquired_at: number;\n readonly heartbeat_at: number;\n}\n\nexport type LockErrorCode = 'LOCK_TIMEOUT' | 'LOCK_LOST';\n\nexport class LockError extends Error {\n readonly code: LockErrorCode;\n constructor(code: LockErrorCode, message: string) {\n super(message);\n this.name = 'LockError';\n this.code = code;\n }\n}\n\nexport function readLock(file: string): LockFileInfo | null {\n try {\n const raw = JSON.parse(readFileSync(file, 'utf8')) as Partial<LockFileInfo>;\n if (\n typeof raw.pid === 'number' &&\n typeof raw.token === 'string' &&\n typeof raw.acquired_at === 'number' &&\n typeof raw.heartbeat_at === 'number'\n ) {\n return { pid: raw.pid, token: raw.token, acquired_at: raw.acquired_at, heartbeat_at: raw.heartbeat_at };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\nfunction lockIsStale(file: string, info: LockFileInfo | null, config: LockConfig, now: number): boolean {\n if (info === null) {\n // Unreadable lock file: only a crashed writer can leave one; age it by mtime.\n try {\n return now - statSync(file).mtimeMs > config.staleMs;\n } catch {\n return false;\n }\n }\n return now - info.heartbeat_at > config.staleMs && !processAlive(info.pid);\n}\n\nexport interface AcquireOptions {\n readonly file: string;\n readonly config: LockConfig;\n readonly now?: () => number;\n}\n\nexport class FileLock {\n readonly file: string;\n readonly token: string;\n private readonly now: () => number;\n private timer: NodeJS.Timeout | undefined;\n private closed = false;\n\n constructor(file: string, token: string, config: LockConfig, now: () => number) {\n this.file = file;\n this.token = token;\n this.now = now;\n this.timer = setInterval(() => this.touch(), config.heartbeatMs);\n this.timer.unref();\n }\n\n touch(): void {\n if (this.closed) return;\n const current = readLock(this.file);\n if (current === null || current.token !== this.token) return;\n this.write({ ...current, heartbeat_at: this.now() });\n }\n\n assertHeld(): void {\n const current = readLock(this.file);\n if (current === null || current.token !== this.token) {\n throw new LockError('LOCK_LOST', `lock ${this.file} is no longer held by this process`);\n }\n }\n\n release(): void {\n if (this.closed) return;\n this.closed = true;\n if (this.timer !== undefined) clearInterval(this.timer);\n const current = readLock(this.file);\n if (current !== null && current.token === this.token) {\n try {\n unlinkSync(this.file);\n } catch {\n // A vanished lock file is already released.\n }\n }\n }\n\n private write(info: LockFileInfo): void {\n const fd = openSync(this.file, 'w');\n try {\n writeSync(fd, JSON.stringify(info));\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n }\n}\n\nexport function acquireLock(options: AcquireOptions): FileLock {\n const now = options.now ?? Date.now;\n const deadline = now() + options.config.timeoutMs;\n const token = randomBytes(8).toString('hex');\n\n for (;;) {\n const info: LockFileInfo = {\n pid: process.pid,\n token,\n acquired_at: now(),\n heartbeat_at: now(),\n };\n try {\n const fd = openSync(options.file, 'wx');\n try {\n writeSync(fd, JSON.stringify(info));\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n return new FileLock(options.file, token, options.config, now);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== 'EEXIST') throw error;\n }\n\n const existing = readLock(options.file);\n if (lockIsStale(options.file, existing, options.config, now())) {\n try {\n unlinkSync(options.file);\n } catch {\n // Someone else cleared it first; the retry loop handles either outcome.\n }\n continue;\n }\n\n if (now() >= deadline) {\n throw new LockError(\n 'LOCK_TIMEOUT',\n `timed out after ${options.config.timeoutMs}ms waiting for ${options.file}`,\n );\n }\n sleepSync(Math.min(50, Math.max(1, deadline - now())));\n }\n}\n\n/** Test helper: overwrite the heartbeat so a fake writer looks abandoned. */\nexport function forceHeartbeat(file: string, at: number): void {\n const info = readLock(file);\n if (info === null) return;\n writeFileSync(file, JSON.stringify({ ...info, heartbeat_at: at }));\n}\n", "import { randomBytes } from 'node:crypto';\n\n/** `mem-YYYYMMDD-8hex`; generated server-side, never accepted from a model. */\nconst ID_PATTERN = /^mem-\\d{8}-[0-9a-f]{8}$/;\n\nexport function isMemoryId(value: string): boolean {\n return ID_PATTERN.test(value);\n}\n\nexport function formatDate(date: Date): string {\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const day = String(date.getDate()).padStart(2, '0');\n return `${year}-${month}-${day}`;\n}\n\nexport function newMemoryId(now: Date = new Date(), bytes: () => Buffer = () => randomBytes(4)): string {\n return `mem-${formatDate(now).replaceAll('-', '')}-${bytes().toString('hex')}`;\n}\n", "import type { MemoryDoc, MemoryId } from './types.ts';\n\n/**\n * Validity is derived, never stored back into a file:\n *\n * effective end = min(valid_until, every successor's valid_from)\n *\n * A memory is active on a date when `valid_from <= date < effective end`.\n * Supersede edges point from the successor to the memory it replaces, so the\n * reverse map below is rebuilt from the files on every scan.\n */\n\nexport type SuccessorMap = ReadonlyMap<MemoryId, readonly MemoryId[]>;\n\nexport function buildSuccessorMap(docs: Iterable<MemoryDoc>): Map<MemoryId, MemoryId[]> {\n const map = new Map<MemoryId, MemoryId[]>();\n for (const doc of docs) {\n for (const target of doc.supersedes) {\n const list = map.get(target);\n if (list === undefined) map.set(target, [doc.id]);\n else list.push(doc.id);\n }\n }\n return map;\n}\n\n/** Today as `YYYY-MM-DD` in the host's local time zone (the store's date basis). */\nexport function today(now: Date = new Date()): string {\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const day = String(now.getDate()).padStart(2, '0');\n return `${year}-${month}-${day}`;\n}\n\nexport interface DatedPeriod {\n readonly valid_from: string;\n readonly valid_until: string | null;\n /** Ids of memories that supersede this one. */\n readonly successors: readonly MemoryId[];\n}\n\n/**\n * `validFromOf` resolves a successor id to its `valid_from`; passing it in keeps\n * the validity helpers independent of a document collection.\n */\nexport function endFor(period: DatedPeriod, validFromOf: (id: MemoryId) => string | undefined): string | null {\n let end = period.valid_until;\n for (const successorId of period.successors) {\n const start = validFromOf(successorId);\n if (start === undefined) continue;\n if (end === null || start < end) end = start;\n }\n return end;\n}\n\nexport function isActiveOn(\n period: DatedPeriod,\n date: string,\n validFromOf: (id: MemoryId) => string | undefined,\n): boolean {\n if (date < period.valid_from) return false;\n const end = endFor(period, validFromOf);\n return end === null || date < end;\n}\n\n/** Build the `validFromOf` lookup used by the helpers above. */\nexport function validFromLookup(docs: Iterable<MemoryDoc>): (id: MemoryId) => string | undefined {\n const map = new Map<MemoryId, string>();\n for (const doc of docs) map.set(doc.id, doc.valid_from);\n return (id) => map.get(id);\n}\n\n/** Active docs on `date`, newest first by valid_from then id (deterministic). */\nexport function activeDocs(docs: Iterable<MemoryDoc>, date: string): MemoryDoc[] {\n const all = [...docs];\n const validFromOf = validFromLookup(all);\n const successors = buildSuccessorMap(all);\n return all\n .filter((doc) =>\n isActiveOn(\n {\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n successors: successors.get(doc.id) ?? [],\n },\n date,\n validFromOf,\n ),\n )\n .sort((left, right) => {\n if (left.valid_from !== right.valid_from) return right.valid_from.localeCompare(left.valid_from);\n return left.id.localeCompare(right.id);\n });\n}\n\n/**\n * Problems that make a new/updated supersede edge invalid. The candidate is\n * not yet in `docs`; its id must not be reachable from any target.\n */\nexport function supersedeProblems(\n candidate: { readonly id: MemoryId; readonly supersedes: readonly MemoryId[]; readonly valid_from: string },\n docs: ReadonlyMap<MemoryId, MemoryDoc>,\n): string[] {\n const problems: string[] = [];\n const seen = new Set<string>();\n for (const target of candidate.supersedes) {\n if (seen.has(target)) problems.push(`supersedes lists \"${target}\" twice`);\n seen.add(target);\n const doc = docs.get(target);\n if (doc === undefined) {\n problems.push(`supersedes target \"${target}\" does not exist`);\n continue;\n }\n if (doc.valid_from > candidate.valid_from) {\n problems.push(`supersedes target \"${target}\" starts after the successor (${doc.valid_from} > ${candidate.valid_from})`);\n }\n const stack = [...doc.supersedes];\n const visited = new Set<MemoryId>();\n while (stack.length > 0) {\n const current = stack.pop() as MemoryId;\n if (current === candidate.id) {\n problems.push(`supersede chain would form a cycle through \"${target}\"`);\n break;\n }\n if (visited.has(current)) continue;\n visited.add(current);\n const next = docs.get(current);\n if (next !== undefined) stack.push(...next.supersedes);\n }\n }\n return problems;\n}\n", "import { createHash } from 'node:crypto';\nimport { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, statSync, writeSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { JournalEntry, JournalIssue } from '../model/types.ts';\n\n/**\n * The single append-only journal: accounting, deletions, decisions and audit\n * notes live in one place (plan v1.3 D31).\n *\n * One JSON object per line. `hash` is the SHA-256 of that line's bytes without\n * the newline; `prev` is the previous line's hash (64 zeros for the first).\n * Segments roll at 5 MiB and are never rotated away or deleted. `op_id` makes a\n * retried append idempotent.\n */\n\nexport const SEGMENT_BYTES = 5 * 1024 * 1024;\nexport const ZERO_HASH = '0'.repeat(64);\n\nexport type JournalOp = JournalEntry['op'];\n\nexport function hashLine(line: string): string {\n return createHash('sha256').update(line, 'utf8').digest('hex');\n}\n\nexport interface JournalHead {\n readonly seq: number;\n readonly hash: string;\n}\n\nexport interface JournalReadResult {\n readonly entries: readonly JournalEntry[];\n readonly hashes: readonly string[];\n readonly issues: readonly JournalIssue[];\n readonly head: JournalHead | null;\n}\n\nexport interface AppendInput {\n readonly op: JournalOp;\n readonly data: Readonly<Record<string, unknown>>;\n readonly opId?: string;\n readonly at?: string;\n}\n\nexport class Journal {\n readonly dir: string;\n\n constructor(dir: string) {\n this.dir = dir;\n }\n\n segments(): string[] {\n try {\n return readdirSync(this.dir)\n .filter((name) => /^\\d{4}\\.jsonl$/.test(name))\n .sort();\n } catch {\n return [];\n }\n }\n\n /** Last accepted entry, without verifying the whole log. */\n head(): JournalHead | null {\n const segments = this.segments();\n for (let index = segments.length - 1; index >= 0; index -= 1) {\n const file = join(this.dir, segments[index] as string);\n const lines = readFileSync(file, 'utf8').split('\\n').filter((line) => line !== '');\n if (lines.length === 0) continue;\n const last = lines[lines.length - 1] as string;\n try {\n const entry = JSON.parse(last) as JournalEntry;\n return { seq: entry.seq, hash: hashLine(last) };\n } catch {\n return null;\n }\n }\n return null;\n }\n\n readAll(): JournalReadResult {\n const entries: JournalEntry[] = [];\n const hashes: string[] = [];\n const issues: JournalIssue[] = [];\n const opIds = new Set<string>();\n let expectedSeq = 1;\n let prev = ZERO_HASH;\n\n for (const name of this.segments()) {\n const file = join(this.dir, name);\n let text: string;\n try {\n text = readFileSync(file, 'utf8');\n } catch (error) {\n issues.push({ kind: 'parse', message: `cannot read ${name}: ${String(error)}` });\n continue;\n }\n const lines = text.split('\\n');\n // A trailing newline is expected; a final non-empty line without one is a\n // torn append and must not be trusted.\n if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();\n for (const line of lines) {\n if (line === '') continue;\n let entry: JournalEntry;\n try {\n entry = JSON.parse(line) as JournalEntry;\n } catch {\n issues.push({ kind: 'parse', message: `${name}: line is not valid JSON`, seq: expectedSeq });\n return { entries, hashes, issues, head: entries.length === 0 ? null : { seq: entries.length, hash: prev } };\n }\n const hash = hashLine(line);\n if (entry.seq !== expectedSeq) {\n issues.push({\n kind: 'seq',\n message: `${name}: expected seq ${expectedSeq}, found ${entry.seq}`,\n seq: entry.seq,\n });\n }\n if (entry.prev !== prev) {\n issues.push({\n kind: 'chain',\n message: `${name}: seq ${entry.seq} prev does not match the previous line hash`,\n seq: entry.seq,\n });\n }\n if (opIds.has(entry.op_id)) {\n issues.push({ kind: 'duplicate-op', message: `${name}: duplicate op_id ${entry.op_id}`, seq: entry.seq });\n }\n opIds.add(entry.op_id);\n entries.push(entry);\n hashes.push(hash);\n expectedSeq = entry.seq + 1;\n prev = hash;\n }\n }\n\n const head = entries.length === 0 ? null : { seq: entries[entries.length - 1]?.seq ?? 0, hash: prev };\n return { entries, hashes, issues, head };\n }\n\n findByOpId(opId: string): JournalEntry | undefined {\n return this.readAll().entries.find((entry) => entry.op_id === opId);\n }\n\n /**\n * Append one entry. The caller must hold the store lock: `head()` and the\n * write are not atomic on their own. A repeated `opId` returns the existing\n * entry instead of appending a second one.\n */\n append(input: AppendInput): JournalEntry {\n mkdirSync(this.dir, { recursive: true });\n if (input.opId !== undefined) {\n const existing = this.findByOpId(input.opId);\n if (existing !== undefined) return existing;\n }\n\n const segments = this.segments();\n const lastSegment = segments[segments.length - 1] ?? '0001.jsonl';\n const head = this.head();\n const seq = head === null ? 1 : head.seq + 1;\n const prev = head === null ? ZERO_HASH : head.hash;\n const entry: JournalEntry = {\n seq,\n prev,\n at: input.at ?? new Date().toISOString(),\n op: input.op,\n op_id: input.opId ?? `op-${seq}-${hashLine(`${seq}:${input.op}:${JSON.stringify(input.data)}`).slice(0, 8)}`,\n data: input.data,\n };\n const line = JSON.stringify(entry);\n\n let segmentPath = join(this.dir, lastSegment);\n let size = 0;\n try {\n size = statSync(segmentPath).size;\n } catch {\n size = 0;\n }\n if (size > 0 && size + Buffer.byteLength(line) + 1 > SEGMENT_BYTES) {\n const nextNumber = Number(lastSegment.slice(0, 4)) + 1;\n segmentPath = join(this.dir, `${String(nextNumber).padStart(4, '0')}.jsonl`);\n }\n\n const fd = openSync(segmentPath, 'a');\n try {\n writeSync(fd, `${line}\\n`);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n return entry;\n }\n}\n\n/** One human-readable line for `mem inspect --audit`. */\nexport function formatJournalEntry(entry: JournalEntry): string {\n const summary = JSON.stringify(entry.data);\n return `${entry.at} #${entry.seq} ${entry.op.padEnd(6)} ${entry.op_id} ${summary}`;\n}\n", "import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Config } from '../config/config.ts';\nimport { ensureDir, writeFileAtomic } from '../fs/atomic.ts';\nimport { acquireLock } from '../fs/lock.ts';\nimport { Journal } from '../journal/journal.ts';\nimport { hashContent, parseMemoryFile, serializeMemory } from '../model/frontmatter.ts';\nimport { projectProblem, relationsProblem, sourceProblem, tagsProblem } from '../model/metadata.ts';\nimport { isMemoryId, newMemoryId } from '../model/ids.ts';\nimport { activeDocs, today } from '../model/validity.ts';\nimport { supersedeProblems } from '../model/validity.ts';\nimport { buildIndex, search } from '../index/bm25.ts';\nimport { cosine, HashEmbeddingProvider } from '../index/embedding.ts';\nimport { fuseScores } from '../index/hybrid.ts';\nimport { embedTexts, readEmbeddingCache, vectorizerCommand } from '../embed/cache.ts';\nimport { TOKENIZER_VERSION } from '../index/tokenizer.ts';\nimport { scanInput } from '../scan/scan.ts';\nimport type {\n Kind,\n MemoryDoc,\n MemoryId,\n RecallResult,\n RecallHit,\n RebuildReport,\n RecordInput,\n ProvenanceEntry,\n Stats,\n WriteResult,\n} from '../model/types.ts';\nimport { memoryPaths, type MemoryPaths } from '../paths.ts';\n\nexport interface StoreOptions {\n readonly home: string;\n readonly config: Config;\n readonly now?: () => Date;\n /** Test seam: called before each commit step; production passes undefined. */\n readonly beforeStep?: (step: string) => void;\n}\n\nexport class MemoryStoreError extends Error {\n readonly code: 'NOT_FOUND' | 'INVALID' | 'CONFLICT';\n constructor(code: MemoryStoreError['code'], message: string) {\n super(message);\n this.name = 'MemoryStoreError';\n this.code = code;\n }\n}\n\nconst KINDS: readonly Kind[] = ['fact', 'pitfall', 'exp'];\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nfunction isRealDate(value: string): boolean {\n const match = DATE.exec(value);\n if (match === null) return false;\n const [, year, month, day] = match;\n const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)));\n return (\n date.getUTCFullYear() === Number(year) &&\n date.getUTCMonth() === Number(month) - 1 &&\n date.getUTCDate() === Number(day)\n );\n}\n\nexport class MemoryStore {\n readonly paths: MemoryPaths;\n readonly config: Config;\n readonly journal: Journal;\n private readonly now: () => Date;\n private readonly beforeStep: ((step: string) => void) | undefined;\n private docs = new Map<MemoryId, MemoryDoc>();\n private quarantined = new Map<MemoryId, string>();\n private deleted = new Set<MemoryId>();\n private accounted = new Map<MemoryId, string>();\n private issues: string[] = [];\n private head: { seq: number; hash: string } | null = null;\n\n constructor(options: StoreOptions) {\n this.paths = memoryPaths(options.home);\n this.config = options.config;\n this.now = options.now ?? (() => new Date());\n this.beforeStep = options.beforeStep;\n this.journal = new Journal(this.paths.journalDir);\n this.reload();\n }\n\n /** Re-read the journal and the memory files; classify each file. */\n reload(): void {\n const read = this.journal.readAll();\n this.issues = read.issues.map((issue) => issue.message);\n this.head = read.head;\n this.docs = new Map();\n this.quarantined = new Map();\n this.deleted = new Set();\n this.accounted = new Map();\n\n const latest = new Map<MemoryId, { hash: string; deleted: boolean }>();\n for (const entry of read.entries) {\n const id = typeof entry.data.id === 'string' ? entry.data.id : undefined;\n if (entry.op === 'record' || entry.op === 'adopt') {\n if (id === undefined || typeof entry.data.sha256 !== 'string') continue;\n latest.set(id, { hash: entry.data.sha256, deleted: latest.get(id)?.deleted ?? false });\n } else if (entry.op === 'delete') {\n if (id === undefined) continue;\n latest.set(id, { hash: latest.get(id)?.hash ?? '', deleted: true });\n this.deleted.add(id);\n }\n }\n for (const [id, value] of latest) {\n if (value.hash !== '') this.accounted.set(id, value.hash);\n }\n\n for (const kind of KINDS) {\n const dir = join(this.paths.memoriesDir, kind);\n let names: string[];\n try {\n names = readdirSync(dir).filter((name) => name.endsWith('.md'));\n } catch {\n continue;\n }\n for (const name of names) {\n const file = join(dir, name);\n const id = name.slice(0, -3);\n try {\n const text = readFileSync(file, 'utf8');\n const doc = parseMemoryFile(text, file, {\n abstractChars: this.config.limits.abstract_chars,\n bodyChars: this.config.limits.body_chars,\n maxRecordChars: this.config.storage.max_record_chars,\n });\n if (!isMemoryId(id) || doc.id !== id) {\n this.quarantined.set(doc.id || id, 'id does not match filename');\n continue;\n }\n if (doc.kind !== kind) {\n this.quarantined.set(doc.id, 'kind does not match directory');\n continue;\n }\n const accountedHash = this.accounted.get(doc.id);\n if (accountedHash === undefined) {\n this.quarantined.set(doc.id, 'not accounted in journal');\n continue;\n }\n if (accountedHash !== doc.content_hash) {\n this.quarantined.set(doc.id, 'content hash differs from journal');\n continue;\n }\n this.docs.set(doc.id, doc);\n } catch (error) {\n this.quarantined.set(id, `parse: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n\n // A journal record whose file is gone is not usable either \u2014 unless the\n // journal also records a delete/purge for it (a tombstone is not corruption).\n for (const id of this.accounted.keys()) {\n if (this.deleted.has(id)) continue;\n if (!this.docs.has(id) && !this.quarantined.has(id)) {\n this.quarantined.set(id, 'accounted in journal but file is missing');\n }\n }\n\n // Tripwire: the manifest records where the journal ended after the last\n // successful rebuild. A *shorter* journal now means truncation, not progress.\n // A *longer* journal means a writer appended without refreshing the\n // manifest (the chain is intact), which is a stale derived file, not\n // truncation \u2014 the next `writeDerived` catches up.\n try {\n const manifest = JSON.parse(readFileSync(this.paths.manifestFile, 'utf8')) as {\n journal_head?: { seq?: number; hash?: string } | null;\n };\n const expected = manifest.journal_head;\n const expectedSeq = expected?.seq;\n const expectedHash = expected?.hash;\n if (expectedSeq === undefined || expectedHash === undefined) {\n // No complete head recorded yet; nothing to compare.\n } else if (this.head === null) {\n this.issues.push('journal is empty but the manifest records a head: possible truncation');\n } else if (expectedSeq !== this.head.seq) {\n if (expectedSeq > this.head.seq) {\n this.issues.push(\n `journal head #${this.head.seq} is behind the manifest (#${String(expectedSeq)}): possible truncation`,\n );\n }\n // expectedSeq < this.head.seq: stale manifest, self-heals on write.\n } else if (expectedHash !== this.head.hash) {\n this.issues.push(\n `journal head #${this.head.seq} differs from the manifest (#${String(expectedSeq)}): possible truncation`,\n );\n }\n } catch {\n // A missing or unreadable manifest is a cache problem, not a journal one.\n }\n }\n\n active(date: string = today(this.now())): readonly MemoryDoc[] {\n const live = activeDocs(this.docs.values(), date);\n return live.filter((doc) => !this.deleted.has(doc.id) && !this.quarantined.has(doc.id));\n }\n\n read(id: MemoryId): MemoryDoc {\n // The host keeps one store open for the app process; `mem decide` / `mem add`\n // write disk underneath it. Re-scan before a single-document read so a\n // record created by the CLI is immediately readable through `memory_read`.\n this.reload();\n const doc = this.docs.get(id);\n if (doc === undefined) {\n const reason = this.quarantined.get(id);\n throw new MemoryStoreError(\n 'NOT_FOUND',\n reason === undefined ? `no memory with id ${id}` : `memory ${id} is quarantined: ${reason}`,\n );\n }\n return doc;\n }\n\n recall(\n query: string,\n options: { limit?: number; asOf?: string; kinds?: readonly Kind[] } = {},\n ): RecallResult {\n const text = query.trim();\n if (text === '') return { hits: [], warnings: ['empty query'] };\n // The host keeps one store open for the whole app process; `mem decide` and\n // other CLI writes change disk underneath it. Re-scan so recall reflects\n // them immediately (plan v1.3 \u00A76.1: recall stays live while the catalog is\n // frozen).\n this.reload();\n const date = options.asOf ?? today(this.now());\n const limit = Math.min(\n options.limit ?? this.config.recall.limit,\n this.config.recall.max_limit,\n );\n const activeSet = activeDocs(this.docs.values(), date).filter(\n (doc) => !this.deleted.has(doc.id) && !this.quarantined.has(doc.id),\n );\n const index = buildIndex(activeSet, TOKENIZER_VERSION);\n const byId = new Map(activeSet.map((doc) => [doc.id, doc]));\n const minScore = this.config.recall.min_score / 1000;\n let ranked: Array<{ id: MemoryId; score: number }>;\n if (this.config.recall.hybrid) {\n const lexicalHits = search(index, text, {\n limit: activeSet.length,\n minScorePermille: 0,\n ...(options.kinds === undefined ? {} : { kinds: options.kinds }),\n });\n const lexical = new Map(lexicalHits.map((hit) => [hit.id, hit.score]));\n const provider = new HashEmbeddingProvider();\n const queryVector = provider.embed(text);\n const vector = new Map<MemoryId, number>();\n const kindFilter = options.kinds === undefined ? undefined : new Set(options.kinds);\n for (const doc of activeSet) {\n if (kindFilter !== undefined && !kindFilter.has(doc.kind)) continue;\n vector.set(doc.id, cosine(provider.embed(`${doc.abstract}\\n${doc.body}`), queryVector));\n }\n ranked = [...fuseScores(lexical, vector, this.config.recall.embedding_weight).entries()]\n .filter(([, score]) => score >= minScore)\n .map(([id, score]) => ({ id, score }))\n .sort((left, right) => {\n if (right.score !== left.score) return right.score - left.score;\n const leftDoc = byId.get(left.id);\n const rightDoc = byId.get(right.id);\n if (leftDoc !== undefined && rightDoc !== undefined && rightDoc.valid_from !== leftDoc.valid_from) {\n return rightDoc.valid_from.localeCompare(leftDoc.valid_from);\n }\n return left.id.localeCompare(right.id);\n })\n .slice(0, limit);\n } else {\n ranked = search(index, text, {\n limit,\n minScorePermille: this.config.recall.min_score,\n ...(options.kinds === undefined ? {} : { kinds: options.kinds }),\n });\n }\n const hits: RecallHit[] = [];\n for (const hit of ranked) {\n const doc = byId.get(hit.id);\n if (doc === undefined) continue;\n hits.push({\n id: doc.id,\n kind: doc.kind,\n abstract: doc.abstract,\n score: hit.score,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n provenance_verifiable: doc.provenance.length > 0,\n });\n }\n return {\n hits,\n warnings: this.quarantined.size === 0 ? [] : [...this.quarantined.values()].slice(0, 5),\n };\n }\n\n /**\n * Hybrid retrieval entry point. Sync `recall` stays BM25/hash-only so the\n * CLI/tests keep a cheap path; the host calls this async version when the\n * sidecar vector cache exists.\n */\n async recallAsync(\n query: string,\n options: { limit?: number; asOf?: string; kinds?: readonly Kind[] } = {},\n ): Promise<RecallResult> {\n const text = query.trim();\n if (text === '' || !this.config.recall.hybrid) return this.recall(query, options);\n const cache = readEmbeddingCache(this.paths.home);\n const command = vectorizerCommand();\n if (cache === undefined || command === undefined) {\n const fallback = this.recall(query, options);\n return {\n ...fallback,\n warnings: [\n ...fallback.warnings,\n cache === undefined\n ? 'hybrid requested but .index/embeddings.json is missing; run `mem embed --apply`'\n : 'hybrid requested but AGENT_MEMORY_VECTORIZER is not set',\n ],\n };\n }\n try {\n const queryVector = (await embedTexts(command, [text])).vectors[0];\n if (queryVector === undefined || queryVector.length !== cache.dimensions) {\n throw new Error(`query vector does not match cache dimensions (${cache.dimensions})`);\n }\n this.reload();\n const date = options.asOf ?? today(this.now());\n const limit = Math.min(options.limit ?? this.config.recall.limit, this.config.recall.max_limit);\n const activeSet = activeDocs(this.docs.values(), date).filter(\n (doc) => !this.deleted.has(doc.id) && !this.quarantined.has(doc.id),\n );\n const index = buildIndex(activeSet, TOKENIZER_VERSION);\n const lexicalHits = search(index, text, {\n limit: activeSet.length,\n minScorePermille: 0,\n ...(options.kinds === undefined ? {} : { kinds: options.kinds }),\n });\n const lexical = new Map(lexicalHits.map((hit) => [hit.id, hit.score]));\n const kindFilter = options.kinds === undefined ? undefined : new Set(options.kinds);\n const vector = new Map<MemoryId, number>();\n for (const doc of activeSet) {\n if (kindFilter !== undefined && !kindFilter.has(doc.kind)) continue;\n const cached = cache.docs[doc.id];\n if (cached === undefined || cached.length !== queryVector.length) continue;\n let dot = 0;\n for (let at = 0; at < queryVector.length; at += 1) dot += (queryVector[at] ?? 0) * (cached[at] ?? 0);\n vector.set(doc.id, Math.max(0, Math.min(1, dot)));\n }\n const minScore = this.config.recall.min_score / 1000;\n const byId = new Map(activeSet.map((doc) => [doc.id, doc]));\n const ranked = [...fuseScores(lexical, vector, this.config.recall.embedding_weight).entries()]\n .filter(([, score]) => score >= minScore)\n .map(([id, score]) => ({ id, score }))\n .sort((left, right) => {\n if (right.score !== left.score) return right.score - left.score;\n const leftDoc = byId.get(left.id);\n const rightDoc = byId.get(right.id);\n if (leftDoc !== undefined && rightDoc !== undefined && rightDoc.valid_from !== leftDoc.valid_from) {\n return rightDoc.valid_from.localeCompare(leftDoc.valid_from);\n }\n return left.id.localeCompare(right.id);\n })\n .slice(0, limit);\n const hits: RecallHit[] = [];\n for (const hit of ranked) {\n const doc = byId.get(hit.id);\n if (doc === undefined) continue;\n hits.push({\n id: doc.id,\n kind: doc.kind,\n abstract: doc.abstract,\n score: hit.score,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n provenance_verifiable: doc.provenance.length > 0,\n });\n }\n return { hits, warnings: this.quarantined.size === 0 ? [] : [...this.quarantined.values()].slice(0, 5) };\n } catch (error) {\n const fallback = this.recall(query, options);\n return {\n ...fallback,\n warnings: [\n ...fallback.warnings,\n `hybrid vectorizer failed (${error instanceof Error ? error.message : String(error)}); fell back to lexical`,\n ],\n };\n }\n }\n\n /**\n * Move records between project labels by rewriting only the `project` field.\n * This is an organisational change, not a supersede: the id and history stay,\n * and the journal records the new content hash plus an audit line.\n */\n moveProjects(\n ids: readonly MemoryId[],\n project: string | null,\n ): { moved: MemoryId[]; failed: { id: MemoryId; reason: string }[] } {\n const projectIssue = projectProblem(project);\n if (projectIssue !== undefined) throw new MemoryStoreError('INVALID', projectIssue);\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent, writes are blocked: ${this.issues[0]}`);\n }\n const moved: MemoryId[] = [];\n const failed: { id: MemoryId; reason: string }[] = [];\n for (const id of ids) {\n const doc = this.docs.get(id);\n if (doc === undefined) {\n failed.push({ id, reason: 'not found' });\n continue;\n }\n const next = {\n id: doc.id,\n mem_schema: doc.mem_schema,\n kind: doc.kind,\n scope: doc.scope,\n project,\n tags: doc.tags ?? [],\n relations: doc.relations ?? [],\n source: doc.source ?? null,\n abstract: doc.abstract,\n created_at: doc.created_at,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n supersedes: doc.supersedes,\n author: doc.author,\n evidence_level: doc.evidence_level,\n error_signatures: doc.error_signatures,\n provenance: doc.provenance,\n body: doc.body,\n };\n const text = serializeMemory(next);\n const file = join(this.paths.memoriesDir, doc.kind, `${doc.id}.md`);\n this.beforeStep?.('before-write');\n writeFileAtomic(file, text);\n const hash = hashContent(text);\n this.journal.append({ op: 'record', data: { id, sha256: hash } });\n this.journal.append({ op: 'audit', data: { event: 'project-move', id, project } });\n moved.push(id);\n }\n this.reload();\n this.writeDerived();\n return { moved, failed };\n } finally {\n lock.release();\n }\n }\n\n /** Update tags/relations in place (organisational metadata, not a revision). */\n updateMeta(\n id: MemoryId,\n patch: { tags?: readonly string[]; relations?: readonly { type: 'relates_to' | 'derived_from'; target: string }[] },\n ): MemoryDoc {\n if (patch.tags !== undefined) {\n const issue = tagsProblem(patch.tags);\n if (issue !== undefined) throw new MemoryStoreError('INVALID', issue);\n }\n if (patch.relations !== undefined) {\n const issue = relationsProblem(patch.relations, id);\n if (issue !== undefined) throw new MemoryStoreError('INVALID', issue);\n }\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent, writes are blocked: ${this.issues[0]}`);\n }\n const doc = this.docs.get(id);\n if (doc === undefined) throw new MemoryStoreError('NOT_FOUND', `no memory with id ${id}`);\n const next = {\n id: doc.id,\n mem_schema: doc.mem_schema,\n kind: doc.kind,\n scope: doc.scope,\n project: doc.project ?? null,\n tags: patch.tags ?? doc.tags ?? [],\n relations: patch.relations ?? doc.relations ?? [],\n source: doc.source ?? null,\n abstract: doc.abstract,\n created_at: doc.created_at,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n supersedes: doc.supersedes,\n author: doc.author,\n evidence_level: doc.evidence_level,\n error_signatures: doc.error_signatures,\n provenance: doc.provenance,\n body: doc.body,\n };\n const text = serializeMemory(next);\n writeFileAtomic(join(this.paths.memoriesDir, doc.kind, `${doc.id}.md`), text);\n this.journal.append({ op: 'record', data: { id, sha256: hashContent(text) } });\n this.journal.append({ op: 'audit', data: { event: 'memory-meta', id } });\n this.reload();\n this.writeDerived();\n return this.docs.get(id) as MemoryDoc;\n } finally {\n lock.release();\n }\n }\n\n stats(): Stats {\n return {\n active: this.active().length,\n total_files: this.docs.size + this.quarantined.size,\n quarantined: this.quarantined.size,\n deleted: this.deleted.size,\n pending_proposals: countPending(this.paths.pendingDir),\n journal_head: this.head,\n journal_consistent: this.issues.length === 0,\n };\n }\n\n /**\n * Write one new memory. The caller supplies an author; provenance/evidence\n * binding arrives with the DSH adapter in S4. Duplicate content returns the\n * existing id without touching its file (plan v1.3 \u00A75.4).\n */\n add(\n input: RecordInput,\n options: { author: 'agent' | 'human'; opId?: string; provenance?: readonly ProvenanceEntry[] },\n ): WriteResult {\n this.validateInput(input);\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError(\n 'CONFLICT',\n `journal is inconsistent, writes are blocked: ${this.issues[0]}`,\n );\n }\n const duplicate = this.findDuplicate(input, options.author);\n if (duplicate !== undefined) {\n this.beforeStep?.('before-journal');\n this.journal.append({\n op: 'audit',\n opId: options.opId === undefined ? undefined : `${options.opId}-dedupe`,\n data: { event: 'dedupe', id: duplicate.id },\n });\n return { id: duplicate.id, content_hash: duplicate.content_hash, deduplicated: true, warnings: [] };\n }\n\n const now = this.now();\n const validFrom = input.valid_from ?? today(now);\n if (!isRealDate(validFrom)) {\n throw new MemoryStoreError('INVALID', `valid_from must be a real YYYY-MM-DD date, found ${validFrom}`);\n }\n const duplicateId = this.allocateId(now);\n const relationIssue = relationsProblem(input.relations ?? [], duplicateId);\n if (relationIssue !== undefined) throw new MemoryStoreError('INVALID', relationIssue);\n const doc = {\n id: duplicateId,\n mem_schema: 2 as const,\n kind: input.kind,\n scope: 'local' as const,\n project: input.project ?? null,\n tags: input.tags ?? [],\n relations: input.relations ?? [],\n source: input.source ?? null,\n abstract: input.abstract,\n created_at: now.toISOString(),\n valid_from: validFrom,\n valid_until: null,\n supersedes: [] as readonly MemoryId[],\n author: options.author,\n evidence_level: input.evidence_level,\n error_signatures: input.error_signatures ?? [],\n provenance: options.provenance ?? [],\n body: input.body,\n };\n const text = serializeMemory(doc);\n const filePath = join(this.paths.memoriesDir, doc.kind, `${doc.id}.md`);\n\n this.beforeStep?.('before-write');\n ensureDir(join(this.paths.memoriesDir, doc.kind));\n writeFileAtomic(filePath, text);\n\n this.beforeStep?.('before-journal');\n const hash = hashContent(text);\n this.journal.append({\n op: 'record',\n ...(options.opId === undefined ? {} : { opId: options.opId }),\n data: { id: doc.id, sha256: hash },\n });\n\n this.beforeStep?.('before-derived');\n this.reload();\n this.writeDerived();\n // The manifest now records the new head; re-scan so `stats()` and later\n // reads do not keep the transient head-vs-manifest mismatch.\n this.reload();\n return { id: doc.id, content_hash: hash, deduplicated: false, warnings: [] };\n } finally {\n lock.release();\n }\n }\n\n /**\n * Accept a hand-placed or hand-edited file after a human reviewed it: append\n * an `adopt` journal line with the file's current hash. The file itself is\n * never rewritten.\n */\n adopt(id: MemoryId): WriteResult {\n if (!isMemoryId(id)) {\n throw new MemoryStoreError('INVALID', `\"${id}\" is not a memory id`);\n }\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent: ${this.issues[0]}`);\n }\n if (this.deleted.has(id)) {\n throw new MemoryStoreError('CONFLICT', `memory ${id} was deleted and cannot be adopted`);\n }\n const file = this.findMemoryFile(id);\n if (file === undefined) {\n throw new MemoryStoreError('NOT_FOUND', `no memory file for ${id}`);\n }\n const text = readFileSync(file, 'utf8');\n let doc: MemoryDoc;\n try {\n doc = parseMemoryFile(text, file, {\n abstractChars: this.config.limits.abstract_chars,\n bodyChars: this.config.limits.body_chars,\n maxRecordChars: this.config.storage.max_record_chars,\n });\n } catch (error) {\n throw new MemoryStoreError(\n 'INVALID',\n `cannot adopt ${id}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (doc.id !== id) {\n throw new MemoryStoreError('INVALID', `file ${file} declares id ${doc.id}, not ${id}`);\n }\n const findings = scanInput({\n abstract: doc.abstract,\n body: doc.body,\n error_signatures: doc.error_signatures,\n });\n if (findings.length > 0) {\n throw new MemoryStoreError(\n 'INVALID',\n `adopt rejected by scan: ${findings.map((finding) => `${finding.rule}@${finding.field}`).join(', ')}`,\n );\n }\n this.journal.append({\n op: 'adopt',\n opId: `adopt-${id}-${doc.content_hash.slice(0, 16)}`,\n data: { id, sha256: doc.content_hash },\n });\n this.reload();\n this.writeDerived();\n this.reload();\n return { id, content_hash: doc.content_hash, deduplicated: false, warnings: [] };\n } finally {\n lock.release();\n }\n }\n\n /**\n * End a memory's validity without touching its file: one `delete` line in the\n * journal removes it from recall and the catalog, while `read` still works.\n */\n remove(id: MemoryId, options: { reason: string; baseHash?: string }): WriteResult {\n if (!isMemoryId(id)) {\n throw new MemoryStoreError('INVALID', `\"${id}\" is not a memory id`);\n }\n if (options.reason.trim() === '') {\n throw new MemoryStoreError('INVALID', 'a delete needs a reason');\n }\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent: ${this.issues[0]}`);\n }\n if (this.deleted.has(id)) {\n throw new MemoryStoreError('CONFLICT', `memory ${id} is already deleted`);\n }\n const doc = this.docs.get(id);\n if (doc === undefined) {\n const reason = this.quarantined.get(id);\n throw new MemoryStoreError(\n 'NOT_FOUND',\n reason === undefined ? `no memory with id ${id}` : `memory ${id} is quarantined: ${reason}`,\n );\n }\n if (options.baseHash !== undefined && options.baseHash !== doc.content_hash) {\n throw new MemoryStoreError('CONFLICT', `memory ${id} changed since base_hash was taken`);\n }\n this.journal.append({\n op: 'delete',\n data: { id, sha256: doc.content_hash, reason: options.reason },\n });\n this.reload();\n this.writeDerived();\n this.reload();\n return { id, content_hash: doc.content_hash, deduplicated: false, warnings: [] };\n } finally {\n lock.release();\n }\n }\n\n /**\n * Write several memories under one lock. Files are written first; if any write\n * fails, the already-written files are removed before rethrowing, so a failed\n * supersede leaves no half-applied replacement (S4.4).\n */\n addMany(\n inputs: readonly (RecordInput & {\n readonly supersedes?: readonly MemoryId[];\n readonly provenance?: readonly ProvenanceEntry[];\n })[],\n options: { author: 'agent' | 'human'; opId?: string },\n ): WriteResult[] {\n if (inputs.length === 0) return [];\n for (const input of inputs) this.validateInput(input);\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent, writes are blocked: ${this.issues[0]}`);\n }\n const now = this.now();\n const prepared = inputs.map((input) => {\n const id = newMemoryId(now);\n const supersedes = input.supersedes ?? [];\n const problems = supersedeProblems(\n { id, supersedes, valid_from: input.valid_from ?? today(now) },\n this.docs,\n );\n if (problems.length > 0) throw new MemoryStoreError('INVALID', problems.join('; '));\n const relationIssue = relationsProblem(input.relations ?? [], id);\n if (relationIssue !== undefined) throw new MemoryStoreError('INVALID', relationIssue);\n const doc = {\n id,\n mem_schema: 2 as const,\n kind: input.kind,\n scope: 'local' as const,\n project: input.project ?? null,\n tags: input.tags ?? [],\n relations: input.relations ?? [],\n source: input.source ?? null,\n abstract: input.abstract,\n created_at: now.toISOString(),\n valid_from: input.valid_from ?? today(now),\n valid_until: null,\n supersedes,\n author: options.author,\n evidence_level: input.evidence_level,\n error_signatures: input.error_signatures ?? [],\n provenance: input.provenance ?? [],\n body: input.body,\n };\n return { id, text: serializeMemory(doc), hash: '', kind: doc.kind };\n });\n\n this.beforeStep?.('before-write');\n const written: string[] = [];\n try {\n for (const entry of prepared) {\n const file = join(this.paths.memoriesDir, entry.kind, `${entry.id}.md`);\n ensureDir(join(this.paths.memoriesDir, entry.kind));\n writeFileAtomic(file, entry.text);\n written.push(file);\n }\n } catch (error) {\n for (const file of written) rmSync(file, { force: true });\n throw error;\n }\n\n this.beforeStep?.('before-journal');\n for (const entry of prepared) {\n const hash = hashContent(entry.text);\n this.journal.append({\n op: 'record',\n ...(options.opId === undefined ? {} : { opId: `${options.opId}-${entry.id}` }),\n data: { id: entry.id, sha256: hash },\n });\n (entry as { hash: string }).hash = hash;\n }\n\n this.beforeStep?.('before-derived');\n this.reload();\n this.writeDerived();\n this.reload();\n return prepared.map((entry) => ({\n id: entry.id,\n content_hash: entry.hash,\n deduplicated: false,\n warnings: [],\n }));\n } finally {\n lock.release();\n }\n }\n\n /**\n * Append an audit/decide line and refresh the manifest in the same lock, so a\n * journal write made outside `add`/`remove` never looks like truncation.\n */\n appendJournal(op: 'audit' | 'decide', data: Readonly<Record<string, unknown>>): void {\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n this.journal.append({ op, data });\n this.reload();\n this.writeDerived();\n this.reload();\n } finally {\n lock.release();\n }\n }\n\n /** Audit append for non-store writers (snapshot capture): refreshes the manifest head too. */\n appendAudit(data: Readonly<Record<string, unknown>>): void {\n this.appendJournal('audit', data);\n }\n\n /** Physically remove one memory (human T2): tombstone in journal, file gone. */\n purge(id: MemoryId, options: { reason: string }): { removed: boolean; proposals: number } {\n if (!isMemoryId(id)) throw new MemoryStoreError('INVALID', `\"${id}\" is not a memory id`);\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n const file = this.findMemoryFile(id);\n if (file === undefined) throw new MemoryStoreError('NOT_FOUND', `no memory file for ${id}`);\n const doc = this.docs.get(id);\n this.journal.append({\n op: 'delete',\n data: { id, purged: true, reason: options.reason, sha256: doc?.content_hash ?? '' },\n });\n rmSync(file, { force: true });\n\n let proposals = 0;\n let names: string[] = [];\n try {\n names = readdirSync(this.paths.pendingDir).filter((name) => name.endsWith('.json'));\n } catch {\n names = [];\n }\n for (const name of names) {\n const path = join(this.paths.pendingDir, name);\n try {\n const proposal = JSON.parse(readFileSync(path, 'utf8')) as { id?: string; targets?: unknown };\n if (Array.isArray(proposal.targets) && proposal.targets.includes(id)) {\n rmSync(path, { force: true });\n this.journal.append({\n op: 'audit',\n data: { event: 'proposal-invalidated', proposal: proposal.id ?? name, target: id },\n });\n proposals += 1;\n }\n } catch {\n // A corrupt pending file is left for `doctor`, not silently deleted.\n }\n }\n\n this.reload();\n this.writeDerived();\n this.reload();\n return { removed: true, proposals };\n } finally {\n lock.release();\n }\n }\n\n rebuild(): RebuildReport {\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n // Rebuilding derived files must not rewrite `journal_head` over a\n // truncated or broken chain: that would hide the damage the manifest\n // tripwire exists to expose.\n throw new MemoryStoreError(\n 'CONFLICT',\n `journal is inconsistent, repair it before rebuild: ${this.issues[0]}`,\n );\n }\n this.writeDerived();\n return {\n records: this.accounted.size,\n files: this.docs.size,\n quarantined: [...this.quarantined.keys()],\n journal_head: this.head,\n journal_consistent: true,\n rebuilt_index: true,\n rebuilt_catalog: true,\n };\n } finally {\n lock.release();\n }\n }\n\n /** Quarantine and journal diagnostics, used by `mem doctor`. */\n diagnostics(): { quarantined: ReadonlyMap<MemoryId, string>; issues: readonly string[]; head: { seq: number; hash: string } | null } {\n return { quarantined: this.quarantined, issues: this.issues, head: this.head };\n }\n\n private writeDerived(): void {\n const active = this.active();\n const manifest = {\n schema: 1,\n tokenizer_version: TOKENIZER_VERSION,\n built_at: this.now().toISOString(),\n journal_head: this.head,\n entries: active.map((doc) => ({\n id: doc.id,\n kind: doc.kind,\n abstract: doc.abstract,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n supersedes: doc.supersedes,\n evidence_level: doc.evidence_level,\n content_hash: doc.content_hash,\n file: doc.file_path,\n })),\n };\n writeFileAtomic(this.paths.manifestFile, `${JSON.stringify(manifest, null, 2)}\\n`);\n\n const order: Record<string, number> = { user_explicit: 0, user_confirmed: 1, observed: 2, inferred: 3 };\n const sorted = [...active].sort((left, right) => {\n const rank = (order[left.evidence_level] ?? 9) - (order[right.evidence_level] ?? 9);\n if (rank !== 0) return rank;\n if (left.valid_from !== right.valid_from) return right.valid_from.localeCompare(left.valid_from);\n return left.id.localeCompare(right.id);\n });\n const lines = ['<!-- generated by mem; do not edit -->', '', '## MEMORY', ''];\n for (const doc of sorted) lines.push(`- [${doc.kind}] ${doc.abstract} \u2014 ${doc.id}`);\n writeFileAtomic(this.paths.memoryIndexFile, `${lines.join('\\n')}\\n`);\n }\n\n private validateInput(input: RecordInput): void {\n if (!KINDS.includes(input.kind)) {\n throw new MemoryStoreError('INVALID', `kind must be one of ${KINDS.join(', ')}`);\n }\n const projectIssue = projectProblem(input.project ?? null);\n if (projectIssue !== undefined) throw new MemoryStoreError('INVALID', projectIssue);\n const tagsIssue = tagsProblem(input.tags ?? []);\n if (tagsIssue !== undefined) throw new MemoryStoreError('INVALID', tagsIssue);\n const sourceIssue = sourceProblem(input.source ?? null);\n if (sourceIssue !== undefined) throw new MemoryStoreError('INVALID', sourceIssue);\n if (typeof input.abstract !== 'string' || input.abstract.trim() === '') {\n throw new MemoryStoreError('INVALID', 'abstract must not be empty');\n }\n if (/[\\r\\n]/.test(input.abstract)) {\n throw new MemoryStoreError('INVALID', 'abstract must be a single line');\n }\n if ([...input.abstract].length > this.config.limits.abstract_chars) {\n throw new MemoryStoreError(\n 'INVALID',\n `abstract exceeds limits.abstract_chars (${this.config.limits.abstract_chars})`,\n );\n }\n if (input.body !== undefined && [...input.body].length > this.config.limits.body_chars) {\n throw new MemoryStoreError(\n 'INVALID',\n `body exceeds limits.body_chars (${this.config.limits.body_chars})`,\n );\n }\n if ((input.evidence_level as string) === 'inferred') {\n throw new MemoryStoreError('INVALID', 'inferred content must go through a proposal');\n }\n const signatures = input.error_signatures ?? [];\n if (signatures.length > 3) throw new MemoryStoreError('INVALID', 'error_signatures allows at most 3 entries');\n for (const signature of signatures) {\n if (signature.length === 0 || [...signature].length > 80) {\n throw new MemoryStoreError('INVALID', 'each error_signatures entry must be 1..80 characters');\n }\n }\n if (input.kind === 'pitfall' && signatures.length === 0) {\n throw new MemoryStoreError('INVALID', 'a pitfall must declare at least one error_signatures entry');\n }\n const findings = scanInput({\n abstract: input.abstract,\n body: input.body,\n error_signatures: signatures,\n });\n if (findings.length > 0) {\n throw new MemoryStoreError(\n 'INVALID',\n `content rejected by scan: ${findings.map((finding) => `${finding.rule}@${finding.field}`).join(', ')}`,\n );\n }\n }\n\n private findMemoryFile(id: MemoryId): string | undefined {\n for (const kind of KINDS) {\n const file = join(this.paths.memoriesDir, kind, `${id}.md`);\n if (existsSync(file)) return file;\n }\n return undefined;\n }\n\n private findDuplicate(input: RecordInput, author: 'agent' | 'human'): MemoryDoc | undefined {\n // Content-only dedupe (user request): the date, author and evidence level\n // do not make the same text a new memory. Importing yesterday's export on\n // a new date must skip, not duplicate.\n void author;\n // The stored body always carries the file's single trailing newline.\n const body = input.body.endsWith('\\n') ? input.body : `${input.body}\\n`;\n for (const doc of this.docs.values()) {\n if (this.deleted.has(doc.id) || this.quarantined.has(doc.id)) continue;\n if (\n doc.kind === input.kind &&\n doc.abstract === input.abstract &&\n doc.body === body &&\n JSON.stringify(doc.error_signatures) === JSON.stringify(input.error_signatures ?? []) &&\n doc.supersedes.length === 0\n ) {\n return doc;\n }\n }\n return undefined;\n }\n\n private allocateId(now: Date): MemoryId {\n for (let attempt = 0; attempt < 100; attempt += 1) {\n const id = newMemoryId(now);\n const exists =\n this.docs.has(id) ||\n this.accounted.has(id) ||\n existsSync(join(this.paths.memoriesDir, 'fact', `${id}.md`)) ||\n existsSync(join(this.paths.memoriesDir, 'pitfall', `${id}.md`)) ||\n existsSync(join(this.paths.memoriesDir, 'exp', `${id}.md`));\n if (!exists) return id;\n }\n throw new MemoryStoreError('CONFLICT', 'could not allocate a unique memory id');\n }\n}\n\nfunction countPending(dir: string): number {\n try {\n return readdirSync(dir).filter((name) => name.endsWith('.json')).length;\n } catch {\n return 0;\n }\n}\n", "/**\n * Tokenizer for the in-memory index (plan v1.3 \u00A76.3).\n *\n * NFKC + lower-case; CJK as bigrams; ASCII words; code-shaped fragments keep\n * their whole form and also split on separators. The version is a cache key:\n * changing the rules must invalidate the index.\n */\n\nexport const TOKENIZER_VERSION = 1;\n\nconst CJK = /[\\u3400-\\u9fff\\uf900-\\ufaff]/;\nconst WORD = /[a-z0-9]/;\nconst WORD_BODY = /[a-z0-9_\\-.:/]/;\nconst SEPARATORS = /[-_.:/]+/;\n\nfunction isCjk(char: string): boolean {\n return CJK.test(char);\n}\n\nexport function tokenize(input: string): string[] {\n const text = input.normalize('NFKC').toLowerCase();\n const tokens: string[] = [];\n let index = 0;\n while (index < text.length) {\n const char = text[index] as string;\n if (isCjk(char)) {\n let end = index;\n while (end < text.length && isCjk(text[end] as string)) end += 1;\n const run = [...text.slice(index, end)];\n if (run.length === 1) {\n tokens.push(run[0] as string);\n } else {\n for (let at = 0; at < run.length - 1; at += 1) {\n tokens.push(`${run[at]}${run[at + 1]}`);\n }\n }\n index = end;\n continue;\n }\n if (WORD.test(char)) {\n let end = index;\n while (end < text.length && WORD_BODY.test(text[end] as string)) end += 1;\n const word = text.slice(index, end);\n if (word !== '') {\n tokens.push(word);\n if (SEPARATORS.test(word)) {\n for (const part of word.split(SEPARATORS)) {\n if (part !== '') tokens.push(part);\n }\n }\n }\n index = end;\n continue;\n }\n index += 1;\n }\n return tokens;\n}\n\n/** A compact token string for tests and diagnostics. */\nexport function tokenizeJoined(input: string): string {\n return tokenize(input).join(' ');\n}\n", "import type { Kind, MemoryDoc, MemoryId } from '../model/types.ts';\nimport { tokenize } from './tokenizer.ts';\n\n/**\n * Field-weighted BM25 over the active set (plan v1.3 \u00A76.3).\n *\n * weights: error_signatures \u00D74, abstract \u00D73, body \u00D71; k1=1.2, b=0.75.\n * A literal hit adds a bonus, so error codes and quoted strings still rank well\n * when tokenization is ambiguous. Scores are normalized to 0..1 (top hit = 1)\n * before `recall.min_score` (per-mille) is applied.\n */\n\nconst K1 = 1.2;\nconst B = 0.75;\nconst WEIGHTS = { abstract: 3, body: 1, signatures: 4 } as const;\nconst LITERAL_BONUS = { abstract: 3, body: 1, signatures: 2 } as const;\n\ninterface FieldStats {\n readonly length: number;\n readonly frequencies: ReadonlyMap<string, number>;\n}\n\nexport interface IndexedDoc {\n readonly id: MemoryId;\n readonly kind: Kind;\n readonly abstract: string;\n readonly body: string;\n readonly error_signatures: readonly string[];\n readonly valid_from: string;\n readonly valid_until: string | null;\n readonly fields: {\n readonly abstract: FieldStats;\n readonly body: FieldStats;\n readonly signatures: FieldStats;\n };\n}\n\nexport interface SearchIndex {\n readonly tokenizer_version: number;\n readonly size: number;\n readonly docs: readonly IndexedDoc[];\n readonly df: ReadonlyMap<string, number>;\n readonly averages: { readonly abstract: number; readonly body: number; readonly signatures: number };\n}\n\nfunction frequencies(tokens: readonly string[]): FieldStats {\n const map = new Map<string, number>();\n for (const token of tokens) map.set(token, (map.get(token) ?? 0) + 1);\n return { length: tokens.length, frequencies: map };\n}\n\nexport function buildIndex(docs: Iterable<MemoryDoc>, tokenizerVersion = 1): SearchIndex {\n const indexed: IndexedDoc[] = [];\n const df = new Map<string, number>();\n let abstractLength = 0;\n let bodyLength = 0;\n let signatureLength = 0;\n\n for (const doc of docs) {\n const abstractTokens = tokenize(doc.abstract);\n const bodyTokens = tokenize(doc.body);\n const signatureTokens = doc.error_signatures.flatMap((signature) => tokenize(signature));\n abstractLength += abstractTokens.length;\n bodyLength += bodyTokens.length;\n signatureLength += signatureTokens.length;\n\n const seen = new Set<string>();\n for (const token of [...abstractTokens, ...bodyTokens, ...signatureTokens]) {\n if (seen.has(token)) continue;\n seen.add(token);\n df.set(token, (df.get(token) ?? 0) + 1);\n }\n\n indexed.push({\n id: doc.id,\n kind: doc.kind,\n abstract: doc.abstract,\n body: doc.body,\n error_signatures: doc.error_signatures,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n fields: {\n abstract: frequencies(abstractTokens),\n body: frequencies(bodyTokens),\n signatures: frequencies(signatureTokens),\n },\n });\n }\n\n const size = indexed.length;\n return {\n tokenizer_version: tokenizerVersion,\n size,\n docs: indexed,\n df,\n averages: {\n abstract: size === 0 ? 0 : abstractLength / size,\n body: size === 0 ? 0 : bodyLength / size,\n signatures: size === 0 ? 0 : signatureLength / size,\n },\n };\n}\n\nfunction idf(index: SearchIndex, term: string): number {\n const df = index.df.get(term) ?? 0;\n return Math.log(1 + (index.size - df + 0.5) / (df + 0.5));\n}\n\nfunction fieldScore(\n frequencies: ReadonlyMap<string, number>,\n length: number,\n average: number,\n term: string,\n): number {\n const tf = frequencies.get(term) ?? 0;\n if (tf === 0 || average === 0) return 0;\n return (tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * length) / average));\n}\n\nexport interface SearchOptions {\n readonly limit: number;\n readonly minScorePermille: number;\n readonly kinds?: readonly Kind[];\n}\n\nexport interface SearchHit {\n readonly id: MemoryId;\n readonly score: number;\n}\n\nexport function search(index: SearchIndex, query: string, options: SearchOptions): SearchHit[] {\n const terms = [...new Set(tokenize(query))];\n if (terms.length === 0 || index.size === 0) return [];\n const literal = query.normalize('NFKC').toLowerCase().trim();\n const kindFilter = options.kinds === undefined ? undefined : new Set(options.kinds);\n\n const scored: Array<{ doc: IndexedDoc; score: number }> = [];\n for (const doc of index.docs) {\n if (kindFilter !== undefined && !kindFilter.has(doc.kind)) continue;\n let score = 0;\n for (const term of terms) {\n const weight = idf(index, term);\n score +=\n weight *\n (WEIGHTS.abstract *\n fieldScore(doc.fields.abstract.frequencies, doc.fields.abstract.length, index.averages.abstract, term) +\n WEIGHTS.body *\n fieldScore(doc.fields.body.frequencies, doc.fields.body.length, index.averages.body, term) +\n WEIGHTS.signatures *\n fieldScore(\n doc.fields.signatures.frequencies,\n doc.fields.signatures.length,\n index.averages.signatures,\n term,\n ));\n }\n if (score === 0) continue;\n if (literal !== '') {\n const normalizedAbstract = doc.abstract.normalize('NFKC').toLowerCase();\n const normalizedBody = doc.body.normalize('NFKC').toLowerCase();\n const signatureText = doc.error_signatures.join('\\n').normalize('NFKC').toLowerCase();\n if (normalizedAbstract.includes(literal)) score += LITERAL_BONUS.abstract * (idf(index, literal) + 1);\n if (normalizedBody.includes(literal)) score += LITERAL_BONUS.body;\n if (signatureText.includes(literal)) score += LITERAL_BONUS.signatures;\n }\n scored.push({ doc, score });\n }\n if (scored.length === 0) return [];\n\n const max = Math.max(...scored.map((entry) => entry.score));\n const minimum = options.minScorePermille / 1000;\n return scored\n .map((entry) => ({ doc: entry.doc, normalized: entry.score / max }))\n .filter((entry) => entry.normalized >= minimum)\n .sort((left, right) => {\n if (right.normalized !== left.normalized) return right.normalized - left.normalized;\n if (right.doc.valid_from !== left.doc.valid_from) return right.doc.valid_from.localeCompare(left.doc.valid_from);\n return left.doc.id.localeCompare(right.doc.id);\n })\n .slice(0, options.limit)\n .map((entry) => ({ id: entry.doc.id, score: Number(entry.normalized.toFixed(6)) }));\n}\n", "import { tokenize } from './tokenizer.ts';\n\n/**\n * Local vector provider seam (V4.0-S2a).\n *\n * `HashEmbeddingProvider` is deterministic and dependency-free: it hashes word\n * and character n-gram features into a fixed vector. It is a *fallback* for\n * tests, offline use and CI, not a semantic model. The ONNX provider (S2b) will\n * implement the same interface and replace the backend without changing the\n * fusion code.\n */\n\nexport interface EmbeddingProvider {\n readonly name: string;\n readonly dimensions: number;\n embed(text: string): Float32Array;\n}\n\nconst DIMENSIONS = 256;\n\nfunction hashFeature(feature: string): number {\n let hash = 2166136261;\n for (let index = 0; index < feature.length; index += 1) {\n hash ^= feature.charCodeAt(index);\n hash = Math.imul(hash, 16777619);\n }\n return hash >>> 0;\n}\n\nexport class HashEmbeddingProvider implements EmbeddingProvider {\n readonly name = 'hash-256';\n readonly dimensions = DIMENSIONS;\n\n embed(text: string): Float32Array {\n const vector = new Float32Array(DIMENSIONS);\n const tokens = tokenize(text);\n const features = [...tokens, ...tokens.map((token) => `#${token}`)];\n for (const feature of features) {\n const bucket = hashFeature(feature) % DIMENSIONS;\n vector[bucket] = (vector[bucket] ?? 0) + 1;\n }\n let norm = 0;\n for (const value of vector) norm += value * value;\n norm = Math.sqrt(norm);\n if (norm > 0) for (let index = 0; index < vector.length; index += 1) vector[index] = (vector[index] ?? 0) / norm;\n return vector;\n }\n}\n\nexport function cosine(left: Float32Array, right: Float32Array): number {\n if (left.length !== right.length) throw new Error('embedding dimensions differ');\n let dot = 0;\n for (let index = 0; index < left.length; index += 1) dot += (left[index] ?? 0) * (right[index] ?? 0);\n return Math.max(0, Math.min(1, dot));\n}\n", "import type { MemoryId } from '../model/types.ts';\n\n/** Fuse normalized lexical and vector scores; both inputs are 0..1. */\nexport function fuseScores(\n lexical: ReadonlyMap<MemoryId, number>,\n vector: ReadonlyMap<MemoryId, number>,\n embeddingWeightPermille: number,\n): Map<MemoryId, number> {\n const weight = Math.min(1000, Math.max(0, embeddingWeightPermille)) / 1000;\n const ids = new Set<MemoryId>([...lexical.keys(), ...vector.keys()]);\n const fused = new Map<MemoryId, number>();\n for (const id of ids) {\n const lexicalScore = lexical.get(id) ?? 0;\n const vectorScore = vector.get(id) ?? 0;\n fused.set(id, (1 - weight) * lexicalScore + weight * vectorScore);\n }\n return fused;\n}\n", "import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * Sidecar vector cache (V4.0-S2b).\n *\n * The plugin never runs ONNX itself. A user-installed vectorizer command reads\n * `{ texts: string[] }` from an input file and writes `{ vectors: number[][] }`\n * to an output file:\n *\n * node my-vectorizer.mjs <input.json> <output.json>\n *\n * `mem embed --apply` fills the cache; `recallAsync` asks the same command for\n * the query vector. File IPC (not stdio pipes) keeps it usable under sandboxes\n * that refuse piped child processes.\n */\n\nexport interface EmbeddingCache {\n readonly schema: 1;\n readonly provider: string;\n readonly dimensions: number;\n readonly generated_at: string;\n readonly docs: Readonly<Record<string, readonly number[]>>;\n}\n\nconst CACHE_SCHEMA = 1;\n\nexport function embeddingsFile(home: string): string {\n return join(memoryPaths(home).indexDir, 'embeddings.json');\n}\n\nexport function readEmbeddingCache(home: string): EmbeddingCache | undefined {\n try {\n const parsed = JSON.parse(readFileSync(embeddingsFile(home), 'utf8')) as Partial<EmbeddingCache>;\n if (parsed.schema !== CACHE_SCHEMA) return undefined;\n if (typeof parsed.provider !== 'string' || typeof parsed.dimensions !== 'number') return undefined;\n if (typeof parsed.generated_at !== 'string' || typeof parsed.docs !== 'object' || parsed.docs === null) {\n return undefined;\n }\n return parsed as EmbeddingCache;\n } catch {\n return undefined;\n }\n}\n\nexport function writeEmbeddingCache(home: string, cache: EmbeddingCache): void {\n writeFileAtomic(embeddingsFile(home), `${JSON.stringify(cache)}\\n`);\n}\n\nexport interface VectorizerResult {\n readonly vectors: readonly (readonly number[])[];\n readonly dimensions: number;\n}\n\nexport function vectorizerCommand(): string | undefined {\n const command = process.env.AGENT_MEMORY_VECTORIZER?.trim();\n return command === undefined || command === '' ? undefined : command;\n}\n\n/** Run the user's vectorizer over a batch of texts. */\nexport async function embedTexts(command: string, texts: readonly string[]): Promise<VectorizerResult> {\n const dir = mkdtempSync(join(tmpdir(), 'agent-memory-embed-'));\n const inputPath = join(dir, 'input.json');\n const outputPath = join(dir, 'output.json');\n try {\n writeFileSync(inputPath, JSON.stringify({ texts }));\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command, [inputPath, outputPath], {\n stdio: 'ignore',\n shell: true,\n windowsHide: true,\n });\n child.once('error', reject);\n child.once('exit', (code) => {\n if (code === 0) resolve();\n else reject(new Error(`vectorizer exited with ${code ?? 'no code'}`));\n });\n });\n const parsed = JSON.parse(readFileSync(outputPath, 'utf8')) as { vectors?: unknown };\n if (!Array.isArray(parsed.vectors) || parsed.vectors.length !== texts.length) {\n throw new Error('vectorizer output must contain one vector per text');\n }\n let dimensions = 0;\n for (const vector of parsed.vectors) {\n if (!Array.isArray(vector) || vector.some((value) => typeof value !== 'number' || !Number.isFinite(value))) {\n throw new Error('vectorizer vectors must be arrays of finite numbers');\n }\n if (dimensions === 0) dimensions = vector.length;\n if (vector.length !== dimensions) throw new Error('vectorizer vectors have inconsistent dimensions');\n }\n return { vectors: parsed.vectors as number[][], dimensions };\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n", "/**\n * Content scanning (plan v1.3 \u00A76.4). Cannot be disabled.\n *\n * Findings carry only a rule id and a field name, never the matched text, so a\n * rejection cannot echo a secret into logs or the journal.\n */\n\nexport type ScanRule = 'invisible' | 'credentials' | 'injection' | 'private_tag';\n\nexport interface ScanFinding {\n readonly rule: ScanRule;\n readonly field: string;\n}\n\nexport class ScanError extends Error {\n readonly findings: readonly ScanFinding[];\n constructor(findings: readonly ScanFinding[]) {\n super(`content rejected by scan: ${findings.map((finding) => `${finding.rule}@${finding.field}`).join(', ')}`);\n this.name = 'ScanError';\n this.findings = findings;\n }\n}\n\nconst INVISIBLE = /[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u2069\\uFEFF]|[\\u{E0000}-\\u{E007F}]/u;\nconst CREDENTIALS = [\n /sk-[A-Za-z0-9_-]{16,}/,\n /AKIA[0-9A-Z]{16}/,\n /-----BEGIN [A-Z ]*PRIVATE KEY-----/,\n /(?:postgres|postgresql|mysql|mongodb|redis):\\/\\/[^\\s]+:[^\\s]+@/i,\n];\nconst INJECTION = [\n /ignore\\s+(all\\s+)?(previous|prior|above)\\s+instructions/i,\n /\u5FFD\u7565(\u4E4B\u524D|\u4EE5\u4E0A|\u524D\u9762)(\u7684)?(\u6240\u6709)?(\u6307\u4EE4|\u6307\u793A)/,\n /disregard\\s+(all\\s+)?(previous|prior)\\s+instructions/i,\n];\nconst PRIVATE_TAG = /<private>[\\s\\S]*?<\\/private>/i;\n\nexport function scanText(field: string, text: string): ScanFinding[] {\n const findings: ScanFinding[] = [];\n if (INVISIBLE.test(text)) findings.push({ rule: 'invisible', field });\n if (CREDENTIALS.some((pattern) => pattern.test(text))) findings.push({ rule: 'credentials', field });\n if (INJECTION.some((pattern) => pattern.test(text))) findings.push({ rule: 'injection', field });\n if (PRIVATE_TAG.test(text)) findings.push({ rule: 'private_tag', field });\n return findings;\n}\n\nexport interface ScannableInput {\n readonly abstract?: string;\n readonly body?: string;\n readonly error_signatures?: readonly string[];\n readonly quote?: string;\n readonly targets?: readonly string[];\n}\n\n/** Scan every field that can reach a file, the journal or the prompt. */\nexport function scanInput(input: ScannableInput): ScanFinding[] {\n const findings: ScanFinding[] = [];\n if (input.abstract !== undefined) findings.push(...scanText('abstract', input.abstract));\n if (input.body !== undefined) findings.push(...scanText('body', input.body));\n if (input.quote !== undefined) findings.push(...scanText('quote', input.quote));\n input.error_signatures?.forEach((signature, index) =>\n findings.push(...scanText(`error_signatures[${index}]`, signature)),\n );\n input.targets?.forEach((target, index) => findings.push(...scanText(`targets[${index}]`, target)));\n return findings;\n}\n\nexport function assertClean(input: ScannableInput): void {\n const findings = scanInput(input);\n if (findings.length > 0) throw new ScanError(findings);\n}\n\n/** T1 path: `<private>\u2026</private>` is not silently stripped; it becomes redacted text. */\nexport function redactPrivate(text: string): string {\n return text.replace(PRIVATE_TAG, '[private]');\n}\n", "import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * RULES.md parser and validator (plan v1.3 \u00A74.3, \u00A79.2).\n *\n * Entry shape:\n *\n * 1. [\u673A\u5668\u95E8\u7981] one line of rule text\n * check: packages/cli/src/main.ts#commandAdd\n * test: packages/core/test/rules/rules.test.ts\n * 2. [\u6A21\u578B\u6307\u5F15] advice for the model, never a system guarantee\n * 3. [\u5E9F\u6B62] a retired entry keeps its number and is labelled\n *\n * A `[\u673A\u5668\u95E8\u7981]` entry is valid only when `check` names an existing symbol, the\n * `test` file exists, and that test file contains a `[neg]` case. `[\u6A21\u578B\u6307\u5F15]`\n * must not claim to be a guarantee.\n */\n\nexport type RuleCategory = 'machine' | 'guide' | 'revoked';\n\nexport interface Rule {\n readonly number: number;\n readonly category: RuleCategory;\n readonly text: string;\n readonly check?: string;\n readonly test?: string;\n}\n\nexport interface RulesParseResult {\n readonly rules: readonly Rule[];\n readonly errors: readonly string[];\n}\n\nconst HEADER = /^(\\d+)\\.\\s*\\[(\u673A\u5668\u95E8\u7981|\u6A21\u578B\u6307\u5F15|\u5E9F\u6B62)\\]\\s*(.*)$/;\nconst EXTRA = /^\\s+(check|test):\\s*(.+)$/;\n\nexport function parseRules(text: string): RulesParseResult {\n const normalized = (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text).replaceAll('\\r\\n', '\\n');\n const rules: Rule[] = [];\n const errors: string[] = [];\n const seen = new Set<number>();\n let current: { number: number; category: RuleCategory; text: string; check?: string; test?: string } | undefined;\n\n const flush = (): void => {\n if (current === undefined) return;\n rules.push({ ...current });\n current = undefined;\n };\n\n for (const raw of normalized.split('\\n')) {\n const line = raw.trimEnd();\n const header = HEADER.exec(line);\n if (header !== null) {\n flush();\n const number = Number(header[1]);\n const label = header[2] as '\u673A\u5668\u95E8\u7981' | '\u6A21\u578B\u6307\u5F15' | '\u5E9F\u6B62';\n if (seen.has(number)) errors.push(`rule ${number}: duplicate number`);\n seen.add(number);\n current = {\n number,\n category: label === '\u673A\u5668\u95E8\u7981' ? 'machine' : label === '\u6A21\u578B\u6307\u5F15' ? 'guide' : 'revoked',\n text: (header[3] ?? '').trim(),\n };\n continue;\n }\n if (current === undefined) continue;\n const extra = EXTRA.exec(line);\n if (extra !== null) {\n if (extra[1] === 'check') current.check = (extra[2] ?? '').trim();\n else current.test = (extra[2] ?? '').trim();\n continue;\n }\n if (line.trim() === '') continue;\n current.text = `${current.text} ${line.trim()}`.trim();\n }\n flush();\n\n for (const rule of rules) {\n if (rule.category === 'machine') {\n if (rule.check === undefined || rule.check === '') errors.push(`rule ${rule.number}: [\u673A\u5668\u95E8\u7981] needs \"check:\"`);\n if (rule.test === undefined || rule.test === '') errors.push(`rule ${rule.number}: [\u673A\u5668\u95E8\u7981] needs \"test:\"`);\n }\n if (rule.category === 'guide' && /\u4FDD\u8BC1|guarantee/i.test(rule.text)) {\n errors.push(`rule ${rule.number}: [\u6A21\u578B\u6307\u5F15] must not be described as a guarantee`);\n }\n }\n return { rules, errors };\n}\n\nexport interface RuleValidationOptions {\n /** Repository root used to resolve `check` and `test` paths. */\n readonly rootDir: string;\n}\n\n/** Resolve a `path#symbol` check and confirm the symbol appears in that file. */\nfunction checkSymbolExists(check: string, rootDir: string): boolean {\n const [path, symbol] = check.split('#');\n if (path === undefined || symbol === undefined || path === '' || symbol === '') return false;\n const file = join(rootDir, path);\n if (!existsSync(file)) return false;\n return readFileSync(file, 'utf8').includes(symbol);\n}\n\nexport function validateRules(rules: readonly Rule[], options: RuleValidationOptions): string[] {\n const errors: string[] = [];\n for (const rule of rules) {\n if (rule.category !== 'machine') continue;\n if (rule.check === undefined || !checkSymbolExists(rule.check, options.rootDir)) {\n errors.push(`rule ${rule.number}: check \"${rule.check ?? ''}\" does not name an existing symbol`);\n }\n if (rule.test === undefined) continue;\n const testFile = join(options.rootDir, rule.test);\n if (!existsSync(testFile)) {\n errors.push(`rule ${rule.number}: test file \"${rule.test}\" does not exist`);\n continue;\n }\n if (!/\\[neg\\]/.test(readFileSync(testFile, 'utf8'))) {\n errors.push(`rule ${rule.number}: test file \"${rule.test}\" has no [neg] case`);\n }\n }\n return errors;\n}\n\nexport function parseAndValidateRules(text: string, options: RuleValidationOptions): RulesParseResult {\n const parsed = parseRules(text);\n return { rules: parsed.rules, errors: [...parsed.errors, ...validateRules(parsed.rules, options)] };\n}\n\n/** Read and parse the store's RULES.md (used by `rules_list`). */\nexport function loadRules(home: string): readonly Rule[] {\n const file = memoryPaths(home).rulesFile;\n if (!existsSync(file)) return [];\n return parseRules(readFileSync(file, 'utf8')).rules;\n}\n\n/** Numbered rendering for injection; `[\u5E9F\u6B62]` is labelled but not enforceable. */\nexport function renderRules(rules: readonly Rule[], options: { includeRevoked?: boolean } = {}): string {\n const lines: string[] = [];\n for (const rule of rules) {\n if (rule.category === 'revoked' && options.includeRevoked !== true) continue;\n const label = rule.category === 'machine' ? '\u673A\u5668\u95E8\u7981' : rule.category === 'guide' ? '\u6A21\u578B\u6307\u5F15' : '\u5E9F\u6B62';\n lines.push(`${rule.number}. [${label}] ${rule.text}`);\n }\n return lines.join('\\n');\n}\n\n/** Raw RULES.md text (comments included); empty when the file is absent. */\nexport function readRulesFile(home: string): string {\n const file = memoryPaths(home).rulesFile;\n return existsSync(file) ? readFileSync(file, 'utf8') : '';\n}\n\n/**\n * Human GUI save path: validate the whole file, then write it atomically.\n * It does not seal policy.json; the caller seals with an explicit human action.\n */\nexport function saveRulesFile(home: string, text: string): void {\n const parsed = parseAndValidateRules(text, { rootDir: home });\n if (parsed.errors.length > 0) {\n throw new Error(`RULES.md rejected: ${parsed.errors.join('; ')}`);\n }\n writeFileAtomic(memoryPaths(home).rulesFile, text);\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { memoryPaths } from '../paths.ts';\nimport { writeFileAtomic } from '../fs/atomic.ts';\n\n/**\n * Frozen per-session injection snapshot (plan v1.3 \u00A76.1).\n *\n * Same session + same prompt schema => byte-identical text on every assemble,\n * even after new writes; a new session captures the current revision. At most\n * 20 snapshots are kept (oldest removed on capture).\n */\n\nexport const PROMPT_SCHEMA_VERSION = 4;\nexport const SNAPSHOT_KEEP = 20;\n\nexport interface SnapshotRecord {\n readonly session_id: string;\n readonly memory_revision: string;\n readonly prompt_schema_version: number;\n readonly created_at: string;\n readonly text: string;\n /** Per-section text so the host can register one prompt section per source. */\n readonly parts?: Readonly<Record<string, string>>;\n readonly sectionList?: readonly { readonly key: string; readonly order: number; readonly text: string }[];\n readonly health?: readonly { readonly key: string; readonly ok: boolean; readonly message?: string }[];\n}\n\nexport function snapshotPath(home: string, sessionId: string): string {\n const name = createHash('sha256').update(sessionId, 'utf8').digest('hex').slice(0, 32);\n return join(memoryPaths(home).snapshotsDir, `${name}.json`);\n}\n\nexport function readSnapshot(home: string, sessionId: string): SnapshotRecord | null {\n const file = snapshotPath(home, sessionId);\n if (!existsSync(file)) return null;\n try {\n const record = JSON.parse(readFileSync(file, 'utf8')) as SnapshotRecord;\n if (\n record.session_id !== sessionId ||\n typeof record.text !== 'string' ||\n typeof record.memory_revision !== 'string' ||\n typeof record.prompt_schema_version !== 'number'\n ) {\n return null;\n }\n return record;\n } catch {\n return null;\n }\n}\n\nexport function writeSnapshot(home: string, record: SnapshotRecord, keep = SNAPSHOT_KEEP): void {\n writeFileAtomic(snapshotPath(home, record.session_id), `${JSON.stringify(record, null, 2)}\\n`);\n pruneSnapshots(home, keep);\n}\n\n/** Keep the newest `keep` snapshot files; a snapshot is a cache, not truth. */\nexport function pruneSnapshots(home: string, keep = SNAPSHOT_KEEP): void {\n const dir = memoryPaths(home).snapshotsDir;\n let names: string[];\n try {\n names = readdirSync(dir).filter((name) => name.endsWith('.json'));\n } catch {\n return;\n }\n if (names.length <= keep) return;\n const byAge = names\n .map((name) => ({ name, mtime: statSync(join(dir, name)).mtimeMs }))\n .sort((left, right) => right.mtime - left.mtime);\n for (const entry of byAge.slice(keep)) {\n try {\n rmSync(join(dir, entry.name), { force: true });\n } catch {\n // A snapshot that cannot be removed is only wasted disk space.\n }\n }\n}\n", "import { createHash, randomBytes } from 'node:crypto';\nimport type { Config } from '../config/config.ts';\nimport type { Policy } from '../policy/policy.ts';\nimport { verifySealedFiles } from '../policy/policy.ts';\nimport type { Rule } from '../rules/rules.ts';\nimport { today } from '../model/validity.ts';\nimport type { MemoryDoc } from '../model/types.ts';\nimport { buildSections, SECTION_ORDERS, type SectionHealth, type SectionSource } from './sections.ts';\nimport { readSnapshot, writeSnapshot, PROMPT_SCHEMA_VERSION } from './snapshot.ts';\n\n/**\n * Injection assembly (plan v1.3 \u00A76.1; architecture v2 P0.5).\n *\n * Sections come from the registry (`sections.ts`): SOUL, GUIDANCE, RULES, USER,\n * then the memory catalog built here. A broken optional section degrades to a\n * visible notice (health entry) instead of failing the whole injection; sealed\n * files and store integrity remain global failures. The text is frozen per\n * session in `.state/snapshots/` and wrapped in a random delimiter.\n */\n\nexport type InjectionErrorCode = 'RULES_INVALID' | 'RULES_OVER_BUDGET' | 'OVER_BUDGET';\n\nexport class InjectionError extends Error {\n readonly code: InjectionErrorCode;\n constructor(code: InjectionErrorCode, message: string) {\n super(message);\n this.name = 'InjectionError';\n this.code = code;\n }\n}\n\nexport interface InjectionSource {\n active(date?: string): readonly MemoryDoc[];\n /** Preferred audit sink: keeps the store manifest head in sync. */\n appendAudit?(data: Record<string, unknown>): void;\n readonly journal?: { append(entry: { op: 'audit'; data: Record<string, unknown> }): unknown };\n}\n\nexport interface AssembleInput {\n readonly home: string;\n readonly config: Config;\n readonly policy: Policy;\n readonly source: InjectionSource;\n readonly sessionId: string;\n readonly asOf?: string;\n readonly now?: () => Date;\n /** Token counter; when absent, chars/2.5 and `estimated: true`. */\n readonly measure?: (text: string) => number;\n /** Test seam: fixed delimiter instead of a random 16-hex one. */\n readonly delimiter?: string;\n /** Test seam: skip snapshot persistence. */\n readonly persist?: boolean;\n /** Extension seam: extra document layers (P0.5 section registry). */\n readonly extraSections?: readonly SectionSource[];\n}\n\nexport interface InjectionBudget {\n readonly counter: 'chars' | 'tokens';\n readonly estimated: boolean;\n readonly sections: Readonly<Record<string, number>>;\n readonly total: number;\n}\n\nexport interface AssembleResult {\n readonly text: string;\n readonly memory_revision: string;\n readonly captured: boolean;\n readonly budget: InjectionBudget;\n readonly sections: readonly string[];\n readonly rules: readonly Rule[];\n /** Per-source text, one entry per source (empty when absent). */\n readonly parts: Readonly<Record<string, string>>;\n /** Rendered section list in order, so the host can register one prompt section per source. */\n readonly sectionList: readonly { readonly key: string; readonly order: number; readonly text: string }[];\n /** Per-section health; a degraded section still appears in `sectionList` as a notice. */\n readonly health: readonly SectionHealth[];\n}\n\nconst EVIDENCE_RANK: Record<string, number> = {\n user_explicit: 0,\n user_confirmed: 1,\n observed: 2,\n inferred: 3,\n};\n\nfunction charCount(text: string): number {\n return [...text].length;\n}\n\nexport function memoryRevision(docs: Iterable<MemoryDoc>): string {\n const lines = [...docs]\n .map((doc) => `${doc.id}:${doc.content_hash}`)\n .sort((left, right) => left.localeCompare(right));\n return createHash('sha256').update(lines.join('\\n'), 'utf8').digest('hex');\n}\n\nfunction catalogLines(docs: readonly MemoryDoc[]): string[] {\n const sorted = [...docs].sort((left, right) => {\n const rank = (EVIDENCE_RANK[left.evidence_level] ?? 9) - (EVIDENCE_RANK[right.evidence_level] ?? 9);\n if (rank !== 0) return rank;\n if (left.valid_from !== right.valid_from) return right.valid_from.localeCompare(left.valid_from);\n return left.id.localeCompare(right.id);\n });\n return sorted.map((doc) => `- [${doc.kind}] ${doc.abstract} \u2014 ${doc.id}`);\n}\n\nfunction fitCatalog(docs: readonly MemoryDoc[], budget: number): string {\n const lines = catalogLines(docs);\n if (lines.length === 0) return '';\n let used = 0;\n const kept: string[] = [];\n for (const line of lines) {\n const cost = charCount(line) + 1;\n if (used + cost > budget) break;\n kept.push(line);\n used += cost;\n }\n const remaining = lines.length - kept.length;\n if (remaining > 0) {\n const hint =\n docs.length > 200\n ? `- \u2026${remaining} \u6761\u672A\u5217\u51FA\uFF08\u7528 memory_recall \u68C0\u7D22\uFF09`\n : `- \u2026${remaining} \u6761\u672A\u5217\u51FA`;\n kept.push(hint);\n }\n return kept.join('\\n');\n}\n\nfunction counted(text: string, counter: 'chars' | 'tokens', measure?: (text: string) => number): number {\n if (counter === 'chars') return charCount(text);\n return measure === undefined ? Math.ceil(charCount(text) / 2.5) : measure(text);\n}\n\nexport function assemble(input: AssembleInput): AssembleResult {\n const now = input.now ?? (() => new Date());\n const date = input.asOf ?? today(now());\n\n // T2: re-check the sealed human files right before reading them, so an edit\n // after startup cannot slip into the prompt.\n verifySealedFiles({ home: input.home, policy: input.policy });\n\n const active = input.source.active(date);\n const revision = memoryRevision(active);\n\n const existing = readSnapshot(input.home, input.sessionId);\n if (\n existing !== null &&\n existing.prompt_schema_version === PROMPT_SCHEMA_VERSION &&\n existing.parts !== undefined &&\n existing.sectionList !== undefined\n ) {\n return {\n text: existing.text,\n memory_revision: existing.memory_revision,\n captured: false,\n budget: { counter: input.config.inject.counter, estimated: input.measure === undefined, sections: {}, total: 0 },\n sections: existing.sectionList.map((section) => section.key),\n rules: [],\n parts: existing.parts,\n sectionList: existing.sectionList,\n health: existing.health ?? [],\n };\n }\n\n const built = buildSections({ home: input.home, config: input.config }, input.extraSections ?? []);\n const sectionList: { key: string; order: number; text: string }[] = [...built.entries];\n const parts: Record<string, string> = {};\n for (const entry of sectionList) parts[entry.key] = entry.text;\n const rules = built.rules;\n\n const catalog = fitCatalog(active, input.config.inject.index_max_chars);\n if (catalog !== '') {\n parts.MEMORY = catalog;\n sectionList.push({ key: 'MEMORY', order: SECTION_ORDERS.MEMORY, text: catalog });\n }\n sectionList.sort((left, right) => left.order - right.order);\n\n let body = sectionList.map((section) => `## ${section.key}\\n${section.text}`).join('\\n\\n');\n const counter = input.config.inject.counter;\n let total = counted(body, counter, input.measure);\n if (total > input.config.inject.total_max_chars) {\n // Only the catalog may be trimmed further; all other sections are capped.\n const indexSection = sectionList.find((section) => section.key === 'MEMORY');\n if (indexSection === undefined) {\n throw new InjectionError('OVER_BUDGET', `injection is over inject.total_max_chars (${input.config.inject.total_max_chars})`);\n }\n const excess = total - input.config.inject.total_max_chars;\n indexSection.text = fitCatalog(active, Math.max(0, input.config.inject.index_max_chars - excess - 8));\n parts.MEMORY = indexSection.text;\n body = sectionList.map((section) => `## ${section.key}\\n${section.text}`).join('\\n\\n');\n total = counted(body, counter, input.measure);\n if (total > input.config.inject.total_max_chars) {\n throw new InjectionError('OVER_BUDGET', `injection is over inject.total_max_chars (${input.config.inject.total_max_chars})`);\n }\n }\n\n const delimiter = input.delimiter ?? randomBytes(8).toString('hex');\n const escaped = body.split(delimiter).join('<escaped>');\n const text = `<<AM-${delimiter}>>\\n${escaped}\\n<<AM-${delimiter}>>`;\n\n const sectionBudgets: Record<string, number> = {};\n for (const section of sectionList) {\n sectionBudgets[section.key] = counted(section.text, counter, input.measure);\n }\n\n const record = {\n session_id: input.sessionId,\n memory_revision: revision,\n prompt_schema_version: PROMPT_SCHEMA_VERSION,\n created_at: now().toISOString(),\n text,\n parts,\n sectionList,\n health: built.health,\n };\n if (input.persist !== false) {\n writeSnapshot(input.home, record);\n try {\n const audit = { event: 'snapshot-capture', session_id: input.sessionId };\n if (input.source.appendAudit !== undefined) {\n input.source.appendAudit(audit);\n } else {\n input.source.journal?.append({ op: 'audit', data: audit });\n }\n } catch {\n // Journal trouble is reported by the store; a snapshot is still usable.\n }\n }\n\n return {\n text,\n memory_revision: revision,\n captured: true,\n budget: {\n counter,\n estimated: counter === 'tokens' && input.measure === undefined,\n sections: sectionBudgets,\n total,\n },\n sections: sectionList.map((section) => section.key),\n rules,\n parts,\n sectionList,\n health: built.health,\n };\n}\n\n/** DSH adapter shape: one protected section, no interpolation. */\nexport function sectionPayload(result: AssembleResult, order = 100) {\n return { name: 'agent-memory', order, text: result.text, interpolate: false as const };\n}\n", "import { existsSync, readFileSync } from 'node:fs';\nimport type { Config } from '../config/config.ts';\nimport { memoryPaths } from '../paths.ts';\nimport { renderGuidance } from '../personalization/guidance.ts';\nimport { parseRules, renderRules, validateRules, type Rule } from '../rules/rules.ts';\n\n/**\n * Section registry (architecture v2, P0.5). Each injected block is one source\n * with its own order, budget and failure mode. A broken optional section only\n * degrades itself (visible notice + health entry); sealed-file and store\n * integrity checks stay outside and remain global.\n *\n * Adding a document layer later means adding one source here (or passing one\n * through `AssembleInput.extraSections`) \u2014 assemble() and the GUI do not change.\n */\n\nexport interface SectionSource {\n readonly key: string;\n readonly order: number;\n /** Hard character cap; undefined means the source enforces its own budget. */\n readonly maxChars?: number;\n /** Render the raw text (parse/validate). Throw to degrade this section. */\n readonly render?: (text: string) => string;\n readonly load: () => string;\n}\n\nexport interface SectionContext {\n readonly home: string;\n readonly config: Config;\n}\n\nexport interface SectionHealth {\n readonly key: string;\n readonly ok: boolean;\n readonly message?: string;\n}\n\nexport interface BuiltSections {\n readonly entries: readonly { key: string; order: number; text: string }[];\n readonly health: readonly SectionHealth[];\n readonly rules: readonly Rule[];\n}\n\nconst COMMENT = /<!--[\\s\\S]*?-->/g;\n\nfunction charCount(text: string): number {\n return [...text].length;\n}\n\nfunction truncate(text: string, budget: number): string {\n const points = [...text];\n if (points.length <= budget) return text;\n if (budget <= 1) return '\u2026';\n return `${points.slice(0, budget - 1).join('')}\u2026`;\n}\n\nfunction readIfExists(file: string): string {\n return existsSync(file) ? readFileSync(file, 'utf8').replace(COMMENT, '').trim() : '';\n}\n\nexport const SECTION_ORDERS = { SOUL: 100, GUIDANCE: 110, RULES: 150, USER: 200, MEMORY: 300 } as const;\n\nexport function builtinSectionSources(context: SectionContext): SectionSource[] {\n const paths = memoryPaths(context.home);\n return [\n {\n key: 'SOUL',\n order: SECTION_ORDERS.SOUL,\n maxChars: context.config.inject.persona_max_chars,\n load: () => readIfExists(paths.soulFile),\n },\n {\n key: 'GUIDANCE',\n order: SECTION_ORDERS.GUIDANCE,\n maxChars: context.config.inject.guidance_max_chars,\n load: () => renderGuidance(context.config.personalization.mode),\n },\n {\n key: 'RULES',\n order: SECTION_ORDERS.RULES,\n render: (text) => {\n const parsed = parseRules(text);\n const errors = [...parsed.errors, ...validateRules(parsed.rules, { rootDir: context.home })];\n if (errors.length > 0) throw new Error(`RULES.md rejected: ${errors.join('; ')}`);\n const rendered = renderRules(parsed.rules, { includeRevoked: false });\n if (charCount(rendered) > context.config.inject.rules_max_chars) {\n throw new Error(\n `RULES.md renders to ${charCount(rendered)} chars, over inject.rules_max_chars (${context.config.inject.rules_max_chars})`,\n );\n }\n return rendered;\n },\n load: () => readIfExists(paths.rulesFile),\n },\n {\n key: 'USER',\n order: SECTION_ORDERS.USER,\n maxChars: context.config.inject.user_max_chars,\n load: () => readIfExists(paths.userFile),\n },\n ];\n}\n\n/** Render every source, degrading only the failing one. */\nexport function buildSections(context: SectionContext, extra: readonly SectionSource[] = []): BuiltSections {\n const sources = [...builtinSectionSources(context), ...extra].sort((left, right) => left.order - right.order);\n const entries: { key: string; order: number; text: string }[] = [];\n const health: SectionHealth[] = [];\n const rules: Rule[] = [];\n\n for (const source of sources) {\n try {\n const loaded = source.load();\n const rendered = source.render === undefined ? loaded : source.render(loaded);\n const text = source.maxChars === undefined ? rendered : truncate(rendered, source.maxChars);\n if (text !== '') entries.push({ key: source.key, order: source.order, text });\n health.push({ key: source.key, ok: true });\n if (source.key === 'RULES') {\n rules.push(...parseRules(loaded).rules);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const notice = `\u26A0 \u672C\u8282\u4E0D\u53EF\u7528\uFF08${source.key}\uFF09\uFF1A${message}`.slice(0, 200);\n entries.push({ key: source.key, order: source.order, text: notice });\n health.push({ key: source.key, ok: false, message });\n }\n }\n\n return { entries, health, rules };\n}\n", "import type { PersonalizationMode } from './mode.ts';\n\n/**\n * `MEMORY_GUIDANCE` section (architecture v2, P3). Short, mode-aware instructions\n * that tell the model how to use the memory surfaces. It is injected right after\n * SOUL and kept inside the guidance budget.\n */\n\nexport function renderGuidance(mode: PersonalizationMode): string {\n const modeLine =\n mode === 'direct'\n ? '- \u81EA\u4E3B\u5224\u65AD\u5E76\u76F4\u63A5\u5199\u5165\uFF0C\u65E0\u9700\u5148\u5F81\u5F97\u540C\u610F\uFF1B\u4ECD\u5FC5\u987B\u4FDD\u7559\u51FA\u5904\u3002'\n : mode === 'readonly'\n ? '- \u53EA\u8BFB\uFF1A\u4E0D\u5F97\u65B0\u589E\u3001\u4FEE\u6539\u6216\u5220\u9664\u8BB0\u5FC6\u4E0E\u504F\u597D\uFF1B\u9700\u8981\u65F6\u628A\u5EFA\u8BAE\u4EA4\u7ED9\u7528\u6237\u3002'\n : '- \u65B0\u589E\u3001\u4FEE\u6539\u6216\u5220\u9664\u8BB0\u5FC6\u4E0E\u504F\u597D\u524D\uFF0C\u5148\u7528\u786E\u8BA4\u5361\u7247\u53D6\u5F97\u7528\u6237\u540C\u610F\uFF1B\u88AB\u62D2\u7EDD\u5C31\u4E0D\u5199\u3002';\n return [\n '## \u8BB0\u5FC6\u4E0E\u65B9\u6CD5\u590D\u7528',\n '- \u504F\u597D\u5199 USER\uFF0C\u4E8B\u5B9E\u4E0E\u7ECF\u9A8C\u5199\u8BB0\u5FC6\uFF0C\u7EA6\u5B9A\u5199 RULES\uFF0C\u53EF\u590D\u7528\u65B9\u6CD5\u7528 skills\u3002',\n '- \u4FEE\u6539\u524D\u5148\u8BFB\u6700\u65B0\u6761\u76EE\uFF1B\u66FF\u6362\u8981\u7ED9\u5B8C\u6574\u6761\u76EE\uFF0C\u907F\u514D\u91CD\u590D\u6216\u77DB\u76FE\u3002',\n '- \u53EA\u901A\u8FC7\u5DE5\u5177\u5199\u5165\uFF0C\u4E0D\u7ED5\u8FC7\uFF1B\u5199\u5165\u5FC5\u987B\u5F15\u7528\u771F\u5B9E\u4E8B\u4EF6\u51FA\u5904\u3002',\n modeLine,\n '- \u5B50 agent \u53EA\u8BFB\u3002',\n ].join('\\n');\n}\n", "import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Config } from '../config/config.ts';\nimport type { MemoryId, ProposalInput, ProposalReplacement } from '../model/types.ts';\nimport { isMemoryId, newMemoryId } from '../model/ids.ts';\nimport { assertClean, redactPrivate } from '../scan/scan.ts';\nimport type { MemoryStore } from '../store/store.ts';\nimport { writeFileAtomic } from '../fs/atomic.ts';\n\n/**\n * Proposal ledger (plan v1.3 \u00A74.6, S4). A proposal is a file under\n * `proposals/pending/`; decisions live in the journal (`op: decide`), so the\n * ledger and history never disagree.\n *\n * Accepting verifies every `base_hash` before touching the store; a failed\n * accept leaves the proposal file in place (S4.4).\n */\n\n/**\n * A replacement carries provenance bound at propose time (verified against the\n * proposing session). It is written into the record on accept, so the evidence\n * does not stop at the pending file (plan v1.3 \u00A77 \"\u8BC1\u636E\u53EF\u6838\u9A8C\").\n */\nexport type { ProposalReplacement };\n\nexport interface Proposal {\n readonly id: string;\n readonly op: 'create' | 'supersede' | 'delete';\n readonly targets: readonly MemoryId[];\n readonly base_hashes: readonly string[];\n readonly replacements: readonly ProposalReplacement[];\n readonly reason: string;\n readonly created_at: string;\n}\n\nexport class ProposalError extends Error {\n readonly code: 'INVALID' | 'NOT_FOUND' | 'CONFLICT';\n constructor(code: ProposalError['code'], message: string) {\n super(message);\n this.name = 'ProposalError';\n this.code = code;\n }\n}\n\nexport interface ProposalDeps {\n readonly store: MemoryStore;\n readonly config: Config;\n}\n\nfunction pendingDir(store: MemoryStore): string {\n return store.paths.pendingDir;\n}\n\nfunction proposalPath(store: MemoryStore, id: string): string {\n return join(pendingDir(store), `${id}.json`);\n}\n\nexport function listProposals(store: MemoryStore): Proposal[] {\n let names: string[];\n try {\n names = readdirSync(pendingDir(store)).filter((name) => name.endsWith('.json'));\n } catch {\n return [];\n }\n const proposals: Proposal[] = [];\n for (const name of names) {\n try {\n proposals.push(JSON.parse(readFileSync(join(pendingDir(store), name), 'utf8')) as Proposal);\n } catch {\n // A corrupt proposal file is not a reason to hide the others.\n }\n }\n return proposals.sort((left, right) => left.created_at.localeCompare(right.created_at));\n}\n\nexport function readProposal(store: MemoryStore, id: string): Proposal {\n const file = proposalPath(store, id);\n if (!existsSync(file)) throw new ProposalError('NOT_FOUND', `no pending proposal ${id}`);\n return JSON.parse(readFileSync(file, 'utf8')) as Proposal;\n}\n\nfunction currentHash(store: MemoryStore, id: MemoryId): string {\n const doc = store.read(id);\n return doc.content_hash;\n}\n\nexport function createProposal(deps: ProposalDeps, input: ProposalInput): Proposal {\n const { store, config } = deps;\n if (input.op === 'create') {\n if (input.replacements.length === 0) throw new ProposalError('INVALID', 'create needs replacements');\n for (const replacement of input.replacements) {\n assertClean({ abstract: replacement.abstract, body: replacement.body, error_signatures: replacement.error_signatures });\n }\n } else if (input.op === 'supersede') {\n if (input.replacements.length === 0) throw new ProposalError('INVALID', 'supersede needs replacements');\n if (input.targets.length === 0) throw new ProposalError('INVALID', 'supersede needs targets');\n const unique = new Set(input.targets);\n if (unique.size !== input.targets.length) throw new ProposalError('INVALID', 'targets must be unique');\n if (input.base_hashes.length !== input.targets.length) {\n throw new ProposalError('INVALID', 'one base_hash per target is required');\n }\n input.targets.forEach((target, index) => {\n if (!isMemoryId(target)) throw new ProposalError('INVALID', `invalid target id: ${target}`);\n const actual = currentHash(store, target);\n if (actual !== input.base_hashes[index]) {\n throw new ProposalError('CONFLICT', `base_hash for ${target} does not match the current content`);\n }\n });\n for (const replacement of input.replacements) {\n assertClean({ abstract: replacement.abstract, body: replacement.body, error_signatures: replacement.error_signatures });\n }\n } else {\n if (!isMemoryId(input.target)) throw new ProposalError('INVALID', `invalid target id: ${input.target}`);\n if (input.reason.trim() === '') throw new ProposalError('INVALID', 'a delete proposal needs a reason');\n if (currentHash(store, input.target) !== input.base_hash) {\n throw new ProposalError('CONFLICT', `base_hash for ${input.target} does not match the current content`);\n }\n assertClean({ targets: [input.target] });\n }\n\n const existing = listProposals(store);\n if (existing.length >= config.proposals.max_pending) {\n throw new ProposalError('CONFLICT', `pending proposals are at proposals.max_pending (${config.proposals.max_pending})`);\n }\n\n const proposal: Proposal = {\n id: `prop-${newMemoryId(new Date())}`,\n op: input.op,\n targets: input.op === 'create' ? [] : input.op === 'supersede' ? input.targets : [input.target],\n base_hashes: input.op === 'create' ? [] : input.op === 'supersede' ? input.base_hashes : [input.base_hash],\n replacements:\n input.op === 'delete'\n ? []\n : input.replacements.map((replacement) => ({\n ...replacement,\n abstract: redactPrivate(replacement.abstract),\n body: redactPrivate(replacement.body),\n })),\n reason: input.op === 'delete' ? input.reason : (input.reason ?? ''),\n created_at: new Date().toISOString(),\n };\n writeFileAtomic(proposalPath(store, proposal.id), `${JSON.stringify(proposal, null, 2)}\\n`);\n store.appendJournal('audit', { event: 'proposal-created', proposal: proposal.id, op: proposal.op });\n return proposal;\n}\n\nexport interface DecideInput {\n readonly id: string;\n readonly decision: 'accept' | 'reject';\n readonly reason?: string;\n}\n\n/** Apply (or reject) one proposal; the pending file is removed only on success. */\nexport function decideProposal(deps: ProposalDeps, input: DecideInput): void {\n const { store } = deps;\n const proposal = readProposal(store, input.id);\n\n if (input.decision === 'reject') {\n store.appendJournal('decide', { proposal: proposal.id, decision: 'reject', reason: input.reason ?? '' });\n rmSync(proposalPath(store, proposal.id), { force: true });\n return;\n }\n\n if (proposal.op === 'delete') {\n const target = proposal.targets[0] as MemoryId;\n const hash = proposal.base_hashes[0] as string;\n if (currentHash(store, target) !== hash) {\n throw new ProposalError('CONFLICT', `target ${target} changed since the proposal was created`);\n }\n store.remove(target, { reason: proposal.reason, baseHash: hash });\n store.journal.append({ op: 'decide', data: { proposal: proposal.id, decision: 'accept' } });\n rmSync(proposalPath(store, proposal.id), { force: true });\n return;\n }\n\n if (proposal.op === 'create') {\n store.addMany(proposal.replacements, { author: 'human', opId: `decide-${proposal.id}` });\n store.appendJournal('decide', { proposal: proposal.id, decision: 'accept' });\n rmSync(proposalPath(store, proposal.id), { force: true });\n return;\n }\n\n proposal.targets.forEach((target, index) => {\n if (currentHash(store, target) !== proposal.base_hashes[index]) {\n throw new ProposalError('CONFLICT', `target ${target} changed since the proposal was created`);\n }\n });\n store.addMany(\n proposal.replacements.map((replacement) => ({ ...replacement, supersedes: proposal.targets })),\n { author: 'human', opId: `decide-${proposal.id}` },\n );\n store.appendJournal('decide', { proposal: proposal.id, decision: 'accept' });\n rmSync(proposalPath(store, proposal.id), { force: true });\n}\n", "import { createHash } from 'node:crypto';\nimport type { ProvenanceEntry } from './model/types.ts';\n\n/**\n * Trusted source binding (plan v1.3 \u00A75.3). The model only supplies\n * `{event_seq, quote}`; the adapter resolves the real event and fills\n * `session_id` / `speaker` / `event_sha256`. A quote that is not a substring of\n * the resolved event, a missing event, or an assistant message used as evidence\n * is rejected.\n */\n\nexport interface EvidenceEvent {\n readonly seq: number;\n readonly speaker: 'user' | 'assistant' | 'tool' | 'system';\n readonly text: string;\n}\n\nexport class EvidenceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'EvidenceError';\n }\n}\n\nexport interface BindEvidenceInput {\n readonly sessionId: string;\n readonly eventSeq: number;\n readonly quote: string;\n readonly lookup: (seq: number) => EvidenceEvent | undefined;\n /** Optional caller-supplied hash; must match the resolved event text. */\n readonly expectedSha256?: string;\n}\n\nexport function bindEvidence(input: BindEvidenceInput): ProvenanceEntry {\n const event = input.lookup(input.eventSeq);\n if (event === undefined) throw new EvidenceError(`event ${input.eventSeq} does not exist in this session`);\n if (event.seq !== input.eventSeq) throw new EvidenceError('event sequence mismatch');\n if (event.speaker === 'assistant') {\n throw new EvidenceError('a model message cannot be its own evidence');\n }\n if (input.quote.length === 0 || [...input.quote].length > 160) {\n throw new EvidenceError('quote must be 1..160 characters');\n }\n if (!event.text.includes(input.quote)) {\n throw new EvidenceError('quote is not a substring of the referenced event');\n }\n const sha256 = createHash('sha256').update(event.text, 'utf8').digest('hex');\n if (input.expectedSha256 !== undefined && input.expectedSha256 !== sha256) {\n throw new EvidenceError('event hash does not match the resolved event');\n }\n return {\n session_id: input.sessionId,\n event_seq: input.eventSeq,\n speaker: event.speaker,\n quote: input.quote,\n event_sha256: sha256,\n };\n}\n", "/** Per-session T0 write budget (plan v1.3 \u00A75.4). In memory on purpose: a crash\n * resets the counter, which can only make the agent ask for a proposal sooner. */\nexport class SessionQuota {\n private readonly used = new Map<string, number>();\n private readonly limit: number;\n\n constructor(limit: number) {\n this.limit = limit;\n }\n\n /** Consume one T0 write; returns false when the session budget is exhausted. */\n consume(sessionId: string): boolean {\n const count = this.used.get(sessionId) ?? 0;\n if (count >= this.limit) return false;\n this.used.set(sessionId, count + 1);\n return true;\n }\n\n usedOf(sessionId: string): number {\n return this.used.get(sessionId) ?? 0;\n }\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { memoryPaths } from '../paths.ts';\nimport { writeFileAtomic } from '../fs/atomic.ts';\n\n/** Persisted set of rejected proposal summary hashes (never re-propose them). */\nexport function loadRejected(home: string): Set<string> {\n const file = join(memoryPaths(home).stateDir, 'distill-rejected.json');\n if (!existsSync(file)) return new Set();\n try {\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as { hashes?: unknown };\n return new Set(Array.isArray(parsed.hashes) ? parsed.hashes.filter((value): value is string => typeof value === 'string') : []);\n } catch {\n return new Set();\n }\n}\n\nexport function addRejected(home: string, hashes: readonly string[]): void {\n const set = loadRejected(home);\n for (const hash of hashes) set.add(hash);\n writeFileAtomic(\n join(memoryPaths(home).stateDir, 'distill-rejected.json'),\n `${JSON.stringify({ hashes: [...set].sort() }, null, 2)}\\n`,\n );\n}\n\n/**\n * Closeout distillation core (plan v1.3 \u00A77, S6).\n *\n * L0 is deterministic tagging over the session log; it never writes memory.\n * The model gets the L0 list plus the active catalog and must answer with a\n * strict JSON contract. Everything it returns is re-validated here: evidence is\n * resolved against real events, assistant messages cannot be their own evidence,\n * a `rule` without machine-check design is downgraded, duplicates and rejected\n * summaries disappear, and at most five proposals survive.\n */\n\nexport interface DistillEvent {\n readonly seq: number;\n readonly speaker: 'user' | 'assistant' | 'tool' | 'system';\n readonly text: string;\n}\n\nexport type L0Kind = 'repeated-error' | 'correction' | 'failure-then-success' | 'rollback';\n\nexport interface L0Signal {\n readonly kind: L0Kind;\n readonly event_seqs: readonly number[];\n readonly summary: string;\n}\n\nconst CORRECTION = /\u4E0D\u5BF9|\u9519\u4E86|\u4E0D\u662F\u8FD9\u6837|\u7EA0\u6B63|actually|correction|rather than|instead/i;\nconst ROLLBACK = /\u56DE\u6EDA|\u64A4\u9500|revert|rollback|undo/i;\nconst FAILURE = /error|failed|\u5931\u8D25|\u62A5\u9519|exception/i;\n\nexport function collectL0(events: readonly DistillEvent[]): L0Signal[] {\n const signals: L0Signal[] = [];\n const failureSeqs = events.filter((event) => event.speaker !== 'user' && FAILURE.test(event.text)).map((event) => event.seq);\n if (failureSeqs.length >= 2) {\n signals.push({\n kind: 'repeated-error',\n event_seqs: failureSeqs.slice(0, 5),\n summary: `${failureSeqs.length} \u4E2A\u5DE5\u5177\u8F93\u51FA\u5305\u542B\u9519\u8BEF/\u5931\u8D25`,\n });\n }\n const corrections = events.filter((event) => event.speaker === 'user' && CORRECTION.test(event.text));\n if (corrections.length > 0) {\n signals.push({\n kind: 'correction',\n event_seqs: corrections.map((event) => event.seq).slice(0, 5),\n summary: '\u7528\u6237\u7EA0\u6B63\u4E86\u5148\u524D\u7684\u8BF4\u6CD5\u6216\u505A\u6CD5',\n });\n }\n const failures = events.filter((event) => event.speaker === 'tool' && FAILURE.test(event.text));\n const successes = events.filter((event) => event.speaker === 'tool' && !FAILURE.test(event.text));\n if (failures.length > 0 && successes.length > 0) {\n signals.push({\n kind: 'failure-then-success',\n event_seqs: [failures[failures.length - 1]?.seq as number, successes[successes.length - 1]?.seq as number],\n summary: '\u5DE5\u5177\u5148\u5931\u8D25\u540E\u6210\u529F',\n });\n }\n const rollbacks = events.filter((event) => ROLLBACK.test(event.text));\n if (rollbacks.length > 0) {\n signals.push({\n kind: 'rollback',\n event_seqs: rollbacks.map((event) => event.seq).slice(0, 5),\n summary: '\u51FA\u73B0\u56DE\u6EDA/\u64A4\u9500',\n });\n }\n return signals;\n}\n\nexport interface CloseoutPromptInput {\n readonly l0: readonly L0Signal[];\n readonly active: readonly { readonly id: string; readonly kind: string; readonly abstract: string }[];\n readonly maxProposals: number;\n}\n\nexport function buildCloseoutPrompt(input: CloseoutPromptInput): string {\n const l0 = input.l0.length === 0 ? '\uFF08\u65E0\uFF09' : input.l0.map((signal) => `- ${signal.kind} [${signal.event_seqs.join(',')}] ${signal.summary}`).join('\\n');\n const catalog = input.active.map((doc) => `- ${doc.id} [${doc.kind}] ${doc.abstract}`).join('\\n');\n return [\n '\u4F60\u6B63\u5728\u505A Agent Memory \u7684\u6536\u5C3E\u84B8\u998F\u3002\u53EA\u8F93\u51FA\u4E00\u4E2A JSON \u5BF9\u8C61\uFF0C\u4E0D\u8981\u8F93\u51FA\u522B\u7684\u6587\u5B57\u3002',\n '',\n 'L0 \u786E\u5B9A\u6027\u7EBF\u7D22\uFF1A',\n l0,\n '',\n '\u5F53\u524D\u6D3B\u52A8\u8BB0\u5FC6\uFF08targets \u53EA\u80FD\u4ECE\u8FD9\u91CC\u9009\uFF09\uFF1A',\n catalog || '\uFF08\u7A7A\uFF09',\n '',\n `\u6700\u591A ${input.maxProposals} \u6761\u63D0\u6848\u3002JSON \u5951\u7EA6\uFF1A`,\n '{\"proposals\":[{\"op\":\"supersede\",\"targets\":[\"mem-...\"],\"reason\":\"...\",\"replacements\":[{\"kind\":\"fact|pitfall|exp\",\"abstract\":\"...\",\"body\":\"...\",\"evidence\":[{\"event_seq\":1,\"quote\":\"\u539F\u6587\u7247\u6BB5\"}]}]}]}',\n '\u6216 {\"proposals\":[],\"message\":\"\u672C\u6B21\u65E0\u65B0\u63D0\u6848\"}\u3002',\n 'evidence \u5FC5\u987B\u5F15\u7528\u771F\u5B9E\u4E8B\u4EF6\uFF1Aevent_seq \u662F\u8BE5\u4E8B\u4EF6\u5E8F\u53F7\uFF0Cquote \u5FC5\u987B\u662F\u8BE5\u4E8B\u4EF6\u539F\u6587\u7684\u5B50\u4E32\uFF1B\u52A9\u624B\u6D88\u606F\u4E0D\u80FD\u5F53\u8BC1\u636E\u3002',\n '\u6CA1\u6709\u673A\u5668\u68C0\u67E5\u8BBE\u8BA1\uFF08check/test/[neg]\uFF09\u7684\u89C4\u5219\u4E0D\u8981\u5199\u6210 rule\uFF0C\u964D\u7EA7\u4E3A pitfall \u6216 fact\u3002',\n '\u5DF2\u5426\u51B3\u7684\u6458\u8981\u3001\u4E0E\u6D3B\u52A8\u8BB0\u5FC6\u91CD\u590D\u7684\u5185\u5BB9\u4E0D\u8981\u518D\u63D0\u3002',\n ].join('\\n');\n}\n\nexport interface CloseoutCandidate {\n readonly op: 'supersede' | 'delete';\n readonly targets: readonly string[];\n readonly reason: string;\n readonly replacements: readonly {\n readonly kind: 'fact' | 'pitfall' | 'exp';\n readonly abstract: string;\n readonly body: string;\n readonly evidence: readonly { readonly event_seq: number; readonly quote: string }[];\n }[];\n}\n\nexport interface ParseDeps {\n readonly events: readonly DistillEvent[];\n readonly activeAbstracts: readonly string[];\n readonly activeIds: readonly string[];\n readonly rejectedHashes?: ReadonlySet<string>;\n readonly maxProposals?: number;\n}\n\nexport interface ParseResult {\n readonly candidates: readonly CloseoutCandidate[];\n readonly message: string | null;\n readonly errors: readonly string[];\n readonly dropped: readonly string[];\n readonly truncated: number;\n}\n\nfunction normalizedAbstract(text: string): string {\n return text.normalize('NFKC').toLowerCase().replace(/\\s+/g, ' ').trim();\n}\n\nexport function summaryHash(candidate: CloseoutCandidate): string {\n const material = [\n candidate.op,\n [...candidate.targets].sort().join(','),\n ...candidate.replacements.map((replacement) => normalizedAbstract(replacement.abstract)),\n ].join('|');\n return createHash('sha256').update(material, 'utf8').digest('hex');\n}\n\nfunction findJson(text: string): unknown {\n const start = text.indexOf('{');\n const end = text.lastIndexOf('}');\n if (start < 0 || end <= start) return undefined;\n try {\n return JSON.parse(text.slice(start, end + 1));\n } catch {\n return undefined;\n }\n}\n\n/** Validate the model's closeout answer against the real session events. */\nexport function parseCloseout(text: string, deps: ParseDeps): ParseResult {\n const errors: string[] = [];\n const dropped: string[] = [];\n const parsed = findJson(text);\n if (typeof parsed !== 'object' || parsed === null) {\n return { candidates: [], message: null, errors: ['closeout answer is not a JSON object'], dropped, truncated: 0 };\n }\n const record = parsed as { proposals?: unknown; message?: unknown };\n const emptyMessage =\n typeof record.message === 'string' &&\n record.message.trim() !== '' &&\n (record.proposals === undefined || (Array.isArray(record.proposals) && record.proposals.length === 0));\n if (emptyMessage) {\n return { candidates: [], message: (record.message as string).trim(), errors, dropped, truncated: 0 };\n }\n if (!Array.isArray(record.proposals)) {\n return { candidates: [], message: null, errors: ['proposals must be an array'], dropped, truncated: 0 };\n }\n const limit = deps.maxProposals ?? 5;\n const truncated = Math.max(0, record.proposals.length - limit);\n const candidates: CloseoutCandidate[] = [];\n const activeIds = new Set(deps.activeIds);\n const activeAbstracts = new Set(deps.activeAbstracts.map(normalizedAbstract));\n const rejected = deps.rejectedHashes ?? new Set<string>();\n const events = new Map(deps.events.map((event) => [event.seq, event]));\n\n for (const raw of record.proposals.slice(0, limit)) {\n if (typeof raw !== 'object' || raw === null) {\n dropped.push('proposal is not an object');\n continue;\n }\n const proposal = raw as {\n op?: unknown;\n targets?: unknown;\n target?: unknown;\n reason?: unknown;\n replacements?: unknown;\n };\n const op = proposal.op === 'delete' ? 'delete' : proposal.op === 'supersede' ? 'supersede' : null;\n if (op === null) {\n dropped.push('unsupported op');\n continue;\n }\n const targets = (op === 'delete' ? [proposal.target] : proposal.targets) as unknown;\n if (!Array.isArray(targets) || targets.length === 0 || !targets.every((target) => typeof target === 'string')) {\n dropped.push('targets must be memory ids');\n continue;\n }\n if (!targets.every((target) => activeIds.has(target as string))) {\n dropped.push('target is not an active memory');\n continue;\n }\n const replacementsRaw = op === 'supersede' ? proposal.replacements : [];\n if (!Array.isArray(replacementsRaw) || (op === 'supersede' && replacementsRaw.length === 0)) {\n dropped.push('supersede needs replacements');\n continue;\n }\n const replacements: CloseoutCandidate['replacements'][number][] = [];\n let failed = false;\n for (const rawReplacement of replacementsRaw) {\n if (typeof rawReplacement !== 'object' || rawReplacement === null) {\n dropped.push('replacement is not an object');\n failed = true;\n break;\n }\n const replacement = rawReplacement as {\n kind?: unknown;\n abstract?: unknown;\n body?: unknown;\n evidence?: unknown;\n };\n if (replacement.kind !== 'fact' && replacement.kind !== 'pitfall' && replacement.kind !== 'exp') {\n dropped.push('replacement kind must be fact/pitfall/exp');\n failed = true;\n break;\n }\n const abstract = typeof replacement.abstract === 'string' ? replacement.abstract : '';\n if (abstract.trim() === '' || !Array.isArray(replacement.evidence) || replacement.evidence.length === 0) {\n dropped.push('replacement needs abstract and evidence');\n failed = true;\n break;\n }\n if (activeAbstracts.has(normalizedAbstract(abstract))) {\n dropped.push(`duplicate of an active memory: ${abstract.slice(0, 24)}`);\n failed = true;\n break;\n }\n const evidence: { event_seq: number; quote: string }[] = [];\n for (const rawEvidence of replacement.evidence) {\n if (typeof rawEvidence !== 'object' || rawEvidence === null) {\n dropped.push('evidence is not an object');\n failed = true;\n break;\n }\n const item = rawEvidence as { event_seq?: unknown; quote?: unknown };\n const event = typeof item.event_seq === 'number' ? events.get(item.event_seq) : undefined;\n const quote = typeof item.quote === 'string' ? item.quote : '';\n if (event === undefined) {\n dropped.push(`evidence event ${String(item.event_seq)} does not exist`);\n failed = true;\n break;\n }\n if (event.speaker === 'assistant') {\n dropped.push('assistant message cannot be evidence');\n failed = true;\n break;\n }\n if (quote === '' || !event.text.includes(quote)) {\n dropped.push('evidence quote is not a substring of the event');\n failed = true;\n break;\n }\n if ([...quote].length > 160) {\n dropped.push('evidence quote is longer than 160 characters');\n failed = true;\n break;\n }\n evidence.push({ event_seq: event.seq, quote });\n }\n if (failed) break;\n replacements.push({\n kind: replacement.kind,\n abstract,\n body: typeof replacement.body === 'string' ? replacement.body : '',\n evidence,\n });\n }\n if (failed) continue;\n\n const candidate: CloseoutCandidate = {\n op,\n targets: targets as string[],\n reason: typeof proposal.reason === 'string' ? proposal.reason : '',\n replacements,\n };\n const hash = summaryHash(candidate);\n if (rejected.has(hash)) {\n dropped.push('already rejected');\n continue;\n }\n if (candidates.some((existing) => summaryHash(existing) === hash)) {\n dropped.push('duplicate proposal');\n continue;\n }\n candidates.push(candidate);\n }\n\n return { candidates, message: null, errors, dropped, truncated };\n}\n\n/** `rule` without machine-check design is downgraded instead of proposed as a rule. */\nexport function downgradeRule(candidate: { readonly kind: string; readonly machine_gate?: { check?: string; test?: string } }): {\n readonly action: 'keep' | 'downgrade';\n readonly to?: 'pitfall';\n} {\n if (candidate.kind !== 'rule') return { action: 'keep' };\n if (candidate.machine_gate?.check !== undefined && candidate.machine_gate.test !== undefined) {\n return { action: 'keep' };\n }\n return { action: 'downgrade', to: 'pitfall' };\n}\n\nexport type RoundState = 'open' | 'submitted' | 'disposed';\n\n/** One closeout round: exactly one submit, then dispose (success/failure/timeout). */\nexport class CloseoutRound {\n readonly id: string;\n private state: RoundState = 'open';\n private readonly expiresAt: number;\n private readonly now: () => number;\n\n constructor(options: { id?: string; timeoutMs?: number; now?: () => number } = {}) {\n this.id = options.id ?? `closeout-${Date.now().toString(36)}`;\n this.now = options.now ?? Date.now;\n this.expiresAt = this.now() + (options.timeoutMs ?? 300_000);\n }\n\n get status(): RoundState {\n if (this.state === 'open' && this.now() > this.expiresAt) this.state = 'disposed';\n return this.state;\n }\n\n submit(): { ok: true } | { ok: false; error: string } {\n if (this.status !== 'open') return { ok: false, error: `round is ${this.status}` };\n this.state = 'submitted';\n return { ok: true };\n }\n\n dispose(): void {\n this.state = 'disposed';\n }\n}\n", "import { createHash } from 'node:crypto';\nimport { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { Config } from '../config/config.ts';\nimport { loadRules } from '../rules/rules.ts';\nimport type { MemoryStore } from '../store/store.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * Operational commands (S7): export/pack, checksums, and the read-only inspect\n * report. Nothing here rewrites a memory file; export copies and hashes,\n * inspect reads.\n */\n\nexport interface ExportResult {\n readonly out: string;\n readonly files: number;\n readonly bytes: number;\n readonly sums: string;\n}\n\nconst INCLUDE = [\n 'config.toml',\n 'policy.json',\n 'SOUL.md',\n 'USER.md',\n 'RULES.md',\n 'memories',\n 'proposals',\n '.state/policy.seal.json',\n '.state/journal',\n '.state/distill-rejected.json',\n];\n\nexport function exportStore(options: { home: string; out: string }): ExportResult {\n const paths = memoryPaths(options.home);\n mkdirSync(options.out, { recursive: true });\n for (const entry of INCLUDE) {\n const source = join(paths.home, entry);\n if (!existsSync(source)) continue;\n const target = join(options.out, entry);\n cpSync(source, target, { recursive: true });\n }\n const lines: string[] = [];\n let files = 0;\n let bytes = 0;\n const walk = (dir: string, base: string): void => {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name);\n if (statSync(full).isDirectory()) {\n walk(full, base);\n continue;\n }\n const rel = relative(base, full).replaceAll('\\\\', '/');\n const data = readFileSync(full);\n lines.push(`${createHash('sha256').update(data).digest('hex')} ${rel}`);\n files += 1;\n bytes += data.length;\n }\n };\n walk(options.out, options.out);\n lines.sort();\n const sums = join(options.out, 'SHA256SUMS');\n writeFileSync(sums, `${lines.join('\\n')}\\n`, 'utf8');\n return { out: options.out, files, bytes, sums };\n}\n\nexport function verifyExport(dir: string): { ok: boolean; problems: readonly string[] } {\n const sums = join(dir, 'SHA256SUMS');\n if (!existsSync(sums)) return { ok: false, problems: ['SHA256SUMS is missing'] };\n const problems: string[] = [];\n for (const line of readFileSync(sums, 'utf8').split('\\n')) {\n if (line.trim() === '') continue;\n const match = /^([0-9a-f]{64}) {2}(.+)$/.exec(line);\n if (match === null) {\n problems.push(`malformed line: ${line.slice(0, 80)}`);\n continue;\n }\n const file = join(dir, match[2] as string);\n if (!existsSync(file)) {\n problems.push(`missing file: ${match[2]}`);\n continue;\n }\n const actual = createHash('sha256').update(readFileSync(file)).digest('hex');\n if (actual !== match[1]) problems.push(`hash mismatch: ${match[2]}`);\n }\n return { ok: problems.length === 0, problems };\n}\n\nexport interface InspectReport {\n readonly active: number;\n readonly byKind: Readonly<Record<string, number>>;\n readonly quarantined: readonly string[];\n readonly pendingProposals: number;\n readonly rules: readonly { number: number; category: string; text: string }[];\n readonly journal: readonly { seq: number; op: string; at: string; op_id: string }[];\n readonly budget: { readonly indexChars: number; readonly totalChars: number };\n readonly journalHead: { readonly seq: number; readonly hash: string } | null;\n /** Character counts of the three human-owned personalization files (0 = absent). */\n readonly personalization: { readonly soul: number; readonly user: number; readonly rules: number };\n /** Injection budgets used to flag truncation in the report. */\n readonly inject: { readonly persona_max_chars: number; readonly user_max_chars: number; readonly rules_max_chars: number };\n}\n\nfunction personalizationChars(home: string): { soul: number; user: number; rules: number } {\n const paths = memoryPaths(home);\n const charsOf = (file: string): number => {\n try {\n if (!existsSync(file)) return 0;\n // Comments are stripped before injection, so they do not count against budgets.\n return [...readFileSync(file, 'utf8').replace(/<!--[\\s\\S]*?-->/g, '')].length;\n } catch {\n return 0;\n }\n };\n return { soul: charsOf(paths.soulFile), user: charsOf(paths.userFile), rules: charsOf(paths.rulesFile) };\n}\n\nexport function inspectStore(options: {\n home: string;\n config: Config;\n store: MemoryStore;\n limit?: number;\n}): InspectReport {\n const active = options.store.active();\n const byKind: Record<string, number> = { fact: 0, pitfall: 0, exp: 0 };\n let chars = 0;\n for (const doc of active) {\n byKind[doc.kind] = (byKind[doc.kind] ?? 0) + 1;\n chars += [...doc.abstract].length + [...doc.body].length;\n }\n const journal = options.store.journal.readAll();\n const limit = options.limit ?? 10;\n return {\n active: active.length,\n byKind,\n quarantined: [...options.store.diagnostics().quarantined.keys()],\n pendingProposals: options.store.stats().pending_proposals,\n rules: loadRules(options.home).map((rule) => ({ number: rule.number, category: rule.category, text: rule.text })),\n journal: journal.entries.slice(-limit).map((entry) => ({\n seq: entry.seq,\n op: entry.op,\n at: entry.at,\n op_id: entry.op_id,\n })),\n budget: { indexChars: [...active.map((doc) => doc.abstract).join('\\n')].length, totalChars: chars },\n journalHead: journal.head,\n personalization: personalizationChars(options.home),\n inject: {\n persona_max_chars: options.config.inject.persona_max_chars,\n user_max_chars: options.config.inject.user_max_chars,\n rules_max_chars: options.config.inject.rules_max_chars,\n },\n };\n}\n", "import { existsSync, readFileSync } from 'node:fs';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * USER.md profile entries (architecture v2, P1). One entry per paragraph,\n * separated by a line containing only `\u00A7`; comments are stripped before\n * reading/writing so the scaffold template stays inert.\n *\n * The file stays human-editable; the agent may only change it through the\n * `user_profile` tool, which requires a confirmation card and a prior read.\n */\n\nexport const PROFILE_SEPARATOR = '\u00A7';\nexport const PROFILE_MAX_CHARS = 10000;\n\nexport class ProfileError extends Error {\n readonly code: 'INVALID' | 'CONFLICT' | 'NOT_FOUND';\n constructor(code: ProfileError['code'], message: string) {\n super(message);\n this.name = 'ProfileError';\n this.code = code;\n }\n}\n\nexport interface ProfileSnapshot {\n readonly entries: readonly string[];\n readonly chars: number;\n}\n\nconst COMMENT = /<!--[\\s\\S]*?-->/g;\n\nexport function stripProfileComments(text: string): string {\n return text.replace(COMMENT, '');\n}\n\nexport function parseProfileEntries(text: string): string[] {\n const entries: string[] = [];\n let current: string[] = [];\n const flush = (): void => {\n const value = current.join('\\n').trim();\n if (value !== '') entries.push(value);\n current = [];\n };\n for (const line of stripProfileComments(text).split(/\\r?\\n/)) {\n if (line.trim() === PROFILE_SEPARATOR) {\n flush();\n continue;\n }\n current.push(line);\n }\n flush();\n return entries;\n}\n\nexport function renderProfileEntries(entries: readonly string[]): string {\n return `${entries.map((entry) => entry.trim()).join(`\\n\\n${PROFILE_SEPARATOR}\\n\\n`)}\\n`;\n}\n\nfunction profileChars(entries: readonly string[]): number {\n return [...renderProfileEntries(entries)].length;\n}\n\nexport function validateProfileEntries(entries: readonly string[]): string[] {\n const problems: string[] = [];\n entries.forEach((entry, index) => {\n const text = entry.trim();\n if (text === '') problems.push(`entry ${index + 1} is empty`);\n if (text.split(/\\r?\\n/).some((line) => line.trim() === PROFILE_SEPARATOR)) {\n problems.push(`entry ${index + 1} contains a separator line; use a new entry instead`);\n }\n });\n if (profileChars(entries) > PROFILE_MAX_CHARS) {\n problems.push(`USER.md would be ${profileChars(entries)} chars, over the ${PROFILE_MAX_CHARS}-char limit`);\n }\n return problems;\n}\n\nexport function loadProfile(home: string): ProfileSnapshot {\n const file = memoryPaths(home).userFile;\n const text = existsSync(file) ? readFileSync(file, 'utf8') : '';\n const entries = parseProfileEntries(text);\n return { entries, chars: profileChars(entries) };\n}\n\nexport function saveProfile(home: string, entries: readonly string[]): ProfileSnapshot {\n const problems = validateProfileEntries(entries);\n if (problems.length > 0) throw new ProfileError('INVALID', problems.join('; '));\n writeFileAtomic(memoryPaths(home).userFile, renderProfileEntries(entries));\n return { entries: entries.map((entry) => entry.trim()), chars: profileChars(entries) };\n}\n\n/** Literal query over entries: substring match, case-insensitive for ASCII. */\nexport function queryProfile(entries: readonly string[], query: string): string[] {\n const needle = query.trim().toLowerCase();\n if (needle === '') return [...entries];\n return entries.filter((entry) => entry.toLowerCase().includes(needle));\n}\n\n/** Find one entry by complete text or a unique literal substring. */\nexport function findProfileEntry(entries: readonly string[], oldText: string): number {\n const needle = oldText.trim();\n if (needle === '') throw new ProfileError('INVALID', 'old_text is required');\n const exact = entries.findIndex((entry) => entry === needle);\n if (exact !== -1) return exact;\n const matches = entries\n .map((entry, index) => ({ entry, index }))\n .filter((item) => item.entry.includes(needle));\n if (matches.length === 0) throw new ProfileError('NOT_FOUND', 'old_text does not match any USER entry');\n if (matches.length > 1) {\n throw new ProfileError('CONFLICT', `old_text matches ${matches.length} entries; give the complete entry`);\n }\n return (matches[0] as { index: number }).index;\n}\n", "import { existsSync } from 'node:fs';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { memoryPaths } from '../paths.ts';\nimport { sealPolicy } from '../policy/policy.ts';\n\n/**\n * Personalization scaffold (architecture v2, P0). Creates the three human-owned\n * files with comment-only templates, then seals SOUL/RULES (USER stays unsealed\n * by default so the agent may propose edits through a confirmation card).\n *\n * Existing files are never overwritten; templates are comments so an untouched\n * file injects nothing (assemble strips HTML comments from these files).\n */\n\nexport const SOUL_TEMPLATE = `<!--\n\u4EBA\u683C\u6458\u8981\uFF1A\u6CE8\u5165\u65F6\u53EA\u53D6\u524D 200 \u5B57\u3002\u7528\u6563\u6587\u5199\u300C\u4F60\u662F\u8C01\u3001\u600E\u4E48\u8BF4\u8BDD\u3001\u8FB9\u754C\u5728\u54EA\u300D\uFF0C\u4E0D\u8981\u5199\u4E8B\u5B9E\u6761\u76EE\u3002\n\u793A\u4F8B\uFF1A\u4F60\u7684\u89D2\u8272\u662F\u2026\u2026\uFF0C\u4EE5\u2026\u2026\u7684\u8EAB\u4EFD\u4E0E\u7528\u6237\u4EA4\u6D41\uFF1B\u8BED\u6C14\u2026\u2026\uFF1B\u4E0D\u786E\u5B9A\u65F6\u5148\u95EE\uFF0C\u4E0D\u66FF\u7528\u6237\u505A\u51B3\u5B9A\u3002\n-->\n`;\n\nexport const USER_TEMPLATE = `<!--\n\u7528\u6237\u504F\u597D\uFF1A\u4E00\u6761\u4E00\u6BB5\uFF0C\u7528\u5355\u72EC\u4E00\u884C \u00A7 \u5206\u9694\uFF1B\u5355\u6761\u5FC5\u987B\u975E\u7A7A\u4E14\u5B8C\u6574\uFF0C\u5355\u6587\u4EF6\u4E0A\u9650 10000 \u5B57\u3002\n\u53EA\u5199\u7528\u6237\u660E\u786E\u8BF4\u8FC7\u7684\u957F\u671F\u80CC\u666F\u3001\u504F\u597D\u4E0E\u534F\u4F5C\u9884\u671F\uFF1B\u4E0D\u5199\u4E34\u65F6\u8981\u6C42\uFF0C\u4E0D\u5199\u4E16\u754C\u4E8B\u5B9E\uFF08\u4E8B\u5B9E\u8FDB\u8BB0\u5FC6\u5E93\uFF09\u3002\n\u793A\u4F8B\uFF1A\n\u7528\u6237\u5E0C\u671B\u88AB\u79F0\u4E3A\u300C\u2026\u2026\u300D\u3002\n\u00A7\n\u7528\u6237\u662F\u2026\u2026\uFF0C\u4E60\u60EF\u2026\u2026\u3002\n-->\n`;\n\nexport const RULES_TEMPLATE = `<!--\n\u89C4\u5219\uFF1A\u4E00\u6761\u4E00\u4E2A\u7F16\u53F7\uFF1B[\u786C] \u89C4\u5219\u5FC5\u987B\u80FD\u88AB\u4EE3\u7801\u6216\u6D4B\u8BD5\u68C0\u67E5\uFF0C[\u8F6F] \u89C4\u5219\u53EA\u5199\u5EFA\u8BAE\u3002\n\u793A\u4F8B\uFF1A\nR1 [\u786C] \u8BB0\u5FC6\u5199\u5165\u5FC5\u987B\u8D70 memory \u5DE5\u5177\uFF0C\u7981\u6B62\u76F4\u63A5\u6539 MEMORY.md\uFF1Bcheck: <\u7B26\u53F7>\uFF1Btest: <\u6D4B\u8BD5\u6587\u4EF6>\nR2 [\u8F6F] \u56DE\u7B54\u524D\u5148\u786E\u8BA4\u5173\u952E\u4E8B\u5B9E\u3002\n-->\n`;\n\nexport interface ScaffoldResult {\n readonly created: readonly string[];\n readonly kept: readonly string[];\n readonly sealSha256: string;\n readonly sealedFiles: { readonly soul: string; readonly user: string; readonly rules: string };\n}\n\nexport function scaffoldPersonalization(options: { home: string; now?: Date }): ScaffoldResult {\n const paths = memoryPaths(options.home);\n const targets: ReadonlyArray<readonly [string, string]> = [\n [paths.soulFile, SOUL_TEMPLATE],\n [paths.userFile, USER_TEMPLATE],\n [paths.rulesFile, RULES_TEMPLATE],\n ];\n const created: string[] = [];\n const kept: string[] = [];\n for (const [file, template] of targets) {\n if (existsSync(file)) {\n kept.push(file);\n continue;\n }\n writeFileAtomic(file, template);\n created.push(file);\n }\n // Human-invoked command: sealing here is intentional and scoped to SOUL/RULES.\n const seal = sealPolicy({\n home: options.home,\n accept: true,\n ...(options.now === undefined ? {} : { now: options.now }),\n });\n return { created, kept, sealSha256: seal.sha256, sealedFiles: seal.sealedFiles };\n}\n", "import type { Config } from '../config/config.ts';\nimport { isMemoryId } from '../model/ids.ts';\nimport { loadProfile, queryProfile } from '../profile/profile.ts';\nimport { scaffoldPersonalization } from '../personalization/scaffold.ts';\nimport { loadRules } from '../rules/rules.ts';\nimport { exportStore, inspectStore } from '../ops/ops.ts';\nimport { sealPolicy } from '../policy/policy.ts';\nimport { decideProposal, listProposals, ProposalError } from '../proposals/proposals.ts';\nimport type { MemoryStore } from '../store/store.ts';\nimport type { Kind, MemoryId } from '../model/types.ts';\n\n/**\n * Human command plane (S8): the same operations the `mem` CLI exposes, but\n * callable from a host UI command (`/mem \u2026`) so a human never has to leave the\n * chat box to review, approve, or fix memories.\n *\n * Hard rule this module preserves: nothing here is reachable from a model tool.\n * `decide` stays a human-only verb; the DSH adapter registers `/mem` through\n * the commands service, which runs outside model history (ADR-0011).\n */\n\nexport interface HumanCommandDeps {\n readonly store: MemoryStore;\n readonly config: Config;\n readonly home: string;\n}\n\nexport interface HumanCommandResult {\n readonly ok: boolean;\n readonly text: string;\n}\n\nexport const HUMAN_COMMAND_HINT =\n 'proposals | decide <id> accept|reject | decide --batch accept|reject | add --kind K --abstract \"\u2026\" --body \"\u2026\" | read <id> | recall <query> | profile [\u5173\u952E\u8BCD] | inspect | scaffold | adopt <id> | delete <id> --reason \"\u2026\" | purge <id> --reason \"\u2026\" --accept | rebuild | export <dir> | seal --accept [--seal-user]';\n\nexport const HUMAN_COMMANDS = [\n 'proposals',\n 'decide',\n 'add',\n 'read',\n 'recall',\n 'profile',\n 'inspect',\n 'scaffold',\n 'adopt',\n 'delete',\n 'purge',\n 'rebuild',\n 'export',\n 'seal',\n 'help',\n] as const;\n\nconst KINDS: readonly Kind[] = ['fact', 'pitfall', 'exp'];\nconst EVIDENCE_LEVELS = ['user_explicit', 'user_confirmed', 'observed'] as const;\n/** Flags that never take a value; everything else consumes the next token. */\nconst BOOLEAN_FLAGS = new Set(['accept', 'batch', 'seal-user']);\n\ninterface Parsed {\n readonly verb: string;\n readonly positionals: readonly string[];\n readonly flags: ReadonlyMap<string, string | true>;\n}\n\n/** A small CLI-shaped tokenizer: quotes group words, `--flag=value` works. */\nfunction tokenize(line: string): string[] {\n const tokens: string[] = [];\n let current = '';\n let started = false;\n let quote: '\"' | \"'\" | undefined;\n for (let index = 0; index < line.length; index += 1) {\n const char = line[index] as string;\n if (quote !== undefined) {\n if (char === '\\\\' && index + 1 < line.length) {\n const next = line[index + 1];\n if (next === quote || next === '\\\\') {\n index += 1;\n current += next as string;\n continue;\n }\n }\n if (char === quote) {\n quote = undefined;\n continue;\n }\n current += char;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n started = true;\n continue;\n }\n if (char === ' ' || char === '\\t' || char === '\\n' || char === '\\r') {\n if (started) {\n tokens.push(current);\n current = '';\n started = false;\n }\n continue;\n }\n current += char;\n started = true;\n }\n if (quote !== undefined) throw new Error('unterminated quote in command input');\n if (started) tokens.push(current);\n return tokens;\n}\n\nfunction parseLine(line: string): Parsed {\n const tokens = tokenize(line);\n const verb = tokens[0] ?? 'help';\n const positionals: string[] = [];\n const flags = new Map<string, string | true>();\n for (let index = 1; index < tokens.length; index += 1) {\n const token = tokens[index] as string;\n if (token.startsWith('--') && token.length > 2) {\n const body = token.slice(2);\n const equals = body.indexOf('=');\n const key = equals === -1 ? body : body.slice(0, equals);\n const value = equals === -1 ? true : body.slice(equals + 1);\n flags.set(key, value);\n if (value === true && !BOOLEAN_FLAGS.has(key)) {\n const next = tokens[index + 1];\n if (next !== undefined && !next.startsWith('--')) {\n flags.set(key, next);\n index += 1;\n }\n }\n continue;\n }\n positionals.push(token);\n }\n return { verb, positionals, flags };\n}\n\nfunction textFlag(parsed: Parsed, name: string): string | undefined {\n const value = parsed.flags.get(name);\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction hasFlag(parsed: Parsed, name: string): boolean {\n return parsed.flags.has(name);\n}\n\nfunction fail(text: string): HumanCommandResult {\n return { ok: false, text };\n}\n\nfunction ok(text: string): HumanCommandResult {\n return { ok: true, text };\n}\n\nfunction usage(): string {\n return [\n '\u7528\u6CD5\uFF1A/mem ' + HUMAN_COMMAND_HINT,\n '\u672C\u8F6E\u56DE\u987E\uFF08\u751F\u6210\u5F85\u5BA1\u63D0\u6848\uFF09\uFF1A/mem-fact \u4E8B\u5B9E\u3001/mem-pitfall \u5751\u3001/mem-exp \u7ECF\u9A8C\u3002',\n '\u6240\u6709\u52A8\u4F5C\u90FD\u7531\u4F60\uFF08\u4EBA\uFF09\u53D1\u8D77\uFF0C\u4E0D\u8FDB\u6A21\u578B\u4E0A\u4E0B\u6587\uFF1B`decide` \u4E0D\u4F1A\u4EE5\u5DE5\u5177\u5F62\u5F0F\u66B4\u9732\u7ED9\u6A21\u578B\u3002',\n ].join('\\n');\n}\n\nfunction formatProposals(deps: HumanCommandDeps): HumanCommandResult {\n const proposals = listProposals(deps.store);\n if (proposals.length === 0) return ok('\u6CA1\u6709\u5F85\u5BA1\u63D0\u6848\u3002');\n const lines: string[] = [];\n for (const proposal of proposals) {\n lines.push(`${proposal.id} ${proposal.op} ${proposal.targets.join(',')} ${proposal.reason}`);\n for (const replacement of proposal.replacements) {\n lines.push(` \u2192 [${replacement.kind}] ${replacement.abstract}`);\n }\n lines.push(` \u51B3\u5B9A\uFF1A/mem decide ${proposal.id} accept | reject`);\n }\n return ok(lines.join('\\n'));\n}\n\nfunction formatRead(id: string, deps: HumanCommandDeps): HumanCommandResult {\n const doc = deps.store.read(id as MemoryId);\n const lines = [\n `${doc.kind} ${doc.id} [${doc.valid_from} .. ${doc.valid_until ?? 'open'}] author=${doc.author}`,\n `abstract: ${doc.abstract}`,\n ];\n if (doc.error_signatures.length > 0) lines.push(`signatures: ${doc.error_signatures.join(' | ')}`);\n lines.push('', doc.body.trimEnd());\n if (doc.provenance.length > 0) {\n lines.push('', 'provenance:');\n for (const entry of doc.provenance) {\n lines.push(` - ${entry.speaker} #${entry.event_seq}: ${entry.quote}`);\n }\n }\n return ok(lines.join('\\n'));\n}\n\nfunction decideOne(proposalId: string, decision: 'accept' | 'reject', deps: HumanCommandDeps): string {\n const proposal = listProposals(deps.store).find((entry) => entry.id === proposalId);\n if (proposal === undefined) throw new ProposalError('NOT_FOUND', `no pending proposal ${proposalId}`);\n decideProposal({ store: deps.store, config: deps.config }, { id: proposalId, decision });\n if (decision === 'reject') return `\u5DF2\u5426\u51B3 ${proposalId}`;\n if (proposal.op === 'delete') {\n return `\u5DF2\u91C7\u7EB3 ${proposalId}\uFF1A${proposal.targets[0] ?? ''} \u5DF2\u5931\u6548\uFF08\u6587\u4EF6\u4ECD\u53EF\u8BFB\uFF09`;\n }\n const created = deps.store\n .active()\n .find((doc) => doc.supersedes.includes(proposal.targets[0] as MemoryId));\n return `\u5DF2\u91C7\u7EB3 ${proposalId}${created === undefined ? '' : ` \u2192 \u65B0\u8BB0\u5F55 ${created.id}`}`;\n}\n\nfunction decide(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n if (hasFlag(parsed, 'batch')) {\n const decision = parsed.positionals[0];\n if (decision !== 'accept' && decision !== 'reject') {\n return fail('\u7528\u6CD5\uFF1A/mem decide --batch accept|reject');\n }\n const pending = listProposals(deps.store);\n if (pending.length === 0) return ok('\u6CA1\u6709\u5F85\u5BA1\u63D0\u6848\u3002');\n const lines: string[] = [];\n let applied = 0;\n for (const proposal of pending) {\n try {\n lines.push(decideOne(proposal.id, decision, deps));\n applied += 1;\n } catch (error) {\n lines.push(`\u5931\u8D25 ${proposal.id}\uFF1A${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return {\n ok: applied === pending.length,\n text: `${decision === 'accept' ? 'accepted' : 'rejected'} ${applied}/${pending.length}\\n${lines.join('\\n')}`,\n };\n }\n const proposalId = parsed.positionals[0];\n const decision = parsed.positionals[1];\n if (proposalId === undefined || (decision !== 'accept' && decision !== 'reject')) {\n return fail('\u7528\u6CD5\uFF1A/mem decide <id> accept|reject');\n }\n return ok(decideOne(proposalId, decision, deps));\n}\n\nfunction add(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const abstract = textFlag(parsed, 'abstract');\n if (abstract === undefined || abstract.trim() === '') {\n return fail('\u7528\u6CD5\uFF1A/mem add --abstract \"\u2026\" [--kind fact|pitfall|exp] [--body \"\u2026\"]');\n }\n const kind = (textFlag(parsed, 'kind') ?? 'fact') as Kind;\n if (!KINDS.includes(kind)) return fail(`--kind \u5FC5\u987B\u662F ${KINDS.join(', ')} \u4E4B\u4E00`);\n const evidenceLevel = (textFlag(parsed, 'evidence-level') ?? 'user_explicit') as string;\n if (!EVIDENCE_LEVELS.includes(evidenceLevel as (typeof EVIDENCE_LEVELS)[number])) {\n return fail(`--evidence-level \u5FC5\u987B\u662F ${EVIDENCE_LEVELS.join(', ')} \u4E4B\u4E00`);\n }\n const signatureText = textFlag(parsed, 'signature') ?? textFlag(parsed, 'error-signature');\n const errorSignatures =\n signatureText === undefined ? [] : signatureText.split(',').map((part) => part.trim()).filter((part) => part !== '');\n const validFrom = textFlag(parsed, 'valid-from');\n const result = deps.store.add(\n {\n kind,\n abstract,\n body: textFlag(parsed, 'body') ?? '',\n evidence_level: evidenceLevel as 'user_explicit' | 'user_confirmed' | 'observed',\n error_signatures: errorSignatures,\n ...(validFrom === undefined ? {} : { valid_from: validFrom }),\n },\n { author: 'human' },\n );\n return ok(`${result.deduplicated ? '\u5DF2\u6709\u540C\u5185\u5BB9\u8BB0\u5F55' : '\u5DF2\u5199\u5165'} ${result.id}`);\n}\n\nfunction recall(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const query = parsed.positionals.slice(0).join(' ');\n if (query.trim() === '') return fail('\u7528\u6CD5\uFF1A/mem recall <query> [--kind fact|pitfall|exp] [--limit N]');\n const kind = textFlag(parsed, 'kind');\n if (kind !== undefined && !KINDS.includes(kind as Kind)) return fail(`--kind \u5FC5\u987B\u662F ${KINDS.join(', ')} \u4E4B\u4E00`);\n const limitText = textFlag(parsed, 'limit');\n const limit = limitText === undefined ? undefined : Number(limitText);\n if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) return fail('--limit \u5FC5\u987B\u662F\u6B63\u6574\u6570');\n const result = deps.store.recall(query, {\n ...(limit === undefined ? {} : { limit }),\n ...(kind === undefined ? {} : { kinds: [kind as Kind] }),\n });\n if (result.hits.length === 0) return ok('\u6CA1\u6709\u5339\u914D\u3002');\n return ok(result.hits.map((hit) => `- [${hit.kind}] ${hit.abstract} \u2014 ${hit.id}`).join('\\n'));\n}\n\nfunction inspect(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const limitText = textFlag(parsed, 'limit');\n const limit = limitText === undefined ? 10 : Number(limitText);\n if (!Number.isSafeInteger(limit) || limit < 1) return fail('--limit \u5FC5\u987B\u662F\u6B63\u6574\u6570');\n const report = inspectStore({ home: deps.home, config: deps.config, store: deps.store, limit });\n const lines = [\n `active ${report.active} (${Object.entries(report.byKind).map(([kind, count]) => `${kind} ${count}`).join(', ')})`,\n `pending proposals ${report.pendingProposals} \u00B7 quarantined ${report.quarantined.length}`,\n `journal head ${report.journalHead === null ? '(none)' : `#${report.journalHead.seq} ${report.journalHead.hash.slice(0, 12)}`}`,\n `rules ${loadRules(deps.home).length}`,\n `budget index ${report.budget.indexChars} \u00B7 total ${report.budget.totalChars}`,\n `personalization SOUL ${report.personalization.soul || '0'} \u00B7 USER ${report.personalization.user || '0'} \u00B7 RULES ${report.personalization.rules || '0'} chars`,\n ];\n if (report.personalization.soul > report.inject.persona_max_chars) {\n lines.push(`\u26A0 SOUL.md ${report.personalization.soul} \u5B57\uFF0C\u8D85\u8FC7\u6CE8\u5165\u4E0A\u9650 ${report.inject.persona_max_chars}\uFF0C\u6CE8\u5165\u65F6\u4F1A\u88AB\u622A\u65AD`);\n }\n if (report.personalization.user > report.inject.user_max_chars) {\n lines.push(`\u26A0 USER.md ${report.personalization.user} \u5B57\uFF0C\u8D85\u8FC7\u6CE8\u5165\u4E0A\u9650 ${report.inject.user_max_chars}\uFF0C\u6CE8\u5165\u65F6\u4F1A\u88AB\u622A\u65AD`);\n }\n if (report.personalization.rules > report.inject.rules_max_chars) {\n lines.push(`\u26A0 RULES.md ${report.personalization.rules} \u5B57\uFF0C\u8D85\u8FC7\u6CE8\u5165\u4E0A\u9650 ${report.inject.rules_max_chars}\uFF0C\u6CE8\u5165\u4F1A\u76F4\u63A5\u62A5\u9519`);\n }\n return ok(lines.join('\\n'));\n}\n\nfunction adopt(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const id = parsed.positionals[0];\n if (id === undefined || !isMemoryId(id)) return fail('\u7528\u6CD5\uFF1A/mem adopt <mem-YYYYMMDD-xxxxxxxx>');\n const result = deps.store.adopt(id);\n return ok(`\u5DF2\u627F\u8BA4 ${result.id}\uFF08\u54C8\u5E0C\u5DF2\u8BB0\u8D26\uFF09`);\n}\n\nfunction remove(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const id = parsed.positionals[0];\n const reason = textFlag(parsed, 'reason');\n if (id === undefined || reason === undefined || reason.trim() === '') {\n return fail('\u7528\u6CD5\uFF1A/mem delete <id> --reason \"\u2026\"');\n }\n const result = deps.store.remove(id as MemoryId, { reason });\n return ok(`\u5DF2\u5220\u9664 ${result.id}\uFF08\u6587\u4EF6\u4FDD\u7559\uFF0C\u53EF read \u8FFD\u6EAF\uFF09`);\n}\n\nfunction purge(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const id = parsed.positionals[0];\n const reason = textFlag(parsed, 'reason') ?? 'purge';\n if (id === undefined) return fail('\u7528\u6CD5\uFF1A/mem purge <id> --reason \"\u2026\" --accept');\n if (!hasFlag(parsed, 'accept')) return fail('purge \u9700\u8981 --accept \u786E\u8BA4\uFF08\u4F1A\u5220\u9664\u6587\u4EF6\uFF09');\n if (!isMemoryId(id)) return fail(`\"${id}\" \u4E0D\u662F\u8BB0\u5FC6 id`);\n const result = deps.store.purge(id as MemoryId, { reason });\n return ok(`\u5DF2\u6E05\u9664 ${id}\uFF08\u5893\u7891\u5DF2\u5199\u5165 journal\uFF0C\u4F5C\u5E9F ${result.proposals} \u4E2A\u5F85\u5BA1\u63D0\u6848\uFF09`);\n}\n\nfunction rebuild(deps: HumanCommandDeps): HumanCommandResult {\n const report = deps.store.rebuild();\n return ok(`\u5DF2\u91CD\u5EFA\u7D22\u5F15\uFF1A${report.files} \u4E2A\u6587\u4EF6\uFF0Cjournal head ${report.journal_head === null ? '(none)' : `#${report.journal_head.seq}`}`);\n}\n\nfunction exportStoreCommand(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const out = parsed.positionals[0];\n if (out === undefined) return fail('\u7528\u6CD5\uFF1A/mem export <dir>');\n const result = exportStore({ home: deps.home, out });\n return ok(`\u5DF2\u5BFC\u51FA ${result.files} \u4E2A\u6587\u4EF6\uFF08${result.bytes} bytes\uFF09\u5230 ${result.out}\\n\u6821\u9A8C\u6E05\u5355\uFF1A${result.sums}`);\n}\n\nfunction seal(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n if (!hasFlag(parsed, 'accept')) return fail('seal \u9700\u8981 --accept \u786E\u8BA4\uFF08\u4F1A\u91CD\u5199\u5C01\u5B58\u54C8\u5E0C\uFF09');\n const result = sealPolicy({\n home: deps.home,\n accept: true,\n sealUser: hasFlag(parsed, 'seal-user'),\n });\n const sealed = [result.sealedFiles.soul, result.sealedFiles.user, result.sealedFiles.rules].filter(\n (value) => value !== '',\n ).length;\n return ok(\n `\u5DF2\u91CD\u65B0\u5C01\u5B58\uFF1A${result.sealPath}\\nsha256: ${result.sha256}\\n\u4EBA\u5DE5\u6587\u4EF6\uFF1A${sealed}` +\n (result.sealedFiles.user === '' ? '\uFF08USER.md \u672A\u5C01\u5B58\uFF0C\u5141\u8BB8 agent \u63D0\u8BAE\u4FEE\u6539\uFF09' : ''),\n );\n}\n\nfunction profile(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const snapshot = loadProfile(deps.home);\n const query = parsed.positionals.join(' ');\n const entries = query.trim() === '' ? [...snapshot.entries] : queryProfile(snapshot.entries, query);\n const warning =\n snapshot.chars > deps.config.inject.user_max_chars\n ? `\\n\u26A0 USER.md ${snapshot.chars} \u5B57\uFF0C\u8D85\u8FC7\u6CE8\u5165\u4E0A\u9650 ${deps.config.inject.user_max_chars}\uFF0C\u6CE8\u5165\u65F6\u4F1A\u88AB\u622A\u65AD`\n : '';\n if (entries.length === 0) return ok(`USER.md \u6CA1\u6709\u5339\u914D\u7684\u6761\u76EE\u3002${warning}`);\n return ok(\n `USER.md\uFF1A${snapshot.entries.length} \u6761 / ${snapshot.chars} \u5B57${warning}\\n` +\n entries.map((entry, index) => `${index + 1}. ${entry}`).join('\\n\\n'),\n );\n}\n\nfunction scaffold(_parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const result = scaffoldPersonalization({ home: deps.home });\n const lines = [`\u5DF2\u91CD\u65B0\u5C01\u5B58\uFF1A${result.sealSha256}`];\n if (result.created.length > 0) lines.push(`\u65B0\u5EFA\uFF1A${result.created.map((file) => file.split(/[\\\\/]/).pop()).join('\u3001')}`);\n if (result.kept.length > 0) lines.push(`\u4FDD\u7559\uFF1A${result.kept.map((file) => file.split(/[\\\\/]/).pop()).join('\u3001')}`);\n lines.push('\u7F16\u8F91\u540E\u8FD0\u884C /mem seal --accept \u751F\u6548\uFF1BUSER.md \u9ED8\u8BA4\u4E0D\u5C01\u5B58\u3002');\n return ok(lines.join('\\n'));\n}\n\n/** Execute one `/mem \u2026` line. Never throws: every failure comes back as text. */\nexport function runHumanCommand(deps: HumanCommandDeps, line: string): HumanCommandResult {\n try {\n const parsed = parseLine(line.trim());\n switch (parsed.verb) {\n case 'help':\n return ok(usage());\n case 'proposals':\n return formatProposals(deps);\n case 'decide':\n return decide(parsed, deps);\n case 'add':\n return add(parsed, deps);\n case 'read': {\n const id = parsed.positionals[0];\n if (id === undefined) return fail('\u7528\u6CD5\uFF1A/mem read <id>');\n return formatRead(id, deps);\n }\n case 'recall':\n return recall(parsed, deps);\n case 'profile':\n return profile(parsed, deps);\n case 'inspect':\n return inspect(parsed, deps);\n case 'scaffold':\n return scaffold(parsed, deps);\n case 'adopt':\n return adopt(parsed, deps);\n case 'delete':\n return remove(parsed, deps);\n case 'purge':\n return purge(parsed, deps);\n case 'rebuild':\n return rebuild(deps);\n case 'export':\n return exportStoreCommand(parsed, deps);\n case 'seal':\n return seal(parsed, deps);\n default:\n return fail(`\u672A\u77E5\u5B50\u547D\u4EE4 ${parsed.verb}\\n${usage()}`);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`\u5931\u8D25\uFF1A${message}`);\n }\n}\n", "import type { Kind } from '../model/types.ts';\nimport type { MemoryStore } from '../store/store.ts';\n\n/**\n * Import an `agent-memory-export-v1` bundle (the JSON produced by the GUI\n * export button or `mem export`). Memory content is re-added through the store\n * so locks, validation, journaling and dedupe stay in one place.\n *\n * - Duplicate content (same content_hash) is skipped, not duplicated.\n * - Imported records are authored by the human doing the import; provenance is\n * carried as-is (the source sessions may not exist on this machine, so the\n * evidence can show as unverifiable rather than being rewritten).\n * - Pending proposals are not imported: a proposal must target a live record\n * in this store, and silently recreating one would bypass the human queue.\n */\n\nexport interface ImportReport {\n readonly imported: number;\n readonly skipped: number;\n readonly failed: readonly { readonly abstract: string; readonly error: string }[];\n readonly ignored_proposals: number;\n}\n\nexport interface ImportMemory {\n readonly kind: string;\n readonly abstract: string;\n readonly body?: string;\n readonly project?: string | null;\n readonly tags?: readonly string[];\n readonly relations?: readonly unknown[];\n readonly source?: { readonly type?: unknown; readonly id?: unknown } | null;\n readonly valid_from?: string;\n readonly error_signatures?: readonly string[];\n readonly evidence_level?: string;\n readonly provenance?: readonly unknown[];\n}\n\nconst KINDS: readonly Kind[] = ['fact', 'pitfall', 'exp'];\nconst LEVELS = new Set(['user_explicit', 'user_confirmed', 'observed']);\n\nexport function importBundle(store: MemoryStore, bundle: unknown): ImportReport {\n if (typeof bundle !== 'object' || bundle === null) throw new Error('bundle must be an object');\n const record = bundle as { format?: unknown; memories?: unknown; proposals?: unknown };\n if (record.format !== 'agent-memory-export-v1' && record.format !== 'agent-memory-export-v2') {\n throw new Error('unsupported bundle format (expected agent-memory-export-v1 or v2)');\n }\n if (!Array.isArray(record.memories)) throw new Error('bundle.memories must be an array');\n\n let imported = 0;\n let skipped = 0;\n const failed: { abstract: string; error: string }[] = [];\n\n for (const raw of record.memories as ImportMemory[]) {\n const abstract = typeof raw?.abstract === 'string' ? raw.abstract : '';\n try {\n if (typeof raw !== 'object' || raw === null) throw new Error('entry must be an object');\n if (typeof raw.kind !== 'string' || !KINDS.includes(raw.kind as Kind)) {\n throw new Error(`kind must be one of ${KINDS.join(', ')}`);\n }\n if (abstract.trim() === '') throw new Error('abstract is required');\n const body = typeof raw.body === 'string' ? raw.body : '';\n const evidenceLevel = typeof raw.evidence_level === 'string' && LEVELS.has(raw.evidence_level)\n ? (raw.evidence_level as 'user_explicit' | 'user_confirmed' | 'observed')\n : 'observed';\n const provenance = Array.isArray(raw.provenance) ? raw.provenance : [];\n const result = store.add(\n {\n kind: raw.kind as Kind,\n abstract,\n body,\n ...(typeof raw.project === 'string' || raw.project === null ? { project: raw.project } : {}),\n ...(Array.isArray(raw.tags)\n ? { tags: raw.tags.filter((entry): entry is string => typeof entry === 'string') }\n : {}),\n ...(Array.isArray(raw.relations)\n ? {\n relations: raw.relations.filter(\n (entry): entry is { type: 'relates_to' | 'derived_from'; target: string } =>\n typeof entry === 'object' &&\n entry !== null &&\n typeof (entry as { type?: unknown }).type === 'string' &&\n typeof (entry as { target?: unknown }).target === 'string',\n ),\n }\n : {}),\n ...(typeof raw.source === 'object' &&\n raw.source !== null &&\n typeof raw.source.type === 'string' &&\n typeof raw.source.id === 'string'\n ? { source: { type: raw.source.type, id: raw.source.id } }\n : {}),\n evidence_level: evidenceLevel,\n ...(typeof raw.valid_from === 'string' ? { valid_from: raw.valid_from } : {}),\n ...(Array.isArray(raw.error_signatures)\n ? { error_signatures: raw.error_signatures.filter((entry): entry is string => typeof entry === 'string') }\n : {}),\n },\n { author: 'human', provenance: provenance as never },\n );\n if (result.deduplicated) skipped += 1;\n else imported += 1;\n } catch (error) {\n failed.push({ abstract: abstract || '(no abstract)', error: error instanceof Error ? error.message : String(error) });\n }\n }\n\n return {\n imported,\n skipped,\n failed,\n ignored_proposals: Array.isArray(record.proposals) ? record.proposals.length : 0,\n };\n}\n", "import { SessionQuota } from '../../core/src/service/quota.ts';\n\n/**\n * Tool surface (plan v1.3 \u00A75.2, \u00A75.4; ADR-0012). Strict schemas, no field names\n * that could smuggle a path or a session; `decide` is never a tool.\n *\n * `memory_review` shows a human button card and then runs the `/mem decide \u2026`\n * command; the verdict comes from the card, never from the model.\n *\n * `registerTools` takes a service object so the adapter stays free of file I/O;\n * the real DSH wiring passes the core-backed service in.\n */\n\nexport const TOOL_NAMES = [\n 'memory_recall',\n 'memory_read',\n 'memory_record',\n 'memory_propose',\n 'memory_review',\n 'memory_context',\n 'rules_list',\n] as const;\nexport type ToolName = (typeof TOOL_NAMES)[number];\n\nconst FORBIDDEN_FIELDS = new Set(['path', 'target', 'session', 'session_id', 'approve']);\n\nfunction objectSchema(properties: Record<string, unknown>, required: string[] = []) {\n return { type: 'object', properties, required, additionalProperties: false };\n}\n\nexport const TOOL_SCHEMAS: Readonly<Record<ToolName, unknown>> = {\n memory_recall: objectSchema(\n {\n query: { type: 'string', minLength: 1 },\n limit: { type: 'integer', minimum: 1 },\n kind: { type: 'string', enum: ['fact', 'pitfall', 'exp'] },\n },\n ['query'],\n ),\n memory_read: objectSchema({ id: { type: 'string' } }, ['id']),\n memory_record: objectSchema(\n {\n kind: { type: 'string', enum: ['fact', 'pitfall', 'exp'] },\n abstract: { type: 'string' },\n body: { type: 'string' },\n evidence: {\n type: 'array',\n minItems: 1,\n items: objectSchema(\n { event_seq: { type: 'integer', minimum: 0 }, quote: { type: 'string' } },\n ['event_seq', 'quote'],\n ),\n },\n valid_from: { type: 'string' },\n project: { type: 'string' },\n tags: { type: 'array', items: { type: 'string' }, maxItems: 8 },\n error_signatures: { type: 'array', items: { type: 'string' }, maxItems: 3 },\n },\n ['kind', 'abstract', 'body', 'evidence'],\n ),\n memory_propose: objectSchema(\n {\n op: { type: 'string', enum: ['create', 'supersede', 'delete'] },\n ids: { type: 'array', items: { type: 'string' }, minItems: 1 },\n base_hashes: { type: 'array', items: { type: 'string' } },\n replacements: {\n type: 'array',\n minItems: 1,\n items: objectSchema(\n {\n kind: { type: 'string', enum: ['fact', 'pitfall', 'exp'] },\n abstract: { type: 'string', minLength: 1 },\n body: { type: 'string' },\n evidence: {\n type: 'array',\n minItems: 1,\n items: objectSchema(\n { event_seq: { type: 'integer', minimum: 0 }, quote: { type: 'string' } },\n ['event_seq', 'quote'],\n ),\n },\n valid_from: { type: 'string' },\n project: { type: 'string' },\n tags: { type: 'array', items: { type: 'string' }, maxItems: 8 },\n error_signatures: { type: 'array', items: { type: 'string' }, maxItems: 3 },\n },\n ['kind', 'abstract', 'body', 'evidence'],\n ),\n },\n reason: { type: 'string' },\n },\n ['op'],\n ),\n memory_review: objectSchema({ id: { type: 'string' } }),\n memory_context: objectSchema({ limit: { type: 'integer', minimum: 1, maximum: 50 } }, []),\n rules_list: objectSchema({}, []),\n};\n\nexport class ToolInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ToolInputError';\n }\n}\n\nfunction forbiddenKeys(value: unknown, path = ''): string[] {\n if (typeof value !== 'object' || value === null) return [];\n if (Array.isArray(value)) return value.flatMap((entry, index) => forbiddenKeys(entry, `${path}[${index}]`));\n const hits: string[] = [];\n for (const [key, child] of Object.entries(value)) {\n if (FORBIDDEN_FIELDS.has(key)) hits.push(`${path}${key}`.replace(/^\\./, ''));\n hits.push(...forbiddenKeys(child, `${path}${key}.`));\n }\n return hits;\n}\n\n/** Schema check used by tests and execute; returns [] when the args are usable. */\nexport function validateToolArgs(name: ToolName, args: unknown): string[] {\n if (typeof args !== 'object' || args === null || Array.isArray(args)) return ['arguments must be an object'];\n const schema = TOOL_SCHEMAS[name] as { properties: Record<string, unknown>; required: string[] };\n const record = args as Record<string, unknown>;\n const problems: string[] = [];\n const forbidden = forbiddenKeys(record);\n if (forbidden.length > 0) problems.push(`forbidden field: ${forbidden.join(', ')}`);\n for (const key of Object.keys(record)) {\n if (!(key in schema.properties)) problems.push(`unknown field: ${key}`);\n }\n for (const key of schema.required) {\n if (!(key in record)) problems.push(`missing field: ${key}`);\n }\n if (name === 'memory_read') {\n if (typeof record.id !== 'string' || !/^mem-\\d{8}-[0-9a-f]{8}$/.test(record.id)) {\n problems.push('id must be a memory id');\n }\n }\n if (name === 'memory_record') {\n if (record.kind === 'pitfall') {\n const signatures = record.error_signatures;\n if (!Array.isArray(signatures) || signatures.length === 0) {\n problems.push('a pitfall needs error_signatures');\n }\n }\n const evidence = record.evidence;\n if (!Array.isArray(evidence) || evidence.length === 0) problems.push('evidence is required');\n }\n if (name === 'memory_review') {\n if (record.id !== undefined && (typeof record.id !== 'string' || !/^prop-mem-\\d{8}-[0-9a-f]{8}$/.test(record.id))) {\n problems.push('id must be a proposal id');\n }\n }\n if (name === 'memory_propose') {\n if (record.op === 'delete' && (typeof record.reason !== 'string' || record.reason.trim() === '')) {\n problems.push('a delete proposal needs reason');\n }\n if (record.op === 'create' || record.op === 'supersede') {\n const replacements = record.replacements;\n if (!Array.isArray(replacements) || replacements.length === 0) {\n problems.push(`a ${record.op} proposal needs replacements`);\n } else {\n replacements.forEach((replacement, index) => {\n problems.push(...replacementProblems(replacement, `replacements[${index}]`));\n });\n }\n }\n if (record.op !== 'create') {\n if (!Array.isArray(record.ids) || record.ids.length === 0) problems.push('ids are required');\n if (!Array.isArray(record.base_hashes) || record.base_hashes.length === 0) {\n problems.push('base_hashes are required');\n }\n }\n if (Array.isArray(record.base_hashes) && Array.isArray(record.ids)) {\n if (record.base_hashes.length !== record.ids.length) problems.push('one base_hash per id is required');\n }\n }\n return problems;\n}\n\nconst KINDS = new Set(['fact', 'pitfall', 'exp']);\n\nfunction replacementProblems(replacement: unknown, path: string): string[] {\n if (typeof replacement !== 'object' || replacement === null || Array.isArray(replacement)) {\n return [`${path} must be an object`];\n }\n const item = replacement as Record<string, unknown>;\n const problems: string[] = [];\n if (typeof item.kind !== 'string' || !KINDS.has(item.kind)) problems.push(`${path}.kind must be fact|pitfall|exp`);\n if (typeof item.abstract !== 'string' || item.abstract.trim() === '') problems.push(`${path}.abstract is required`);\n if (typeof item.body !== 'string') problems.push(`${path}.body is required`);\n if (item.kind === 'pitfall') {\n const signatures = item.error_signatures;\n if (!Array.isArray(signatures) || signatures.length === 0) problems.push(`${path} pitfall needs error_signatures`);\n }\n const evidence = item.evidence;\n if (!Array.isArray(evidence) || evidence.length === 0) {\n problems.push(`${path}.evidence is required`);\n return problems;\n }\n evidence.forEach((entry, index) => {\n if (typeof entry !== 'object' || entry === null) {\n problems.push(`${path}.evidence[${index}] must be an object`);\n return;\n }\n const evidenceItem = entry as Record<string, unknown>;\n if (!Number.isInteger(evidenceItem.event_seq) || (evidenceItem.event_seq as number) < 0) {\n problems.push(`${path}.evidence[${index}].event_seq must be a non-negative integer`);\n }\n if (typeof evidenceItem.quote !== 'string' || evidenceItem.quote === '') {\n problems.push(`${path}.evidence[${index}].quote is required`);\n }\n });\n return problems;\n}\n\nexport interface ToolService {\n readonly config: { readonly quota: { readonly t0_per_session: number } };\n /** Assistant write mode from `personalization.mode`. */\n readonly mode: 'confirm' | 'direct' | 'readonly';\n recall(input: { query: string; limit?: number; kind?: string }): unknown;\n read(id: string): unknown;\n record(input: unknown, actor: TrustedActor, exec?: unknown): unknown;\n propose(input: unknown, actor: TrustedActor, exec?: unknown): unknown;\n context(exec?: unknown, limit?: number): unknown;\n rules(): unknown;\n}\n\n/**\n * Host-side review card hooks (ADR-0012). `memory_propose` opens the card right\n * after a proposal is stored; `memory_review` re-opens it for a deferred one.\n * The hook turns the click into `/mem decide \u2026` and returns the outcome.\n */\nexport interface ToolHooks {\n readonly reviewProposal?: (proposal: unknown, exec?: unknown) => Promise<unknown>;\n readonly reviewPending?: (proposalId: string | undefined, exec?: unknown) => Promise<unknown>;\n}\n\nexport interface TrustedActor {\n readonly sessionId: string;\n readonly delegationDepth: number;\n}\n\n/** Capability groups (architecture v2 P0.5): preset/GUI/MCP compose these. */\nexport type CapabilityGroup = 'facts.read' | 'facts.write' | 'proposals.review' | 'rules.read';\n\nexport function capabilitiesFor(\n mode: 'confirm' | 'direct' | 'readonly',\n delegationDepth: number,\n): readonly CapabilityGroup[] {\n const capabilities: CapabilityGroup[] = ['facts.read', 'rules.read'];\n if (delegationDepth === 0) {\n capabilities.push('proposals.review');\n if (mode !== 'readonly') capabilities.push('facts.write');\n }\n return capabilities;\n}\n\nexport interface ToolRegistry {\n register(definition: unknown): unknown;\n}\n\nexport interface RegisteredTool {\n readonly names: readonly ToolName[];\n}\n\n/**\n * Register read tools always and write tools only for a top-level agent. The\n * quota (if supplied) rejects the (limit+1)-th T0 write in one session.\n */\nexport function registerTools(\n ctx: { readonly tools: ToolRegistry },\n service: ToolService,\n actor: TrustedActor,\n quota: SessionQuota = new SessionQuota(service.config.quota.t0_per_session),\n hooks: ToolHooks = {},\n): RegisteredTool {\n const capabilities = new Set(capabilitiesFor(service.mode, actor.delegationDepth));\n const names: ToolName[] = ['memory_recall', 'memory_read', 'memory_context', 'rules_list'];\n if (capabilities.has('proposals.review')) names.push('memory_review');\n if (capabilities.has('facts.write')) names.push('memory_record', 'memory_propose');\n\n/** Tool copy is human-facing; Chinese is the project's default (user preference). */\nconst TOOL_DESCRIPTIONS: Readonly<Record<ToolName, string>> = {\n memory_recall: '\u68C0\u7D22\u957F\u671F\u8BB0\u5FC6\uFF1A\u6309\u67E5\u8BE2\u8FD4\u56DE\u76F8\u5173\u6458\u8981\u4E0E\u8BB0\u5FC6\u7F16\u53F7',\n memory_read: '\u8BFB\u53D6\u4E00\u6761\u8BB0\u5FC6\u7684\u5168\u6587\u3001\u51FA\u5904\u4E0E\u72B6\u6001',\n memory_record: '\u5199\u5165\u4E00\u6761\u65B0\u8BB0\u5FC6\uFF08\u5FC5\u987B\u7ED9\u51FA\u771F\u5B9E\u4E8B\u4EF6\u51FA\u5904\uFF09',\n memory_propose: '\u63D0\u51FA\u8BB0\u5FC6\u4FEE\u8BA2\u6216\u5220\u9664\u63D0\u6848\uFF0C\u7B49\u5F85\u4EBA\u786E\u8BA4',\n memory_review: '\u4E3A\u5F85\u5BA1\u63D0\u6848\u5F39\u51FA\u4E2D\u6587\u5BA1\u6279\u5361\u7247',\n memory_context: '\u67E5\u770B\u5F53\u524D\u4F1A\u8BDD\u6700\u8FD1\u4E8B\u4EF6\uFF0C\u53D6\u5F97\u53EF\u7528\u4E8E\u51FA\u5904\u7684 event_seq',\n rules_list: '\u5217\u51FA\u5F53\u524D\u751F\u6548\u7684\u89C4\u5219',\n};\n\n const execute = (name: ToolName, handler: (args: Record<string, unknown>, exec?: unknown) => unknown) => ({\n name,\n description: TOOL_DESCRIPTIONS[name],\n parameters: TOOL_SCHEMAS[name],\n output: {\n schema: { type: 'object' },\n render: (_args: unknown, value: unknown) => {\n const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);\n // Point the human at the review paths; `decide` itself stays out of the\n // tool surface (ADR-0011/0012).\n const candidate = typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {};\n const proposal = (candidate.proposal as { id?: unknown } | undefined) ?? candidate;\n const review = candidate.review as { decision?: unknown } | undefined;\n const proposalId = name === 'memory_propose' && review === undefined ? proposal.id : undefined;\n const hint =\n typeof proposalId === 'string'\n ? `\\n\\n\u4EBA\u5728\u804A\u5929\u6846\u51B3\u5B9A\uFF1A/mem decide ${proposalId} accept \u6216 reject\uFF1B\u4E5F\u53EF\u8C03\u7528 memory_review \u91CD\u65B0\u5F39\u51FA\u5361\u7247`\n : '';\n return [{ type: 'text', text: text + hint }];\n },\n },\n execute: async (args: unknown, exec?: unknown) => {\n const problems = validateToolArgs(name, args);\n if (problems.length > 0) throw new ToolInputError(problems.join('; '));\n return handler(args as Record<string, unknown>, exec);\n },\n });\n\n const handlers: Record<string, (args: Record<string, unknown>, exec?: unknown) => unknown> = {\n memory_recall: (args) =>\n service.recall({\n query: String(args.query),\n ...(typeof args.limit === 'number' ? { limit: args.limit } : {}),\n ...(typeof args.kind === 'string' ? { kind: args.kind } : {}),\n }),\n memory_read: (args) => service.read(String(args.id)),\n memory_record: (args, exec) => {\n if (service.mode === 'readonly') {\n throw new ToolInputError('\u5F53\u524D\u4E3A readonly \u6A21\u5F0F\uFF1A\u53EA\u80FD\u8BFB\u53D6\u8BB0\u5FC6\uFF0C\u4E0D\u80FD\u5199\u5165');\n }\n if (!quota.consume(actor.sessionId)) {\n throw new ToolInputError('T0 write quota is exhausted for this session; use memory_propose instead');\n }\n const { evidence, ...rest } = args;\n return service.record({ ...rest, evidence }, actor, exec);\n },\n memory_propose: async (args, exec) => {\n if (service.mode === 'readonly') {\n throw new ToolInputError('\u5F53\u524D\u4E3A readonly \u6A21\u5F0F\uFF1A\u53EA\u80FD\u8BFB\u53D6\u8BB0\u5FC6\uFF0C\u4E0D\u80FD\u63D0\u51FA\u4FEE\u6539');\n }\n const proposal = (await service.propose(args, actor, exec)) as { id?: string };\n if (hooks.reviewProposal === undefined) return proposal;\n const review = await hooks.reviewProposal(proposal, exec);\n return { proposal, review };\n },\n memory_review: async (args, exec) => {\n if (hooks.reviewPending === undefined) {\n throw new ToolInputError('proposal review is unavailable in this host');\n }\n return hooks.reviewPending(typeof args.id === 'string' ? args.id : undefined, exec);\n },\n memory_context: (args, exec) =>\n service.context(exec, typeof args.limit === 'number' ? args.limit : undefined),\n rules_list: () => service.rules(),\n };\n\n for (const name of names) {\n ctx.tools.register(execute(name, handlers[name] as (args: Record<string, unknown>, exec?: unknown) => unknown));\n }\n return { names };\n}\n", "import type { Config } from '../../core/src/config/config.ts';\nimport type { Proposal } from '../../core/src/proposals/proposals.ts';\nimport { runHumanCommand, type HumanCommandResult } from '../../core/src/human/command.ts';\nimport type { MemoryStore } from '../../core/src/store/store.ts';\n\n/**\n * S9 review card: turn a pending memory proposal into a Chinese button card\n * through the host `userQuestions` service, then translate the human's click\n * into the SAME `/mem decide \u2026` command line the chat command plane uses and\n * execute it through the host `commands` service.\n *\n * The model never sees or supplies the verdict: the card's answer comes from a\n * human UI, and `decide` is still not a tool (ADR-0012).\n */\n\nexport const REVIEW_LABELS = {\n accept: '\u91C7\u7EB3',\n reject: '\u9A73\u56DE',\n defer: '\u6682\u4E0D\u5904\u7406',\n} as const;\n\nexport type ReviewDecision = 'accept' | 'reject' | 'defer';\n\nexport interface ReviewQuestionOption {\n readonly label: string;\n readonly description: string;\n}\n\nexport interface ReviewQuestion {\n readonly id: string;\n readonly header: string;\n readonly question: string;\n readonly detail: string;\n readonly options: readonly ReviewQuestionOption[];\n}\n\nexport interface ReviewAnswer {\n readonly answers: readonly {\n readonly id: string;\n readonly selected: readonly string[];\n readonly custom?: string;\n }[];\n}\n\nexport interface UserQuestionsLike {\n ask(request: unknown): Promise<ReviewAnswer>;\n}\n\nexport interface CommandsExecutorLike {\n execute?(\n agent: unknown,\n line: string,\n attachments: readonly unknown[],\n signal: AbortSignal,\n ): Promise<{ readonly result: { readonly kind?: string; readonly text?: string } } | undefined>;\n}\n\nexport interface ReviewExecLike {\n readonly agent?: unknown;\n readonly signal?: AbortSignal;\n readonly callId?: string;\n}\n\nexport interface ReviewDeps {\n readonly store: MemoryStore;\n readonly config: Config;\n readonly home: string;\n readonly userQuestions?: UserQuestionsLike;\n readonly commands?: CommandsExecutorLike;\n}\n\nexport interface ReviewOutcome {\n readonly decision: ReviewDecision;\n readonly command?: string;\n readonly result?: HumanCommandResult;\n readonly message: string;\n}\n\n/** The card copy: proposal content first, then the three choices. */\nexport function buildReviewQuestion(proposal: Proposal): ReviewQuestion {\n const lines: string[] = [];\n const verb = proposal.op === 'supersede' ? '\u66FF\u4EE3' : '\u5220\u9664';\n lines.push(`**\u63D0\u6848**\uFF1A\\`${proposal.id}\\`\uFF08${verb}\uFF09`);\n lines.push(`**\u76EE\u6807**\uFF1A${proposal.targets.join('\u3001')}`);\n if (proposal.reason.trim() !== '') lines.push(`**\u7406\u7531**\uFF1A${formatBody(proposal.reason)}`);\n for (const replacement of proposal.replacements) {\n lines.push('', `### [${replacement.kind}] ${replacement.abstract}`);\n if (replacement.body.trim() !== '') lines.push('', formatBody(replacement.body));\n const provenance = replacement.provenance ?? [];\n if (provenance.length > 0) {\n const first = provenance[0] as { session_id: string; event_seq: number; quote: string };\n lines.push(\n '',\n `**\u51FA\u5904**\uFF1A${provenance.length} \u6761\uFF08${first.session_id} #${first.event_seq}\u300C${first.quote}\u300D\uFF09`,\n );\n }\n }\n lines.push('', '\u91C7\u7EB3\u540E\u5199\u5165 journal \u5E76\u4F7F\u76EE\u6807\u8BB0\u5F55\u5931\u6548\uFF1B\u9A73\u56DE\u4FDD\u7559\u539F\u8BB0\u5F55\uFF1B\u6682\u4E0D\u5904\u7406\u5219\u63D0\u6848\u7EE7\u7EED\u5F85\u5BA1\u3002');\n return {\n id: proposal.id,\n header: '\u8BB0\u5FC6\u63D0\u6848',\n question: `\u662F\u5426\u91C7\u7EB3\u63D0\u6848 ${proposal.id}\uFF1F`,\n detail: lines.join('\\n'),\n options: [\n { label: REVIEW_LABELS.accept, description: '\u5E94\u7528\u66FF\u6362\uFF0C\u5199\u5165 journal\uFF0C\u76EE\u6807\u8BB0\u5F55\u5931\u6548' },\n { label: REVIEW_LABELS.reject, description: '\u4FDD\u7559\u539F\u8BB0\u5F55\uFF0C\u63D0\u6848\u4F5C\u5E9F\u5E76\u8BB0\u5165 journal' },\n { label: REVIEW_LABELS.defer, description: '\u4FDD\u7559\u63D0\u6848\uFF0C\u7A0D\u540E\u518D\u51B3\u5B9A' },\n ],\n };\n}\n\n/**\n * Card typography: put enumerations (`1)` `2\uFF09` `3\u3001`) on their own lines and\n * render them as an ordered list, so a body that was written inline is readable\n * in the card instead of one long paragraph.\n */\nexport function formatBody(text: string): string {\n const source = text.trim();\n if (source === '') return '';\n const broken = source.replace(/(?<![\\p{L}\\p{N}])\\s*(?=\\d{1,2}[)\uFF09]\\s?)/gu, '\\n');\n return broken\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line !== '')\n .map((line) => line.replace(/^(\\d{1,2})[)\uFF09]\\s*/, '$1. '))\n .join('\\n');\n}\n\n/** Map the human's answer to a decision; unknown text defers. */\nexport function decisionFromAnswer(answer: ReviewAnswer): ReviewDecision {\n const item = answer.answers[0];\n if (item === undefined) return 'defer';\n const chosen = item.selected[0] ?? item.custom?.trim() ?? '';\n if (chosen === REVIEW_LABELS.accept) return 'accept';\n if (chosen === REVIEW_LABELS.reject) return 'reject';\n return 'defer';\n}\n\n/** The command line the click becomes; `undefined` when the human deferred. */\nexport function commandForDecision(proposalId: string, decision: ReviewDecision): string | undefined {\n if (decision === 'defer') return undefined;\n return `/mem decide ${proposalId} ${decision}`;\n}\n\nasync function executeCommandLine(\n deps: ReviewDeps,\n agent: unknown,\n line: string,\n signal: AbortSignal | undefined,\n): Promise<HumanCommandResult> {\n if (deps.commands !== undefined && typeof deps.commands.execute === 'function') {\n const execution = await deps.commands.execute(agent, line, [], signal ?? new AbortController().signal);\n if (execution !== undefined) {\n const kind = execution.result.kind === 'success' ? 'success' : 'error';\n return { ok: kind === 'success', text: execution.result.text ?? '' };\n }\n }\n return runHumanCommand({ store: deps.store, config: deps.config, home: deps.home }, line);\n}\n\n/** Show one card, then run the corresponding `/mem` command on the human's click. */\nexport async function reviewProposal(\n deps: ReviewDeps,\n proposal: Proposal,\n exec: ReviewExecLike | undefined,\n): Promise<ReviewOutcome> {\n if (deps.userQuestions === undefined) {\n return { decision: 'defer', message: '\u5F53\u524D\u73AF\u5883\u6CA1\u6709\u4EA4\u4E92\u754C\u9762\uFF0C\u63D0\u6848\u4FDD\u7559\u5F85\u51B3\u5B9A' };\n }\n if (exec?.agent === undefined) {\n return { decision: 'defer', message: '\u9700\u8981\u6D3B\u52A8\u4F1A\u8BDD\u624D\u80FD\u5F39\u51FA\u5BA1\u6279\u5361\u7247\uFF0C\u63D0\u6848\u4FDD\u7559\u5F85\u51B3\u5B9A' };\n }\n const question = buildReviewQuestion(proposal);\n const answer = await deps.userQuestions.ask({\n questions: [question],\n agent: exec.agent,\n ...(exec.signal === undefined ? {} : { signal: exec.signal }),\n ...(exec.callId === undefined ? {} : { wait: { callId: exec.callId } }),\n });\n const decision = decisionFromAnswer(answer);\n const line = commandForDecision(proposal.id, decision);\n if (line === undefined) {\n return { decision, message: '\u5DF2\u6682\u7F13\uFF0C\u63D0\u6848\u7EE7\u7EED\u5F85\u5BA1' };\n }\n const result = await executeCommandLine(deps, exec.agent, line, exec.signal);\n return { decision, command: line, result, message: result.text };\n}\n", "import {\n loadProfile,\n ProfileError,\n queryProfile,\n saveProfile,\n findProfileEntry,\n validateProfileEntries,\n PROFILE_MAX_CHARS,\n} from '../../core/src/index.ts';\nimport type { MemoryStore } from '../../core/src/store/store.ts';\nimport type { UserQuestionsLike } from './review.ts';\n\n/**\n * `user_profile` tool (architecture v2, P1). The agent may read USER.md freely;\n * a write requires (1) a read earlier in the same session and (2) a human\n * confirmation card. The file stays human-editable; SOUL/RULES stay sealed.\n */\n\nexport const USER_PROFILE_TOOL = 'user_profile';\n\nexport const PROFILE_LABELS = { confirm: '\u786E\u8BA4', cancel: '\u53D6\u6D88' } as const;\n\nexport interface ProfileToolDeps {\n readonly home: string;\n readonly store: Pick<MemoryStore, 'appendAudit'>;\n readonly resolveQuestions: () => UserQuestionsLike | undefined;\n /** Assistant write mode from `personalization.mode`. */\n readonly mode: 'confirm' | 'direct' | 'readonly';\n /** Sessions that already read USER.md; writes require an entry here. */\n readonly readSessions: Set<string>;\n}\n\nexport interface ProfileToolInput {\n readonly op: 'read' | 'add' | 'replace' | 'remove';\n readonly query?: string;\n readonly content?: string;\n readonly old_text?: string;\n}\n\ninterface ExecLike {\n readonly agent?: { readonly session?: { readonly id?: string }; followup?: unknown };\n readonly signal?: AbortSignal;\n readonly callId?: string;\n}\n\nexport interface RegisteredProfileTool {\n readonly name: string;\n readonly description: string;\n readonly parameters: unknown;\n readonly output: unknown;\n execute(args: unknown, exec?: unknown): Promise<unknown>;\n}\n\nfunction fail(message: string): never {\n throw new Error(message);\n}\n\nfunction sessionOf(exec: unknown): string {\n const execLike = exec as ExecLike | undefined;\n return execLike?.agent?.session?.id ?? 'unknown-session';\n}\n\nfunction buildQuestion(action: string, current: readonly string[], proposed: readonly string[], content: string) {\n const lines = [\n `**\u52A8\u4F5C**\uFF1A${action}`,\n '',\n '**\u5F53\u524D USER.md**\uFF1A',\n current.length === 0 ? '\uFF08\u7A7A\uFF09' : current.map((entry, index) => `${index + 1}. ${entry}`).join('\\n'),\n '',\n '**\u4FEE\u6539\u540E**\uFF1A',\n proposed.map((entry, index) => `${index + 1}. ${entry}`).join('\\n'),\n '',\n `\uFF08\u5355\u6587\u4EF6\u4E0A\u9650 ${PROFILE_MAX_CHARS} \u5B57\uFF1B\u786E\u8BA4\u540E\u5199\u5165 USER.md\uFF09`,\n ];\n return {\n id: 'user_profile',\n header: '\u7528\u6237\u504F\u597D\u66F4\u65B0',\n question: '\u662F\u5426\u628A\u8FD9\u6761\u4FEE\u6539\u5199\u5165 USER.md\uFF1F',\n detail: lines.join('\\n'),\n options: [\n { label: '\u786E\u8BA4', description: '\u5199\u5165 USER.md\uFF0C\u7ACB\u5373\u751F\u6548\uFF08\u4E0B\u4E00\u8F6E\u6CE8\u5165\u53EF\u89C1\uFF09' },\n { label: '\u53D6\u6D88', description: '\u4E0D\u4FEE\u6539\u6587\u4EF6' },\n ],\n actions: content,\n };\n}\n\nexport function profileParameters(): unknown {\n return {\n type: 'object',\n properties: {\n op: { type: 'string', enum: ['read', 'add', 'replace', 'remove'] },\n query: { type: 'string', description: 'read: literal keyword; omit to list every entry' },\n content: { type: 'string', description: 'add/replace: one complete entry' },\n old_text: { type: 'string', description: 'replace/remove: complete old entry or a unique literal substring' },\n },\n required: ['op'],\n additionalProperties: false,\n };\n}\n\nexport async function executeUserProfile(\n deps: ProfileToolDeps,\n args: unknown,\n exec: unknown,\n): Promise<unknown> {\n const input = args as ProfileToolInput;\n const session = sessionOf(exec);\n const snapshot = loadProfile(deps.home);\n\n if (input.op === 'read') {\n const entries = input.query === undefined || input.query.trim() === ''\n ? [...snapshot.entries]\n : queryProfile(snapshot.entries, input.query);\n deps.readSessions.add(session);\n return { entries, total: snapshot.entries.length, chars: snapshot.chars, limit: PROFILE_MAX_CHARS };\n }\n\n if (!deps.readSessions.has(session)) {\n fail('\u5148\u8BFB\u53D6 USER.md\uFF08user_profile op=read\uFF09\uFF0C\u518D\u4FEE\u6539');\n }\n if (deps.mode === 'readonly') {\n fail('\u5F53\u524D\u4E3A readonly \u6A21\u5F0F\uFF1A\u53EA\u80FD\u8BFB\u53D6\u504F\u597D\uFF0C\u4E0D\u80FD\u4FEE\u6539');\n }\n\n let proposed: string[];\n let action: string;\n let content = '';\n if (input.op === 'add') {\n if (typeof input.content !== 'string' || input.content.trim() === '') fail('add \u9700\u8981 content\uFF08\u5B8C\u6574\u6761\u76EE\uFF09');\n content = input.content.trim();\n proposed = [...snapshot.entries, content];\n action = '\u65B0\u589E\u4E00\u6761\u504F\u597D';\n } else {\n if (typeof input.old_text !== 'string' || input.old_text.trim() === '') fail(`${input.op} \u9700\u8981 old_text`);\n const index = findProfileEntry(snapshot.entries, input.old_text);\n if (input.op === 'remove') {\n proposed = snapshot.entries.filter((_, position) => position !== index);\n action = '\u5220\u9664\u4E00\u6761\u504F\u597D';\n } else {\n if (typeof input.content !== 'string' || input.content.trim() === '') fail('replace \u9700\u8981 content\uFF08\u5B8C\u6574\u65B0\u6761\u76EE\uFF09');\n content = input.content.trim();\n proposed = snapshot.entries.map((entry, position) => (position === index ? content : entry));\n action = '\u66FF\u6362\u4E00\u6761\u504F\u597D';\n }\n }\n const problems = validateProfileEntries(proposed);\n if (problems.length > 0) fail(problems.join('; '));\n\n if (deps.mode === 'confirm') {\n const questions = deps.resolveQuestions();\n if (questions === undefined) fail('\u5F53\u524D\u73AF\u5883\u6CA1\u6709\u4EA4\u4E92\u754C\u9762\uFF0C\u65E0\u6CD5\u786E\u8BA4 USER.md \u4FEE\u6539');\n if (session === 'unknown-session') fail('\u9700\u8981\u6D3B\u52A8\u4F1A\u8BDD\u624D\u80FD\u786E\u8BA4 USER.md \u4FEE\u6539');\n const question = buildQuestion(action, snapshot.entries, proposed, content);\n const answer = await questions.ask({\n questions: [question],\n agent: (exec as ExecLike | undefined)?.agent,\n ...(((exec as ExecLike | undefined)?.signal === undefined)\n ? {}\n : { signal: (exec as ExecLike).signal }),\n ...(((exec as ExecLike | undefined)?.callId === undefined)\n ? {}\n : { wait: { callId: (exec as ExecLike).callId } }),\n });\n const chosen = answer.answers[0]?.selected[0] ?? answer.answers[0]?.custom?.trim() ?? '';\n if (chosen !== PROFILE_LABELS.confirm) {\n return { ok: false, cancelled: true, entries: snapshot.entries };\n }\n }\n\n const saved = saveProfile(deps.home, proposed);\n deps.store.appendAudit({ event: 'user-profile', action: input.op, entries: saved.entries.length, chars: saved.chars });\n return { ok: true, action: input.op, entries: saved.entries, chars: saved.chars };\n}\n\n/** Register `user_profile` on the host tool registry (top-level agents only). */\nexport function registerUserProfileTool(\n ctx: { readonly tools: { register(definition: unknown): unknown } },\n deps: ProfileToolDeps,\n): void {\n ctx.tools.register({\n name: USER_PROFILE_TOOL,\n description: 'Agent Memory\uFF1A\u8BFB\u53D6\u6216\u4FEE\u6539 USER.md \u504F\u597D\u6761\u76EE\uFF08\u4FEE\u6539\u9700\u4EBA\u786E\u8BA4\uFF09',\n parameters: profileParameters(),\n output: {\n schema: { type: 'object' },\n render: (_args: unknown, value: unknown) => [\n { type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) },\n ],\n },\n execute: async (args: unknown, exec?: unknown) => executeUserProfile(deps, args, exec),\n });\n}\n\nexport { ProfileError };\n", "/**\n * Session-history tools (architecture v2, P2). These are thin, read-only\n * wrappers over the host's native `sessionQuery` service (SQLite FTS5 index\n * included), so the model can search prior conversations without a second\n * index of our own.\n */\n\nexport const SESSION_TOOL_NAMES = [\n 'session_search',\n 'session_event_search',\n 'session_event_read',\n 'session_event_trace',\n 'session_trace',\n] as const;\nexport type SessionToolName = (typeof SESSION_TOOL_NAMES)[number];\n\nexport interface SessionQueryLike {\n searchSessions?(request: { query: string; limit?: number }): Promise<{ items: readonly unknown[] }>;\n searchEvents?(request: { sessionId: string; query: string; limit?: number }): Promise<{ items: readonly unknown[] }>;\n readEvent?(request: {\n sessionId: string;\n seq: number;\n before?: number;\n after?: number;\n }): Promise<Record<string, unknown>>;\n traceEvent?(request: { sessionId: string; seq: number }): Promise<Record<string, unknown>>;\n traceSession?(sessionId: string): Promise<Record<string, unknown>>;\n}\n\nexport interface SessionToolDeps {\n readonly resolveQuery: () => SessionQueryLike | undefined;\n readonly sessionId: string;\n}\n\ninterface ExecLike {\n readonly agent?: { readonly session?: { readonly id?: string } };\n}\n\nconst SNIPPET_MAX = 500;\nconst TEXT_MAX = 4000;\n\nfunction clip(text: string, max: number): string {\n const points = [...text];\n return points.length <= max ? text : `${points.slice(0, max).join('')}\u2026`;\n}\n\nfunction textOf(data: unknown): string {\n if (typeof data !== 'object' || data === null) return '';\n const record = data as { content?: unknown; text?: unknown; message?: unknown };\n if (typeof record.content === 'string') return record.content;\n if (Array.isArray(record.content)) {\n return record.content\n .map((block) =>\n typeof block === 'object' && block !== null && typeof (block as { text?: unknown }).text === 'string'\n ? (block as { text: string }).text\n : '',\n )\n .filter((text) => text !== '')\n .join('\\n');\n }\n if (typeof record.text === 'string') return record.text;\n if (typeof record.message === 'object' && record.message !== null) return textOf(record.message);\n return '';\n}\n\nfunction sessionIdOf(deps: SessionToolDeps, exec: unknown): string {\n const execLike = exec as ExecLike | undefined;\n return execLike?.agent?.session?.id ?? deps.sessionId;\n}\n\nfunction serviceOrFail(deps: SessionToolDeps): SessionQueryLike {\n const query = deps.resolveQuery();\n if (query === undefined) {\n throw new Error('host session query service is unavailable in this composition');\n }\n return query;\n}\n\nfunction limitOf(value: unknown, fallback = 5): number {\n return typeof value === 'number' && Number.isInteger(value) && value >= 1 ? Math.min(value, 10) : fallback;\n}\n\nfunction integerOf(value: unknown, name: string): number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new Error(`${name} must be a non-negative integer`);\n }\n return value;\n}\n\nfunction summarizeEvent(item: unknown): Record<string, unknown> {\n const record = (item ?? {}) as Record<string, unknown>;\n const sessionId = (record.sessionId ?? record.session_id ?? '') as string;\n return {\n session_id: sessionId,\n seq: record.seq,\n type: record.type,\n snippet: typeof record.snippet === 'string' ? clip(record.snippet, SNIPPET_MAX) : undefined,\n };\n}\n\nexport interface RegisteredSessionTool {\n readonly name: SessionToolName;\n readonly description: string;\n readonly parameters: unknown;\n readonly output: unknown;\n execute(args: unknown, exec?: unknown): Promise<unknown>;\n}\n\nfunction definition(\n name: SessionToolName,\n description: string,\n properties: Record<string, unknown>,\n required: string[],\n handler: (args: Record<string, unknown>, exec?: unknown) => Promise<unknown>,\n): RegisteredSessionTool {\n return {\n name,\n description,\n parameters: { type: 'object', properties, required, additionalProperties: false },\n output: {\n schema: { type: 'object' },\n render: (_args: unknown, value: unknown) => [\n { type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) },\n ],\n },\n execute: async (args: unknown, exec?: unknown) => {\n if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new Error('arguments must be an object');\n const record = args as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!(key in properties)) throw new Error(`unknown field: ${key}`);\n }\n for (const key of required) {\n if (!(key in record)) throw new Error(`missing field: ${key}`);\n }\n return handler(record, exec);\n },\n };\n}\n\nexport function sessionToolDefinitions(deps: SessionToolDeps): RegisteredSessionTool[] {\n return [\n definition(\n 'session_search',\n 'Agent Memory\uFF1A\u8DE8\u4F1A\u8BDD\u5168\u6587\u68C0\u7D22\uFF0C\u6BCF\u4E2A\u4F1A\u8BDD\u8FD4\u56DE\u6700\u5339\u914D\u7684\u4E00\u6761',\n {\n query: { type: 'string', minLength: 1 },\n limit: { type: 'integer', minimum: 1, maximum: 10 },\n },\n ['query'],\n async (args) => {\n const query = serviceOrFail(deps);\n const page = await query.searchSessions?.({\n query: String(args.query),\n limit: limitOf(args.limit),\n });\n return {\n results: (page?.items ?? []).map((item) => {\n const hit = item as { bestMatch?: unknown; header?: { id?: string; title?: string } };\n const best = summarizeEvent(hit.bestMatch);\n return {\n session_id: hit.header?.id ?? best.session_id,\n title: hit.header?.title,\n seq: best.seq,\n snippet: best.snippet,\n };\n }),\n };\n },\n ),\n definition(\n 'session_event_search',\n 'Agent Memory\uFF1A\u5728\u5355\u4E2A\u4F1A\u8BDD\u5185\u5168\u6587\u68C0\u7D22\u4E8B\u4EF6\uFF08\u9ED8\u8BA4\u5F53\u524D\u4F1A\u8BDD\uFF09',\n {\n query: { type: 'string', minLength: 1 },\n session_id: { type: 'string' },\n limit: { type: 'integer', minimum: 1, maximum: 10 },\n },\n ['query'],\n async (args, exec) => {\n const query = serviceOrFail(deps);\n const page = await query.searchEvents?.({\n sessionId: typeof args.session_id === 'string' ? args.session_id : sessionIdOf(deps, exec),\n query: String(args.query),\n limit: limitOf(args.limit),\n });\n return { results: (page?.items ?? []).map(summarizeEvent) };\n },\n ),\n definition(\n 'session_event_read',\n 'Agent Memory\uFF1A\u8BFB\u53D6\u4E00\u6761\u4E8B\u4EF6\u7684\u5B8C\u6574\u539F\u6587\u4E0E\u524D\u540E\u82E5\u5E72\u6761\u7A97\u53E3',\n {\n seq: { type: 'integer', minimum: 0 },\n session_id: { type: 'string' },\n before: { type: 'integer', minimum: 0, maximum: 5 },\n after: { type: 'integer', minimum: 0, maximum: 5 },\n },\n ['seq'],\n async (args, exec) => {\n const query = serviceOrFail(deps);\n const seq = integerOf(args.seq, 'seq');\n const window = await query.readEvent?.({\n sessionId: typeof args.session_id === 'string' ? args.session_id : sessionIdOf(deps, exec),\n seq,\n before: typeof args.before === 'number' ? args.before : 1,\n after: typeof args.after === 'number' ? args.after : 1,\n });\n const target = (window?.target ?? {}) as Record<string, unknown>;\n return {\n session_id: typeof args.session_id === 'string' ? args.session_id : sessionIdOf(deps, exec),\n seq: target.seq,\n type: target.type,\n text: clip(textOf(target.data), TEXT_MAX),\n start_seq: window?.startSeq,\n end_seq: window?.endSeq,\n };\n },\n ),\n definition(\n 'session_event_trace',\n 'Agent Memory\uFF1A\u67E5\u770B\u4E00\u6761\u4E8B\u4EF6\u7684\u66FF\u6362\u94FE\u4E0E\u5F15\u7528\u6765\u6E90',\n {\n seq: { type: 'integer', minimum: 0 },\n session_id: { type: 'string' },\n },\n ['seq'],\n async (args, exec) => {\n const query = serviceOrFail(deps);\n const seq = integerOf(args.seq, 'seq');\n const trace = await query.traceEvent?.({\n sessionId: typeof args.session_id === 'string' ? args.session_id : sessionIdOf(deps, exec),\n seq,\n });\n return {\n target: trace?.target,\n replaced_by: trace?.replacedBy,\n replacement_chain: trace?.replacementChain,\n replaced_event_seqs: trace?.replacedEventSeqs,\n cited_source_seqs: trace?.citedSourceSeqs,\n };\n },\n ),\n definition(\n 'session_trace',\n 'Agent Memory\uFF1A\u67E5\u770B\u4F1A\u8BDD\u8C31\u7CFB\uFF08\u7956\u5148\u4E0E\u540E\u4EE3\uFF0C\u9ED8\u8BA4\u5F53\u524D\u4F1A\u8BDD\uFF09',\n { session_id: { type: 'string' } },\n [],\n async (args, exec) => {\n const query = serviceOrFail(deps);\n const target = typeof args.session_id === 'string' ? args.session_id : sessionIdOf(deps, exec);\n const trace = await query.traceSession?.(target);\n return { session_id: target, ...(trace ?? {}) };\n },\n ),\n ];\n}\n\nexport function registerSessionTools(\n ctx: { readonly tools: { register(definition: unknown): unknown } },\n deps: SessionToolDeps,\n): void {\n for (const tool of sessionToolDefinitions(deps)) ctx.tools.register(tool);\n}\n", "import {\n createProposal,\n createProject,\n decideProposal,\n deleteProject,\n importBundle,\n listProjects,\n listProposals,\n loadProfile,\n memoryPaths,\n readRulesFile,\n saveProfile,\n saveRulesFile,\n sealPolicy,\n} from '../../core/src/index.ts';\nimport type { Config } from '../../core/src/config/config.ts';\nimport type { MemoryDoc, MemoryId } from '../../core/src/model/types.ts';\nimport type { MemoryStore } from '../../core/src/store/store.ts';\n\n/**\n * V2 GUI data plane. P1 projections are read-only; P2 adds human write routes\n * that reuse the existing proposal + decision pipeline and journal. No file\n * I/O here beyond the core API.\n */\n\nconst KIND_ORDER = ['fact', 'pitfall', 'exp'] as const;\nconst KIND_LABEL: Record<string, string> = { fact: '\u4E8B\u5B9E', pitfall: '\u5751', exp: '\u7ECF\u9A8C' };\nconst KIND_PREFIX: Record<string, string> = { fact: 'F', pitfall: 'P', exp: 'E' };\n\nfunction byDateDesc(left: MemoryDoc, right: MemoryDoc): number {\n // Sort by the date the UI shows (valid_from), not import/creation time:\n // restored entries keep their original date and must not jump to the top.\n if (left.valid_from !== right.valid_from) return right.valid_from.localeCompare(left.valid_from);\n if (left.created_at !== right.created_at) return right.created_at.localeCompare(left.created_at);\n return right.id.localeCompare(left.id);\n}\n\n/** Stable human-readable serial: F-01, P-02, \u2026 in date-desc order within a kind. */\nexport function serialsFor(docs: readonly MemoryDoc[]): ReadonlyMap<MemoryId, string> {\n const serials = new Map<MemoryId, string>();\n for (const kind of KIND_ORDER) {\n const sorted = docs.filter((doc) => doc.kind === kind).sort(byDateDesc);\n sorted.forEach((doc, index) => {\n serials.set(doc.id, `${KIND_PREFIX[kind]}-${String(index + 1).padStart(2, '0')}`);\n });\n }\n return serials;\n}\n\n/** Human-facing summary: whitespace collapsed, hard cap of 12 characters. */\nexport function summarize(text: string, limit = 12): string {\n const clean = text.replace(/\\s+/g, ' ').trim();\n const points = [...clean];\n return points.length <= limit ? clean : points.slice(0, limit).join('');\n}\n\n/** Existing memory: `F-01 \u4E2D\u6587\u4F18\u5148\u504F\u597D`; new content: just the summary. */\nexport function displayName(serial: string, abstract: string): string {\n const text = summarize(abstract);\n return serial === '' ? text : `${serial} ${text}`;\n}\n\n/** Human GUI \"new memory\": content-only dedupe applies, audit marks the GUI. */\nexport function createGui(\n store: MemoryStore,\n input: {\n kind: string;\n abstract: string;\n body?: string;\n valid_from?: string;\n error_signatures?: readonly string[];\n },\n) {\n if (!KIND_ORDER.includes(input.kind as (typeof KIND_ORDER)[number])) {\n throw new Error(`kind must be one of ${KIND_ORDER.join(', ')}`);\n }\n const abstract = typeof input.abstract === 'string' ? input.abstract.trim() : '';\n if (abstract === '') throw new Error('abstract is required');\n const result = store.add(\n {\n kind: input.kind as (typeof KIND_ORDER)[number],\n abstract,\n body: typeof input.body === 'string' ? input.body : '',\n evidence_level: 'user_explicit',\n ...(typeof input.valid_from === 'string' && input.valid_from !== ''\n ? { valid_from: input.valid_from }\n : {}),\n ...(Array.isArray(input.error_signatures)\n ? { error_signatures: input.error_signatures.filter((entry): entry is string => typeof entry === 'string') }\n : {}),\n },\n { author: 'human' },\n );\n store.appendJournal('audit', {\n event: 'gui-create',\n id: result.id,\n deduplicated: result.deduplicated,\n });\n const serial = serialsFor(store.active()).get(result.id) ?? '';\n return {\n id: result.id,\n deduplicated: result.deduplicated,\n display: displayName(serial, abstract),\n };\n}\n\nexport interface SummarySuggestion {\n readonly id: string;\n readonly text: string;\n readonly category: string;\n readonly basis: readonly string[];\n readonly confidence: '\u9AD8' | '\u4E2D' | '\u4F4E';\n}\n\n/**\n * Deterministic \"\u6574\u7406\u8BB0\u5FC6\" projection. Read-only: it never writes RULES.\n * Suggestions are candidate model-guide lines; a human must select them and\n * still press save in the RULES editor.\n */\nexport function summarizeGui(store: MemoryStore) {\n const docs = store.active();\n const serials = serialsFor(docs);\n const byKind = { fact: 0, pitfall: 0, exp: 0 };\n for (const doc of docs) byKind[doc.kind] += 1;\n\n const sorted = [...docs].sort(byDateDesc);\n const recent = sorted.slice(0, 5).map((doc) => ({\n serial: serials.get(doc.id) ?? '',\n kind: doc.kind,\n abstract: doc.abstract,\n }));\n\n const signatures = new Map<string, { count: number; ids: string[] }>();\n for (const doc of docs) {\n if (doc.kind !== 'pitfall') continue;\n for (const signature of doc.error_signatures) {\n const entry = signatures.get(signature) ?? { count: 0, ids: [] };\n entry.count += 1;\n entry.ids.push(doc.id);\n signatures.set(signature, entry);\n }\n }\n const topSignatures = [...signatures.entries()]\n .map(([signature, entry]) => ({\n signature,\n count: entry.count,\n basis: entry.ids.map((id) => serials.get(id) ?? ''),\n }))\n .sort((left, right) => right.count - left.count || left.signature.localeCompare(right.signature))\n .slice(0, 5);\n\n const suggestions: SummarySuggestion[] = [];\n for (const item of topSignatures) {\n if (item.count < 2) continue;\n suggestions.push({\n id: `sig-${suggestions.length + 1}`,\n text: `\u9047\u5230\u300C${item.signature}\u300D\u65F6\uFF0C\u5148\u6309\u5DF2\u6709\u7ECF\u9A8C\u6392\u67E5\uFF0C\u907F\u514D\u91CD\u590D\u8E29\u5751\u3002`,\n category: '\u6A21\u578B\u6307\u5F15',\n basis: item.basis,\n confidence: '\u9AD8',\n });\n }\n if (suggestions.length === 0) {\n suggestions.push({\n id: 'generic-1',\n text: '\u65B0\u589E\u8BB0\u5FC6\u524D\u5148\u68C0\u7D22\u662F\u5426\u5DF2\u6709\u540C\u7C7B\u7ED3\u8BBA\uFF0C\u907F\u514D\u91CD\u590D\u8BB0\u5F55\u3002',\n category: '\u6A21\u578B\u6307\u5F15',\n basis: recent.slice(0, 3).map((entry) => entry.serial).filter((serial) => serial !== ''),\n confidence: '\u4E2D',\n });\n }\n\n return {\n total: docs.length,\n by_kind: byKind,\n recent,\n top_signatures: topSignatures,\n suggestions: suggestions.slice(0, 8),\n };\n}\n\n/** Path only: the GUI never reads or writes SOUL.md. */\nexport function soulPathGui(home: string): { path: string; hint: string } {\n return {\n path: memoryPaths(home).soulFile,\n hint: '\u6B64\u6587\u4EF6\u53EA\u7531\u4F60\u7F16\u8F91\uFF1B\u672C\u63D2\u4EF6\u4E0D\u8BFB\u53D6\u3001\u4E0D\u4FEE\u6539\u5B83\u7684\u5185\u5BB9\u3002\u4FEE\u6539\u540E\u70B9\u4E0B\u65B9\u300C\u4E00\u952E\u5C01\u5B58\u300D\u3002',\n };\n}\n\n/**\n * Human GUI seal: the click is the explicit acceptance. Sealing hashes the\n * sealed files but never returns or edits their contents.\n */\nexport function sealGui(home: string, store: MemoryStore) {\n const result = sealPolicy({ home, accept: true });\n store.appendJournal('audit', { event: 'gui-seal', sha256: result.sha256 });\n return { sealed: true, sha256: result.sha256 };\n}\n\nfunction summary(doc: MemoryDoc, serial: string) {\n return {\n serial,\n display: displayName(serial, doc.abstract),\n id: doc.id,\n kind: doc.kind,\n abstract: doc.abstract,\n project: doc.project ?? null,\n tags: doc.tags ?? [],\n relations: doc.relations ?? [],\n source: doc.source ?? null,\n author: doc.author,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n evidence_level: doc.evidence_level,\n created_at: doc.created_at,\n supersedes: doc.supersedes,\n };\n}\n\nexport function buildList(store: MemoryStore) {\n const active = store.active();\n const serials = serialsFor(active);\n const groups = KIND_ORDER.map((kind) => ({\n kind,\n label: KIND_LABEL[kind] ?? kind,\n items: active\n .filter((doc) => doc.kind === kind)\n .sort(byDateDesc)\n .map((doc) => summary(doc, serials.get(doc.id) ?? '')),\n }));\n return {\n total: active.length,\n pending: store.stats().pending_proposals,\n groups,\n };\n}\n\nexport function buildItem(store: MemoryStore, id: string) {\n const doc = store.read(id as MemoryId);\n const serial = serialsFor(store.active()).get(doc.id) ?? '';\n return {\n ...summary(doc, serial),\n body: doc.body,\n error_signatures: doc.error_signatures,\n provenance: doc.provenance,\n content_hash: doc.content_hash,\n };\n}\n\nexport async function buildSearch(store: MemoryStore, query: string, limit = 20) {\n const result = await store.recallAsync(query, { limit });\n const serials = serialsFor(store.active());\n return {\n query,\n hits: result.hits.map((hit) => ({\n serial: serials.get(hit.id) ?? '',\n id: hit.id,\n kind: hit.kind,\n abstract: hit.abstract,\n score: hit.score,\n provenance_verifiable: hit.provenance_verifiable,\n })),\n warnings: result.warnings,\n };\n}\n\nexport interface GraphNode {\n readonly id: string;\n readonly serial: string;\n readonly display: string;\n readonly kind: string;\n readonly project: string;\n readonly tags: readonly string[];\n readonly relations: readonly { type: string; target: string }[];\n readonly supersedes: readonly string[];\n readonly valid_from: string;\n}\n\nexport interface GraphProject {\n readonly name: string;\n readonly count: number;\n readonly last_updated: string | null;\n}\n\n/** Read-only worktree projection (S4): projects, memory nodes and three edge types. */\nexport function buildGraph(store: MemoryStore, home: string) {\n const active = store.active();\n const serials = serialsFor(active);\n const registered = listProjects(home).map((project) => project.name);\n const registeredSet = new Set(registered);\n const effectiveProject = (doc: MemoryDoc): string =>\n doc.project !== null && doc.project !== undefined && registeredSet.has(doc.project) ? doc.project : '\u672A\u5F52\u7C7B';\n const names = new Set(registered);\n for (const doc of active) names.add(effectiveProject(doc));\n const projects: GraphProject[] = [...names].map((name) => {\n const docs = active.filter((doc) => effectiveProject(doc) === name);\n const last = docs.map((doc) => doc.valid_from).sort().at(-1) ?? null;\n return { name, count: docs.length, last_updated: last };\n });\n projects.sort((left, right) => right.count - left.count || left.name.localeCompare(right.name));\n\n const limited = active\n .slice()\n .sort((left, right) => right.valid_from.localeCompare(left.valid_from) || right.created_at.localeCompare(left.created_at))\n .slice(0, 200);\n const ids = new Set(limited.map((doc) => doc.id));\n const nodes: GraphNode[] = limited.map((doc) => {\n const serial = serials.get(doc.id) ?? '';\n return {\n id: doc.id,\n serial,\n display: displayName(serial, doc.abstract),\n kind: doc.kind,\n project: effectiveProject(doc),\n tags: doc.tags ?? [],\n relations: (doc.relations ?? []).map((relation) => ({ type: relation.type, target: relation.target })),\n supersedes: doc.supersedes,\n valid_from: doc.valid_from,\n };\n });\n const edges: { from: string; to: string; type: string }[] = [];\n for (const doc of limited) {\n for (const target of doc.supersedes) {\n if (ids.has(target)) edges.push({ from: doc.id, to: target, type: 'supersedes' });\n }\n for (const relation of doc.relations ?? []) {\n if (ids.has(relation.target)) edges.push({ from: doc.id, to: relation.target, type: relation.type });\n }\n }\n const conflicts: { a: string; b: string; project: string; reason: string }[] = [];\n for (let left = 0; left < limited.length; left += 1) {\n for (let right = left + 1; right < limited.length; right += 1) {\n const a = limited[left] as MemoryDoc;\n const b = limited[right] as MemoryDoc;\n if (effectiveProject(a) !== effectiveProject(b)) continue;\n const shared = (a.tags ?? []).some((tag) => (b.tags ?? []).includes(tag));\n if (!shared) continue;\n const charsA = new Set([...a.abstract.replace(/\\s+/g, '')]);\n const charsB = new Set([...b.abstract.replace(/\\s+/g, '')]);\n let overlap = 0;\n for (const char of charsA) if (charsB.has(char)) overlap += 1;\n const similarity = overlap / Math.max(1, new Set([...charsA, ...charsB]).size);\n if (similarity >= 0.8) {\n conflicts.push({ a: a.id, b: b.id, project: effectiveProject(a), reason: '\u540C\u9879\u76EE\u540C\u6807\u7B7E\u4E14\u6458\u8981\u9AD8\u5EA6\u91CD\u53E0' });\n }\n }\n }\n return {\n schema: 1,\n generated_at: new Date().toISOString(),\n truncated: active.length > limited.length,\n projects,\n nodes,\n edges,\n conflicts,\n };\n}\n\nexport function exportBundle(store: MemoryStore) { const active = store.active();\n const serials = serialsFor(active);\n const memories = active\n .slice()\n .sort(byDateDesc)\n .map((doc) => ({\n ...summary(doc, serials.get(doc.id) ?? ''),\n body: doc.body,\n error_signatures: doc.error_signatures,\n provenance: doc.provenance,\n content_hash: doc.content_hash,\n }));\n return {\n format: 'agent-memory-export-v2',\n exported_at: new Date().toISOString(),\n memories,\n proposals: listProposals(store).map((proposal) => ({\n id: proposal.id,\n op: proposal.op,\n targets: proposal.targets,\n reason: proposal.reason,\n created_at: proposal.created_at,\n })),\n };\n}\n\nexport interface GuiRouteDeps {\n readonly store: MemoryStore;\n readonly home: string;\n readonly mode: string;\n readonly modules: readonly { name: string; ok: boolean; error?: string }[];\n readonly config: Config;\n}\n\n/** Pending proposals with display serials and target abstracts. */\nexport function buildProposals(store: MemoryStore) {\n const serials = serialsFor(store.active());\n const abstractOf = (id: string): string => {\n try {\n return store.read(id as MemoryId).abstract;\n } catch {\n return '\uFF08\u5DF2\u4E0D\u5B58\u5728\uFF09';\n }\n };\n return listProposals(store).map((proposal) => ({\n id: proposal.id,\n op: proposal.op,\n reason: proposal.reason,\n created_at: proposal.created_at,\n targets: proposal.targets.map((id) => {\n const serial = serials.get(id) ?? '';\n const abstract = abstractOf(id);\n return { id, serial, abstract, display: displayName(serial, abstract) };\n }),\n replacements: proposal.replacements.map((replacement) => ({\n kind: replacement.kind,\n abstract: replacement.abstract,\n display: summarize(replacement.abstract),\n body: replacement.body,\n })),\n }));\n}\n\n/** Human GUI decision: same proposal pipeline as `/mem decide`, audited as GUI. */\nexport function decideGui(\n store: MemoryStore,\n config: Config,\n id: string,\n decision: 'accept' | 'reject',\n note?: string,\n): void {\n decideProposal({ store, config }, { id, decision, ...(note === undefined ? {} : { reason: note }) });\n store.appendJournal('audit', { event: 'gui-decide', proposal: id, decision });\n}\n\n/**\n * Human GUI revise: create the supersede proposal, then accept it in the same\n * human action. Provenance survives from the old record; the decision line is\n * the GUI confirmation.\n */\nexport function reviseGui(\n store: MemoryStore,\n config: Config,\n id: string,\n input: { abstract: string; body: string },\n): void {\n const target = store.read(id as MemoryId);\n const proposal = createProposal(\n { store, config },\n {\n op: 'supersede',\n targets: [id],\n base_hashes: [target.content_hash],\n reason: '\u56FE\u5F62\u754C\u9762\u4FEE\u8BA2',\n replacements: [\n {\n kind: target.kind,\n abstract: input.abstract,\n body: input.body,\n evidence_level: 'user_confirmed',\n error_signatures: target.error_signatures,\n provenance: target.provenance,\n },\n ],\n },\n );\n decideProposal({ store, config }, { id: proposal.id, decision: 'accept' });\n store.appendJournal('audit', { event: 'gui-revise', target: id, proposal: proposal.id });\n}\n\n/** Human GUI delete: delete proposal + immediate acceptance. */\n/**\n * Human GUI delete is a hard delete: the memory file is removed and pending\n * proposals targeting it are invalidated. Superseded ancestors are removed in\n * the same action, otherwise purging the revision would revive the old version.\n * The journal keeps a delete line with the reason and content hash only \u2014 no\n * body, no recoverable copy.\n */\nexport function deleteGui(store: MemoryStore, config: Config, id: string, reason = '\u56FE\u5F62\u754C\u9762\u5220\u9664'): void {\n void config;\n const target = store.read(id as MemoryId);\n const ids: string[] = [id];\n const collect = (docId: string): void => {\n if (ids.includes(docId)) return;\n ids.push(docId);\n try {\n for (const parent of store.read(docId as MemoryId).supersedes) collect(parent);\n } catch {\n // An already-purged ancestor is skipped; the visible one is still removed.\n }\n };\n for (const parent of target.supersedes) collect(parent);\n\n let proposals = 0;\n for (const each of ids) {\n try {\n proposals += store.purge(each as MemoryId, { reason }).proposals;\n } catch {\n // Missing files are fine; the goal is that none of these ids stay active.\n }\n }\n store.appendJournal('audit', { event: 'gui-purge', target: id, removed: ids.length, proposals });\n}\n\nexport function readProfileGui(home: string) {\n const profile = loadProfile(home);\n return { entries: [...profile.entries], chars: profile.chars };\n}\n\nexport function saveProfileGui(home: string, store: MemoryStore, entries: readonly string[]) {\n const profile = saveProfile(home, entries);\n store.appendJournal('audit', { event: 'gui-profile', entries: profile.entries.length });\n return profile;\n}\n\nexport function readRulesGui(home: string) {\n return { text: readRulesFile(home) };\n}\n\n/**\n * Human GUI RULES write. Only reachable from the GUI route (no model tool and\n * no CLI command), validates first, then seals policy with the human click as\n * the explicit acceptance.\n */\nexport function saveRulesGui(home: string, store: MemoryStore, text: string) {\n saveRulesFile(home, text);\n const sealed = sealPolicy({ home, accept: true });\n store.appendJournal('audit', { event: 'gui-rules', sha256: sealed.sha256 });\n return { sealed: true };\n}\n\n\nexport interface GuiConnection {\n readonly fetch?: { register(route: unknown): unknown };\n}\n\nfunction json(value: unknown, status = 200): Response {\n return new Response(JSON.stringify(value), {\n status,\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n 'x-agent-memory-api-version': '1',\n },\n });\n}\n\nfunction errorResponse(message: string, status = 400): Response {\n return json({ ok: false, error: message }, status);\n}\n\nasync function readJson(request: Request): Promise<Record<string, unknown>> {\n try {\n const value = (await request.json()) as unknown;\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\n/** Register the P1 read-only routes (paths own their full `/api` prefix). */\nexport function guiRoutes(deps: GuiRouteDeps): unknown[] {\n const status = {\n path: '/api/agent-memory/status',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => {\n const stats = deps.store.stats();\n return json({\n ok: true,\n home: deps.home,\n active: stats.active,\n pending: stats.pending_proposals,\n journal_head: stats.journal_head,\n mode: deps.mode,\n modules: deps.modules,\n });\n },\n };\n\n const list = {\n path: '/api/agent-memory/list',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => json(buildList(deps.store)),\n };\n\n const graph = {\n path: '/api/agent-memory/graph',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => json(buildGraph(deps.store, deps.home)),\n };\n\n const projects = {\n path: '/api/agent-memory/projects',\n methods: ['GET', 'POST', 'DELETE'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n if (request.method === 'GET') return json({ projects: listProjects(deps.home) });\n if (request.method === 'DELETE') {\n const name = new URL(request.url).searchParams.get('name') ?? '';\n if (name === '') return errorResponse('name is required');\n return deleteProject(deps.home, name) ? json({ ok: true }) : errorResponse('project not found', 404);\n }\n const body = await readJson(request);\n if (typeof body.name !== 'string' || body.name.trim() === '') return errorResponse('name is required');\n try {\n const project = createProject({\n home: deps.home,\n name: body.name,\n ...(typeof body.description === 'string' ? { description: body.description } : {}),\n });\n return json({ project });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const moveProject = {\n path: '/api/agent-memory/projects/move',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n if (!Array.isArray(body.ids) || body.ids.some((id) => typeof id !== 'string')) {\n return errorResponse('ids must be a string array');\n }\n if (body.project !== null && typeof body.project !== 'string') {\n return errorResponse('project must be a string or null');\n }\n const target = body.project as string | null;\n if (target !== null && !listProjects(deps.home).some((project) => project.name === target)) {\n return errorResponse(`unknown project: ${target}`, 409);\n }\n try {\n const result = deps.store.moveProjects(body.ids as string[], target);\n return json({ ok: true, ...result });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const meta = {\n path: '/api/agent-memory/meta',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n if (typeof body.id !== 'string' || body.id === '') return errorResponse('id is required');\n if (body.tags !== undefined && (!Array.isArray(body.tags) || body.tags.some((tag) => typeof tag !== 'string'))) {\n return errorResponse('tags must be a string array');\n }\n if (\n body.relations !== undefined &&\n (!Array.isArray(body.relations) ||\n body.relations.some(\n (relation) =>\n typeof relation !== 'object' ||\n relation === null ||\n typeof (relation as { type?: unknown }).type !== 'string' ||\n typeof (relation as { target?: unknown }).target !== 'string',\n ))\n ) {\n return errorResponse('relations must be {type,target} objects');\n }\n try {\n const doc = deps.store.updateMeta(body.id, {\n ...(body.tags === undefined ? {} : { tags: body.tags as string[] }),\n ...(body.relations === undefined\n ? {}\n : { relations: body.relations as { type: 'relates_to' | 'derived_from'; target: string }[] }),\n });\n return json({ ok: true, id: doc.id, project: doc.project ?? null, tags: doc.tags ?? [], relations: doc.relations ?? [] });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const item = {\n path: '/api/agent-memory/item',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const id = new URL(request.url).searchParams.get('id') ?? '';\n if (!/^mem-\\d{8}-[0-9a-f]{8}$/.test(id)) return errorResponse('id must be a memory id');\n try {\n return json(buildItem(deps.store, id));\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 404);\n }\n },\n };\n\n const search = {\n path: '/api/agent-memory/search',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const query = (new URL(request.url).searchParams.get('q') ?? '').trim();\n if (query === '') return errorResponse('q is required');\n return json(await buildSearch(deps.store, query));\n },\n };\n\n const exportRoute = {\n path: '/api/agent-memory/export',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => {\n const body = JSON.stringify(exportBundle(deps.store), null, 2);\n return new Response(body, {\n status: 200,\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'content-disposition': `attachment; filename=\"agent-memory-${new Date().toISOString().slice(0, 10)}.json\"`,\n 'cache-control': 'no-store',\n },\n });\n },\n };\n\n const proposalsRoute = {\n path: '/api/agent-memory/proposals',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => json(buildProposals(deps.store)),\n };\n\n const decideRoute = {\n path: '/api/agent-memory/proposals/decide',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n const id = typeof body.id === 'string' ? body.id : '';\n const decision = body.decision === 'accept' || body.decision === 'reject' ? body.decision : null;\n if (id === '' || decision === null) return errorResponse('id and decision are required');\n try {\n decideGui(deps.store, deps.config, id, decision, typeof body.note === 'string' ? body.note : undefined);\n return json({ ok: true });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const reviseRoute = {\n path: '/api/agent-memory/revise',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n const id = typeof body.id === 'string' ? body.id : '';\n const abstract = typeof body.abstract === 'string' ? body.abstract.trim() : '';\n const text = typeof body.body === 'string' ? body.body : '';\n if (id === '' || abstract === '') return errorResponse('id and abstract are required');\n try {\n reviseGui(deps.store, deps.config, id, { abstract, body: text });\n return json({ ok: true });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const deleteRoute = {\n path: '/api/agent-memory/delete',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n const id = typeof body.id === 'string' ? body.id : '';\n if (id === '') return errorResponse('id is required');\n try {\n deleteGui(deps.store, deps.config, id);\n return json({ ok: true });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const importRoute = {\n path: '/api/agent-memory/import',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n try {\n const report = importBundle(deps.store, body);\n deps.store.appendJournal('audit', {\n event: 'gui-import',\n imported: report.imported,\n skipped: report.skipped,\n failed: report.failed.length,\n });\n return json(report);\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error));\n }\n },\n };\n\n const createRoute = {\n path: '/api/agent-memory/create',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n try {\n return json(\n createGui(deps.store, {\n kind: typeof body.kind === 'string' ? body.kind : '',\n abstract: typeof body.abstract === 'string' ? body.abstract : '',\n ...(typeof body.body === 'string' ? { body: body.body } : {}),\n ...(typeof body.valid_from === 'string' ? { valid_from: body.valid_from } : {}),\n ...(Array.isArray(body.error_signatures)\n ? { error_signatures: body.error_signatures.filter((entry): entry is string => typeof entry === 'string') }\n : {}),\n }),\n );\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error));\n }\n },\n };\n\n const summarizeRoute = {\n path: '/api/agent-memory/summarize',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => json(summarizeGui(deps.store)),\n };\n\n const soulPathRoute = {\n path: '/api/agent-memory/soul-path',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => json(soulPathGui(deps.home)),\n };\n\n const sealRoute = {\n path: '/api/agent-memory/policy/seal',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async () => {\n try {\n return json(sealGui(deps.home, deps.store));\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const profileRoute = {\n path: '/api/agent-memory/profile',\n methods: ['GET', 'POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n if (request.method === 'GET') return json(readProfileGui(deps.home));\n const body = await readJson(request);\n const entries = Array.isArray(body.entries)\n ? body.entries.filter((entry): entry is string => typeof entry === 'string')\n : null;\n if (entries === null) return errorResponse('entries must be a string array');\n try {\n return json(saveProfileGui(deps.home, deps.store, entries));\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error));\n }\n },\n };\n\n const rulesRoute = {\n path: '/api/agent-memory/rules',\n methods: ['GET', 'POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n if (request.method === 'GET') return json(readRulesGui(deps.home));\n const body = await readJson(request);\n const text = typeof body.text === 'string' ? body.text : null;\n if (text === null) return errorResponse('text is required');\n try {\n return json(saveRulesGui(deps.home, deps.store, text));\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n return [\n status,\n list,\n graph,\n projects,\n moveProject,\n meta,\n item,\n search,\n exportRoute,\n proposalsRoute,\n decideRoute,\n reviseRoute,\n deleteRoute,\n importRoute,\n createRoute,\n summarizeRoute,\n soulPathRoute,\n sealRoute,\n profileRoute,\n rulesRoute,\n ];\n}\n\nexport function registerGuiRoutes(\n connection: GuiConnection,\n deps: GuiRouteDeps,\n effect: ((install: () => unknown, label?: string) => unknown) | undefined,\n): void {\n if (connection.fetch === undefined) return;\n const install = (): void => {\n for (const route of guiRoutes(deps)) connection.fetch?.register(route);\n };\n if (effect !== undefined) effect(install, 'agent-memory: gui routes');\n else install();\n}\n", "import {\n assemble,\n bindEvidence,\n createProposal,\n loadRules,\n MemoryStore,\n startup,\n type Kind,\n type ProposalInput,\n type ProposalReplacement,\n type Runtime,\n} from '../../core/src/index.ts';\nimport type { EvidenceEvent } from '../../core/src/actor.ts';\nimport type { ToolService } from './tools.ts';\n\n/**\n * Host-side service used by the plugin tools (S4).\n *\n * The adapter may only call core; all file I/O happens inside `MemoryStore`.\n * Evidence binding goes through the host's durable session store\n * (`ctx.sessionPersistence.open(id, 'read').read(seq, 1)`), so the model can\n * only cite events that really exist in the calling session.\n */\n\nexport interface SessionEventLike {\n readonly type: string;\n readonly seq: number;\n readonly data: unknown;\n}\n\nexport interface SessionHandleLike {\n read(offset?: number, length?: number): Promise<{ events: readonly SessionEventLike[] }>;\n close(): Promise<void>;\n}\n\nexport interface SessionPersistenceLike {\n open(id: string, access: 'read'): Promise<SessionHandleLike>;\n}\n\n/** Live session store (`ctx.sessions`), the sanctioned fallback in \u00A75.3. */\nexport interface SessionLike {\n readonly seq?: number;\n eventAt(seq: number): SessionEventLike | undefined;\n}\n\nexport interface SessionStoreLike {\n get(id: string): SessionLike | undefined;\n}\n\nexport interface HostSessionContext {\n readonly sessionId: string;\n readonly persistence?: SessionPersistenceLike;\n readonly sessions?: SessionStoreLike;\n}\n\nexport interface PromptSectionLike {\n readonly name: string;\n readonly order: number;\n readonly text: string;\n readonly interpolate: false;\n}\n\nexport interface HostService extends ToolService {\n readonly store: MemoryStore;\n readonly runtime: Runtime;\n readonly home: string;\n readonly mode: 'confirm' | 'direct' | 'readonly';\n readonly session: HostSessionContext;\n assembleSection(sessionId?: string): PromptSectionLike;\n /** One prompt section per human/maintained source, in injection order. */\n assembleSections(sessionId?: string): PromptSectionLike[];\n}\n\ninterface ToolExecLike {\n readonly agent?: { readonly session?: { readonly id?: string } };\n}\n\nfunction speakerOf(type: string): 'user' | 'assistant' | 'tool' | 'system' {\n if (type.startsWith('assistant')) return 'assistant';\n if (type.startsWith('tool')) return 'tool';\n if (type.startsWith('system')) return 'system';\n return 'user';\n}\n\nfunction textOf(data: unknown): string {\n if (typeof data !== 'object' || data === null) return '';\n const record = data as { content?: unknown; text?: unknown; message?: unknown };\n if (typeof record.content === 'string') return record.content;\n if (Array.isArray(record.content)) {\n return record.content\n .map((block) =>\n typeof block === 'object' && block !== null && typeof (block as { text?: unknown }).text === 'string'\n ? ((block as { text: string }).text)\n : '',\n )\n .filter((text) => text !== '')\n .join('\\n');\n }\n if (typeof record.text === 'string') return record.text;\n if (typeof record.message === 'object' && record.message !== null) return textOf(record.message);\n return '';\n}\n\nexport function openHostService(\n home: string,\n session: HostSessionContext,\n options: { readonly onFailure?: (error: unknown) => void } = {},\n): HostService | null {\n let runtime: Runtime;\n try {\n runtime = startup({ home });\n } catch (error) {\n // The host keeps running with the probe fallback, but the failure must not\n // disappear: the caller surfaces it (repair command included) to the model.\n options.onFailure?.(error);\n return null;\n }\n const store = new MemoryStore({ home, config: runtime.config });\n\n const lookupEvent = async (sessionId: string, seq: number): Promise<EvidenceEvent> => {\n // Live session fallback is sanctioned by plan \u00A75.3; it is also what desktop\n // compositions expose (`ctx.sessions`) when the durable service is absent.\n const live = session.sessions?.get(sessionId);\n if (live !== undefined) {\n const event = live.eventAt(seq);\n if (event === undefined || event.seq !== seq) {\n throw new Error(`event ${seq} does not exist in this session`);\n }\n return { seq: event.seq, speaker: speakerOf(event.type), text: textOf(event.data) };\n }\n if (session.persistence === undefined) {\n throw new Error('trusted source binding is unavailable in this host session');\n }\n const handle = await session.persistence.open(sessionId, 'read');\n try {\n const { events } = await handle.read(seq, 1);\n const event = events[0];\n if (event === undefined || event.seq !== seq) throw new Error(`event ${seq} does not exist in this session`);\n return { seq: event.seq, speaker: speakerOf(event.type), text: textOf(event.data) };\n } finally {\n await handle.close();\n }\n };\n\n return {\n store,\n runtime,\n home,\n mode: runtime.config.personalization.mode,\n session,\n config: runtime.config,\n async recall(input) {\n return store.recallAsync(input.query, {\n ...(input.limit === undefined ? {} : { limit: input.limit }),\n ...(input.kind === undefined ? {} : { kinds: [input.kind as Kind] }),\n });\n },\n read(id) {\n return store.read(id);\n },\n async record(input, actor, exec?: unknown) {\n const execLike = exec as ToolExecLike | undefined;\n const sessionId = execLike?.agent?.session?.id ?? actor.sessionId;\n const raw = input as {\n kind: Kind;\n abstract: string;\n body: string;\n valid_from?: string;\n project?: string;\n tags?: readonly string[];\n error_signatures?: readonly string[];\n evidence: readonly { event_seq: number; quote: string }[];\n };\n const provenance = [];\n for (const entry of raw.evidence) {\n const event = await lookupEvent(sessionId, entry.event_seq);\n provenance.push(\n bindEvidence({\n sessionId,\n eventSeq: entry.event_seq,\n quote: entry.quote,\n lookup: () => event,\n }),\n );\n }\n return store.add(\n {\n kind: raw.kind,\n abstract: raw.abstract,\n body: raw.body,\n evidence_level: 'observed',\n ...(raw.valid_from === undefined ? {} : { valid_from: raw.valid_from }),\n ...(raw.project === undefined ? {} : { project: raw.project }),\n ...(raw.tags === undefined ? {} : { tags: raw.tags }),\n ...(raw.error_signatures === undefined ? {} : { error_signatures: raw.error_signatures }),\n },\n { author: 'agent', provenance },\n );\n },\n context(exec, limit = 10) {\n const execLike = exec as ToolExecLike | undefined;\n const sessionId = execLike?.agent?.session?.id ?? session.sessionId;\n const live = session.sessions?.get(sessionId);\n if (live === undefined) return { events: [] };\n const events: Array<{ seq: number; speaker: string; preview: string }> = [];\n const end = live.seq ?? 0;\n for (let seq = 0; seq < end; seq += 1) {\n const event = live.eventAt(seq);\n if (event === undefined) continue;\n if (event.type !== 'user/message' && event.type !== 'system/message' && event.type !== 'tool/result') {\n continue;\n }\n const text = textOf(event.data);\n if (text === '') continue;\n events.push({ seq: event.seq, speaker: speakerOf(event.type), preview: text.slice(0, 120) });\n }\n return { events: events.slice(-limit) };\n },\n async propose(input, actor, exec?: unknown) {\n const execLike = exec as ToolExecLike | undefined;\n const sessionId = execLike?.agent?.session?.id ?? actor.sessionId;\n const raw = input as {\n op: 'create' | 'supersede' | 'delete';\n ids?: readonly string[];\n base_hashes?: readonly string[];\n replacements?: readonly {\n kind: Kind;\n abstract: string;\n body: string;\n evidence_level?: 'user_explicit' | 'user_confirmed' | 'observed';\n valid_from?: string;\n project?: string;\n tags?: readonly string[];\n error_signatures?: readonly string[];\n evidence?: readonly { event_seq: number; quote: string }[];\n }[];\n reason?: string;\n };\n const replacements: ProposalReplacement[] = [];\n for (const replacement of raw.replacements ?? []) {\n const provenance = [];\n for (const entry of replacement.evidence ?? []) {\n const event = await lookupEvent(sessionId, entry.event_seq);\n provenance.push(\n bindEvidence({\n sessionId,\n eventSeq: entry.event_seq,\n quote: entry.quote,\n lookup: () => event,\n }),\n );\n }\n replacements.push({\n kind: replacement.kind,\n abstract: replacement.abstract,\n body: replacement.body,\n evidence_level: replacement.evidence_level ?? 'observed',\n ...(replacement.valid_from === undefined ? {} : { valid_from: replacement.valid_from }),\n ...(replacement.project === undefined ? {} : { project: replacement.project }),\n ...(replacement.tags === undefined ? {} : { tags: replacement.tags }),\n ...(replacement.error_signatures === undefined\n ? {}\n : { error_signatures: replacement.error_signatures }),\n provenance,\n });\n }\n const proposalInput: ProposalInput =\n raw.op === 'delete'\n ? {\n op: 'delete',\n target: (raw.ids ?? [])[0] as string,\n base_hash: (raw.base_hashes ?? [])[0] as string,\n reason: raw.reason ?? 'agent proposal',\n }\n : raw.op === 'create'\n ? {\n op: 'create',\n replacements,\n ...(raw.reason === undefined ? {} : { reason: raw.reason }),\n }\n : {\n op: 'supersede',\n targets: raw.ids ?? [],\n base_hashes: raw.base_hashes ?? [],\n replacements,\n ...(raw.reason === undefined ? {} : { reason: raw.reason }),\n };\n return createProposal({ store, config: runtime.config }, proposalInput);\n },\n rules() {\n return { rules: loadRules(home) };\n },\n assembleSection(sessionId = session.sessionId) {\n const result = assemble({\n home,\n config: runtime.config,\n policy: runtime.policy,\n source: store,\n sessionId,\n });\n return { name: 'agent-memory' as const, order: 100, text: result.text, interpolate: false as const };\n },\n assembleSections(sessionId = session.sessionId) {\n const result = assemble({\n home,\n config: runtime.config,\n policy: runtime.policy,\n source: store,\n sessionId,\n });\n return result.sectionList.map((section) => ({\n name: `agent-memory:${section.key.toLowerCase()}`,\n order: section.order,\n text: section.text,\n interpolate: false as const,\n }));\n },\n };\n}\n"],
|
|
5
|
-
"mappings": ";AAcA,SAAS,kBAAkB;;;ACkBpB,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAA0B,SAAiB,OAA2B,CAAC,GAAG;AACpF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU,KAAK,WAAW,CAAC;AAChC,SAAK,OAAO,KAAK;AACjB,SAAK,aAAa,KAAK;AACvB,SAAK,OAAO,KAAK,QAAQ,CAAC;AAC1B,SAAK,aAAa,KAAK;AAAA,EACzB;AAAA;AAAA,EAGA,SAAiB;AACf,UAAM,QAAQ,CAAC,gCAAgC,KAAK,IAAI,MAAM,KAAK,OAAO,EAAE;AAC5E,QAAI,KAAK,eAAe,OAAW,OAAM,KAAK,WAAW,KAAK,UAAU,EAAE;AAC1E,eAAW,UAAU,KAAK,QAAS,OAAM,KAAK,OAAO,MAAM,EAAE;AAC7D,QAAI,KAAK,eAAe,QAAW;AAGjC,YAAM,KA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AAe,SAAS,iBAAiB;AAAA,MAC3C,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AAED,QAAM,UAAU,QAA4B,KAAK,cAAc;AAC/D,QAAM,YACJ,mBAAmB,SACf,aACA,GAAG,UAAU;AAAA;AAAA;AAAA,EAAiD,cAAc;AAClF,WAAS,QAAQ;AAAA,IACf,MAAM;AAAA,IACN,OAAO;AAAA,IACP,aAAa;AAAA,IACb,MAAM;AAAA,EACR,CAAC;AAED,QAAM,WAAW,QAAsB,KAAK,UAAU;AACtD,YAAU,SAAS;AAAA,IACjB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS,CAAC,eAAuE;AAC/E,YAAM,QAAQ,WAAW;AACzB,UAAI,OAAO,aAAa,QAAW;AACjC,eAAO,EAAE,MAAM,SAAS,MAAM,sCAAsC;AAAA,MACtE;AACA,YAAM,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAMb,IAAI,WAAW,OAAO,WAAW;AAAA,QACjC,MAAM;AAAA,QACN,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,qCAAqC,CAAC;AAAA,QACtE,QAAQ,EAAE,MAAM,OAAO;AAAA,MACzB,CAAC;AACD,aAAO,EAAE,MAAM,WAAW,MAAM,wBAAwB;AAAA,IAC1D;AAAA,EACF,CAAC;AACH;",
|
|
6
|
-
"names": ["existsSync", "isAbsolute", "join", "resolve", "name", "fail", "inject", "recall", "join", "isAbsolute", "resolve", "createHash", "readFileSync", "name", "createHash", "readFileSync", "name", "seal", "readFileSync", "existsSync", "name", "existsSync", "readFileSync", "TIMESTAMP", "existsSync", "readFileSync", "name", "name", "project", "name", "randomBytes", "closeSync", "fsyncSync", "openSync", "readFileSync", "statSync", "writeFileSync", "readFileSync", "statSync", "openSync", "fsyncSync", "closeSync", "randomBytes", "randomBytes", "createHash", "closeSync", "fsyncSync", "mkdirSync", "openSync", "readFileSync", "statSync", "writeSync", "join", "name", "existsSync", "readdirSync", "readFileSync", "rmSync", "join", "frequencies", "normalizedAbstract", "readFileSync", "rmSync", "writeFileSync", "join", "join", "readFileSync", "join", "writeFileSync", "resolve", "readFileSync", "rmSync", "KINDS", "DATE", "join", "readdirSync", "name", "readFileSync", "rmSync", "existsSync", "existsSync", "readFileSync", "join", "join", "existsSync", "readFileSync", "createHash", "existsSync", "readFileSync", "readdirSync", "rmSync", "statSync", "join", "name", "createHash", "join", "existsSync", "readFileSync", "readdirSync", "statSync", "rmSync", "createHash", "randomBytes", "existsSync", "readFileSync", "existsSync", "readFileSync", "charCount", "createHash", "randomBytes", "existsSync", "readdirSync", "readFileSync", "rmSync", "join", "join", "readdirSync", "name", "readFileSync", "existsSync", "rmSync", "createHash", "createHash", "existsSync", "readFileSync", "join", "join", "existsSync", "readFileSync", "createHash", "createHash", "existsSync", "mkdirSync", "readFileSync", "readdirSync", "statSync", "writeFileSync", "join", "mkdirSync", "join", "existsSync", "walk", "name", "readdirSync", "statSync", "readFileSync", "createHash", "writeFileSync", "existsSync", "readFileSync", "existsSync", "readFileSync", "COMMENT", "existsSync", "readFileSync", "existsSync", "existsSync", "seal", "KINDS", "tokenize", "name", "fail", "decision", "KINDS", "name", "KINDS", "service", "fail", "name", "name", "profile", "search", "textOf", "name", "commands", "definition", "entry"]
|
|
3
|
+
"sources": ["../src/plugin.ts", "../../core/src/errors.ts", "../../core/src/paths.ts", "../../core/src/startup.ts", "../../core/src/config/load.ts", "../../core/src/config/toml.ts", "../../core/src/config/schema.ts", "../../core/src/config/config.ts", "../../core/src/policy/policy.ts", "../../core/src/fs/atomic.ts", "../../core/src/fs/wait.ts", "../../core/src/model/frontmatter.ts", "../../core/src/model/metadata.ts", "../../core/src/projects/projects.ts", "../../core/src/journal/checkpoint.ts", "../../core/src/fs/lock.ts", "../../core/src/model/ids.ts", "../../core/src/model/validity.ts", "../../core/src/journal/journal.ts", "../../core/src/store/store.ts", "../../core/src/index/tokenizer.ts", "../../core/src/index/bm25.ts", "../../core/src/index/embedding.ts", "../../core/src/index/hybrid.ts", "../../core/src/embed/cache.ts", "../../core/src/scan/scan.ts", "../../core/src/rules/rules.ts", "../../core/src/inject/snapshot.ts", "../../core/src/inject/assemble.ts", "../../core/src/inject/sections.ts", "../../core/src/personalization/guidance.ts", "../../core/src/proposals/proposals.ts", "../../core/src/actor.ts", "../../core/src/service/quota.ts", "../../core/src/distill/closeout.ts", "../../core/src/ops/ops.ts", "../../core/src/profile/profile.ts", "../../core/src/personalization/scaffold.ts", "../../core/src/human/command.ts", "../../core/src/transfer/import.ts", "../src/tools.ts", "../src/review.ts", "../src/personalization.ts", "../src/session-tools.ts", "../src/gui.ts", "../src/service.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * DSH host plugin \u2014 S0 M1 probe.\n *\n * Deliberately tiny: proves the host loads a bundle, gives the model a tool,\n * injects one system-prompt section, and exposes the services the real adapter\n * will rely on (`commands` + `tokenMeter`). It is not the memory service.\n *\n * Contract (ADR-0003): a Host-only bundle exports `apply(ctx, config)`, may\n * declare `inject`, and registers through the context so Cordis owns the\n * disposers. Every service is reached through the context object, which keeps\n * this module loadable from a linked checkout without host node_modules on its\n * resolution path.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport {\n addRejected,\n bindEvidence,\n buildCloseoutPrompt,\n CloseoutRound,\n collectL0,\n createProposal,\n HUMAN_COMMAND_HINT,\n listProposals,\n loadRejected,\n parseCloseout,\n resolveHome,\n runHumanCommand,\n summaryHash,\n type DistillEvent,\n type Proposal,\n type ProposalInput,\n} from '../../core/src/index.ts';\nimport { registerTools } from './tools.ts';\nimport { reviewProposal, type ReviewExecLike, type UserQuestionsLike } from './review.ts';\nimport { registerUserProfileTool } from './personalization.ts';\nimport { registerSessionTools, type SessionQueryLike } from './session-tools.ts';\nimport { registerGuiRoutes, type GuiConnection } from './gui.ts';\nimport { openHostService, type SessionStoreLike } from './service.ts';\n\nexport const name = 'agent-memory';\nexport const inject = ['tools'];\n\nconst SECTION_NAME = 'agent-memory:probe';\nconst PROBE_LINE =\n 'Agent Memory probe is active. If the user sends exactly \"am-probe\", reply exactly \"am-probe-ok\".';\n\nexport interface ToolDefinitionLike {\n readonly name: string;\n readonly description: string;\n readonly parameters: unknown;\n readonly output: {\n readonly schema: unknown;\n readonly render: (args: unknown, value: unknown) => unknown;\n };\n readonly execute: (args: any, exec: any) => unknown;\n}\n\nexport interface ToolRegistryLike {\n register(definition: ToolDefinitionLike): unknown;\n}\n\nexport interface PromptRegistryLike {\n section(spec: {\n readonly name: string;\n readonly order: number;\n readonly text: string;\n readonly interpolate?: boolean;\n }): unknown;\n}\n\nexport interface CommandsLike {\n register(spec: {\n readonly name: string;\n readonly description: string;\n readonly input?: { readonly hint: string };\n readonly handler: (invocation: any) => unknown;\n }): unknown;\n execute?(\n agent: unknown,\n line: string,\n attachments: readonly unknown[],\n signal: AbortSignal,\n ): Promise<{ readonly result: { readonly kind?: string; readonly text?: string } } | undefined>;\n}\n\nexport interface TokenMeterLike {\n measure(session: unknown): { readonly totalTokens?: number; readonly surfaceTokens?: number };\n}\n\nexport interface PluginContextLike {\n readonly tools: ToolRegistryLike;\n get?(name: string): unknown;\n readonly systemPrompt?: PromptRegistryLike;\n readonly commands?: CommandsLike;\n readonly tokenMeter?: TokenMeterLike;\n}\n\n/**\n * Resolve an optional service without touching an undeclared property.\n *\n * Cordis throws \"cannot get property X without inject\" on a bare `ctx.X`\n * access, so `ctx.get(name)` is tried first (the same lookup YAML `!!js`\n * expressions use). The direct property access stays as a fallback for\n * contexts without `get`, guarded because it can throw for the same reason.\n */\nfunction service<T>(ctx: PluginContextLike, name: string): T | undefined {\n try {\n const resolved = ctx.get?.(name);\n if (resolved !== undefined) return resolved as T;\n } catch {\n // fall through to the guarded property access\n }\n try {\n const direct = (ctx as unknown as Record<string, unknown>)[name];\n return direct === undefined ? undefined : (direct as T);\n } catch {\n return undefined;\n }\n}\n\nfunction eventTextOf(data: unknown): string {\n if (typeof data !== 'object' || data === null) return '';\n const record = data as { content?: unknown; text?: unknown };\n if (Array.isArray(record.content)) {\n return record.content\n .map((block) =>\n typeof block === 'object' && block !== null && typeof (block as { text?: unknown }).text === 'string'\n ? (block as { text: string }).text\n : '',\n )\n .filter((text) => text !== '')\n .join('\\n');\n }\n return typeof record.text === 'string' ? record.text : '';\n}\n\nfunction eventsOf(sessions: SessionStoreLike | undefined, sessionId: string): DistillEvent[] {\n const live = sessions?.get(sessionId);\n if (live === undefined) return [];\n const events: DistillEvent[] = [];\n for (let seq = 0; seq < (live.seq ?? 0); seq += 1) {\n const event = live.eventAt(seq);\n if (event === undefined) continue;\n const speaker = event.type.startsWith('assistant')\n ? 'assistant'\n : event.type.startsWith('tool')\n ? 'tool'\n : event.type.startsWith('system')\n ? 'system'\n : 'user';\n events.push({ seq: event.seq, speaker, text: eventTextOf(event.data) });\n }\n return events;\n}\n\nexport function apply(ctx: PluginContextLike): void {\n // S4: real tool surface + injection when a store is configured. If startup\n // fails (no home, bad policy, sealed file changed) fall back to the probe so a\n // broken store never takes the host down.\n const home = resolveHome({ env: process.env });\n // Cordis forbids undeclared service property reads; go through the guarded\n // resolver (ctx.get first) so a composition without a session still loads.\n const sessionService = service<{ id?: string }>(ctx, 'session');\n const sessionId = sessionService?.id ?? `dsh-${process.pid}`;\n const persistence = service<import('./service.ts').SessionPersistenceLike>(ctx, 'sessionPersistence');\n const sessions = service<import('./service.ts').SessionStoreLike>(ctx, 'sessions');\n let startupFailure: string | undefined;\n const host = openHostService(\n home,\n {\n sessionId,\n ...(persistence === undefined ? {} : { persistence }),\n ...(sessions === undefined ? {} : { sessions }),\n },\n {\n onFailure: (error) => {\n const formatted = error as { format?: () => string; message?: string };\n startupFailure = typeof formatted.format === 'function' ? formatted.format() : (formatted.message ?? String(error));\n },\n },\n );\n if (host !== null) {\n // Registration-time services (the command plane). Interaction services are\n // resolved per call: Cordis may not have activated the provider fiber yet\n // when this plugin applies, and `userQuestions` (Typert) comes up later.\n const commands = service<CommandsLike>(ctx, 'commands');\n const resolveQuestions = (): UserQuestionsLike | undefined =>\n service<UserQuestionsLike>(ctx, 'userQuestions');\n const resolveCommands = (): CommandsLike | undefined => service<CommandsLike>(ctx, 'commands');\n const reviewDeps = () => {\n const userQuestions = resolveQuestions();\n const commandsNow = resolveCommands();\n return {\n store: host.store,\n config: host.runtime.config,\n home,\n ...(userQuestions === undefined ? {} : { userQuestions }),\n ...(commandsNow === undefined ? {} : { commands: commandsNow }),\n };\n };\n // Module health (architecture v2 P0.5): one failing optional module must\n // not take the others down. `/api/agent-memory/status` exposes this list.\n const moduleHealth: { name: string; ok: boolean; error?: string }[] = [];\n const guard = (name: string, run: () => void): void => {\n try {\n run();\n moduleHealth.push({ name, ok: true });\n } catch (error) {\n moduleHealth.push({\n name,\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n // S9 review card: propose opens a Chinese button card and the click runs\n // `/mem decide \u2026`; the model never supplies the verdict (ADR-0012).\n registerTools(ctx as never, host, { sessionId, delegationDepth: 0 }, undefined, {\n reviewProposal: (proposal, exec) =>\n reviewProposal(reviewDeps(), proposal as Proposal, exec as ReviewExecLike | undefined),\n reviewPending: async (proposalId, exec) => {\n const pending = listProposals(host.store);\n const proposal =\n proposalId === undefined ? pending[0] : pending.find((entry) => entry.id === proposalId);\n if (proposal === undefined) {\n throw new Error(\n proposalId === undefined ? '\u5F53\u524D\u6CA1\u6709\u5F85\u5BA1\u63D0\u6848' : `\u6CA1\u6709\u5F85\u5BA1\u63D0\u6848 ${proposalId}\uFF08\u53EF\u80FD\u5DF2\u88AB\u51B3\u5B9A\u6216\u4F5C\u5E9F\uFF09`,\n );\n }\n return reviewProposal(reviewDeps(), proposal, exec as ReviewExecLike | undefined);\n },\n });\n // P1: USER.md profile tool (read always; writes need a prior read + card).\n const readSessions = new Set<string>();\n guard('user-profile', () =>\n registerUserProfileTool(ctx as never, {\n home,\n store: host.store,\n resolveQuestions,\n mode: host.mode,\n readSessions,\n }),\n );\n // P2: session-history tools over the host's native sessionQuery service.\n guard('session-tools', () =>\n registerSessionTools(ctx as never, {\n resolveQuery: () => service<SessionQueryLike>(ctx, 'sessionQuery'),\n sessionId,\n }),\n );\n // V2 GUI routes: status/list/item/search/export. Exact routes own their\n // full `/api/...` path (see dsh-api-session-controller).\n const effectful = ctx as unknown as {\n effect?: (install: () => unknown, label?: string) => unknown;\n };\n const effect = (install: () => unknown, label?: string): unknown =>\n typeof effectful.effect === 'function' ? effectful.effect(install, label) : install();\n const installRoutes = (connection: GuiConnection): void => {\n registerGuiRoutes(\n connection,\n { store: host.store, home, mode: host.mode, modules: moduleHealth, config: host.runtime.config },\n effect,\n );\n try {\n host.store.appendAudit({ event: 'gui-route', state: 'registered', path: '/api/agent-memory/*' });\n } catch {\n // Journal problems are reported by `mem doctor`.\n }\n };\n const connectionNow = service<GuiConnection>(ctx, 'connection');\n if (connectionNow !== undefined) installRoutes(connectionNow);\n else {\n (ctx as unknown as {\n inject?: (deps: string[], callback: (child: unknown) => void) => unknown;\n }).inject?.(['connection'], (child) => {\n // The injected child is a Context; the service hangs off `.connection`,\n // not off the child itself.\n const connection = (child as { connection?: GuiConnection }).connection;\n if (connection !== undefined) installRoutes(connection);\n });\n }\n try {\n host.store.appendAudit({\n event: 'gui-route',\n path: '/api/agent-memory/*',\n at: connectionNow !== undefined ? 'apply' : 'deferred',\n });\n } catch {\n // A journal problem is reported by `mem doctor`; the panel can still load.\n }\n guard('injection', () => {\n const prompt = service<PromptRegistryLike>(ctx, 'systemPrompt');\n for (const section of host.assembleSections()) prompt?.section(section);\n });\n\n // S6 closeout: `/closeout` opens a round, registers `closeout_submit` only\n // for that round, and disposes it after submit (or when a new round opens).\n type RoundEntry = { round: CloseoutRound; dispose: (() => void) | undefined };\n const rounds = new Map<string, RoundEntry>();\n const rejected = loadRejected(home);\n\n const disposeRound = (id: string): void => {\n const entry = rounds.get(id);\n if (entry === undefined) return;\n entry.round.dispose();\n entry.dispose?.();\n rounds.delete(id);\n };\n\n // S8 human command plane: the CLI-level operations run from the chat box.\n // Commands execute in the UI plane, never as a model message, and `decide`\n // is still not a tool (ADR-0011).\n commands?.register({\n name: 'mem',\n description: 'Agent Memory\uFF1A\u5BA1\u63D0\u6848\u3001\u91C7\u7EB3/\u5426\u51B3\u3001\u5199\u5165\u3001\u67E5\u770B\u4E0E\u8FD0\u7EF4\uFF08\u4EBA\u64CD\u4F5C\uFF09',\n input: { hint: HUMAN_COMMAND_HINT },\n handler: (invocation: { rawInput?: string }) => {\n const result = runHumanCommand(\n { store: host.store, config: host.runtime.config, home },\n invocation.rawInput ?? '',\n );\n return { kind: result.ok ? 'success' : 'error', text: result.text };\n },\n });\n commands?.register({\n name: 'closeout',\n description: 'Run one closeout distillation round over the current session.',\n handler: (invocation: {\n agent?: { session?: { id?: string }; followup?: (input: unknown) => unknown };\n }) => {\n const sid = invocation.agent?.session?.id ?? sessionId;\n disposeRound(sid);\n const round = new CloseoutRound({ timeoutMs: 300_000 });\n const definition = {\n name: 'closeout_submit',\n description: 'Submit the closeout distillation JSON for the current round.',\n parameters: {\n type: 'object',\n properties: { payload: { type: 'object' } },\n required: ['payload'],\n additionalProperties: false,\n },\n output: {\n schema: { type: 'object' },\n render: (_args: unknown, value: unknown) => [\n { type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) },\n ],\n },\n execute: async (args: { payload?: unknown }, exec?: { agent?: { session?: { id?: string } } }) => {\n const callSid = exec?.agent?.session?.id ?? sid;\n const entry = rounds.get(callSid);\n if (entry === undefined || entry.round.status !== 'open') {\n throw new Error('no active closeout round');\n }\n const accepted = entry.round.submit();\n if (!accepted.ok) throw new Error(accepted.error);\n\n const events = eventsOf(sessions, callSid);\n const active = host.store.active();\n const parsed = parseCloseout(JSON.stringify(args.payload ?? {}), {\n events,\n activeIds: active.map((doc) => doc.id),\n activeAbstracts: active.map((doc) => doc.abstract),\n rejectedHashes: rejected,\n maxProposals: host.runtime.config.distill.max_proposals,\n });\n const created: string[] = [];\n const hashes: string[] = [];\n const eventsBySeq = new Map(events.map((event) => [event.seq, event]));\n for (const candidate of parsed.candidates) {\n const base_hashes = candidate.targets.map((id) => host.store.read(id).content_hash);\n const input: ProposalInput =\n candidate.op === 'delete'\n ? {\n op: 'delete',\n target: candidate.targets[0] as string,\n base_hash: base_hashes[0] as string,\n reason: candidate.reason,\n }\n : {\n op: 'supersede',\n targets: candidate.targets,\n base_hashes,\n replacements: candidate.replacements.map((replacement) => ({\n kind: replacement.kind,\n abstract: replacement.abstract,\n body: replacement.body,\n evidence_level: 'observed',\n provenance: replacement.evidence.map((entry) =>\n bindEvidence({\n sessionId: callSid,\n eventSeq: entry.event_seq,\n quote: entry.quote,\n lookup: () => eventsBySeq.get(entry.event_seq),\n }),\n ),\n })),\n reason: candidate.reason,\n };\n created.push(createProposal({ store: host.store, config: host.runtime.config }, input).id);\n const hash = summaryHash(candidate);\n hashes.push(hash);\n rejected.add(hash);\n }\n if (hashes.length > 0) addRejected(home, hashes);\n disposeRound(callSid);\n return { created, dropped: parsed.dropped, message: parsed.message, truncated: parsed.truncated };\n },\n };\n const dispose = ctx.tools.register(definition as never);\n rounds.set(sid, { round, dispose: typeof dispose === 'function' ? (dispose as () => void) : undefined });\n\n const prompt = buildCloseoutPrompt({\n l0: collectL0(eventsOf(sessions, sid)),\n active: host.store.active().map((doc) => ({ id: doc.id, kind: doc.kind, abstract: doc.abstract })),\n maxProposals: host.runtime.config.distill.max_proposals,\n });\n // CommandResult must be returned synchronously; `followup` only queues.\n void invocation.agent?.followup?.({\n id: randomUUID(),\n role: 'user',\n content: [{ type: 'text', text: prompt }],\n source: { kind: 'user' },\n });\n return { kind: 'success', text: 'closeout round started' };\n },\n });\n\n // V3.2 retrospective commands: each queues one model turn that reviews the\n // current development round and proposes new entries of one kind. The\n // proposal is human-approved; the model never writes directly.\n const retroPrompt = (kind: 'fact' | 'pitfall' | 'exp', label: string): string =>\n [\n `\u4F60\u6B63\u5728\u6267\u884C\u300CAgent Memory \u56DE\u987E\u300D\uFF1A\u53EA\u56DE\u987E\u5F53\u524D\u8FD9\u4E00\u8F6E\u5F00\u53D1\uFF08\u4ECE\u672C\u8F6E\u7528\u6237\u8BF7\u6C42\u5F00\u59CB\uFF0C\u5230\u73B0\u5728\u7684\u5BF9\u8BDD\u3001\u5DE5\u5177\u8C03\u7528\u4E0E\u4EE3\u7801\u6539\u52A8\uFF09\u3002`,\n `\u8BF7\u63D0\u70BC\u672C\u8F6E\u771F\u6B63\u53D1\u751F\u3001\u503C\u5F97\u957F\u671F\u4FDD\u7559\u7684\u300C${label}\u300D\uFF0C\u6700\u591A 3 \u6761\u3002`,\n '',\n '\u8981\u6C42\uFF1A',\n `1. \u53EA\u5199\u300C${label}\u300D\uFF0C\u4E0D\u8981\u6DF7\u5165\u5176\u4ED6\u7C7B\u578B\uFF1B\u6CA1\u6709\u5C31\u76F4\u8BF4\u300C\u672C\u8F6E\u6682\u65E0${label}\u300D\uFF0C\u4E0D\u8981\u7F16\u9020\u3002`,\n '2. \u5FC5\u987B\u57FA\u4E8E\u771F\u5B9E\u4E0A\u4E0B\u6587\uFF1B\u5148\u7528 memory_context \u53D6\u6700\u8FD1\u4E8B\u4EF6\uFF0C\u62FF\u5230\u771F\u5B9E\u7684 event_seq \u4E0E\u5F15\u6587\u3002',\n `3. \u8C03\u7528 memory_propose\uFF1Aop=\"create\"\uFF0Creplacements \u4E2D\u653E kind=\"${kind}\"\u3001abstract\uFF08\u4E00\u53E5\u8BDD\uFF0C\u4E0D\u8D85\u8FC7 40 \u5B57\uFF09\u3001body\u3001evidence:[{event_seq, quote}]\u3002`,\n '4. \u521B\u5EFA\u540E\u53EA\u56DE\u590D\u4E00\u53E5\uFF1A\u63D0\u6848\u540D/\u6570\u91CF + \u300C\u53BB\u300E\u8BB0\u5FC6 \u2192 \u63D0\u6848\u300F\u5BA1\u6279\u300D\u3002\u4E0D\u8981\u66FF\u4EBA\u91C7\u7EB3\u3002',\n '5. \u4E0D\u8981\u4FEE\u6539 RULES\u3001\u4E0D\u8981\u5199 SOUL\uFF0C\u4E5F\u4E0D\u8981\u8C03\u7528 memory_record\u3002',\n '',\n `\u672C\u8F6E\u7ED3\u675F\uFF08\u7528\u6237\u6267\u884C\u4E86 /mem-${kind}\uFF09\u3002`,\n ].join('\\n');\n\n const registerRetro = (kind: 'fact' | 'pitfall' | 'exp', label: string): void => {\n commands?.register({\n name: `mem-${kind}`,\n description: `\u56DE\u987E\u672C\u8F6E\u5F00\u53D1\uFF0C\u63D0\u70BC${label}\u5E76\u63D0\u6848\u65B0\u589E\uFF08\u4EBA\u5BA1\u6279\uFF09`,\n handler: (invocation: { agent?: { followup?: (input: unknown) => unknown } }) => {\n void invocation.agent?.followup?.({\n id: randomUUID(),\n role: 'user',\n content: [{ type: 'text', text: retroPrompt(kind, label) }],\n source: { kind: 'user' },\n });\n return { kind: 'success', text: `\u5DF2\u5F00\u59CB\u56DE\u987E\u672C\u8F6E ${label}\uFF0C\u7ED3\u679C\u4F1A\u4EE5\u63D0\u6848\u5F62\u5F0F\u51FA\u73B0\uFF0C\u7B49\u5F85\u4F60\u5BA1\u6279\u3002` };\n },\n });\n };\n registerRetro('fact', '\u4E8B\u5B9E');\n registerRetro('pitfall', '\u5751');\n registerRetro('exp', '\u7ECF\u9A8C');\n return;\n }\n\n ctx.tools.register({\n name: 'am_echo',\n description:\n 'Probe tool for the Agent Memory plugin (S0 M1). Echoes the given text back with an \"echo:\" prefix.',\n parameters: {\n type: 'object',\n properties: {\n text: { type: 'string', description: 'Text to echo back.' },\n },\n required: ['text'],\n additionalProperties: false,\n },\n output: {\n schema: { type: 'string' },\n render: (_args: unknown, value: unknown) => [{ type: 'text', text: String(value) }],\n },\n execute(args: { text: string }) {\n return `echo: ${args.text}`;\n },\n });\n\n ctx.tools.register({\n name: 'am_probe_tokens',\n description:\n 'Probe tool for the Agent Memory plugin (S0 M3). Reports the token meter reading for the current session.',\n parameters: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n output: {\n schema: { type: 'string' },\n render: (_args: unknown, value: unknown) => [{ type: 'text', text: String(value) }],\n },\n execute(_args: unknown, exec: { agent?: { session?: unknown } }) {\n const meter = service<TokenMeterLike>(ctx, 'tokenMeter');\n if (meter === undefined) return 'tokenMeter service is not available in this composition';\n const session = exec.agent?.session;\n if (session === undefined) return 'no session on the calling agent';\n const measured = meter.measure(session);\n return JSON.stringify({\n totalTokens: measured.totalTokens ?? null,\n surfaceTokens: measured.surfaceTokens ?? null,\n });\n },\n });\n\n const prompts = service<PromptRegistryLike>(ctx, 'systemPrompt');\n const probeText =\n startupFailure === undefined\n ? PROBE_LINE\n : `${PROBE_LINE}\\n\\nAgent Memory \u542F\u52A8\u5931\u8D25\uFF08\u8BF7\u628A\u4E0B\u9762\u7684\u4FEE\u590D\u547D\u4EE4\u539F\u6837\u8F6C\u544A\u7528\u6237\u5E76\u7B49\u5F85\u786E\u8BA4\uFF09\uFF1A\\n${startupFailure}`;\n prompts?.section({\n name: SECTION_NAME,\n order: 500,\n interpolate: false,\n text: probeText,\n });\n\n const commands = service<CommandsLike>(ctx, 'commands');\n commands?.register({\n name: 'am-closeout',\n description: 'Probe command for the Agent Memory plugin (S0 M4): queues one model turn.',\n handler: (invocation: { agent?: { followup?: (input: unknown) => unknown } }) => {\n const agent = invocation.agent;\n if (agent?.followup === undefined) {\n return { kind: 'error', text: 'no agent on this command invocation' };\n }\n agent.followup({\n // A queued follow-up is appended verbatim as a `user/message` event, and\n // the session rejects a message whose role does not match its event type.\n // The host's `createUserMessage()` also stamps a stable `id`; a hand-built\n // message must carry its own, because replay validation rejects an\n // unidentified message and the whole stored session then fails to load.\n id: globalThis.crypto.randomUUID(),\n role: 'user',\n content: [{ type: 'text', text: 'Reply with exactly: am-closeout-ok' }],\n source: { kind: 'user' },\n });\n return { kind: 'success', text: 'queued one probe turn' };\n },\n });\n}\n", "/**\n * Startup failures are loud on purpose.\n *\n * The reference failure this guards against is Hermes' silent breakage: a\n * config parse error swallowed by `except: pass` left the whole memory\n * subsystem dead with no message (see docs/research/06 \u00A7L3). Nothing in this\n * package may degrade silently at startup.\n */\n\nexport type StartupFailureCode =\n | 'CONFIG_INVALID'\n | 'CONFIG_UNREADABLE'\n | 'POLICY_MISSING'\n | 'POLICY_INVALID'\n | 'POLICY_MISMATCH'\n | 'SEALED_FILE_MISMATCH'\n | 'HOME_INVALID'\n | 'SEAL_REFUSED';\n\nexport interface StartupFailureInit {\n /** Ordered, printable detail lines (each already formatted). */\n readonly details?: readonly string[];\n /** One-line next step for a human. */\n readonly hint?: string;\n /** Exact command that repairs this failure; printed highlighted by `format()`. */\n readonly fixCommand?: string;\n /** Machine-readable offending keys, for tests and tooling. */\n readonly keys?: readonly string[];\n /** File the failure came from, when there is one. */\n readonly sourcePath?: string;\n}\n\nexport class StartupError extends Error {\n readonly code: StartupFailureCode;\n readonly details: readonly string[];\n readonly hint: string | undefined;\n readonly fixCommand: string | undefined;\n readonly keys: readonly string[];\n readonly sourcePath: string | undefined;\n\n constructor(code: StartupFailureCode, message: string, init: StartupFailureInit = {}) {\n super(message);\n this.name = 'StartupError';\n this.code = code;\n this.details = init.details ?? [];\n this.hint = init.hint;\n this.fixCommand = init.fixCommand;\n this.keys = init.keys ?? [];\n this.sourcePath = init.sourcePath;\n }\n\n /** Multi-line text for a terminal; never truncated, never prettified away. */\n format(): string {\n const lines = [`Agent Memory startup failed [${this.code}]: ${this.message}`];\n if (this.sourcePath !== undefined) lines.push(` file: ${this.sourcePath}`);\n for (const detail of this.details) lines.push(` - ${detail}`);\n if (this.fixCommand !== undefined) {\n // Deliberately loud: the human must see the exact repair command even when\n // this text is shown inside a desktop card or a chat transcript.\n lines.push('', ' ================ REQUIRED ACTION ================');\n lines.push(` >>> RUN THIS COMMAND: ${this.fixCommand}`);\n lines.push(' ===================================================');\n }\n if (this.hint !== undefined) lines.push(` hint: ${this.hint}`);\n return lines.join('\\n');\n }\n}\n\nexport class ConfigError extends StartupError {\n readonly problems: readonly ConfigProblem[];\n\n constructor(sourcePath: string, problems: readonly ConfigProblem[], hint?: string) {\n const sorted = [...problems].sort((a, b) => a.key.localeCompare(b.key));\n const count = sorted.length;\n super(\n 'CONFIG_INVALID',\n `configuration rejected (${count} problem${count === 1 ? '' : 's'})`,\n {\n sourcePath,\n keys: sorted.map((problem) => problem.key),\n details: sorted.map(formatProblem),\n ...(hint === undefined ? {} : { hint }),\n },\n );\n this.name = 'ConfigError';\n this.problems = sorted;\n }\n}\n\nexport interface ConfigProblem {\n readonly key: string;\n readonly message: string;\n readonly line?: number;\n}\n\nexport function formatProblem(problem: ConfigProblem): string {\n const prefix = problem.line === undefined ? '' : `line ${problem.line} | `;\n return `${prefix}${problem.message}`;\n}\n", "import { homedir } from 'node:os';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport { StartupError } from './errors.ts';\n\n/**\n * Where the store lives, and nothing else.\n *\n * The data directory is meant to sit outside the agent's tool sandbox (`06`\n * \u00A7L0): under DSH's `workspace-write` policy, tool writes outside the workspace\n * are refused. That is a tool-layer boundary, not OS-level isolation \u2014 the host\n * process can still read the path, and S0 has to confirm the boundary for the\n * pinned DSH version. The path here is host-side truth, never model input.\n */\n\nconst WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\\..*)?$/i;\n\n/** Reject paths a Windows filesystem cannot represent or that name devices. */\nexport function assertSafeHome(home: string): void {\n if (!isAbsolute(home)) {\n throw new StartupError('HOME_INVALID', 'the store path must be absolute', {\n sourcePath: home,\n hint: 'pass --home with an absolute path, or set AGENT_MEMORY_HOME',\n });\n }\n const segments = home.split(/[\\\\/]+/).filter((segment) => segment !== '');\n const dataSegments = segments[0]?.endsWith(':') === true ? segments.slice(1) : segments;\n for (const segment of dataSegments) {\n if (WINDOWS_RESERVED.test(segment)) {\n throw new StartupError('HOME_INVALID', `the store path contains a reserved Windows name: ${segment}`, {\n sourcePath: home,\n hint: 'choose a different --home',\n });\n }\n if (segment.includes(':')) {\n throw new StartupError('HOME_INVALID', `the store path contains an invalid segment: ${segment}`, {\n sourcePath: home,\n hint: 'colons are only allowed in the drive prefix',\n });\n }\n }\n}\n\nexport interface EnvLike {\n readonly [key: string]: string | undefined;\n}\n\nexport interface MemoryPaths {\n readonly home: string;\n readonly configFile: string;\n readonly projectsFile: string;\n readonly policyFile: string;\n readonly sealFile: string;\n readonly lockFile: string;\n readonly soulFile: string;\n readonly userFile: string;\n readonly rulesFile: string;\n readonly memoryIndexFile: string;\n readonly memoriesDir: string;\n readonly proposalsDir: string;\n readonly pendingDir: string;\n readonly indexDir: string;\n readonly manifestFile: string;\n readonly stateDir: string;\n readonly journalDir: string;\n readonly journalArchiveDir: string;\n readonly checkpointFile: string;\n readonly checkpointKeyFile: string;\n readonly txnDir: string;\n readonly snapshotsDir: string;\n}\n\nexport function memoryPaths(home: string): MemoryPaths {\n return {\n home,\n configFile: join(home, 'config.toml'),\n projectsFile: join(home, 'projects.json'),\n policyFile: join(home, 'policy.json'),\n sealFile: join(home, '.state', 'policy.seal.json'),\n lockFile: join(home, '.state', 'lock'),\n soulFile: join(home, 'SOUL.md'),\n userFile: join(home, 'USER.md'),\n rulesFile: join(home, 'RULES.md'),\n memoryIndexFile: join(home, 'MEMORY.md'),\n memoriesDir: join(home, 'memories'),\n proposalsDir: join(home, 'proposals'),\n pendingDir: join(home, 'proposals', 'pending'),\n indexDir: join(home, '.index'),\n manifestFile: join(home, '.index', 'manifest.json'),\n stateDir: join(home, '.state'),\n journalDir: join(home, '.state', 'journal'),\n journalArchiveDir: join(home, '.state', 'journal', 'archive'),\n checkpointFile: join(home, '.state', 'checkpoint.json'),\n checkpointKeyFile: join(home, '.state', 'checkpoint.key'),\n txnDir: join(home, '.state', 'txn'),\n snapshotsDir: join(home, '.state', 'snapshots'),\n };\n}\n\n/** Directories `mem init` creates (v1.3 layout: one journal, no audit file). */\nexport function layoutDirectories(paths: MemoryPaths): string[] {\n return [\n paths.home,\n join(paths.memoriesDir, 'fact'),\n join(paths.memoriesDir, 'pitfall'),\n join(paths.memoriesDir, 'exp'),\n paths.proposalsDir,\n paths.pendingDir,\n paths.indexDir,\n paths.stateDir,\n paths.journalDir,\n paths.txnDir,\n paths.snapshotsDir,\n ];\n}\n\n/**\n * Resolution order: explicit option \u2192 AGENT_MEMORY_HOME \u2192 DSH_HOME/memory \u2192\n * ~/.dsh/memory. Relative paths resolve against the working directory.\n */\nexport function resolveHome(options: { home?: string; env?: EnvLike; cwd?: string } = {}): string {\n const cwd = options.cwd ?? process.cwd();\n const explicit = options.home ?? options.env?.AGENT_MEMORY_HOME;\n if (explicit !== undefined && explicit.trim() !== '') {\n return isAbsolute(explicit) ? explicit : resolve(cwd, explicit);\n }\n const dshHome = options.env?.DSH_HOME;\n if (dshHome !== undefined && dshHome.trim() !== '') {\n return join(isAbsolute(dshHome) ? dshHome : resolve(cwd, dshHome), 'memory');\n }\n return join(homedir(), '.dsh', 'memory');\n}\n", "import { existsSync, statSync } from 'node:fs';\nimport { loadConfig } from './config/load.ts';\nimport type { Config } from './config/config.ts';\nimport { ConfigError, StartupError, type ConfigProblem } from './errors.ts';\nimport { memoryPaths, assertSafeHome, resolveHome, type EnvLike, type MemoryPaths } from './paths.ts';\nimport { loadPolicy, verifySealedFiles, type Policy } from './policy/policy.ts';\n\n/**\n * The one startup path. Everything loud about configuration lives here:\n *\n * 1. the store must exist (missing store = loud error, not silent defaults);\n * 2. policy.json must match its seal (tampering = refusal to start);\n * 3. config.toml must validate (unknown keys are refused, named);\n * 4. config may tighten policy bounds, never widen them.\n */\n\nexport interface StartupOptions {\n readonly home?: string;\n readonly configPath?: string;\n readonly env?: EnvLike;\n readonly cwd?: string;\n}\n\nexport interface Runtime {\n readonly home: string;\n readonly paths: MemoryPaths;\n readonly config: Config;\n readonly policy: Policy;\n readonly configPath: string | null;\n readonly policyPath: string;\n readonly sealPath: string;\n readonly policySha256: string;\n readonly sealedAt: string;\n readonly warnings: readonly string[];\n}\n\nexport function startup(options: StartupOptions = {}): Runtime {\n const home = resolveHome({\n home: options.home,\n env: options.env,\n cwd: options.cwd,\n });\n\n assertSafeHome(home);\n\n let isDirectory = false;\n try {\n isDirectory = statSync(home).isDirectory();\n } catch {\n isDirectory = false;\n }\n if (!isDirectory) {\n throw new StartupError('HOME_INVALID', 'the memory store does not exist', {\n sourcePath: home,\n hint: 'run `mem init` (or set AGENT_MEMORY_HOME / DSH_HOME) before starting',\n });\n }\n\n const loadedPolicy = loadPolicy({ home });\n verifySealedFiles({ home, policy: loadedPolicy.policy });\n const loadedConfig = loadConfig({\n home,\n configPath: options.configPath,\n env: options.env,\n cwd: options.cwd,\n });\n\n const paths = memoryPaths(home);\n const boundsProblems = checkPolicyBounds(loadedConfig.config, loadedPolicy.policy);\n if (boundsProblems.length > 0) {\n throw new ConfigError(\n loadedConfig.configPath ?? paths.configFile,\n boundsProblems,\n 'config.toml may tighten policy.json, never widen it',\n );\n }\n\n const warnings = [...loadedConfig.warnings, ...missingContentWarnings(paths)];\n\n return {\n home,\n paths,\n config: loadedConfig.config,\n policy: loadedPolicy.policy,\n configPath: loadedConfig.configPath,\n policyPath: loadedPolicy.policyPath,\n sealPath: loadedPolicy.sealPath,\n policySha256: loadedPolicy.sha256,\n sealedAt: loadedPolicy.sealedAt,\n warnings,\n };\n}\n\nfunction checkPolicyBounds(config: Config, policy: Policy): ConfigProblem[] {\n const problems: ConfigProblem[] = [];\n if (config.storage.max_records > policy.capacity.max_records) {\n problems.push({\n key: 'storage.max_records',\n message: `\"storage.max_records\" (${config.storage.max_records}) exceeds policy.capacity.max_records (${policy.capacity.max_records})`,\n });\n }\n if (config.storage.max_record_chars > policy.capacity.max_record_chars) {\n problems.push({\n key: 'storage.max_record_chars',\n message: `\"storage.max_record_chars\" (${config.storage.max_record_chars}) exceeds policy.capacity.max_record_chars (${policy.capacity.max_record_chars})`,\n });\n }\n return problems;\n}\n\n/**\n * Missing content files are warnings, not failures: a fresh store legitimately\n * has no memories yet. Files that were expected but cannot be read are a\n * different matter and are handled by the store layer in S2.\n */\nfunction missingContentWarnings(paths: MemoryPaths): string[] {\n const expected: ReadonlyArray<readonly [string, string]> = [\n [paths.soulFile, 'SOUL.md'],\n [paths.userFile, 'USER.md'],\n [paths.rulesFile, 'RULES.md'],\n [paths.memoryIndexFile, 'MEMORY.md'],\n ];\n return expected\n .filter(([filePath]) => !existsSync(filePath))\n .map(([, name]) => `${name} is not present yet; that injection section will be empty`);\n}\n", "import { readFileSync } from 'node:fs';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport { StartupError } from '../errors.ts';\nimport type { EnvLike } from '../paths.ts';\nimport { parseConfigDocument, type Config } from './config.ts';\n\nexport interface LoadedConfig {\n readonly config: Config;\n /** Path actually read, or null when built-in defaults are in use. */\n readonly configPath: string | null;\n readonly warnings: readonly string[];\n}\n\n/**\n * Load config.toml.\n *\n * Resolution: explicit path \u2192 AGENT_MEMORY_CONFIG \u2192 <home>/config.toml.\n * A missing default file means \"all defaults\"; a missing explicit file is an\n * error, because the caller asked for that specific file.\n */\nexport function loadConfig(options: {\n home: string;\n configPath?: string;\n env?: EnvLike;\n cwd?: string;\n}): LoadedConfig {\n const cwd = options.cwd ?? process.cwd();\n const fromEnv = options.env?.AGENT_MEMORY_CONFIG;\n const explicit = options.configPath ?? (fromEnv === undefined || fromEnv.trim() === '' ? undefined : fromEnv);\n const configPath =\n explicit === undefined\n ? join(options.home, 'config.toml')\n : isAbsolute(explicit)\n ? explicit\n : resolve(cwd, explicit);\n\n let text: string;\n try {\n text = readFileSync(configPath, 'utf8');\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT' && explicit === undefined) {\n return {\n config: parseConfigDocument('', configPath).config,\n configPath: null,\n warnings: [`${configPath} not found; built-in defaults are in use`],\n };\n }\n if (code === 'ENOENT') {\n throw new StartupError('CONFIG_UNREADABLE', 'the config file does not exist', {\n sourcePath: configPath,\n hint: 'create it with `mem init`, or drop --config / AGENT_MEMORY_CONFIG',\n });\n }\n throw new StartupError('CONFIG_UNREADABLE', 'the config file cannot be read', {\n sourcePath: configPath,\n details: [error instanceof Error ? error.message : String(error)],\n });\n }\n\n const { config } = parseConfigDocument(text, configPath);\n return { config, configPath, warnings: [] };\n}\n", "/**\n * A deliberately small TOML subset.\n *\n * ADR-0001 explains why this is hand-written instead of a dependency: runtime\n * dependencies are zero, and a half-understood config file is worse than a\n * rejected one. Supported syntax is exactly:\n *\n * - comments (`#` to end of line, outside strings)\n * - `[table]` and `[nested.table]` headers\n * - `key = value` with bare keys ([A-Za-z0-9_-]+)\n * - basic strings (\"...\" with \\\\ \\\" \\n \\r \\t), literal strings ('...')\n * - integers (decimal, optional sign) and booleans\n * - single-line, homogeneous arrays of those scalars\n *\n * Anything else - floats, dates, inline tables, dotted keys, multi-line\n * strings, nested arrays, arrays of tables - is refused with a line number.\n */\n\nexport type RawScalar = string | number | boolean;\nexport type RawValue = RawScalar | readonly RawScalar[];\nexport interface RawTable {\n readonly [key: string]: RawValue | RawTable;\n}\n\nexport interface TomlDocument {\n readonly root: RawTable;\n readonly lineOf: (key: string) => number | undefined;\n}\n\nexport class TomlSyntaxError extends Error {\n readonly line: number;\n readonly sourcePath: string | undefined;\n\n constructor(message: string, line: number, sourcePath?: string) {\n super(sourcePath === undefined ? `line ${line}: ${message}` : `${sourcePath}:${line}: ${message}`);\n this.name = 'TomlSyntaxError';\n this.line = line;\n this.sourcePath = sourcePath;\n }\n}\n\nconst BARE_KEY = /^[A-Za-z0-9_-]+$/;\nconst INTEGER = /^[+-]?\\d+$/;\nconst FLOAT = /^[+-]?(?:\\d+\\.\\d*|\\.\\d+|\\d+[eE][+-]?\\d+|\\d+\\.\\d*[eE][+-]?\\d+)$/;\nconst ESCAPES: Readonly<Record<string, string>> = {\n '\\\\': '\\\\',\n '\"': '\"',\n n: '\\n',\n r: '\\r',\n t: '\\t',\n};\n\nexport function isRawTable(value: unknown): value is RawTable {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction errorAt(message: string, line: number, sourcePath?: string): TomlSyntaxError {\n return new TomlSyntaxError(message, line, sourcePath);\n}\n\n/** Windows editors add a UTF-8 BOM; it is not part of the first key. */\nexport function stripBom(text: string): string {\n return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n}\n\n/** Drop a trailing `#` comment, respecting quoted spans. */\nfunction stripTrailingComment(line: string): string {\n let quote: string | null = null;\n for (let index = 0; index < line.length; index += 1) {\n const char = line[index];\n if (quote !== null) {\n if (quote === '\"' && char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = null;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n continue;\n }\n if (char === '#') return line.slice(0, index);\n }\n return line;\n}\n\nexport function parseRestrictedToml(text: string, options: { sourcePath?: string } = {}): TomlDocument {\n const sourcePath = options.sourcePath;\n const root: Record<string, unknown> = {};\n const lines = new Map<string, number>();\n const tables = new Set<string>();\n let current: Record<string, unknown> = root;\n let currentPath: string[] = [];\n const rawLines = stripBom(text).split(/\\r\\n|\\n|\\r/);\n\n for (let index = 0; index < rawLines.length; index += 1) {\n const lineNumber = index + 1;\n const line = stripTrailingComment(rawLines[index] ?? '').trim();\n if (line === '') continue;\n\n if (line.startsWith('[[')) {\n throw errorAt('arrays of tables ([[...]]) are not supported', lineNumber, sourcePath);\n }\n\n if (line.startsWith('[')) {\n const header = /^\\[\\s*([^[\\]]*?)\\s*\\]$/.exec(line);\n if (header === null) throw errorAt(`malformed table header: ${line}`, lineNumber, sourcePath);\n const headerText = header[1] ?? '';\n const segments = headerText.split('.').map((segment) => segment.trim());\n if (segments.some((segment) => segment === '' || !BARE_KEY.test(segment))) {\n throw errorAt(`invalid table name: ${headerText}`, lineNumber, sourcePath);\n }\n const tableKey = segments.join('.');\n if (tables.has(tableKey)) throw errorAt(`duplicate table [${tableKey}]`, lineNumber, sourcePath);\n let node = root;\n for (const segment of segments) {\n const existing = node[segment];\n if (existing === undefined) {\n const created: Record<string, unknown> = {};\n node[segment] = created;\n node = created;\n } else if (isRawTable(existing)) {\n node = existing;\n } else {\n throw errorAt(`[${tableKey}] conflicts with an existing value named \"${segment}\"`, lineNumber, sourcePath);\n }\n }\n tables.add(tableKey);\n current = node;\n currentPath = segments;\n continue;\n }\n\n const assignment = findAssignment(line);\n if (assignment < 0) throw errorAt(`expected \"key = value\": ${line}`, lineNumber, sourcePath);\n const keyText = line.slice(0, assignment).trim();\n const valueText = line.slice(assignment + 1).trim();\n if (keyText === '') throw errorAt('missing key before \"=\"', lineNumber, sourcePath);\n if (keyText.includes('.')) {\n throw errorAt('dotted keys are not supported; declare a [table] header instead', lineNumber, sourcePath);\n }\n const key = unquoteKey(keyText, lineNumber, sourcePath);\n if (key === undefined) throw errorAt(`invalid key: ${keyText}`, lineNumber, sourcePath);\n if (valueText === '') throw errorAt(`missing value for key \"${key}\"`, lineNumber, sourcePath);\n const fullKey = [...currentPath, key].join('.');\n if (Object.prototype.hasOwnProperty.call(current, key)) {\n throw errorAt(`duplicate key \"${fullKey}\"`, lineNumber, sourcePath);\n }\n current[key] = parseValue(valueText, lineNumber, sourcePath, fullKey);\n lines.set(fullKey, lineNumber);\n }\n\n return { root: root as RawTable, lineOf: (key: string) => lines.get(key) };\n}\n\nfunction findAssignment(line: string): number {\n let quote: string | null = null;\n for (let index = 0; index < line.length; index += 1) {\n const char = line[index];\n if (quote !== null) {\n if (quote === '\"' && char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = null;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n continue;\n }\n if (char === '=') return index;\n }\n return -1;\n}\n\nfunction unquoteKey(keyText: string, line: number, sourcePath?: string): string | undefined {\n if (keyText.startsWith('\"') || keyText.startsWith(\"'\")) {\n if (keyText.length < 2 || keyText.at(-1) !== keyText[0]) {\n throw errorAt('unterminated quoted key', line, sourcePath);\n }\n return parseQuoted(keyText, line, sourcePath);\n }\n if (!BARE_KEY.test(keyText)) return undefined;\n return keyText;\n}\n\nfunction parseValue(\n text: string,\n line: number,\n sourcePath: string | undefined,\n key: string,\n): RawValue {\n if (text === 'true') return true;\n if (text === 'false') return false;\n if (INTEGER.test(text)) {\n const value = Number(text);\n if (!Number.isSafeInteger(value)) throw errorAt(`\"${key}\": integer is outside the safe range`, line, sourcePath);\n return value;\n }\n if (text.startsWith('\"\"\"') || text.startsWith(\"'''\")) {\n throw errorAt(`\"${key}\": multi-line strings are not supported`, line, sourcePath);\n }\n if (text.startsWith('\"') || text.startsWith(\"'\")) {\n if (text.length < 2 || text.at(-1) !== text[0]) {\n throw errorAt(`\"${key}\": unterminated string`, line, sourcePath);\n }\n return parseQuoted(text, line, sourcePath);\n }\n if (text.startsWith('[')) return parseArray(text, line, sourcePath, key);\n if (text.startsWith('{')) throw errorAt(`\"${key}\": inline tables are not supported`, line, sourcePath);\n if (FLOAT.test(text)) throw errorAt(`\"${key}\": floats are not supported; use an integer`, line, sourcePath);\n throw errorAt(`\"${key}\": unsupported value: ${text}`, line, sourcePath);\n}\n\nfunction parseQuoted(text: string, line: number, sourcePath?: string): string {\n const quote = text[0];\n if (quote !== '\"' && quote !== \"'\") throw errorAt('not a quoted string', line, sourcePath);\n const body = text.slice(1, -1);\n if (quote === \"'\") return body;\n let out = '';\n for (let index = 0; index < body.length; index += 1) {\n const char = body[index];\n if (char !== '\\\\') {\n out += char;\n continue;\n }\n const next = body[index + 1];\n if (next === undefined) throw errorAt('trailing backslash in string', line, sourcePath);\n const replacement = ESCAPES[next];\n if (replacement === undefined) {\n throw errorAt(\n `unsupported escape \"\\\\${next}\" (supported: \\\\\\\\ \\\\\" \\\\n \\\\r \\\\t)`,\n line,\n sourcePath,\n );\n }\n out += replacement;\n index += 1;\n }\n return out;\n}\n\nfunction parseArray(\n text: string,\n line: number,\n sourcePath: string | undefined,\n key: string,\n): readonly RawScalar[] {\n if (!text.endsWith(']')) throw errorAt(`\"${key}\": unterminated array`, line, sourcePath);\n const inner = text.slice(1, -1).trim();\n if (inner === '') return [];\n const items = splitTopLevel(inner, line, sourcePath);\n const values = items.map((item) => parseValue(item, line, sourcePath, key));\n const kinds = new Set(values.map((value) => typeof value));\n if (kinds.size > 1) throw errorAt(`\"${key}\": arrays must hold values of a single type`, line, sourcePath);\n return values as readonly RawScalar[];\n}\n\nfunction splitTopLevel(inner: string, line: number, sourcePath?: string): string[] {\n const items: string[] = [];\n let current = '';\n let quote: string | null = null;\n for (let index = 0; index < inner.length; index += 1) {\n const char = inner[index];\n if (quote !== null) {\n current += char;\n if (quote === '\"' && char === '\\\\') {\n const next = inner[index + 1];\n if (next !== undefined) {\n current += next;\n index += 1;\n }\n continue;\n }\n if (char === quote) quote = null;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n current += char;\n continue;\n }\n if (char === '[' || char === '{') {\n throw errorAt('nested arrays and inline tables are not supported', line, sourcePath);\n }\n if (char === ',') {\n items.push(current.trim());\n current = '';\n continue;\n }\n current += char;\n }\n if (quote !== null) throw errorAt('unterminated string inside array', line, sourcePath);\n items.push(current.trim());\n if (items.some((item) => item === '')) throw errorAt('empty element in array', line, sourcePath);\n return items;\n}\n\n/** Serialize a string as a TOML basic string (used for generated defaults). */\nexport function quoteTomlString(value: string): string {\n const escaped = value\n .replaceAll('\\\\', '\\\\\\\\')\n .replaceAll('\"', '\\\\\"')\n .replaceAll('\\n', '\\\\n')\n .replaceAll('\\r', '\\\\r')\n .replaceAll('\\t', '\\\\t');\n return `\"${escaped}\"`;\n}\n", "/**\n * Declarative schema validation shared by config.toml and policy.json.\n *\n * Both files are strict: an unknown key is a startup failure, never a warning\n * that gets ignored. The messages name the offending dotted key so a human can\n * fix it without reading this source file.\n */\n\nimport type { ConfigProblem } from '../errors.ts';\nimport { isRawTable, type RawScalar, type RawTable, type RawValue } from './toml.ts';\n\nexport type FieldSpec =\n | { readonly type: 'string'; readonly default?: string; readonly nonEmpty?: boolean }\n | {\n readonly type: 'int';\n readonly default?: number;\n readonly min?: number;\n readonly max?: number;\n }\n | { readonly type: 'bool'; readonly default?: boolean }\n | { readonly type: 'enum'; readonly values: readonly string[]; readonly default?: string }\n | {\n readonly type: 'string[]';\n readonly values?: readonly string[];\n readonly default?: readonly string[];\n };\n\nexport interface TableSpec {\n readonly [key: string]: FieldSpec | TableSpec;\n}\n\nexport interface ValidationResult {\n readonly values: RawTable;\n readonly problems: readonly ConfigProblem[];\n}\n\nexport interface ValidateOptions {\n readonly prefix?: string;\n readonly lineOf?: (key: string) => number | undefined;\n}\n\nexport function isFieldSpec(spec: FieldSpec | TableSpec): spec is FieldSpec {\n return 'type' in spec;\n}\n\nexport function isArrayValue(value: unknown): value is readonly RawScalar[] {\n return Array.isArray(value);\n}\n\nexport function validateAgainstSchema(\n schema: TableSpec,\n raw: RawTable,\n options: ValidateOptions = {},\n): ValidationResult {\n const problems: ConfigProblem[] = [];\n const values = walk(schema, raw, options.prefix ?? '', problems, options.lineOf);\n return { values, problems };\n}\n\n/** Every field key of a schema, dotted and sorted. Used by the docs gate. */\nexport function schemaKeys(schema: TableSpec, prefix = ''): string[] {\n const keys: string[] = [];\n for (const [name, spec] of Object.entries(schema)) {\n const key = prefix === '' ? name : `${prefix}.${name}`;\n if (isFieldSpec(spec)) keys.push(key);\n else keys.push(...schemaKeys(spec, key));\n }\n return keys.sort();\n}\n\n/** All-default values for a schema. */\nexport function schemaDefaults(schema: TableSpec): RawTable {\n return validateAgainstSchema(schema, {}).values;\n}\n\nfunction walk(\n schema: TableSpec,\n raw: RawTable,\n prefix: string,\n problems: ConfigProblem[],\n lineOf: ((key: string) => number | undefined) | undefined,\n): RawTable {\n const out: Record<string, RawValue | RawTable> = {};\n const seen = new Set<string>();\n const known = new Map(Object.entries(schema));\n\n for (const [name, rawValue] of Object.entries(raw)) {\n seen.add(name);\n const key = prefix === '' ? name : `${prefix}.${name}`;\n const line = lineOf?.(key);\n const spec = known.get(name);\n\n if (spec === undefined) {\n problems.push({\n key,\n message: unknownKeyMessage(key, name, known),\n ...(line === undefined ? {} : { line }),\n });\n continue;\n }\n\n if (isFieldSpec(spec)) {\n if (isRawTable(rawValue)) {\n problems.push({\n key,\n message: `\"${key}\" must be ${typeLabel(spec)}, not a table`,\n ...(line === undefined ? {} : { line }),\n });\n continue;\n }\n const checked = checkField(spec, rawValue, key, problems);\n if (checked !== undefined) out[name] = checked;\n continue;\n }\n\n if (!isRawTable(rawValue)) {\n problems.push({\n key,\n message: `\"${key}\" must be a table ([${key}]), not ${describeValue(rawValue)}`,\n ...(line === undefined ? {} : { line }),\n });\n continue;\n }\n out[name] = walk(spec, rawValue, key, problems, lineOf);\n }\n\n for (const [name, spec] of Object.entries(schema)) {\n if (seen.has(name)) continue;\n const key = prefix === '' ? name : `${prefix}.${name}`;\n if (isFieldSpec(spec)) {\n if (spec.default !== undefined) out[name] = spec.default;\n else problems.push({ key, message: `missing required key \"${key}\"` });\n continue;\n }\n out[name] = walk(spec, {}, key, problems, lineOf);\n }\n\n return out;\n}\n\nfunction checkField(\n spec: FieldSpec,\n value: RawValue,\n key: string,\n problems: ConfigProblem[],\n): RawValue | undefined {\n const fail = (message: string): undefined => {\n problems.push({ key, message });\n return undefined;\n };\n\n switch (spec.type) {\n case 'string': {\n if (typeof value !== 'string') return fail(`\"${key}\" must be ${typeLabel(spec)}, not ${describeValue(value)}`);\n if (spec.nonEmpty === true && value.trim() === '') return fail(`\"${key}\" must not be empty`);\n return value;\n }\n case 'int': {\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n return fail(`\"${key}\" must be ${typeLabel(spec)}, not ${describeValue(value)}`);\n }\n if (spec.min !== undefined && value < spec.min) {\n return fail(`\"${key}\" must be at least ${spec.min}, found ${value}`);\n }\n if (spec.max !== undefined && value > spec.max) {\n return fail(`\"${key}\" must be at most ${spec.max}, found ${value}`);\n }\n return value;\n }\n case 'bool': {\n if (typeof value !== 'boolean') return fail(`\"${key}\" must be ${typeLabel(spec)}, not ${describeValue(value)}`);\n return value;\n }\n case 'enum': {\n if (typeof value !== 'string' || !spec.values.includes(value)) {\n return fail(`\"${key}\" must be ${typeLabel(spec)}, not ${describeValue(value)}`);\n }\n return value;\n }\n case 'string[]': {\n if (!isArrayValue(value) || !value.every((item) => typeof item === 'string')) {\n return fail(`\"${key}\" must be ${typeLabel(spec)}, not ${describeValue(value)}`);\n }\n const strings = value as readonly string[];\n if (spec.values !== undefined) {\n const bad = strings.find((item) => !spec.values?.includes(item));\n if (bad !== undefined) return fail(`\"${key}\" may only contain ${typeLabel(spec)}; found \"${bad}\"`);\n }\n return strings;\n }\n }\n}\n\nexport function typeLabel(spec: FieldSpec): string {\n switch (spec.type) {\n case 'string':\n return 'a string';\n case 'int':\n return 'an integer';\n case 'bool':\n return 'a boolean';\n case 'enum':\n return `one of ${spec.values.map((value) => `\"${value}\"`).join(', ')}`;\n case 'string[]':\n return spec.values === undefined\n ? 'an array of strings'\n : `an array of ${spec.values.map((value) => `\"${value}\"`).join(', ')}`;\n }\n}\n\nfunction describeValue(value: unknown): string {\n if (isRawTable(value)) return 'a table';\n if (isArrayValue(value)) return 'an array';\n if (typeof value === 'string') return `the string ${JSON.stringify(value)}`;\n if (typeof value === 'number') return `the integer ${value}`;\n return `the boolean ${String(value)}`;\n}\n\nfunction unknownKeyMessage(key: string, name: string, known: ReadonlyMap<string, FieldSpec | TableSpec>): string {\n const suggestion = suggestKey(name, known.keys());\n if (suggestion === undefined) return `unknown key \"${key}\"`;\n const prefix = key.slice(0, key.length - name.length);\n return `unknown key \"${key}\" (did you mean \"${prefix}${suggestion}\"?)`;\n}\n\nfunction suggestKey(name: string, candidates: Iterable<string>): string | undefined {\n let best: { candidate: string; distance: number } | undefined;\n for (const candidate of candidates) {\n const distance = editDistance(name.toLowerCase(), candidate.toLowerCase());\n if (distance > 2) continue;\n if (best === undefined || distance < best.distance) best = { candidate, distance };\n }\n return best?.candidate;\n}\n\nfunction editDistance(a: string, b: string): number {\n const rows = a.length + 1;\n const cols = b.length + 1;\n let previous: number[] = Array.from({ length: cols }, (_, index) => index);\n for (let row = 1; row < rows; row += 1) {\n const current: number[] = [row];\n for (let col = 1; col < cols; col += 1) {\n const cost = a[row - 1] === b[col - 1] ? 0 : 1;\n const above = previous[col] ?? 0;\n const left = current[col - 1] ?? 0;\n const diagonal = previous[col - 1] ?? 0;\n current[col] = Math.min(above + 1, left + 1, diagonal + cost);\n }\n previous = current;\n }\n return previous[cols - 1] ?? 0;\n}\n", "/**\n * config.toml: every user-tunable number, with no security-relevant switch.\n *\n * The split with policy.json is deliberate and checked at startup:\n * policy.json (sealed, human-only) sets the outermost bounds; config.toml may\n * tighten them but can never widen them. See docs/config.md.\n */\n\nimport { ConfigError, type ConfigProblem } from '../errors.ts';\nimport type { RawTable } from './toml.ts';\nimport { isRawTable, parseRestrictedToml, TomlSyntaxError } from './toml.ts';\nimport { schemaKeys, validateAgainstSchema, type TableSpec } from './schema.ts';\n\nexport interface Config {\n readonly schema_version: number;\n readonly storage: {\n readonly max_records: number;\n readonly max_record_chars: number;\n };\n readonly inject: {\n readonly persona_max_chars: number;\n readonly guidance_max_chars: number;\n readonly user_max_chars: number;\n readonly rules_max_chars: number;\n readonly index_max_chars: number;\n readonly total_max_chars: number;\n readonly protect: boolean;\n readonly counter: 'chars' | 'tokens';\n };\n readonly recall: {\n readonly limit: number;\n readonly min_score: number;\n readonly max_limit: number;\n readonly hybrid: boolean;\n readonly embedding_weight: number;\n };\n readonly distill: {\n readonly max_proposals: number;\n readonly require_quote: boolean;\n };\n readonly lock: {\n readonly heartbeat_ms: number;\n readonly stale_ms: number;\n readonly timeout_ms: number;\n };\n readonly limits: {\n readonly abstract_chars: number;\n readonly body_chars: number;\n };\n readonly quota: {\n readonly t0_per_session: number;\n };\n readonly proposals: {\n readonly max_pending: number;\n };\n readonly personalization: {\n readonly mode: 'confirm' | 'direct' | 'readonly';\n };\n}\n\n/**\n * Limits copied from the V1.0 plan (06 \u00A76.1 budgets, 08 \u00A7sub-budgets, v1.3 \u00A78).\n *\n * `recall.min_score` is an integer per-mille score (500 = 0.5) because the\n * restricted TOML subset deliberately has no floats. S3 interprets it as a\n * normalized BM25 threshold; S2a's substring recall ignores it.\n */\nexport const configSchema: TableSpec = {\n schema_version: { type: 'int', default: 2, min: 2, max: 2 },\n storage: {\n max_records: { type: 'int', default: 1000, min: 1, max: 100_000 },\n max_record_chars: { type: 'int', default: 10_000, min: 100, max: 200_000 },\n },\n inject: {\n persona_max_chars: { type: 'int', default: 200, min: 0, max: 5_000 },\n guidance_max_chars: { type: 'int', default: 300, min: 0, max: 2_000 },\n user_max_chars: { type: 'int', default: 1_100, min: 0, max: 20_000 },\n rules_max_chars: { type: 'int', default: 1_200, min: 0, max: 10_000 },\n index_max_chars: { type: 'int', default: 1_200, min: 0, max: 20_000 },\n total_max_chars: { type: 'int', default: 4_000, min: 0, max: 40_000 },\n protect: { type: 'bool', default: true },\n counter: { type: 'enum', values: ['chars', 'tokens'], default: 'chars' },\n },\n recall: {\n limit: { type: 'int', default: 5, min: 1, max: 100 },\n min_score: { type: 'int', default: 500, min: 0, max: 1_000 },\n max_limit: { type: 'int', default: 20, min: 1, max: 100 },\n hybrid: { type: 'bool', default: false },\n embedding_weight: { type: 'int', default: 400, min: 0, max: 1_000 },\n },\n distill: {\n max_proposals: { type: 'int', default: 5, min: 1, max: 5 },\n require_quote: { type: 'bool', default: true },\n },\n lock: {\n heartbeat_ms: { type: 'int', default: 15_000, min: 1_000, max: 60_000 },\n stale_ms: { type: 'int', default: 300_000, min: 5_000, max: 3_600_000 },\n timeout_ms: { type: 'int', default: 60_000, min: 1_000, max: 600_000 },\n },\n limits: {\n abstract_chars: { type: 'int', default: 120, min: 20, max: 1_000 },\n body_chars: { type: 'int', default: 4_000, min: 100, max: 200_000 },\n },\n quota: {\n t0_per_session: { type: 'int', default: 20, min: 1, max: 1_000 },\n },\n proposals: {\n max_pending: { type: 'int', default: 50, min: 1, max: 1_000 },\n },\n personalization: {\n mode: { type: 'enum', values: ['confirm', 'direct', 'readonly'], default: 'confirm' },\n },\n};\n\n/**\n * The config file written by `mem init`. Every key is present so a human can see\n * what is tunable without reading the schema.\n */\nexport const CONFIG_TEMPLATE = `# Agent Memory V1.0 - \u7528\u6237\u914D\u7F6E\uFF08\u4EBA\u53EF\u6539\uFF1Bagent \u4E0D\u9700\u8981\u6539\uFF09\n# \u6BCF\u4E2A\u952E\u90FD\u5728\u542F\u52A8\u65F6\u6821\u9A8C\uFF1A\u672A\u77E5\u952E\u3001\u7C7B\u578B\u9519\u8BEF\u3001\u8D85\u8303\u56F4\u90FD\u4F1A\u8BA9\u542F\u52A8\u54CD\u4EAE\u5931\u8D25\uFF0C\u5E76\u70B9\u540D\u51FA\u9519\u952E\u3002\n# \u8BF4\u660E\u89C1 docs/config.md\u3002\u5B89\u5168\u8FB9\u754C\u4E0D\u5728\u8FD9\u4E2A\u6587\u4EF6\u91CC\uFF0C\u800C\u5728 policy.json\uFF08\u54C8\u5E0C\u5C01\u5B58\uFF09\u3002\n\nschema_version = 2\n\n[storage]\n# \u8BB0\u5FC6\u6761\u76EE\u4E0A\u9650\uFF1B\u8D85\u8FC7\u540E\u5199\u5165\u88AB\u62D2\u7EDD\uFF08\u4E0D\u81EA\u52A8\u6DD8\u6C70\uFF09\u3002\nmax_records = 1000\n# \u5355\u6761\u8BB0\u5FC6\u6587\u4EF6\u5B57\u7B26\u4E0A\u9650\uFF08\u542B frontmatter\uFF09\u3002\nmax_record_chars = 10000\n\n[inject]\n# \u5E38\u9A7B\u6CE8\u5165\u7684\u4E94\u4E2A\u5206\u533A\u9884\u7B97\uFF08\u5B57\u7B26\u6570\uFF09\u4E0E\u5408\u8BA1\u4E0A\u9650\u3002\npersona_max_chars = 200\nguidance_max_chars = 300\nuser_max_chars = 1100\nrules_max_chars = 1200\nindex_max_chars = 1200\ntotal_max_chars = 4000\n# \u6CE8\u5165\u6BB5\u6253 protected \u6807\u8BB0\uFF1A\u538B\u7F29\u4E0D\u5F97\u89E6\u53CA\u3002\nprotect = true\n# \u9884\u7B97\u8BA1\u91CF\u65B9\u5F0F\uFF1Achars\uFF08\u5B57\u7B26\uFF0C\u4FDD\u5B88\uFF09\u6216 tokens\uFF08S3 \u8D77\u7528 tokenMeter\uFF09\u3002\ncounter = \"chars\"\n\n[recall]\n# \u5355\u6B21\u68C0\u7D22\u9ED8\u8BA4\u8FD4\u56DE\u6761\u6570\uFF0C\u4EE5\u53CA\u4E0A\u9650\u3002\nlimit = 5\nmax_limit = 20\n# \u5343\u5206\u5236\u9608\u503C\uFF08500 = 0.5\uFF09\uFF1BS2a \u5B50\u4E32\u53EC\u56DE\u4E0D\u4F7F\u7528\uFF0CS3 BM25 \u4F7F\u7528\u3002\nmin_score = 500\n# \u6DF7\u5408\u68C0\u7D22\uFF1A\u9ED8\u8BA4\u5173\u95ED\uFF1B\u5F00\u542F\u540E BM25 \u4E0E\u672C\u5730\u5411\u91CF\u5206\u6570\u878D\u5408\uFF08S2a \u7528\u786E\u5B9A\u6027 hash \u515C\u5E95\uFF09\u3002\nhybrid = false\n# \u5411\u91CF\u5728\u878D\u5408\u5206\u6570\u4E2D\u7684\u6743\u91CD\uFF08\u5343\u5206\u5236\uFF0C400 = 0.4\uFF09\u3002\nembedding_weight = 400\n\n[distill]\n# \u6BCF\u6B21\u6536\u5C3E\u84B8\u998F\u6700\u591A\u51E0\u6761\u63D0\u6848\uFF08V1.0 \u89C4\u683C\u786C\u4E0A\u9650 5\uFF09\u3002\nmax_proposals = 5\n# \u63D0\u6848\u5FC5\u987B\u5E26\u539F\u6587\u5F15\u7528\u3002\nrequire_quote = true\n\n[lock]\n# \u5199\u9501\uFF1A\u5FC3\u8DF3\u95F4\u9694\u3001\u9648\u65E7\u9608\u503C\u3001\u83B7\u53D6\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09\u3002\nheartbeat_ms = 15000\nstale_ms = 300000\ntimeout_ms = 60000\n\n[limits]\n# \u5355\u6761\u8BB0\u5FC6\u7684\u6458\u8981\u4E0E\u6B63\u6587\u5B57\u7B26\u4E0A\u9650\u3002\nabstract_chars = 120\nbody_chars = 4000\n\n[quota]\n# \u6BCF\u4E2A\u4F1A\u8BDD\u5141\u8BB8\u7684 T0 \u5199\u5165\u6761\u6570\uFF08S4 \u8D77\u5F3A\u5236\u6267\u884C\uFF09\u3002\nt0_per_session = 20\n\n[proposals]\n# \u5F85\u5BA1\u63D0\u6848\u4E0A\u9650\u3002\nmax_pending = 50\n\n[personalization]\n# \u52A9\u624B\u5199\u8BB0\u5FC6\u7684\u6743\u9650\uFF1Aconfirm\uFF08\u6BCF\u6B21\u5148\u786E\u8BA4\uFF09/ direct\uFF08\u81EA\u4E3B\u5199\u5165\uFF09/ readonly\uFF08\u53EA\u8BFB\uFF09\u3002\nmode = \"confirm\"\n`;\n\nexport function defaultConfig(): Config {\n return validateConfigTable({}).config;\n}\n\nexport function configKeys(): string[] {\n return schemaKeys(configSchema);\n}\n\nexport function validateConfigTable(\n raw: RawTable,\n options: { lineOf?: (key: string) => number | undefined } = {},\n): { config: Config; problems: ConfigProblem[] } {\n const { values, problems: schemaProblems } = validateAgainstSchema(configSchema, raw, options);\n const problems = [...schemaProblems];\n const config = values as unknown as Config;\n const inject = values.inject;\n if (isRawTable(inject)) {\n const parts = [\n inject.persona_max_chars,\n inject.guidance_max_chars,\n inject.user_max_chars,\n inject.rules_max_chars,\n inject.index_max_chars,\n ];\n const total = inject.total_max_chars;\n if (parts.every((part): part is number => typeof part === 'number') && typeof total === 'number') {\n const sum = parts.reduce((acc, part) => acc + part, 0);\n if (sum > total) {\n problems.push({\n key: 'inject.total_max_chars',\n message: `the five injection sections add up to ${sum} chars, more than inject.total_max_chars (${total})`,\n });\n }\n }\n }\n const recall = values.recall;\n if (isRawTable(recall)) {\n const limit = recall.limit;\n const max = recall.max_limit;\n if (typeof limit === 'number' && typeof max === 'number' && limit > max) {\n problems.push({\n key: 'recall.limit',\n message: `\"recall.limit\" (${limit}) must not exceed recall.max_limit (${max})`,\n });\n }\n }\n return { config, problems };\n}\n\n/** Parse config text strictly. Throws ConfigError (which names every bad key). */\nexport function parseConfig(text: string, sourcePath: string): Config {\n return parseConfigDocument(text, sourcePath).config;\n}\n\nexport function parseConfigDocument(\n text: string,\n sourcePath: string,\n): { config: Config; problems: ConfigProblem[]; lineOf: (key: string) => number | undefined } {\n let parsed: ReturnType<typeof parseRestrictedToml>;\n try {\n parsed = parseRestrictedToml(text, { sourcePath });\n } catch (error) {\n if (error instanceof TomlSyntaxError) {\n throw new ConfigError(sourcePath, [\n { key: '<syntax>', message: `${error.message.replace(`${sourcePath}:`, '').trim()}` },\n ]);\n }\n throw error;\n }\n const { config, problems } = validateConfigTable(parsed.root, { lineOf: parsed.lineOf });\n if (problems.length > 0) {\n throw new ConfigError(sourcePath, problems, 'fix the named keys; unknown keys are refused, never ignored');\n }\n return { config, problems, lineOf: parsed.lineOf };\n}\n", "import { createHash } from 'node:crypto';\r\nimport { existsSync, readFileSync } from 'node:fs';\r\nimport { isRawTable, stripBom, type RawTable } from '../config/toml.ts';\r\nimport { schemaKeys, validateAgainstSchema, type TableSpec } from '../config/schema.ts';\r\nimport { StartupError, type ConfigProblem } from '../errors.ts';\r\nimport { writeFileAtomic } from '../fs/atomic.ts';\r\nimport { hashContent } from '../model/frontmatter.ts';\r\nimport { memoryPaths } from '../paths.ts';\r\n\r\n/**\r\n * policy.json: the attack surface that must not be editable by the agent.\r\n *\r\n * It is sealed with a SHA-256 of its bytes. Every startup recomputes the hash;\r\n * any mismatch aborts startup instead of loading a relaxed policy (`06` L3).\r\n * Re-sealing is a human action: `mem policy seal --accept`.\r\n *\r\n * The optional `sealed_files` hashes make the human-maintained SOUL/USER/RULES\r\n * editable only through a deliberate re-seal: an empty string skips a file.\r\n */\r\n\r\nexport interface Policy {\r\n readonly version: number;\r\n readonly capacity: {\r\n readonly max_records: number;\r\n readonly max_record_chars: number;\r\n };\r\n readonly scan: {\r\n readonly invisible_unicode: 'reject';\r\n readonly credentials: 'reject';\r\n readonly injection: 'reject' | 'flag';\r\n readonly private_tag: 'reject' | 'confirm';\r\n };\r\n readonly rules: {\r\n readonly agent_writable: false;\r\n };\r\n readonly sealed_files: {\r\n readonly soul: string;\r\n readonly user: string;\r\n readonly rules: string;\r\n };\r\n}\r\n\r\nexport const policySchema: TableSpec = {\r\n version: { type: 'int', default: 2, min: 1, max: 2 },\r\n capacity: {\r\n max_records: { type: 'int', default: 1000, min: 1, max: 100_000 },\r\n max_record_chars: { type: 'int', default: 10_000, min: 100, max: 200_000 },\r\n },\r\n scan: {\r\n invisible_unicode: { type: 'enum', values: ['reject'], default: 'reject' },\r\n credentials: { type: 'enum', values: ['reject'], default: 'reject' },\r\n injection: { type: 'enum', values: ['reject', 'flag'], default: 'reject' },\r\n private_tag: { type: 'enum', values: ['reject', 'confirm'], default: 'confirm' },\r\n },\r\n rules: {\r\n agent_writable: { type: 'bool', default: false },\r\n },\r\n sealed_files: {\r\n soul: { type: 'string', default: '' },\r\n user: { type: 'string', default: '' },\r\n rules: { type: 'string', default: '' },\r\n },\r\n};\r\n\r\nexport const POLICY_TEMPLATE = `{\r\n \"version\": 2,\r\n \"capacity\": {\r\n \"max_records\": 1000,\r\n \"max_record_chars\": 10000\r\n },\r\n \"scan\": {\r\n \"invisible_unicode\": \"reject\",\r\n \"credentials\": \"reject\",\r\n \"injection\": \"reject\",\r\n \"private_tag\": \"confirm\"\r\n },\r\n \"rules\": {\r\n \"agent_writable\": false\r\n },\r\n \"sealed_files\": {\r\n \"soul\": \"\",\r\n \"user\": \"\",\r\n \"rules\": \"\"\r\n }\r\n}\r\n`;\r\n\r\nexport interface SealRecord {\r\n readonly policy: string;\r\n readonly sha256: string;\r\n readonly sealed_at: string;\r\n}\r\n\r\nexport interface LoadedPolicy {\r\n readonly policy: Policy;\r\n readonly policyPath: string;\r\n readonly sealPath: string;\r\n readonly sha256: string;\r\n readonly sealedAt: string;\r\n}\r\n\r\nexport function policyKeys(): string[] {\r\n return schemaKeys(policySchema);\r\n}\r\n\r\nexport function defaultPolicy(): Policy {\r\n return parsePolicyText(POLICY_TEMPLATE).policy;\r\n}\r\n\r\nexport function hashBytes(data: string | Uint8Array): string {\r\n return createHash('sha256').update(data).digest('hex');\r\n}\r\n\r\nexport function parsePolicyText(text: string): { policy: Policy; problems: ConfigProblem[] } {\r\n let raw: unknown;\r\n try {\r\n raw = JSON.parse(stripBom(text));\r\n } catch (error) {\r\n const message = error instanceof Error ? error.message : String(error);\r\n return {\r\n policy: {} as Policy,\r\n problems: [{ key: '<json>', message: `policy is not valid JSON: ${message}` }],\r\n };\r\n }\r\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\r\n return {\r\n policy: {} as Policy,\r\n problems: [{ key: '<root>', message: 'policy must be a JSON object' }],\r\n };\r\n }\r\n const { values, problems: schemaProblems } = validateAgainstSchema(policySchema, raw as RawTable);\r\n const problems = [...schemaProblems];\r\n const policy = values as unknown as Policy;\r\n const rules = values.rules;\r\n if (isRawTable(rules) && rules.agent_writable === true) {\r\n problems.push({\r\n key: 'rules.agent_writable',\r\n message: '\"rules.agent_writable\" must stay false in V1.0: the agent has no channel to RULES.md',\r\n });\r\n }\r\n const sealed = values.sealed_files;\r\n if (isRawTable(sealed)) {\r\n for (const key of ['soul', 'user', 'rules'] as const) {\r\n const value = sealed[key];\r\n if (typeof value === 'string' && value !== '' && !/^[0-9a-f]{64}$/.test(value)) {\r\n problems.push({\r\n key: `sealed_files.${key}`,\r\n message: `\"sealed_files.${key}\" must be empty or a 64-character lowercase hex hash`,\r\n });\r\n }\r\n }\r\n }\r\n return { policy, problems };\r\n}\r\n\r\nexport interface SealedFileHashes {\r\n readonly soul: string;\r\n readonly user: string;\r\n readonly rules: string;\r\n}\r\n\r\n/**\r\n * Normalized hashes of the human-maintained files. A missing file seals as an\r\n * empty string, which means \"skip this file\".\r\n */\r\nexport function computeSealedFiles(home: string): SealedFileHashes {\r\n const paths = memoryPaths(home);\r\n const hashOf = (file: string): string => {\r\n try {\r\n return existsSync(file) ? hashContent(readFileSync(file, 'utf8')) : '';\r\n } catch {\r\n return '';\r\n }\r\n };\r\n return { soul: hashOf(paths.soulFile), user: hashOf(paths.userFile), rules: hashOf(paths.rulesFile) };\r\n}\r\n\r\n/**\r\n * Startup check for the sealed human files. Editing SOUL/USER/RULES without a\r\n * deliberate re-seal stops startup with the file named.\r\n */\r\nexport function verifySealedFiles(options: { home: string; policy: Policy }): void {\r\n const paths = memoryPaths(options.home);\r\n const targets: ReadonlyArray<readonly [keyof SealedFileHashes, string, string]> = [\r\n ['soul', paths.soulFile, 'SOUL.md'],\r\n ['user', paths.userFile, 'USER.md'],\r\n ['rules', paths.rulesFile, 'RULES.md'],\r\n ];\r\n for (const [key, file, name] of targets) {\r\n const expected = options.policy.sealed_files[key];\r\n if (expected === '') continue;\r\n const actual = existsSync(file) ? hashContent(readFileSync(file, 'utf8')) : '';\r\n if (actual !== expected) {\r\n const homeArg = /\\s/.test(options.home) ? `\"${options.home}\"` : options.home;\r\n throw new StartupError('SEALED_FILE_MISMATCH', `${name} does not match its sealed hash`, {\r\n sourcePath: file,\r\n details: [`sealed sha256 ${expected}`, `actual sha256 ${actual === '' ? '(missing)' : actual}`],\r\n fixCommand: `mem policy seal --home ${homeArg} --accept`,\r\n hint: `\u7F16\u8F91 ${name} \u540E\u5FC5\u987B\u91CD\u65B0\u5C01\u5B58\uFF1B\u4E5F\u53EF\u4EE5\u5728\u804A\u5929\u6846\u8FD0\u884C /mem seal --accept`,\r\n });\r\n }\r\n }\r\n}\r\n\r\nexport function loadPolicy(options: { home: string }): LoadedPolicy {\r\n const paths = memoryPaths(options.home);\r\n const policyText = readFileText(paths.policyFile, {\r\n code: 'POLICY_MISSING',\r\n message: 'policy.json is missing from the store',\r\n hint: 'run `mem init` to create the store, then seal the policy',\r\n });\r\n const sealText = readFileText(paths.sealFile, {\r\n code: 'POLICY_MISSING',\r\n message: 'policy.json is not sealed',\r\n hint: 'a human must review it and run `mem policy seal --accept`',\r\n });\r\n\r\n const seal = parseSeal(sealText, paths.sealFile);\r\n const sha256 = hashBytes(policyText);\r\n if (seal.sha256 !== sha256) {\r\n throw new StartupError('POLICY_MISMATCH', 'policy.json does not match its sealed hash', {\r\n sourcePath: paths.policyFile,\r\n details: [`sealed sha256 ${seal.sha256}`, `actual sha256 ${sha256}`],\r\n hint: 'the policy is immutable at runtime; after a deliberate human edit run `mem policy seal --accept`',\r\n });\r\n }\r\n\r\n const { policy, problems } = parsePolicyText(policyText);\r\n if (problems.length > 0) throw policyProblems(paths.policyFile, problems);\r\n\r\n return { policy, sha256, sealedAt: seal.sealed_at, policyPath: paths.policyFile, sealPath: paths.sealFile };\r\n}\r\n\r\nexport interface SealResult {\r\n readonly sealPath: string;\r\n readonly sha256: string;\r\n /** Hash that was sealed before this call, if any. */\r\n readonly previousSha256: string | null;\r\n /** Normalized hashes of SOUL/USER/RULES at the moment of sealing. */\r\n readonly sealedFiles: SealedFileHashes;\r\n}\r\n\r\n/**\r\n * Re-seal the policy. Requires `accept === true`, which only the CLI passes\r\n * after a human typed the flag; nothing in the agent's tool surface can reach\r\n * this function.\r\n */\r\nexport function sealPolicy(options: {\r\n home: string;\r\n accept: boolean;\r\n now?: Date;\r\n /** Seal USER.md too. Default false: the agent may propose USER edits. */\r\n sealUser?: boolean;\r\n}): SealResult {\r\n const paths = memoryPaths(options.home);\r\n if (!options.accept) {\r\n throw new StartupError('SEAL_REFUSED', 'refusing to re-seal policy.json without explicit confirmation', {\r\n sourcePath: paths.policyFile,\r\n hint: 'review the file, then run `mem policy seal --accept`; the agent has no path to this action',\r\n });\r\n }\r\n\r\n const policyText = readFileText(paths.policyFile, {\r\n code: 'POLICY_MISSING',\r\n message: 'policy.json is missing from the store',\r\n hint: 'run `mem init` first',\r\n });\r\n const { policy, problems } = parsePolicyText(policyText);\r\n if (problems.length > 0) throw policyProblems(paths.policyFile, problems);\r\n\r\n const computed = computeSealedFiles(options.home);\r\n const sealedFiles: SealedFileHashes = {\r\n soul: computed.soul,\r\n user: options.sealUser === true ? computed.user : '',\r\n rules: computed.rules,\r\n };\r\n const nextText = `${JSON.stringify({ ...policy, sealed_files: sealedFiles }, null, 2)}\\n`;\r\n writeFileAtomic(paths.policyFile, nextText);\r\n\r\n const previous = tryReadSeal(paths.sealFile);\r\n const sha256 = hashBytes(nextText);\r\n writeSeal(paths.sealFile, { policy: 'policy.json', sha256, sealed_at: (options.now ?? new Date()).toISOString() });\r\n return { sealPath: paths.sealFile, sha256, previousSha256: previous?.sha256 ?? null, sealedFiles };\r\n}\r\n\r\n/**\r\n * Used by `mem init`: seal when unsealed, accept when already sealed and\r\n * matching, refuse when the file changed under an existing seal.\r\n */\r\nexport function sealIfNeeded(options: { home: string; now?: Date }): SealResult {\r\n const paths = memoryPaths(options.home);\r\n const policyText = readFileText(paths.policyFile, {\r\n code: 'POLICY_MISSING',\r\n message: 'policy.json is missing from the store',\r\n hint: 'run `mem init` first',\r\n });\r\n const { problems } = parsePolicyText(policyText);\r\n if (problems.length > 0) throw policyProblems(paths.policyFile, problems);\r\n\r\n const sha256 = hashBytes(policyText);\r\n const sealedFiles = computeSealedFiles(options.home);\r\n const existing = tryReadSeal(paths.sealFile);\r\n if (existing !== null) {\r\n if (existing.sha256 !== sha256) {\r\n throw new StartupError('POLICY_MISMATCH', 'policy.json changed after it was sealed', {\r\n sourcePath: paths.policyFile,\r\n details: [`sealed sha256 ${existing.sha256}`, `actual sha256 ${sha256}`],\r\n hint: 'verify the change, then run `mem policy seal --accept`',\r\n });\r\n }\r\n return { sealPath: paths.sealFile, sha256, previousSha256: existing.sha256, sealedFiles };\r\n }\r\n writeSeal(paths.sealFile, { policy: 'policy.json', sha256, sealed_at: (options.now ?? new Date()).toISOString() });\r\n return { sealPath: paths.sealFile, sha256, previousSha256: null, sealedFiles };\r\n}\r\n\r\nfunction writeSeal(sealPath: string, record: SealRecord): void {\r\n writeFileAtomic(sealPath, `${JSON.stringify(record, null, 2)}\\n`);\r\n}\r\n\r\nfunction parseSeal(text: string, sealPath: string): SealRecord {\r\n let raw: unknown;\r\n try {\r\n raw = JSON.parse(stripBom(text));\r\n } catch (error) {\r\n const message = error instanceof Error ? error.message : String(error);\r\n throw new StartupError('POLICY_INVALID', 'the policy seal file is not valid JSON', {\r\n sourcePath: sealPath,\r\n details: [message],\r\n hint: 'run `mem policy seal --accept` to write a fresh seal',\r\n });\r\n }\r\n if (typeof raw !== 'object' || raw === null) {\r\n throw new StartupError('POLICY_INVALID', 'the policy seal file must be a JSON object', {\r\n sourcePath: sealPath,\r\n });\r\n }\r\n const record = raw as Record<string, unknown>;\r\n const allowed = new Set(['policy', 'sha256', 'sealed_at']);\r\n const unknown = Object.keys(record).filter((key) => !allowed.has(key));\r\n if (unknown.length > 0) {\r\n throw new StartupError('POLICY_INVALID', 'the policy seal file has unknown keys', {\r\n sourcePath: sealPath,\r\n details: unknown.map((key) => `unknown key \"${key}\"`),\r\n });\r\n }\r\n const sha256 = record.sha256;\r\n if (typeof record.policy !== 'string' || typeof sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(sha256)) {\r\n throw new StartupError('POLICY_INVALID', 'the policy seal file is malformed', {\r\n sourcePath: sealPath,\r\n details: ['expected { \"policy\": string, \"sha256\": <64 hex chars>, \"sealed_at\": string }'],\r\n });\r\n }\r\n const sealedAt = typeof record.sealed_at === 'string' ? record.sealed_at : '';\r\n return { policy: record.policy, sha256, sealed_at: sealedAt };\r\n}\r\n\r\nfunction tryReadSeal(sealPath: string): SealRecord | null {\r\n let text: string;\r\n try {\r\n text = readFileSync(sealPath, 'utf8');\r\n } catch {\r\n return null;\r\n }\r\n return parseSeal(text, sealPath);\r\n}\r\n\r\nfunction readFileText(filePath: string, missing: { code: 'POLICY_MISSING'; message: string; hint: string }): string {\r\n try {\r\n return readFileSync(filePath, 'utf8');\r\n } catch (error) {\r\n const code = (error as NodeJS.ErrnoException).code;\r\n if (code === 'ENOENT') {\r\n throw new StartupError(missing.code, missing.message, {\r\n sourcePath: filePath,\r\n hint: missing.hint,\r\n });\r\n }\r\n throw new StartupError('POLICY_INVALID', 'the policy file cannot be read', {\r\n sourcePath: filePath,\r\n details: [error instanceof Error ? error.message : String(error)],\r\n });\r\n }\r\n}\r\n\r\nfunction policyProblems(sourcePath: string, problems: readonly ConfigProblem[]): StartupError {\r\n return new StartupError('POLICY_INVALID', `policy rejected (${problems.length} problem${problems.length === 1 ? '' : 's'})`, {\r\n sourcePath,\r\n keys: problems.map((problem) => problem.key),\r\n details: problems.map((problem) => problem.message),\r\n hint: 'fix policy.json, then have a human run `mem policy seal --accept`',\r\n });\r\n}\r\n", "import { randomBytes } from 'node:crypto';\nimport { closeSync, mkdirSync, openSync, renameSync, rmSync, fsyncSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { sleepSync } from './wait.ts';\n\n/**\n * Atomic replace: write a sibling temp file, fsync it, then rename over the\n * target. On Windows, rename can hit `EPERM`/`EBUSY` while an indexer or\n * antivirus holds the target; a short bounded retry is the documented behaviour\n * (plan v1.3 \u00A76.2), and a persistent failure is a loud error, never a half\n * write.\n *\n * Directory entries are not fsynced: Windows cannot flush a directory handle.\n * The store therefore promises \"detectable and recoverable after a crash\", not\n * zero loss on power failure (plan v1.3 \u00A72.2).\n */\nexport interface AtomicWriteOptions {\n readonly retries?: number;\n readonly retryDelayMs?: number;\n}\n\nexport function writeFileAtomic(\n filePath: string,\n data: string | Uint8Array,\n options: AtomicWriteOptions = {},\n): void {\n mkdirSync(dirname(filePath), { recursive: true });\n const tempPath = `${filePath}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`;\n const retries = options.retries ?? 5;\n const delay = options.retryDelayMs ?? 20;\n\n try {\n const fd = openSync(tempPath, 'w');\n try {\n writeFileSync(fd, typeof data === 'string' ? data : Buffer.from(data));\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n\n for (let attempt = 0; ; attempt += 1) {\n try {\n renameSync(tempPath, filePath);\n return;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if ((code !== 'EPERM' && code !== 'EBUSY') || attempt >= retries) throw error;\n sleepSync(delay * (attempt + 1));\n }\n }\n } catch (error) {\n rmSync(tempPath, { force: true });\n throw error;\n }\n}\n\nexport function ensureDir(dir: string): void {\n mkdirSync(dir, { recursive: true });\n}\n", "/** Synchronous sleep for retry loops; avoids busy-waiting. */\nexport function sleepSync(ms: number): void {\n if (ms <= 0) return;\n const cell = new Int32Array(new SharedArrayBuffer(4));\n Atomics.wait(cell, 0, 0, ms);\n}\n", "import { createHash } from 'node:crypto';\nimport type { EvidenceLevel, Kind, MemoryDoc, MemoryRelation, ProvenanceEntry, RelationType } from './types.ts';\nimport { projectProblem, relationsProblem, sourceProblem, tagsProblem } from './metadata.ts';\n\n/**\n * Frontmatter is one `key: <JSON value>` per line between two `---` fences.\n *\n * That is the whole format: no YAML parser, no aliases, no multi-line values.\n * Unknown or duplicated keys, missing required fields, a second inline object on\n * one line, or a value whose JSON type is wrong all refuse the file \u2014 a\n * half-understood memory is worse than a rejected one.\n */\n\nexport interface MemoryLimits {\n readonly abstractChars: number;\n readonly bodyChars: number;\n readonly maxRecordChars: number;\n}\n\nexport class FrontmatterError extends Error {\n readonly field: string;\n readonly filePath: string | undefined;\n\n constructor(field: string, message: string, filePath?: string) {\n super(`${field}: ${message}`);\n this.name = 'FrontmatterError';\n this.field = field;\n this.filePath = filePath;\n }\n}\n\nconst FIELD_ORDER = [\n 'id',\n 'mem_schema',\n 'kind',\n 'scope',\n 'project',\n 'tags',\n 'relations',\n 'source',\n 'abstract',\n 'created_at',\n 'valid_from',\n 'valid_until',\n 'supersedes',\n 'author',\n 'evidence_level',\n 'error_signatures',\n 'provenance',\n] as const;\n\nconst FIELD_SET = new Set<string>(FIELD_ORDER);\nconst KINDS = new Set<Kind>(['fact', 'pitfall', 'exp']);\nconst EVIDENCE = new Set<EvidenceLevel>(['user_explicit', 'user_confirmed', 'observed', 'inferred']);\nconst SPEAKERS = new Set(['user', 'assistant', 'tool', 'system']);\n\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst TIMESTAMP = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/;\nconst ID = /^mem-\\d{8}-[0-9a-f]{8}$/;\nconst SHA256 = /^[0-9a-f]{64}$/;\n\nexport function normalizeText(text: string): string {\n const withoutBom = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n return withoutBom.replaceAll('\\r\\n', '\\n').replace(/\\n*$/, '\\n');\n}\n\nexport function hashContent(text: string): string {\n return createHash('sha256').update(normalizeText(text), 'utf8').digest('hex');\n}\n\nfunction isValidDate(value: string): boolean {\n const match = DATE.exec(value);\n if (match === null) return false;\n const [, year, month, day] = match;\n const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)));\n return (\n date.getUTCFullYear() === Number(year) &&\n date.getUTCMonth() === Number(month) - 1 &&\n date.getUTCDate() === Number(day)\n );\n}\n\nfunction fail(field: string, message: string, filePath?: string): never {\n throw new FrontmatterError(field, message, filePath);\n}\n\nfunction requireString(value: unknown, field: string, filePath: string | undefined): string {\n if (typeof value !== 'string') fail(field, `must be a string, found ${JSON.stringify(value)}`, filePath);\n return value;\n}\n\nfunction requireArray(value: unknown, field: string, filePath: string | undefined): readonly unknown[] {\n if (!Array.isArray(value)) fail(field, `must be an array, found ${JSON.stringify(value)}`, filePath);\n return value;\n}\n\nexport function parseMemoryFile(text: string, filePath: string, limits: MemoryLimits): MemoryDoc {\n const normalized = normalizeText(text);\n if (!normalized.startsWith('---\\n')) fail('frontmatter', 'file must start with a \"---\" fence', filePath);\n const end = normalized.indexOf('\\n---\\n', 4);\n if (end < 0) fail('frontmatter', 'missing closing \"---\" fence', filePath);\n\n const header = normalized.slice(4, end);\n const body = normalized.slice(end + 5);\n\n const values = new Map<string, unknown>();\n for (const line of header.split('\\n')) {\n if (line.trim() === '') fail('frontmatter', 'blank line inside the frontmatter', filePath);\n const separator = line.indexOf(': ');\n if (separator < 0) fail('frontmatter', `line is not \"key: <JSON>\": ${line.slice(0, 40)}`, filePath);\n const key = line.slice(0, separator);\n if (!/^[a-z_]+$/.test(key)) fail('frontmatter', `invalid key \"${key}\"`, filePath);\n if (!FIELD_SET.has(key)) fail(key, 'unknown frontmatter key', filePath);\n if (values.has(key)) fail(key, 'duplicate frontmatter key', filePath);\n let parsed: unknown;\n try {\n parsed = JSON.parse(line.slice(separator + 2));\n } catch {\n fail(key, 'value is not valid JSON', filePath);\n }\n values.set(key, parsed);\n }\n\n for (const field of ['id', 'mem_schema', 'kind', 'scope', 'abstract', 'created_at', 'valid_from']) {\n if (!values.has(field)) fail(field, 'missing required field', filePath);\n }\n\n const id = requireString(values.get('id'), 'id', filePath);\n if (!ID.test(id)) fail('id', 'must look like mem-YYYYMMDD-8hex', filePath);\n if (values.get('mem_schema') !== 1 && values.get('mem_schema') !== 2) {\n fail('mem_schema', 'must be 1 or 2', filePath);\n }\n const memSchema = values.get('mem_schema') as 1 | 2;\n const kind = requireString(values.get('kind'), 'kind', filePath);\n if (!KINDS.has(kind as Kind)) fail('kind', 'must be fact, pitfall or exp', filePath);\n if (values.get('scope') !== 'local') fail('scope', 'must be \"local\" in V1', filePath);\n\n const rawProject = values.has('project') ? values.get('project') : null;\n const projectIssue = projectProblem(rawProject);\n if (projectIssue !== undefined) fail('project', projectIssue, filePath);\n const project = rawProject === null || rawProject === undefined ? null : (rawProject as string);\n\n const rawTags = values.has('tags') ? values.get('tags') : [];\n const tagsIssue = tagsProblem(rawTags);\n if (tagsIssue !== undefined) fail('tags', tagsIssue, filePath);\n const tags = requireArray(rawTags, 'tags', filePath).map((entry) => entry as string);\n\n const rawRelations = values.has('relations') ? values.get('relations') : [];\n const relationsIssue = relationsProblem(rawRelations, id);\n if (relationsIssue !== undefined) fail('relations', relationsIssue, filePath);\n const relations = requireArray(rawRelations, 'relations', filePath).map((entry) => {\n const relation = entry as { type: RelationType; target: string };\n return { type: relation.type, target: relation.target } satisfies MemoryRelation;\n });\n\n const rawSource = values.has('source') ? values.get('source') : null;\n const sourceIssue = sourceProblem(rawSource);\n if (sourceIssue !== undefined) fail('source', sourceIssue, filePath);\n const source = rawSource === null || rawSource === undefined ? null : (rawSource as { type: string; id: string });\n\n const abstract = requireString(values.get('abstract'), 'abstract', filePath);\n if (abstract.trim() === '') fail('abstract', 'must not be empty', filePath);\n if (/[\\r\\n]/.test(abstract)) fail('abstract', 'must be a single line', filePath);\n if ([...abstract].length > limits.abstractChars) {\n fail('abstract', `exceeds limits.abstract_chars (${limits.abstractChars})`, filePath);\n }\n\n const createdAt = requireString(values.get('created_at'), 'created_at', filePath);\n if (!TIMESTAMP.test(createdAt)) fail('created_at', 'must be an ISO timestamp with an offset', filePath);\n\n const validFrom = requireString(values.get('valid_from'), 'valid_from', filePath);\n if (!isValidDate(validFrom)) fail('valid_from', 'must be a real YYYY-MM-DD date', filePath);\n\n const rawValidUntil = values.has('valid_until') ? values.get('valid_until') : null;\n let validUntil: string | null = null;\n if (rawValidUntil !== null) {\n validUntil = requireString(rawValidUntil, 'valid_until', filePath);\n if (!isValidDate(validUntil)) fail('valid_until', 'must be null or a real YYYY-MM-DD date', filePath);\n if (validUntil <= validFrom) fail('valid_until', 'must be after valid_from', filePath);\n }\n\n const rawSupersedes = values.has('supersedes') ? values.get('supersedes') : [];\n const supersedes = requireArray(rawSupersedes, 'supersedes', filePath).map((entry) => {\n const target = requireString(entry, 'supersedes[]', filePath);\n if (!ID.test(target)) fail('supersedes[]', `invalid memory id \"${target}\"`, filePath);\n return target;\n });\n if (new Set(supersedes).size !== supersedes.length) fail('supersedes', 'must not contain duplicates', filePath);\n if (supersedes.includes(id)) fail('supersedes', 'must not reference itself', filePath);\n\n const author = requireString(values.get('author'), 'author', filePath);\n if (author !== 'agent' && author !== 'human') fail('author', 'must be agent or human', filePath);\n\n const evidenceLevel = requireString(values.get('evidence_level'), 'evidence_level', filePath);\n if (!EVIDENCE.has(evidenceLevel as EvidenceLevel)) {\n fail('evidence_level', 'must be user_explicit, user_confirmed, observed or inferred', filePath);\n }\n\n const rawSignatures = values.has('error_signatures') ? values.get('error_signatures') : [];\n const errorSignatures = requireArray(rawSignatures, 'error_signatures', filePath).map((entry) => {\n const signature = requireString(entry, 'error_signatures[]', filePath);\n if (signature.length === 0) fail('error_signatures[]', 'must not be empty', filePath);\n if ([...signature].length > 80) fail('error_signatures[]', 'must be at most 80 characters', filePath);\n return signature;\n });\n if (errorSignatures.length > 3) fail('error_signatures', 'must contain at most 3 entries', filePath);\n if (kind === 'pitfall' && errorSignatures.length === 0) {\n fail('error_signatures', 'a pitfall must declare at least one signature', filePath);\n }\n\n const rawProvenance = values.has('provenance') ? values.get('provenance') : [];\n const provenance = requireArray(rawProvenance, 'provenance', filePath).map((entry) => {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {\n fail('provenance[]', 'must be an object', filePath);\n }\n const record = entry as Record<string, unknown>;\n const sessionId = requireString(record.session_id, 'provenance[].session_id', filePath);\n const eventSeq = record.event_seq;\n if (typeof eventSeq !== 'number' || !Number.isSafeInteger(eventSeq) || eventSeq < 0) {\n fail('provenance[].event_seq', 'must be a non-negative integer', filePath);\n }\n const speaker = requireString(record.speaker, 'provenance[].speaker', filePath);\n if (!SPEAKERS.has(speaker)) fail('provenance[].speaker', 'must be user, assistant, tool or system', filePath);\n const quote = requireString(record.quote, 'provenance[].quote', filePath);\n if ([...quote].length > 160) fail('provenance[].quote', 'must be at most 160 characters', filePath);\n const eventSha = requireString(record.event_sha256, 'provenance[].event_sha256', filePath);\n if (!SHA256.test(eventSha)) fail('provenance[].event_sha256', 'must be 64 lowercase hex characters', filePath);\n return { session_id: sessionId, event_seq: eventSeq, speaker, quote, event_sha256: eventSha } as ProvenanceEntry;\n });\n if (author === 'agent' && provenance.length === 0) {\n fail('provenance', 'an agent-authored memory needs at least one provenance entry', filePath);\n }\n\n if ([...body].length > limits.bodyChars) {\n fail('body', `exceeds limits.body_chars (${limits.bodyChars})`, filePath);\n }\n if ([...normalized].length > limits.maxRecordChars) {\n fail('file', `exceeds storage.max_record_chars (${limits.maxRecordChars})`, filePath);\n }\n\n return {\n id,\n mem_schema: memSchema,\n kind: kind as Kind,\n scope: 'local',\n project,\n tags,\n relations,\n source,\n abstract,\n created_at: createdAt,\n valid_from: validFrom,\n valid_until: validUntil,\n supersedes,\n author,\n evidence_level: evidenceLevel as EvidenceLevel,\n error_signatures: errorSignatures,\n provenance,\n body,\n file_path: filePath,\n content_hash: hashContent(normalized),\n };\n}\n\n/** Serialize in the fixed field order so diffs stay stable. */\nexport function serializeMemory(doc: Omit<MemoryDoc, 'file_path' | 'content_hash'>): string {\n const values: Record<string, unknown> = {\n id: doc.id,\n mem_schema: doc.mem_schema,\n kind: doc.kind,\n scope: doc.scope,\n project: doc.project ?? null,\n tags: doc.tags ?? [],\n relations: doc.relations ?? [],\n source: doc.source ?? null,\n abstract: doc.abstract,\n created_at: doc.created_at,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n supersedes: doc.supersedes,\n author: doc.author,\n evidence_level: doc.evidence_level,\n error_signatures: doc.error_signatures,\n provenance: doc.provenance,\n };\n const lines = FIELD_ORDER.map((field) => `${field}: ${JSON.stringify(values[field])}`);\n const body = doc.body.endsWith('\\n') ? doc.body : `${doc.body}\\n`;\n return `---\\n${lines.join('\\n')}\\n---\\n${body}`;\n}\n", "import type { MemoryRelation, MemorySource, RelationType } from './types.ts';\n\n/**\n * Metadata limits for the v1.4 fields (`project`, `tags`, `relations`).\n *\n * Kept in one module so the file parser and the store reject the same shapes.\n * Relations deliberately stop at three edge families: `supersedes` remains its\n * own immutable field; `relates_to`/`derived_from` live here.\n */\n\nexport const PROJECT_NAME_MAX = 64;\nexport const TAG_MAX = 32;\nexport const TAGS_MAX = 8;\nexport const RELATIONS_MAX = 16;\n\nconst RELATION_TYPES: readonly RelationType[] = ['relates_to', 'derived_from'];\nconst MEMORY_ID = /^mem-\\d{8}-[0-9a-f]{8}$/;\n\nexport function projectProblem(value: unknown): string | undefined {\n if (value === null || value === undefined) return undefined;\n if (typeof value !== 'string') return 'project must be a string or null';\n const name = value.trim();\n if (name === '') return 'project must not be empty';\n if (name !== value) return 'project must not have leading or trailing whitespace';\n if ([...name].length > PROJECT_NAME_MAX) {\n return `project must be at most ${PROJECT_NAME_MAX} characters`;\n }\n if (/[\\r\\n]/.test(name)) return 'project must be a single line';\n if (/[\\\\/]/.test(name)) return 'project must not contain path separators';\n if (name === '\u672A\u5F52\u7C7B') return 'project name \"\u672A\u5F52\u7C7B\" is reserved for the default bucket';\n return undefined;\n}\n\nexport function tagsProblem(value: unknown): string | undefined {\n if (!Array.isArray(value)) return 'tags must be an array';\n if (value.length > TAGS_MAX) return `tags allows at most ${TAGS_MAX} entries`;\n const seen = new Set<string>();\n for (const entry of value) {\n if (typeof entry !== 'string') return 'each tag must be a string';\n if (entry.length === 0) return 'tags must not contain empty entries';\n if ([...entry].length > TAG_MAX) return `each tag must be at most ${TAG_MAX} characters`;\n if (/[\\r\\n]/.test(entry)) return 'tags must be single-line';\n if (seen.has(entry)) return `duplicate tag \"${entry}\"`;\n seen.add(entry);\n }\n return undefined;\n}\n\nexport function relationsProblem(value: unknown, selfId?: string): string | undefined {\n if (!Array.isArray(value)) return 'relations must be an array';\n if (value.length > RELATIONS_MAX) return `relations allows at most ${RELATIONS_MAX} entries`;\n const seen = new Set<string>();\n for (const entry of value) {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {\n return 'each relation must be an object';\n }\n const relation = entry as { type?: unknown; target?: unknown };\n if (typeof relation.type !== 'string' || !RELATION_TYPES.includes(relation.type as RelationType)) {\n return 'relation.type must be relates_to or derived_from';\n }\n if (typeof relation.target !== 'string' || !MEMORY_ID.test(relation.target)) {\n return 'relation.target must look like mem-YYYYMMDD-8hex';\n }\n if (relation.target === selfId) return 'a relation must not target itself';\n const key = `${relation.type}:${relation.target}`;\n if (seen.has(key)) return 'relations must not contain duplicates';\n seen.add(key);\n }\n return undefined;\n}\n\nexport function normalizeRelations(value: readonly MemoryRelation[] | undefined): readonly MemoryRelation[] {\n if (value === undefined || value.length === 0) return [];\n return value.map((relation) => ({ type: relation.type, target: relation.target }));\n}\n\n/** External provenance marker for imported records (Mem0 first). */\nexport function sourceProblem(value: unknown): string | undefined {\n if (value === null || value === undefined) return undefined;\n if (typeof value !== 'object' || Array.isArray(value)) return 'source must be an object or null';\n const source = value as { type?: unknown; id?: unknown };\n if (typeof source.type !== 'string' || source.type.length === 0 || [...source.type].length > 32) {\n return 'source.type must be a non-empty string up to 32 characters';\n }\n if (typeof source.id !== 'string' || source.id.length === 0 || [...source.id].length > 128) {\n return 'source.id must be a non-empty string up to 128 characters';\n }\n if (/[\\r\\n]/.test(source.type) || /[\\r\\n]/.test(source.id)) return 'source values must be single-line';\n return undefined;\n}\n\nexport function normalizeSource(value: MemorySource | null | undefined): MemorySource | null {\n if (value === null || value === undefined) return null;\n return { type: value.type, id: value.id };\n}\n", "import { existsSync, readFileSync } from 'node:fs';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { projectProblem, PROJECT_NAME_MAX } from '../model/metadata.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * User-created project registry (v1.4).\n *\n * Projects are labels, not folders: a memory points at a project name, and the\n * registry only decides which names the UI offers. Deleting a project therefore\n * never deletes memories; they simply stop matching a live project.\n *\n * The file is plain JSON at `<home>/projects.json` and is intentionally small:\n * `{ schema: 1, projects: [{ name, description, created_at, updated_at }] }`.\n */\n\nexport interface Project {\n readonly name: string;\n readonly description: string;\n readonly created_at: string;\n readonly updated_at: string;\n}\n\nexport interface ProjectRegistry {\n readonly schema: 1;\n readonly projects: readonly Project[];\n}\n\nexport class ProjectError extends Error {\n readonly code: 'INVALID' | 'EXISTS' | 'NOT_FOUND';\n constructor(code: ProjectError['code'], message: string) {\n super(message);\n this.name = 'ProjectError';\n this.code = code;\n }\n}\n\nconst DESCRIPTION_MAX = 280;\nconst TIMESTAMP = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nfunction readRegistry(home: string): ProjectRegistry {\n const file = memoryPaths(home).projectsFile;\n if (!existsSync(file)) return { schema: 1, projects: [] };\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(file, 'utf8').replace(/^\\uFEFF/, ''));\n } catch {\n throw new ProjectError('INVALID', `projects.json is not valid JSON: ${file}`);\n }\n if (typeof parsed !== 'object' || parsed === null) {\n throw new ProjectError('INVALID', 'projects.json must be an object');\n }\n const record = parsed as { schema?: unknown; projects?: unknown };\n if (record.schema !== 1) throw new ProjectError('INVALID', 'projects.json schema must be 1');\n if (!Array.isArray(record.projects)) throw new ProjectError('INVALID', 'projects.json projects must be an array');\n const seen = new Set<string>();\n const projects: Project[] = [];\n for (const raw of record.projects) {\n if (typeof raw !== 'object' || raw === null) throw new ProjectError('INVALID', 'each project must be an object');\n const entry = raw as { name?: unknown; description?: unknown; created_at?: unknown; updated_at?: unknown };\n const issue = projectProblem(entry.name);\n if (issue !== undefined) throw new ProjectError('INVALID', issue);\n if (typeof entry.description !== 'string' || [...entry.description].length > DESCRIPTION_MAX) {\n throw new ProjectError('INVALID', `project description must be a string up to ${DESCRIPTION_MAX} characters`);\n }\n if (typeof entry.created_at !== 'string' || !TIMESTAMP.test(entry.created_at)) {\n throw new ProjectError('INVALID', 'project created_at must be an ISO timestamp');\n }\n if (typeof entry.updated_at !== 'string' || !TIMESTAMP.test(entry.updated_at)) {\n throw new ProjectError('INVALID', 'project updated_at must be an ISO timestamp');\n }\n const name = entry.name as string;\n if (seen.has(name.toLocaleLowerCase())) throw new ProjectError('INVALID', `duplicate project name: ${name}`);\n seen.add(name.toLocaleLowerCase());\n projects.push({\n name,\n description: entry.description,\n created_at: entry.created_at,\n updated_at: entry.updated_at,\n });\n }\n return { schema: 1, projects };\n}\n\nfunction writeRegistry(home: string, registry: ProjectRegistry): void {\n writeFileAtomic(memoryPaths(home).projectsFile, `${JSON.stringify(registry, null, 2)}\\n`);\n}\n\nexport function listProjects(home: string): readonly Project[] {\n return readRegistry(home).projects;\n}\n\nexport function projectExists(home: string, name: string): boolean {\n const lower = name.toLocaleLowerCase();\n return readRegistry(home).projects.some((project) => project.name.toLocaleLowerCase() === lower);\n}\n\nexport function createProject(options: {\n home: string;\n name: string;\n description?: string;\n now?: Date;\n}): Project {\n const name = options.name.trim();\n const issue = projectProblem(name);\n if (issue !== undefined) throw new ProjectError('INVALID', issue);\n if (name.length > PROJECT_NAME_MAX) throw new ProjectError('INVALID', 'project name is too long');\n const description = (options.description ?? '').trim();\n if ([...description].length > DESCRIPTION_MAX) {\n throw new ProjectError('INVALID', `project description must be at most ${DESCRIPTION_MAX} characters`);\n }\n if (/[\\r\\n]/.test(description)) throw new ProjectError('INVALID', 'project description must be a single line');\n const registry = readRegistry(options.home);\n if (registry.projects.some((project) => project.name.toLocaleLowerCase() === name.toLocaleLowerCase())) {\n throw new ProjectError('EXISTS', `project already exists: ${name}`);\n }\n const at = (options.now ?? new Date()).toISOString();\n const project: Project = { name, description, created_at: at, updated_at: at };\n writeRegistry(options.home, { schema: 1, projects: [...registry.projects, project] });\n return project;\n}\n\n/** Create an empty registry during `mem init`; existing files are kept. */\nexport function ensureProjectsFile(home: string): boolean {\n const file = memoryPaths(home).projectsFile;\n if (existsSync(file)) return false;\n writeRegistry(home, { schema: 1, projects: [] });\n return true;\n}\n\n/**\n * Remove a project label. Memories keep their frontmatter untouched; callers\n * map an unknown project to the \"\u672A\u5F52\u7C7B\" bucket. If the name is later recreated,\n * those memories become visible under it again by design.\n */\nexport function deleteProject(home: string, name: string): boolean {\n const registry = readRegistry(home);\n const lower = name.toLocaleLowerCase();\n const kept = registry.projects.filter((project) => project.name.toLocaleLowerCase() !== lower);\n if (kept.length === registry.projects.length) return false;\n writeRegistry(home, { schema: 1, projects: kept });\n return true;\n}\n", "import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * V5.0-S2 checkpoint: a small, HMAC-protected snapshot of the journal head and\n * the accounted document hashes. Startup can trust it, then replay only the\n * journal tail. The journal remains the append-only audit source.\n */\n\nexport const CHECKPOINT_SCHEMA = 1;\n\nexport interface CheckpointDoc {\n readonly id: string;\n readonly sha256: string;\n readonly deleted: boolean;\n}\n\nexport interface Checkpoint {\n readonly schema: 1;\n readonly created_at: string;\n readonly journal: { readonly seq: number; readonly hash: string; readonly segment?: string };\n readonly docs: readonly CheckpointDoc[];\n readonly journal_root: string;\n readonly docs_root: string;\n readonly hmac: string;\n}\n\nexport interface CheckpointRead {\n readonly checkpoint?: Checkpoint;\n readonly error?: string;\n}\n\nfunction sha256(text: string): string {\n return createHash('sha256').update(text, 'utf8').digest('hex');\n}\n\n/** Binary Merkle root over hex leaves; odd node is promoted. */\nexport function merkleRoot(leaves: readonly string[]): string {\n if (leaves.length === 0) return sha256('');\n let level = leaves.map((leaf) => sha256(leaf));\n while (level.length > 1) {\n const next: string[] = [];\n for (let index = 0; index < level.length; index += 2) {\n const left = level[index] as string;\n const right = level[index + 1];\n next.push(right === undefined ? left : sha256(`${left}${right}`));\n }\n level = next;\n }\n return level[0] as string;\n}\n\nfunction docsRoot(docs: readonly CheckpointDoc[]): string {\n return merkleRoot(docs.map((doc) => `${doc.id}:${doc.sha256}:${doc.deleted ? '1' : '0'}`).sort());\n}\n\nfunction readKey(home: string): Buffer | undefined {\n const file = memoryPaths(home).checkpointKeyFile;\n if (!existsSync(file)) return undefined;\n const key = readFileSync(file);\n if (key.length !== 32) throw new Error('checkpoint key must be 32 bytes');\n return key;\n}\n\nfunction checkpointKey(home: string): Buffer {\n const existing = readKey(home);\n if (existing !== undefined) return existing;\n const file = memoryPaths(home).checkpointKeyFile;\n const key = randomBytes(32);\n try {\n writeFileSync(file, key, { flag: 'wx', mode: 0o600 });\n return key;\n } catch {\n const raced = readKey(home);\n if (raced !== undefined) return raced;\n throw new Error('checkpoint key is unreadable');\n }\n}\n\nfunction canonical(checkpoint: Omit<Checkpoint, 'hmac'>): string {\n return JSON.stringify({\n schema: checkpoint.schema,\n created_at: checkpoint.created_at,\n journal: checkpoint.journal,\n docs: checkpoint.docs,\n journal_root: checkpoint.journal_root,\n docs_root: checkpoint.docs_root,\n });\n}\n\nexport function writeCheckpoint(home: string, input: {\n journal: { seq: number; hash: string; segment?: string };\n docs: readonly CheckpointDoc[];\n journalRoot: string;\n now?: Date;\n}): Checkpoint {\n const docs = input.docs.slice().sort((left, right) => left.id.localeCompare(right.id));\n const body = {\n schema: CHECKPOINT_SCHEMA as 1,\n created_at: (input.now ?? new Date()).toISOString(),\n journal: input.journal,\n docs,\n journal_root: input.journalRoot,\n docs_root: docsRoot(docs),\n };\n const hmac = createHmac('sha256', checkpointKey(home)).update(canonical(body), 'utf8').digest('hex');\n const checkpoint: Checkpoint = { ...body, hmac };\n writeFileAtomic(memoryPaths(home).checkpointFile, `${JSON.stringify(checkpoint, null, 2)}\\n`);\n return checkpoint;\n}\n\nexport function readCheckpoint(home: string): CheckpointRead {\n const file = memoryPaths(home).checkpointFile;\n if (!existsSync(file)) return {};\n let parsed: Checkpoint;\n try {\n parsed = JSON.parse(readFileSync(file, 'utf8')) as Checkpoint;\n } catch {\n return { error: 'checkpoint is not valid JSON' };\n }\n if (parsed.schema !== CHECKPOINT_SCHEMA) return { error: `unsupported checkpoint schema ${String(parsed.schema)}` };\n if (typeof parsed.hmac !== 'string' || parsed.hmac === '') return { error: 'checkpoint has no HMAC' };\n if (docsRoot(parsed.docs) !== parsed.docs_root) return { error: 'checkpoint docs root mismatch' };\n let key: Buffer;\n try {\n const found = readKey(home);\n if (found === undefined) return { error: 'checkpoint key is missing (restore .state/checkpoint.key or remove checkpoint)' };\n key = found;\n } catch (error) {\n return { error: error instanceof Error ? error.message : String(error) };\n }\n const expected = createHmac('sha256', key).update(canonical({\n schema: parsed.schema,\n created_at: parsed.created_at,\n journal: parsed.journal,\n docs: parsed.docs,\n journal_root: parsed.journal_root,\n docs_root: parsed.docs_root,\n }), 'utf8').digest('hex');\n const left = Buffer.from(expected, 'hex');\n const right = Buffer.from(parsed.hmac, 'hex');\n if (left.length !== right.length || !timingSafeEqual(left, right)) return { error: 'checkpoint HMAC mismatch' };\n return { checkpoint: parsed };\n}\n\n/** Ensure the key exists (backup/restore and diagnostics). */\nexport function ensureCheckpointKey(home: string): void {\n checkpointKey(home);\n}\n", "import { randomBytes } from 'node:crypto';\nimport { closeSync, fsyncSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';\nimport { sleepSync } from './wait.ts';\n\n/**\n * Single-writer lock with a lease.\n *\n * Acquired before the first read and held across read \u2192 validate \u2192 write \u2192\n * journal \u2192 derived files (plan v1.3 \u00A76.2). A lease only becomes stale when its\n * heartbeat is older than `stale_ms` **and** the recorded PID is gone; a live\n * process keeps the lock even if its heartbeat is late, so a slow operation is\n * never silently overwritten.\n */\n\nexport interface LockConfig {\n readonly heartbeatMs: number;\n readonly staleMs: number;\n readonly timeoutMs: number;\n}\n\nexport interface LockFileInfo {\n readonly pid: number;\n readonly token: string;\n readonly acquired_at: number;\n readonly heartbeat_at: number;\n}\n\nexport type LockErrorCode = 'LOCK_TIMEOUT' | 'LOCK_LOST';\n\nexport class LockError extends Error {\n readonly code: LockErrorCode;\n constructor(code: LockErrorCode, message: string) {\n super(message);\n this.name = 'LockError';\n this.code = code;\n }\n}\n\nexport function readLock(file: string): LockFileInfo | null {\n try {\n const raw = JSON.parse(readFileSync(file, 'utf8')) as Partial<LockFileInfo>;\n if (\n typeof raw.pid === 'number' &&\n typeof raw.token === 'string' &&\n typeof raw.acquired_at === 'number' &&\n typeof raw.heartbeat_at === 'number'\n ) {\n return { pid: raw.pid, token: raw.token, acquired_at: raw.acquired_at, heartbeat_at: raw.heartbeat_at };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\nfunction lockIsStale(file: string, info: LockFileInfo | null, config: LockConfig, now: number): boolean {\n if (info === null) {\n // Unreadable lock file: only a crashed writer can leave one; age it by mtime.\n try {\n return now - statSync(file).mtimeMs > config.staleMs;\n } catch {\n return false;\n }\n }\n return now - info.heartbeat_at > config.staleMs && !processAlive(info.pid);\n}\n\nexport interface AcquireOptions {\n readonly file: string;\n readonly config: LockConfig;\n readonly now?: () => number;\n}\n\nexport class FileLock {\n readonly file: string;\n readonly token: string;\n private readonly now: () => number;\n private timer: NodeJS.Timeout | undefined;\n private closed = false;\n\n constructor(file: string, token: string, config: LockConfig, now: () => number) {\n this.file = file;\n this.token = token;\n this.now = now;\n this.timer = setInterval(() => this.touch(), config.heartbeatMs);\n this.timer.unref();\n }\n\n touch(): void {\n if (this.closed) return;\n const current = readLock(this.file);\n if (current === null || current.token !== this.token) return;\n this.write({ ...current, heartbeat_at: this.now() });\n }\n\n assertHeld(): void {\n const current = readLock(this.file);\n if (current === null || current.token !== this.token) {\n throw new LockError('LOCK_LOST', `lock ${this.file} is no longer held by this process`);\n }\n }\n\n release(): void {\n if (this.closed) return;\n this.closed = true;\n if (this.timer !== undefined) clearInterval(this.timer);\n const current = readLock(this.file);\n if (current !== null && current.token === this.token) {\n try {\n unlinkSync(this.file);\n } catch {\n // A vanished lock file is already released.\n }\n }\n }\n\n private write(info: LockFileInfo): void {\n const fd = openSync(this.file, 'w');\n try {\n writeSync(fd, JSON.stringify(info));\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n }\n}\n\nexport function acquireLock(options: AcquireOptions): FileLock {\n const now = options.now ?? Date.now;\n const deadline = now() + options.config.timeoutMs;\n const token = randomBytes(8).toString('hex');\n\n for (;;) {\n const info: LockFileInfo = {\n pid: process.pid,\n token,\n acquired_at: now(),\n heartbeat_at: now(),\n };\n try {\n const fd = openSync(options.file, 'wx');\n try {\n writeSync(fd, JSON.stringify(info));\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n return new FileLock(options.file, token, options.config, now);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== 'EEXIST') throw error;\n }\n\n const existing = readLock(options.file);\n if (lockIsStale(options.file, existing, options.config, now())) {\n try {\n unlinkSync(options.file);\n } catch {\n // Someone else cleared it first; the retry loop handles either outcome.\n }\n continue;\n }\n\n if (now() >= deadline) {\n throw new LockError(\n 'LOCK_TIMEOUT',\n `timed out after ${options.config.timeoutMs}ms waiting for ${options.file}`,\n );\n }\n sleepSync(Math.min(50, Math.max(1, deadline - now())));\n }\n}\n\n/** Test helper: overwrite the heartbeat so a fake writer looks abandoned. */\nexport function forceHeartbeat(file: string, at: number): void {\n const info = readLock(file);\n if (info === null) return;\n writeFileSync(file, JSON.stringify({ ...info, heartbeat_at: at }));\n}\n", "import { randomBytes } from 'node:crypto';\n\n/** `mem-YYYYMMDD-8hex`; generated server-side, never accepted from a model. */\nconst ID_PATTERN = /^mem-\\d{8}-[0-9a-f]{8}$/;\n\nexport function isMemoryId(value: string): boolean {\n return ID_PATTERN.test(value);\n}\n\nexport function formatDate(date: Date): string {\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const day = String(date.getDate()).padStart(2, '0');\n return `${year}-${month}-${day}`;\n}\n\nexport function newMemoryId(now: Date = new Date(), bytes: () => Buffer = () => randomBytes(4)): string {\n return `mem-${formatDate(now).replaceAll('-', '')}-${bytes().toString('hex')}`;\n}\n", "import type { MemoryDoc, MemoryId } from './types.ts';\n\n/**\n * Validity is derived, never stored back into a file:\n *\n * effective end = min(valid_until, every successor's valid_from)\n *\n * A memory is active on a date when `valid_from <= date < effective end`.\n * Supersede edges point from the successor to the memory it replaces, so the\n * reverse map below is rebuilt from the files on every scan.\n */\n\nexport type SuccessorMap = ReadonlyMap<MemoryId, readonly MemoryId[]>;\n\nexport function buildSuccessorMap(docs: Iterable<MemoryDoc>): Map<MemoryId, MemoryId[]> {\n const map = new Map<MemoryId, MemoryId[]>();\n for (const doc of docs) {\n for (const target of doc.supersedes) {\n const list = map.get(target);\n if (list === undefined) map.set(target, [doc.id]);\n else list.push(doc.id);\n }\n }\n return map;\n}\n\n/** Today as `YYYY-MM-DD` in the host's local time zone (the store's date basis). */\nexport function today(now: Date = new Date()): string {\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const day = String(now.getDate()).padStart(2, '0');\n return `${year}-${month}-${day}`;\n}\n\nexport interface DatedPeriod {\n readonly valid_from: string;\n readonly valid_until: string | null;\n /** Ids of memories that supersede this one. */\n readonly successors: readonly MemoryId[];\n}\n\n/**\n * `validFromOf` resolves a successor id to its `valid_from`; passing it in keeps\n * the validity helpers independent of a document collection.\n */\nexport function endFor(period: DatedPeriod, validFromOf: (id: MemoryId) => string | undefined): string | null {\n let end = period.valid_until;\n for (const successorId of period.successors) {\n const start = validFromOf(successorId);\n if (start === undefined) continue;\n if (end === null || start < end) end = start;\n }\n return end;\n}\n\nexport function isActiveOn(\n period: DatedPeriod,\n date: string,\n validFromOf: (id: MemoryId) => string | undefined,\n): boolean {\n if (date < period.valid_from) return false;\n const end = endFor(period, validFromOf);\n return end === null || date < end;\n}\n\n/** Build the `validFromOf` lookup used by the helpers above. */\nexport function validFromLookup(docs: Iterable<MemoryDoc>): (id: MemoryId) => string | undefined {\n const map = new Map<MemoryId, string>();\n for (const doc of docs) map.set(doc.id, doc.valid_from);\n return (id) => map.get(id);\n}\n\n/** Active docs on `date`, newest first by valid_from then id (deterministic). */\nexport function activeDocs(docs: Iterable<MemoryDoc>, date: string): MemoryDoc[] {\n const all = [...docs];\n const validFromOf = validFromLookup(all);\n const successors = buildSuccessorMap(all);\n return all\n .filter((doc) =>\n isActiveOn(\n {\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n successors: successors.get(doc.id) ?? [],\n },\n date,\n validFromOf,\n ),\n )\n .sort((left, right) => {\n if (left.valid_from !== right.valid_from) return right.valid_from.localeCompare(left.valid_from);\n return left.id.localeCompare(right.id);\n });\n}\n\n/**\n * Problems that make a new/updated supersede edge invalid. The candidate is\n * not yet in `docs`; its id must not be reachable from any target.\n */\nexport function supersedeProblems(\n candidate: { readonly id: MemoryId; readonly supersedes: readonly MemoryId[]; readonly valid_from: string },\n docs: ReadonlyMap<MemoryId, MemoryDoc>,\n): string[] {\n const problems: string[] = [];\n const seen = new Set<string>();\n for (const target of candidate.supersedes) {\n if (seen.has(target)) problems.push(`supersedes lists \"${target}\" twice`);\n seen.add(target);\n const doc = docs.get(target);\n if (doc === undefined) {\n problems.push(`supersedes target \"${target}\" does not exist`);\n continue;\n }\n if (doc.valid_from > candidate.valid_from) {\n problems.push(`supersedes target \"${target}\" starts after the successor (${doc.valid_from} > ${candidate.valid_from})`);\n }\n const stack = [...doc.supersedes];\n const visited = new Set<MemoryId>();\n while (stack.length > 0) {\n const current = stack.pop() as MemoryId;\n if (current === candidate.id) {\n problems.push(`supersede chain would form a cycle through \"${target}\"`);\n break;\n }\n if (visited.has(current)) continue;\n visited.add(current);\n const next = docs.get(current);\n if (next !== undefined) stack.push(...next.supersedes);\n }\n }\n return problems;\n}\n", "import { createHash } from 'node:crypto';\nimport { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, statSync, writeSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { JournalEntry, JournalIssue } from '../model/types.ts';\n\n/**\n * The single append-only journal: accounting, deletions, decisions and audit\n * notes live in one place (plan v1.3 D31).\n *\n * One JSON object per line. `hash` is the SHA-256 of that line's bytes without\n * the newline; `prev` is the previous line's hash (64 zeros for the first).\n * Segments roll at 5 MiB and are never rotated away or deleted. `op_id` makes a\n * retried append idempotent.\n */\n\nexport const SEGMENT_BYTES = 5 * 1024 * 1024;\nexport const ZERO_HASH = '0'.repeat(64);\n\ninterface ArchiveIndex {\n readonly schema: 1;\n readonly through_seq: number;\n readonly through_hash: string;\n}\n\nfunction readArchiveIndex(dir: string): ArchiveIndex | undefined {\n const file = join(dir, 'archive', 'index.json');\n if (!existsSync(file)) return undefined;\n try {\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as ArchiveIndex;\n if (parsed.schema !== 1 || typeof parsed.through_seq !== 'number' || typeof parsed.through_hash !== 'string') {\n return undefined;\n }\n return parsed;\n } catch {\n return undefined;\n }\n}\n\nexport type JournalOp = JournalEntry['op'];\n\nexport function hashLine(line: string): string {\n return createHash('sha256').update(line, 'utf8').digest('hex');\n}\n\nexport interface JournalHead {\n readonly seq: number;\n readonly hash: string;\n}\n\nexport interface JournalStats {\n readonly segments: number;\n readonly lines: number;\n readonly bytes: number;\n readonly first_seq: number | null;\n readonly last_seq: number | null;\n readonly largest_segment_bytes: number;\n}\n\nexport interface JournalReadResult {\n readonly entries: readonly JournalEntry[];\n readonly hashes: readonly string[];\n readonly issues: readonly JournalIssue[];\n readonly head: JournalHead | null;\n}\n\nexport interface AppendInput {\n readonly op: JournalOp;\n readonly data: Readonly<Record<string, unknown>>;\n readonly opId?: string;\n readonly at?: string;\n}\n\nexport class Journal {\n readonly dir: string;\n\n constructor(dir: string) {\n this.dir = dir;\n }\n\n segments(): string[] {\n try {\n return readdirSync(this.dir)\n .filter((name) => /^\\d{4}\\.jsonl$/.test(name))\n .sort();\n } catch {\n return [];\n }\n }\n\n /** Last accepted entry, without verifying the whole log. */\n head(): JournalHead | null {\n const segments = this.segments();\n for (let index = segments.length - 1; index >= 0; index -= 1) {\n const file = join(this.dir, segments[index] as string);\n const lines = readFileSync(file, 'utf8').split('\\n').filter((line) => line !== '');\n if (lines.length === 0) continue;\n const last = lines[lines.length - 1] as string;\n try {\n const entry = JSON.parse(last) as JournalEntry;\n return { seq: entry.seq, hash: hashLine(last) };\n } catch {\n return null;\n }\n }\n const archive = readArchiveIndex(this.dir);\n return archive === undefined ? null : { seq: archive.through_seq, hash: archive.through_hash };\n }\n\n readAll(): JournalReadResult {\n const entries: JournalEntry[] = [];\n const hashes: string[] = [];\n const issues: JournalIssue[] = [];\n const opIds = new Set<string>();\n const archive = readArchiveIndex(this.dir);\n let expectedSeq = archive === undefined ? 1 : archive.through_seq + 1;\n let prev = archive === undefined ? ZERO_HASH : archive.through_hash;\n\n for (const name of this.segments()) {\n const file = join(this.dir, name);\n let text: string;\n try {\n text = readFileSync(file, 'utf8');\n } catch (error) {\n issues.push({ kind: 'parse', message: `cannot read ${name}: ${String(error)}` });\n continue;\n }\n const lines = text.split('\\n');\n // A trailing newline is expected; a final non-empty line without one is a\n // torn append and must not be trusted.\n if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();\n for (const line of lines) {\n if (line === '') continue;\n let entry: JournalEntry;\n try {\n entry = JSON.parse(line) as JournalEntry;\n } catch {\n issues.push({ kind: 'parse', message: `${name}: line is not valid JSON`, seq: expectedSeq });\n return { entries, hashes, issues, head: entries.length === 0 ? null : { seq: entries.length, hash: prev } };\n }\n const hash = hashLine(line);\n if (archive !== undefined && entry.seq < expectedSeq) continue;\n if (entry.seq !== expectedSeq) {\n issues.push({\n kind: 'seq',\n message: `${name}: expected seq ${expectedSeq}, found ${entry.seq}`,\n seq: entry.seq,\n });\n }\n if (entry.prev !== prev) {\n issues.push({\n kind: 'chain',\n message: `${name}: seq ${entry.seq} prev does not match the previous line hash`,\n seq: entry.seq,\n });\n }\n if (opIds.has(entry.op_id)) {\n issues.push({ kind: 'duplicate-op', message: `${name}: duplicate op_id ${entry.op_id}`, seq: entry.seq });\n }\n opIds.add(entry.op_id);\n entries.push(entry);\n hashes.push(hash);\n expectedSeq = entry.seq + 1;\n prev = hash;\n }\n }\n\n const head = entries.length === 0\n ? (archive === undefined ? null : { seq: archive.through_seq, hash: archive.through_hash })\n : { seq: entries[entries.length - 1]?.seq ?? 0, hash: prev };\n return { entries, hashes, issues, head };\n }\n\n /** Cheap operational summary for `mem doctor` / metrics. */\n stats(): JournalStats {\n const segments = this.segments();\n let lines = 0;\n let bytes = 0;\n let largest = 0;\n let firstSeq: number | null = null;\n let lastSeq: number | null = null;\n for (const name of segments) {\n const text = readFileSync(join(this.dir, name), 'utf8');\n const size = Buffer.byteLength(text);\n bytes += size;\n largest = Math.max(largest, size);\n const rows = text.split('\\n').filter((line) => line !== '');\n lines += rows.length;\n if (firstSeq === null && rows.length > 0) {\n try {\n firstSeq = (JSON.parse(rows[0] as string) as { seq?: number }).seq ?? null;\n } catch {\n firstSeq = null;\n }\n }\n if (rows.length > 0) {\n try {\n lastSeq = (JSON.parse(rows[rows.length - 1] as string) as { seq?: number }).seq ?? lastSeq;\n } catch {\n // doctor reports parse issues separately\n }\n }\n }\n return { segments: segments.length, lines, bytes, first_seq: firstSeq, last_seq: lastSeq, largest_segment_bytes: largest };\n }\n\n /**\n * Replay only entries after a checkpoint. Old lines are skipped without JSON\n * parsing; the checkpoint's last line hash is the expected `prev`.\n */\n readAfter(afterSeq: number, prevHash: string, fromSegment?: string): JournalReadResult {\n if (afterSeq === 0) return this.readAll();\n const allSegments = this.segments();\n const start = fromSegment === undefined ? 0 : allSegments.indexOf(fromSegment);\n const segments = start < 0 ? allSegments : allSegments.slice(start);\n const entries: JournalEntry[] = [];\n const hashes: string[] = [];\n const issues: JournalIssue[] = [];\n let expectedSeq = afterSeq + 1;\n let prev = prevHash;\n let seenTail = false;\n for (const name of segments) {\n const text = readFileSync(join(this.dir, name), 'utf8');\n for (const line of text.split('\\n')) {\n if (line === '') continue;\n const seqMatch = /^\\{\"seq\":(\\d+)/.exec(line);\n if (seqMatch !== null && Number(seqMatch[1]) <= afterSeq) continue;\n let entry: JournalEntry;\n try {\n entry = JSON.parse(line) as JournalEntry;\n } catch {\n issues.push({ kind: 'parse', message: `${name}: line is not valid JSON`, seq: expectedSeq });\n return { entries, hashes, issues, head: { seq: afterSeq, hash: prevHash } };\n }\n if (entry.seq !== expectedSeq) {\n issues.push({\n kind: 'seq',\n message: `${name}: expected seq ${expectedSeq}, found ${entry.seq}`,\n seq: entry.seq,\n });\n }\n if (entry.prev !== prev) {\n issues.push({\n kind: 'chain',\n message: `${name}: seq ${entry.seq} prev does not match the checkpoint/previous line`,\n seq: entry.seq,\n });\n }\n const hash = hashLine(line);\n if (entry.seq < expectedSeq) continue;\n entries.push(entry);\n hashes.push(hash);\n expectedSeq = entry.seq + 1;\n prev = hash;\n seenTail = true;\n }\n }\n const head = seenTail ? { seq: expectedSeq - 1, hash: prev } : { seq: afterSeq, hash: prevHash };\n return { entries, hashes, issues, head };\n }\n\n findByOpId(opId: string): JournalEntry | undefined {\n return this.readAll().entries.find((entry) => entry.op_id === opId);\n }\n\n /**\n * Append one entry. The caller must hold the store lock: `head()` and the\n * write are not atomic on their own. A repeated `opId` returns the existing\n * entry instead of appending a second one.\n */\n append(input: AppendInput): JournalEntry {\n mkdirSync(this.dir, { recursive: true });\n if (input.opId !== undefined) {\n const existing = this.findByOpId(input.opId);\n if (existing !== undefined) return existing;\n }\n\n const segments = this.segments();\n const lastSegment = segments[segments.length - 1] ?? '0001.jsonl';\n const head = this.head();\n const seq = head === null ? 1 : head.seq + 1;\n const prev = head === null ? ZERO_HASH : head.hash;\n const entry: JournalEntry = {\n seq,\n prev,\n at: input.at ?? new Date().toISOString(),\n op: input.op,\n op_id: input.opId ?? `op-${seq}-${hashLine(`${seq}:${input.op}:${JSON.stringify(input.data)}`).slice(0, 8)}`,\n data: input.data,\n };\n const line = JSON.stringify(entry);\n\n let segmentPath = join(this.dir, lastSegment);\n let size = 0;\n try {\n size = statSync(segmentPath).size;\n } catch {\n size = 0;\n }\n if (size > 0 && size + Buffer.byteLength(line) + 1 > SEGMENT_BYTES) {\n const nextNumber = Number(lastSegment.slice(0, 4)) + 1;\n segmentPath = join(this.dir, `${String(nextNumber).padStart(4, '0')}.jsonl`);\n }\n\n const fd = openSync(segmentPath, 'a');\n try {\n writeSync(fd, `${line}\\n`);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n return entry;\n }\n\n /**\n * Append a batch with one fsync. Bulk import writes files first, then one\n * journal batch makes the whole import durable. A torn final line is ignored\n * by recovery just like a single torn append.\n */\n appendBatch(inputs: readonly AppendInput[]): JournalEntry[] {\n if (inputs.length === 0) return [];\n mkdirSync(this.dir, { recursive: true });\n const segments = this.segments();\n let segmentPath = join(this.dir, segments[segments.length - 1] ?? '0001.jsonl');\n let size = 0;\n try {\n size = statSync(segmentPath).size;\n } catch {\n size = 0;\n }\n let head = this.head();\n const entries: JournalEntry[] = [];\n let fd = openSync(segmentPath, 'a');\n try {\n for (const input of inputs) {\n const seq = head === null ? 1 : head.seq + 1;\n const prev = head === null ? ZERO_HASH : head.hash;\n const entry: JournalEntry = {\n seq,\n prev,\n at: input.at ?? new Date().toISOString(),\n op: input.op,\n op_id: input.opId ?? `op-${seq}-${hashLine(`${seq}:${input.op}:${JSON.stringify(input.data)}`).slice(0, 8)}`,\n data: input.data,\n };\n const line = JSON.stringify(entry);\n if (size > 0 && size + Buffer.byteLength(line) + 1 > SEGMENT_BYTES) {\n closeSync(fd);\n const baseName = segmentPath.split(/[\\\\/]/).pop() as string;\n const nextNumber = Number(baseName.slice(0, 4)) + 1;\n segmentPath = join(this.dir, `${String(nextNumber).padStart(4, '0')}.jsonl`);\n fd = openSync(segmentPath, 'a');\n size = 0;\n }\n writeSync(fd, `${line}\\n`);\n size += Buffer.byteLength(line) + 1;\n head = { seq, hash: hashLine(line) };\n entries.push(entry);\n }\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n return entries;\n }\n}\n\n/** One human-readable line for `mem inspect --audit`. */\nexport function formatJournalEntry(entry: JournalEntry): string {\n const summary = JSON.stringify(entry.data);\n return `${entry.at} #${entry.seq} ${entry.op.padEnd(6)} ${entry.op_id} ${summary}`;\n}\n", "import { existsSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { gzipSync } from 'node:zlib';\nimport { createHash } from 'node:crypto';\nimport { join } from 'node:path';\nimport type { Config } from '../config/config.ts';\nimport { ensureDir, writeFileAtomic } from '../fs/atomic.ts';\nimport { acquireLock } from '../fs/lock.ts';\nimport { Journal, hashLine, type JournalStats } from '../journal/journal.ts';\nimport { merkleRoot, readCheckpoint, writeCheckpoint } from '../journal/checkpoint.ts';\nimport { hashContent, parseMemoryFile, serializeMemory } from '../model/frontmatter.ts';\nimport { projectProblem, relationsProblem, sourceProblem, tagsProblem } from '../model/metadata.ts';\nimport { isMemoryId, newMemoryId } from '../model/ids.ts';\nimport { activeDocs, today } from '../model/validity.ts';\nimport { supersedeProblems } from '../model/validity.ts';\nimport { buildIndex, search } from '../index/bm25.ts';\nimport { cosine, HashEmbeddingProvider } from '../index/embedding.ts';\nimport { fuseScores } from '../index/hybrid.ts';\nimport { embedTexts, readEmbeddingCache, vectorizerCommand } from '../embed/cache.ts';\nimport { TOKENIZER_VERSION } from '../index/tokenizer.ts';\nimport { scanInput } from '../scan/scan.ts';\nimport type {\n Kind,\n MemoryDoc,\n MemoryId,\n RecallResult,\n RecallHit,\n RebuildReport,\n RecordInput,\n ProvenanceEntry,\n Stats,\n WriteResult,\n} from '../model/types.ts';\nimport { memoryPaths, type MemoryPaths } from '../paths.ts';\n\nexport interface StoreOptions {\n readonly home: string;\n readonly config: Config;\n readonly now?: () => Date;\n /** Test seam: called before each commit step; production passes undefined. */\n readonly beforeStep?: (step: string) => void;\n}\n\nexport class MemoryStoreError extends Error {\n readonly code: 'NOT_FOUND' | 'INVALID' | 'CONFLICT';\n constructor(code: MemoryStoreError['code'], message: string) {\n super(message);\n this.name = 'MemoryStoreError';\n this.code = code;\n }\n}\n\nconst KINDS: readonly Kind[] = ['fact', 'pitfall', 'exp'];\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nfunction isRealDate(value: string): boolean {\n const match = DATE.exec(value);\n if (match === null) return false;\n const [, year, month, day] = match;\n const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)));\n return (\n date.getUTCFullYear() === Number(year) &&\n date.getUTCMonth() === Number(month) - 1 &&\n date.getUTCDate() === Number(day)\n );\n}\n\nexport class MemoryStore {\n readonly paths: MemoryPaths;\n readonly config: Config;\n readonly journal: Journal;\n private readonly now: () => Date;\n private readonly beforeStep: ((step: string) => void) | undefined;\n private docs = new Map<MemoryId, MemoryDoc>();\n private quarantined = new Map<MemoryId, string>();\n private deleted = new Set<MemoryId>();\n private accounted = new Map<MemoryId, string>();\n private issues: string[] = [];\n private head: { seq: number; hash: string } | null = null;\n private lastReloadMs = 0;\n private lastCheckpointSeq = 0;\n private checkpointState: { seq: number; created_at: string } | null = null;\n private cachedIndex: { revision: number; asOf: string; index: ReturnType<typeof buildIndex> } | null = null;\n private revision = 0;\n private fileMeta = new Map<MemoryId, { mtimeMs: number; size: number }>();\n private dirtyDerived = 0;\n private pendingAdds: {\n input: RecordInput;\n options: { author: 'agent' | 'human'; opId?: string; provenance?: readonly ProvenanceEntry[] };\n resolve: (result: WriteResult) => void;\n reject: (error: unknown) => void;\n }[] = [];\n private addTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(options: StoreOptions) {\n this.paths = memoryPaths(options.home);\n this.config = options.config;\n this.now = options.now ?? (() => new Date());\n this.beforeStep = options.beforeStep;\n this.journal = new Journal(this.paths.journalDir);\n this.reload();\n if (this.journal.stats().lines > 50_000) {\n try {\n this.maintain({ force: true });\n } catch (error) {\n this.issues.push(`automatic journal maintenance failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n\n /** Re-read the journal checkpoint and the memory files; classify each file. */\n reload(): void {\n const started = performance.now();\n const previousDocs = this.docs;\n const previousMeta = this.fileMeta;\n this.issues = [];\n this.docs = new Map();\n this.quarantined = new Map();\n this.deleted = new Set();\n this.accounted = new Map();\n this.revision += 1;\n this.cachedIndex = null;\n this.fileMeta = new Map();\n\n const latest = new Map<MemoryId, { hash: string; deleted: boolean }>();\n const checkpointRead = readCheckpoint(this.paths.home);\n let read;\n if (checkpointRead.checkpoint !== undefined) {\n const checkpoint = checkpointRead.checkpoint;\n this.lastCheckpointSeq = checkpoint.journal.seq;\n this.checkpointState = { seq: checkpoint.journal.seq, created_at: checkpoint.created_at };\n for (const doc of checkpoint.docs) {\n latest.set(doc.id, { hash: doc.sha256, deleted: doc.deleted });\n if (doc.deleted) this.deleted.add(doc.id);\n if (doc.sha256 !== '') this.accounted.set(doc.id, doc.sha256);\n }\n const tail = this.journal.readAfter(\n checkpoint.journal.seq,\n checkpoint.journal.hash,\n checkpoint.journal.segment,\n );\n read = { entries: tail.entries, issues: tail.issues, head: tail.head ?? checkpoint.journal };\n const journalHead = this.journal.head();\n if (journalHead !== null && journalHead.seq < checkpoint.journal.seq) {\n read = {\n ...read,\n issues: [...read.issues, {\n kind: 'chain',\n message: `journal is behind checkpoint (#${checkpoint.journal.seq}): possible truncation`,\n }],\n };\n }\n } else {\n this.lastCheckpointSeq = 0;\n this.checkpointState = null;\n read = this.journal.readAll();\n if (checkpointRead.error !== undefined) {\n read = {\n ...read,\n issues: [...read.issues, { kind: 'parse', message: `checkpoint: ${checkpointRead.error}` }],\n };\n }\n }\n this.issues = read.issues.map((issue) => issue.message);\n this.head = read.head;\n\n for (const entry of read.entries) {\n const id = typeof entry.data.id === 'string' ? entry.data.id : undefined;\n if (entry.op === 'record' || entry.op === 'adopt') {\n if (id === undefined || typeof entry.data.sha256 !== 'string') continue;\n latest.set(id, { hash: entry.data.sha256, deleted: latest.get(id)?.deleted ?? false });\n } else if (entry.op === 'delete') {\n if (id === undefined) continue;\n latest.set(id, { hash: latest.get(id)?.hash ?? '', deleted: true });\n this.deleted.add(id);\n }\n }\n for (const [id, value] of latest) {\n if (value.hash !== '') this.accounted.set(id, value.hash);\n if (value.deleted) this.deleted.add(id);\n }\n\n for (const kind of KINDS) {\n const dir = join(this.paths.memoriesDir, kind);\n let names: string[];\n try {\n names = readdirSync(dir).filter((name) => name.endsWith('.md'));\n } catch {\n continue;\n }\n for (const name of names) {\n const file = join(dir, name);\n const id = name.slice(0, -3);\n try {\n const stat = statSync(file);\n const cachedDoc = previousDocs.get(id);\n const cachedMeta = previousMeta.get(id);\n let doc: MemoryDoc;\n if (\n cachedDoc !== undefined &&\n cachedMeta !== undefined &&\n cachedMeta.mtimeMs === stat.mtimeMs &&\n cachedMeta.size === stat.size\n ) {\n doc = cachedDoc;\n } else {\n const text = readFileSync(file, 'utf8');\n doc = parseMemoryFile(text, file, {\n abstractChars: this.config.limits.abstract_chars,\n bodyChars: this.config.limits.body_chars,\n maxRecordChars: this.config.storage.max_record_chars,\n });\n }\n if (!isMemoryId(id) || doc.id !== id) {\n this.quarantined.set(doc.id || id, 'id does not match filename');\n continue;\n }\n if (doc.kind !== kind) {\n this.quarantined.set(doc.id, 'kind does not match directory');\n continue;\n }\n const accountedHash = this.accounted.get(doc.id);\n if (accountedHash === undefined) {\n this.quarantined.set(doc.id, 'not accounted in journal');\n continue;\n }\n if (accountedHash !== doc.content_hash) {\n this.quarantined.set(doc.id, 'content hash differs from journal');\n continue;\n }\n this.docs.set(doc.id, doc);\n this.fileMeta.set(doc.id, { mtimeMs: stat.mtimeMs, size: stat.size });\n } catch (error) {\n this.quarantined.set(id, `parse: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n\n // A journal record whose file is gone is not usable either \u2014 unless the\n // journal also records a delete/purge for it (a tombstone is not corruption).\n for (const id of this.accounted.keys()) {\n if (this.deleted.has(id)) continue;\n if (!this.docs.has(id) && !this.quarantined.has(id)) {\n this.quarantined.set(id, 'accounted in journal but file is missing');\n }\n }\n\n // Tripwire: the manifest records where the journal ended after the last\n // successful rebuild. A *shorter* journal now means truncation, not progress.\n // A *longer* journal means a writer appended without refreshing the\n // manifest (the chain is intact), which is a stale derived file, not\n // truncation \u2014 the next `writeDerived` catches up.\n try {\n const manifest = JSON.parse(readFileSync(this.paths.manifestFile, 'utf8')) as {\n journal_head?: { seq?: number; hash?: string } | null;\n };\n const expected = manifest.journal_head;\n const expectedSeq = expected?.seq;\n const expectedHash = expected?.hash;\n if (expectedSeq === undefined || expectedHash === undefined) {\n // No complete head recorded yet; nothing to compare.\n } else if (this.head === null) {\n this.issues.push('journal is empty but the manifest records a head: possible truncation');\n } else if (expectedSeq !== this.head.seq) {\n if (expectedSeq > this.head.seq) {\n this.issues.push(\n `journal head #${this.head.seq} is behind the manifest (#${String(expectedSeq)}): possible truncation`,\n );\n }\n // expectedSeq < this.head.seq: stale manifest, self-heals on write.\n } else if (expectedHash !== this.head.hash) {\n this.issues.push(\n `journal head #${this.head.seq} differs from the manifest (#${String(expectedSeq)}): possible truncation`,\n );\n }\n } catch {\n // A missing or unreadable manifest is a cache problem, not a journal one.\n }\n this.lastReloadMs = performance.now() - started;\n }\n\n active(date: string = today(this.now())): readonly MemoryDoc[] {\n const live = activeDocs(this.docs.values(), date);\n return live.filter((doc) => !this.deleted.has(doc.id) && !this.quarantined.has(doc.id));\n }\n\n read(id: MemoryId): MemoryDoc {\n // The host keeps one store open for the app process; `mem decide` / `mem add`\n // write disk underneath it. Re-scan before a single-document read so a\n // record created by the CLI is immediately readable through `memory_read`.\n this.reload();\n const doc = this.docs.get(id);\n if (doc === undefined) {\n const reason = this.quarantined.get(id);\n throw new MemoryStoreError(\n 'NOT_FOUND',\n reason === undefined ? `no memory with id ${id}` : `memory ${id} is quarantined: ${reason}`,\n );\n }\n return doc;\n }\n\n recall(\n query: string,\n options: { limit?: number; asOf?: string; kinds?: readonly Kind[] } = {},\n ): RecallResult {\n const text = query.trim();\n if (text === '') return { hits: [], warnings: ['empty query'] };\n // Recall is the hot path: skip the full reload when the journal head is\n // unchanged (external CLI writes still move the head and force a reload).\n this.reloadIfJournalChanged();\n const date = options.asOf ?? today(this.now());\n const limit = Math.min(\n options.limit ?? this.config.recall.limit,\n this.config.recall.max_limit,\n );\n const activeSet = activeDocs(this.docs.values(), date).filter(\n (doc) => !this.deleted.has(doc.id) && !this.quarantined.has(doc.id),\n );\n const index = this.indexFor(activeSet, date);\n const byId = new Map(activeSet.map((doc) => [doc.id, doc]));\n const minScore = this.config.recall.min_score / 1000;\n let ranked: Array<{ id: MemoryId; score: number }>;\n if (this.config.recall.hybrid) {\n const lexicalHits = search(index, text, {\n limit: activeSet.length,\n minScorePermille: 0,\n ...(options.kinds === undefined ? {} : { kinds: options.kinds }),\n });\n const lexical = new Map(lexicalHits.map((hit) => [hit.id, hit.score]));\n const provider = new HashEmbeddingProvider();\n const queryVector = provider.embed(text);\n const vector = new Map<MemoryId, number>();\n const kindFilter = options.kinds === undefined ? undefined : new Set(options.kinds);\n for (const doc of activeSet) {\n if (kindFilter !== undefined && !kindFilter.has(doc.kind)) continue;\n vector.set(doc.id, cosine(provider.embed(`${doc.abstract}\\n${doc.body}`), queryVector));\n }\n ranked = [...fuseScores(lexical, vector, this.config.recall.embedding_weight).entries()]\n .filter(([, score]) => score >= minScore)\n .map(([id, score]) => ({ id, score }))\n .sort((left, right) => {\n if (right.score !== left.score) return right.score - left.score;\n const leftDoc = byId.get(left.id);\n const rightDoc = byId.get(right.id);\n if (leftDoc !== undefined && rightDoc !== undefined && rightDoc.valid_from !== leftDoc.valid_from) {\n return rightDoc.valid_from.localeCompare(leftDoc.valid_from);\n }\n return left.id.localeCompare(right.id);\n })\n .slice(0, limit);\n } else {\n ranked = search(index, text, {\n limit,\n minScorePermille: this.config.recall.min_score,\n ...(options.kinds === undefined ? {} : { kinds: options.kinds }),\n });\n }\n const hits: RecallHit[] = [];\n for (const hit of ranked) {\n const doc = byId.get(hit.id);\n if (doc === undefined) continue;\n hits.push({\n id: doc.id,\n kind: doc.kind,\n abstract: doc.abstract,\n score: hit.score,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n provenance_verifiable: doc.provenance.length > 0,\n });\n }\n return {\n hits,\n warnings: this.quarantined.size === 0 ? [] : [...this.quarantined.values()].slice(0, 5),\n };\n }\n\n /**\n * Hybrid retrieval entry point. Sync `recall` stays BM25/hash-only so the\n * CLI/tests keep a cheap path; the host calls this async version when the\n * sidecar vector cache exists.\n */\n async recallAsync(\n query: string,\n options: { limit?: number; asOf?: string; kinds?: readonly Kind[] } = {},\n ): Promise<RecallResult> {\n const text = query.trim();\n if (text === '' || !this.config.recall.hybrid) return this.recall(query, options);\n const cache = readEmbeddingCache(this.paths.home);\n const command = vectorizerCommand();\n if (cache === undefined || command === undefined) {\n const fallback = this.recall(query, options);\n return {\n ...fallback,\n warnings: [\n ...fallback.warnings,\n cache === undefined\n ? 'hybrid requested but .index/embeddings.json is missing; run `mem embed --apply`'\n : 'hybrid requested but AGENT_MEMORY_VECTORIZER is not set',\n ],\n };\n }\n try {\n const queryVector = (await embedTexts(command, [text])).vectors[0];\n if (queryVector === undefined || queryVector.length !== cache.dimensions) {\n throw new Error(`query vector does not match cache dimensions (${cache.dimensions})`);\n }\n this.reloadIfJournalChanged();\n const date = options.asOf ?? today(this.now());\n const limit = Math.min(options.limit ?? this.config.recall.limit, this.config.recall.max_limit);\n const activeSet = activeDocs(this.docs.values(), date).filter(\n (doc) => !this.deleted.has(doc.id) && !this.quarantined.has(doc.id),\n );\n const index = this.indexFor(activeSet, date);\n const lexicalHits = search(index, text, {\n limit: activeSet.length,\n minScorePermille: 0,\n ...(options.kinds === undefined ? {} : { kinds: options.kinds }),\n });\n const lexical = new Map(lexicalHits.map((hit) => [hit.id, hit.score]));\n const kindFilter = options.kinds === undefined ? undefined : new Set(options.kinds);\n const vector = new Map<MemoryId, number>();\n for (const doc of activeSet) {\n if (kindFilter !== undefined && !kindFilter.has(doc.kind)) continue;\n const cached = cache.docs[doc.id];\n if (cached === undefined || cached.length !== queryVector.length) continue;\n let dot = 0;\n for (let at = 0; at < queryVector.length; at += 1) dot += (queryVector[at] ?? 0) * (cached[at] ?? 0);\n vector.set(doc.id, Math.max(0, Math.min(1, dot)));\n }\n const minScore = this.config.recall.min_score / 1000;\n const byId = new Map(activeSet.map((doc) => [doc.id, doc]));\n const ranked = [...fuseScores(lexical, vector, this.config.recall.embedding_weight).entries()]\n .filter(([, score]) => score >= minScore)\n .map(([id, score]) => ({ id, score }))\n .sort((left, right) => {\n if (right.score !== left.score) return right.score - left.score;\n const leftDoc = byId.get(left.id);\n const rightDoc = byId.get(right.id);\n if (leftDoc !== undefined && rightDoc !== undefined && rightDoc.valid_from !== leftDoc.valid_from) {\n return rightDoc.valid_from.localeCompare(leftDoc.valid_from);\n }\n return left.id.localeCompare(right.id);\n })\n .slice(0, limit);\n const hits: RecallHit[] = [];\n for (const hit of ranked) {\n const doc = byId.get(hit.id);\n if (doc === undefined) continue;\n hits.push({\n id: doc.id,\n kind: doc.kind,\n abstract: doc.abstract,\n score: hit.score,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n provenance_verifiable: doc.provenance.length > 0,\n });\n }\n return { hits, warnings: this.quarantined.size === 0 ? [] : [...this.quarantined.values()].slice(0, 5) };\n } catch (error) {\n const fallback = this.recall(query, options);\n return {\n ...fallback,\n warnings: [\n ...fallback.warnings,\n `hybrid vectorizer failed (${error instanceof Error ? error.message : String(error)}); fell back to lexical`,\n ],\n };\n }\n }\n\n /**\n * Move records between project labels by rewriting only the `project` field.\n * This is an organisational change, not a supersede: the id and history stay,\n * and the journal records the new content hash plus an audit line.\n */\n moveProjects(\n ids: readonly MemoryId[],\n project: string | null,\n ): { moved: MemoryId[]; failed: { id: MemoryId; reason: string }[] } {\n const projectIssue = projectProblem(project);\n if (projectIssue !== undefined) throw new MemoryStoreError('INVALID', projectIssue);\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent, writes are blocked: ${this.issues[0]}`);\n }\n const moved: MemoryId[] = [];\n const failed: { id: MemoryId; reason: string }[] = [];\n for (const id of ids) {\n const doc = this.docs.get(id);\n if (doc === undefined) {\n failed.push({ id, reason: 'not found' });\n continue;\n }\n const next = {\n id: doc.id,\n mem_schema: doc.mem_schema,\n kind: doc.kind,\n scope: doc.scope,\n project,\n tags: doc.tags ?? [],\n relations: doc.relations ?? [],\n source: doc.source ?? null,\n abstract: doc.abstract,\n created_at: doc.created_at,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n supersedes: doc.supersedes,\n author: doc.author,\n evidence_level: doc.evidence_level,\n error_signatures: doc.error_signatures,\n provenance: doc.provenance,\n body: doc.body,\n };\n const text = serializeMemory(next);\n const file = join(this.paths.memoriesDir, doc.kind, `${doc.id}.md`);\n this.beforeStep?.('before-write');\n writeFileAtomic(file, text);\n const hash = hashContent(text);\n this.journal.append({ op: 'record', data: { id, sha256: hash } });\n this.journal.append({ op: 'audit', data: { event: 'project-move', id, project } });\n moved.push(id);\n }\n this.reload();\n this.writeDerived();\n return { moved, failed };\n } finally {\n lock.release();\n }\n }\n\n /** Update tags/relations in place (organisational metadata, not a revision). */\n updateMeta(\n id: MemoryId,\n patch: { tags?: readonly string[]; relations?: readonly { type: 'relates_to' | 'derived_from'; target: string }[] },\n ): MemoryDoc {\n if (patch.tags !== undefined) {\n const issue = tagsProblem(patch.tags);\n if (issue !== undefined) throw new MemoryStoreError('INVALID', issue);\n }\n if (patch.relations !== undefined) {\n const issue = relationsProblem(patch.relations, id);\n if (issue !== undefined) throw new MemoryStoreError('INVALID', issue);\n }\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent, writes are blocked: ${this.issues[0]}`);\n }\n const doc = this.docs.get(id);\n if (doc === undefined) throw new MemoryStoreError('NOT_FOUND', `no memory with id ${id}`);\n const next = {\n id: doc.id,\n mem_schema: doc.mem_schema,\n kind: doc.kind,\n scope: doc.scope,\n project: doc.project ?? null,\n tags: patch.tags ?? doc.tags ?? [],\n relations: patch.relations ?? doc.relations ?? [],\n source: doc.source ?? null,\n abstract: doc.abstract,\n created_at: doc.created_at,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n supersedes: doc.supersedes,\n author: doc.author,\n evidence_level: doc.evidence_level,\n error_signatures: doc.error_signatures,\n provenance: doc.provenance,\n body: doc.body,\n };\n const text = serializeMemory(next);\n writeFileAtomic(join(this.paths.memoriesDir, doc.kind, `${doc.id}.md`), text);\n this.journal.append({ op: 'record', data: { id, sha256: hashContent(text) } });\n this.journal.append({ op: 'audit', data: { event: 'memory-meta', id } });\n this.reload();\n this.writeDerived();\n return this.docs.get(id) as MemoryDoc;\n } finally {\n lock.release();\n }\n }\n\n /** Force checkpoint + archive old segments; returns what moved. */\n maintain(options: { force?: boolean; retentionDays?: number } = {}): { archived: string[]; pruned: string[]; checkpointed: boolean } {\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent, repair before maintain: ${this.issues[0]}`);\n }\n const checkpointed = this.checkpoint();\n const archived = this.archiveOldSegments(options.force ?? false);\n const pruned = this.pruneArchives(options.retentionDays ?? 365);\n this.reload();\n return { archived, pruned, checkpointed };\n } finally {\n lock.release();\n }\n }\n\n private archiveOldSegments(force: boolean): string[] {\n if (this.head === null) return [];\n const read = readCheckpoint(this.paths.home);\n if (read.checkpoint === undefined) return [];\n const checkpointSegment = read.checkpoint.journal.segment;\n if (checkpointSegment === undefined) return [];\n const segments = this.journal.segments();\n const at = segments.indexOf(checkpointSegment);\n if (at <= 0) return [];\n if (!force && this.journal.stats().lines <= 50_000) return [];\n\n const archiveDir = this.paths.journalArchiveDir;\n ensureDir(archiveDir);\n const archived: string[] = [];\n const toDelete: string[] = [];\n let throughSeq = 0;\n let throughHash = '';\n for (const name of segments.slice(0, at)) {\n const file = join(this.paths.journalDir, name);\n const text = readFileSync(file, 'utf8');\n const lines = text.split('\\n').filter((line) => line !== '');\n if (lines.length === 0) continue;\n const hashes = lines.map((line) => hashLine(line));\n const first = JSON.parse(lines[0] as string) as { seq: number };\n const last = JSON.parse(lines[lines.length - 1] as string) as { seq: number };\n const lastHash = hashLine(lines[lines.length - 1] as string);\n const meta = {\n schema: 1,\n segment: name,\n first_seq: first.seq,\n last_seq: last.seq,\n count: lines.length,\n bytes: Buffer.byteLength(text),\n sha256: createHash('sha256').update(text, 'utf8').digest('hex'),\n root: merkleRoot(hashes),\n archived_at: this.now().toISOString(),\n };\n const base = name.replace(/\\.jsonl$/, '');\n writeFileSync(join(archiveDir, `${base}.jsonl.gz`), gzipSync(Buffer.from(text)));\n writeFileAtomic(join(archiveDir, `${base}.meta.json`), `${JSON.stringify(meta, null, 2)}\\n`);\n throughSeq = last.seq;\n throughHash = lastHash;\n toDelete.push(file);\n archived.push(name);\n }\n if (archived.length > 0) {\n writeFileAtomic(\n join(archiveDir, 'index.json'),\n `${JSON.stringify({ schema: 1, through_seq: throughSeq, through_hash: throughHash, segments: archived }, null, 2)}\\n`,\n );\n // Delete originals only after the archive index is durable. A crash after\n // this point leaves duplicate lines, which readAll skips by seq.\n for (const file of toDelete) rmSync(file, { force: true });\n this.journal.append({ op: 'audit', data: { event: 'journal-archive', segments: archived, through_seq: throughSeq } });\n }\n return archived;\n }\n\n private pruneArchives(retentionDays: number): string[] {\n if (retentionDays <= 0) return [];\n const dir = this.paths.journalArchiveDir;\n if (!existsSync(dir)) return [];\n const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1000;\n const pruned: string[] = [];\n for (const name of readdirSync(dir)) {\n if (!name.endsWith('.jsonl.gz')) continue;\n const file = join(dir, name);\n try {\n const stat = statSync(file);\n if (stat.mtimeMs < cutoff) {\n rmSync(file, { force: true });\n pruned.push(name);\n }\n } catch {\n // keep; verify reports it\n }\n }\n return pruned;\n }\n\n private indexFor(activeSet: readonly MemoryDoc[], asOf: string): ReturnType<typeof buildIndex> {\n if (this.cachedIndex !== null && this.cachedIndex.revision === this.revision && this.cachedIndex.asOf === asOf) {\n return this.cachedIndex.index;\n }\n const index = buildIndex(activeSet, TOKENIZER_VERSION);\n this.cachedIndex = { revision: this.revision, asOf, index };\n return index;\n }\n\n /** Recall fast path: skip a full reload when the journal head is unchanged. */\n private reloadIfJournalChanged(): void {\n const head = this.journal.head();\n if (\n this.issues.length === 0 &&\n head !== null &&\n this.head !== null &&\n head.seq === this.head.seq &&\n head.hash === this.head.hash\n ) {\n return;\n }\n this.reload();\n }\n\n stats(): Stats {\n return {\n active: this.active().length,\n total_files: this.docs.size + this.quarantined.size,\n quarantined: this.quarantined.size,\n deleted: this.deleted.size,\n pending_proposals: countPending(this.paths.pendingDir),\n journal_head: this.head,\n journal_consistent: this.issues.length === 0,\n };\n }\n\n /**\n * Write one new memory. The caller supplies an author; provenance/evidence\n * binding arrives with the DSH adapter in S4. Duplicate content returns the\n * existing id without touching its file (plan v1.3 \u00A75.4).\n */\n add(\n input: RecordInput,\n options: { author: 'agent' | 'human'; opId?: string; provenance?: readonly ProvenanceEntry[] },\n ): WriteResult {\n this.validateInput(input);\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError(\n 'CONFLICT',\n `journal is inconsistent, writes are blocked: ${this.issues[0]}`,\n );\n }\n const duplicate = this.findDuplicate(input, options.author);\n if (duplicate !== undefined) {\n this.beforeStep?.('before-journal');\n this.journal.append({\n op: 'audit',\n opId: options.opId === undefined ? undefined : `${options.opId}-dedupe`,\n data: { event: 'dedupe', id: duplicate.id },\n });\n return { id: duplicate.id, content_hash: duplicate.content_hash, deduplicated: true, warnings: [] };\n }\n\n const now = this.now();\n const validFrom = input.valid_from ?? today(now);\n if (!isRealDate(validFrom)) {\n throw new MemoryStoreError('INVALID', `valid_from must be a real YYYY-MM-DD date, found ${validFrom}`);\n }\n const duplicateId = this.allocateId(now);\n const relationIssue = relationsProblem(input.relations ?? [], duplicateId);\n if (relationIssue !== undefined) throw new MemoryStoreError('INVALID', relationIssue);\n const doc = {\n id: duplicateId,\n mem_schema: 2 as const,\n kind: input.kind,\n scope: 'local' as const,\n project: input.project ?? null,\n tags: input.tags ?? [],\n relations: input.relations ?? [],\n source: input.source ?? null,\n abstract: input.abstract,\n created_at: now.toISOString(),\n valid_from: validFrom,\n valid_until: null,\n supersedes: [] as readonly MemoryId[],\n author: options.author,\n evidence_level: input.evidence_level,\n error_signatures: input.error_signatures ?? [],\n provenance: options.provenance ?? [],\n body: input.body,\n };\n const text = serializeMemory(doc);\n const filePath = join(this.paths.memoriesDir, doc.kind, `${doc.id}.md`);\n\n this.beforeStep?.('before-write');\n ensureDir(join(this.paths.memoriesDir, doc.kind));\n writeFileAtomic(filePath, text);\n\n this.beforeStep?.('before-journal');\n const hash = hashContent(text);\n const entry = this.journal.append({\n op: 'record',\n ...(options.opId === undefined ? {} : { opId: options.opId }),\n data: { id: doc.id, sha256: hash },\n });\n\n this.beforeStep?.('before-derived');\n const parsed = parseMemoryFile(text, filePath, {\n abstractChars: this.config.limits.abstract_chars,\n bodyChars: this.config.limits.body_chars,\n maxRecordChars: this.config.storage.max_record_chars,\n });\n this.docs.set(parsed.id, parsed);\n this.accounted.set(parsed.id, hash);\n this.deleted.delete(parsed.id);\n this.head = { seq: entry.seq, hash: hashLine(JSON.stringify(entry)) };\n this.revision += 1;\n this.cachedIndex = null;\n try {\n const stat = statSync(filePath);\n this.fileMeta.set(parsed.id, { mtimeMs: stat.mtimeMs, size: stat.size });\n } catch {\n // derived cache; reload can recover\n }\n this.writeDerived();\n return { id: doc.id, content_hash: hash, deduplicated: false, warnings: [] };\n } finally {\n lock.release();\n }\n }\n\n /**\n * Group-commit variant of `add`: concurrent callers are coalesced for a short\n * window, then written with one journal fsync. Sequential awaited calls still\n * pay one commit each; use it when several producers write at once.\n */\n addAsync(\n input: RecordInput,\n options: { author: 'agent' | 'human'; opId?: string; provenance?: readonly ProvenanceEntry[] },\n ): Promise<WriteResult> {\n return new Promise((resolve, reject) => {\n this.pendingAdds.push({ input, options, resolve, reject });\n if (this.addTimer === undefined) {\n this.addTimer = setTimeout(() => {\n this.addTimer = undefined;\n this.flushAddGroup();\n }, 2);\n }\n });\n }\n\n private flushAddGroup(): void {\n const pending = this.pendingAdds.splice(0);\n if (pending.length === 0) return;\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent, writes are blocked: ${this.issues[0]}`);\n }\n const unique: typeof pending = [];\n for (const job of pending) {\n const duplicate = this.findDuplicate(job.input, job.options.author);\n if (duplicate === undefined) {\n unique.push(job);\n } else {\n this.appendAudit({ event: 'dedupe', id: duplicate.id });\n job.resolve({ id: duplicate.id, content_hash: duplicate.content_hash, deduplicated: true, warnings: [] });\n }\n }\n for (const author of ['human', 'agent'] as const) {\n const group = unique.filter((job) => job.options.author === author);\n if (group.length === 0) continue;\n const commonOpId = group.length === 1 ? group[0]?.options.opId : undefined;\n const results = this.addMany(\n group.map((job) => ({\n ...job.input,\n ...(job.options.provenance === undefined ? {} : { provenance: job.options.provenance }),\n })),\n { author, ...(commonOpId === undefined ? {} : { opId: commonOpId }) },\n );\n for (let index = 0; index < group.length; index += 1) {\n (group[index] as (typeof group)[number]).resolve(results[index] as WriteResult);\n }\n }\n } catch (error) {\n for (const job of pending) job.reject(error);\n }\n }\n\n /**\n * Accept a hand-placed or hand-edited file after a human reviewed it: append\n * an `adopt` journal line with the file's current hash. The file itself is\n * never rewritten.\n */\n adopt(id: MemoryId): WriteResult {\n if (!isMemoryId(id)) {\n throw new MemoryStoreError('INVALID', `\"${id}\" is not a memory id`);\n }\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent: ${this.issues[0]}`);\n }\n if (this.deleted.has(id)) {\n throw new MemoryStoreError('CONFLICT', `memory ${id} was deleted and cannot be adopted`);\n }\n const file = this.findMemoryFile(id);\n if (file === undefined) {\n throw new MemoryStoreError('NOT_FOUND', `no memory file for ${id}`);\n }\n const text = readFileSync(file, 'utf8');\n let doc: MemoryDoc;\n try {\n doc = parseMemoryFile(text, file, {\n abstractChars: this.config.limits.abstract_chars,\n bodyChars: this.config.limits.body_chars,\n maxRecordChars: this.config.storage.max_record_chars,\n });\n } catch (error) {\n throw new MemoryStoreError(\n 'INVALID',\n `cannot adopt ${id}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (doc.id !== id) {\n throw new MemoryStoreError('INVALID', `file ${file} declares id ${doc.id}, not ${id}`);\n }\n const findings = scanInput({\n abstract: doc.abstract,\n body: doc.body,\n error_signatures: doc.error_signatures,\n });\n if (findings.length > 0) {\n throw new MemoryStoreError(\n 'INVALID',\n `adopt rejected by scan: ${findings.map((finding) => `${finding.rule}@${finding.field}`).join(', ')}`,\n );\n }\n this.journal.append({\n op: 'adopt',\n opId: `adopt-${id}-${doc.content_hash.slice(0, 16)}`,\n data: { id, sha256: doc.content_hash },\n });\n this.reload();\n this.writeDerived();\n this.reload();\n return { id, content_hash: doc.content_hash, deduplicated: false, warnings: [] };\n } finally {\n lock.release();\n }\n }\n\n /**\n * End a memory's validity without touching its file: one `delete` line in the\n * journal removes it from recall and the catalog, while `read` still works.\n */\n remove(id: MemoryId, options: { reason: string; baseHash?: string }): WriteResult {\n if (!isMemoryId(id)) {\n throw new MemoryStoreError('INVALID', `\"${id}\" is not a memory id`);\n }\n if (options.reason.trim() === '') {\n throw new MemoryStoreError('INVALID', 'a delete needs a reason');\n }\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent: ${this.issues[0]}`);\n }\n if (this.deleted.has(id)) {\n throw new MemoryStoreError('CONFLICT', `memory ${id} is already deleted`);\n }\n const doc = this.docs.get(id);\n if (doc === undefined) {\n const reason = this.quarantined.get(id);\n throw new MemoryStoreError(\n 'NOT_FOUND',\n reason === undefined ? `no memory with id ${id}` : `memory ${id} is quarantined: ${reason}`,\n );\n }\n if (options.baseHash !== undefined && options.baseHash !== doc.content_hash) {\n throw new MemoryStoreError('CONFLICT', `memory ${id} changed since base_hash was taken`);\n }\n this.journal.append({\n op: 'delete',\n data: { id, sha256: doc.content_hash, reason: options.reason },\n });\n this.reload();\n this.writeDerived();\n this.reload();\n return { id, content_hash: doc.content_hash, deduplicated: false, warnings: [] };\n } finally {\n lock.release();\n }\n }\n\n /**\n * Write several memories under one lock. Files are written first; if any write\n * fails, the already-written files are removed before rethrowing, so a failed\n * supersede leaves no half-applied replacement (S4.4).\n */\n addMany(\n inputs: readonly (RecordInput & {\n readonly supersedes?: readonly MemoryId[];\n readonly provenance?: readonly ProvenanceEntry[];\n })[],\n options: { author: 'agent' | 'human'; opId?: string },\n ): WriteResult[] {\n if (inputs.length === 0) return [];\n for (const input of inputs) this.validateInput(input);\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n throw new MemoryStoreError('CONFLICT', `journal is inconsistent, writes are blocked: ${this.issues[0]}`);\n }\n const now = this.now();\n const prepared = inputs.map((input) => {\n const id = newMemoryId(now);\n const supersedes = input.supersedes ?? [];\n const problems = supersedeProblems(\n { id, supersedes, valid_from: input.valid_from ?? today(now) },\n this.docs,\n );\n if (problems.length > 0) throw new MemoryStoreError('INVALID', problems.join('; '));\n const relationIssue = relationsProblem(input.relations ?? [], id);\n if (relationIssue !== undefined) throw new MemoryStoreError('INVALID', relationIssue);\n const doc = {\n id,\n mem_schema: 2 as const,\n kind: input.kind,\n scope: 'local' as const,\n project: input.project ?? null,\n tags: input.tags ?? [],\n relations: input.relations ?? [],\n source: input.source ?? null,\n abstract: input.abstract,\n created_at: now.toISOString(),\n valid_from: input.valid_from ?? today(now),\n valid_until: null,\n supersedes,\n author: options.author,\n evidence_level: input.evidence_level,\n error_signatures: input.error_signatures ?? [],\n provenance: input.provenance ?? [],\n body: input.body,\n };\n return { id, text: serializeMemory(doc), hash: '', kind: doc.kind };\n });\n\n this.beforeStep?.('before-write');\n const written: string[] = [];\n try {\n for (const entry of prepared) {\n const file = join(this.paths.memoriesDir, entry.kind, `${entry.id}.md`);\n ensureDir(join(this.paths.memoriesDir, entry.kind));\n writeFileAtomic(file, entry.text);\n written.push(file);\n }\n } catch (error) {\n for (const file of written) rmSync(file, { force: true });\n throw error;\n }\n\n this.beforeStep?.('before-journal');\n const journalEntries = this.journal.appendBatch(\n prepared.map((entry) => ({\n op: 'record' as const,\n ...(options.opId === undefined ? {} : { opId: `${options.opId}-${entry.id}` }),\n data: { id: entry.id, sha256: hashContent(entry.text) },\n })),\n );\n for (let index = 0; index < prepared.length; index += 1) {\n const entry = prepared[index] as { id: string; text: string; hash: string; kind: string };\n entry.hash = hashContent(entry.text);\n const file = join(this.paths.memoriesDir, entry.kind, `${entry.id}.md`);\n const parsed = parseMemoryFile(entry.text, file, {\n abstractChars: this.config.limits.abstract_chars,\n bodyChars: this.config.limits.body_chars,\n maxRecordChars: this.config.storage.max_record_chars,\n });\n this.docs.set(parsed.id, parsed);\n this.accounted.set(parsed.id, entry.hash);\n this.deleted.delete(parsed.id);\n try {\n const stat = statSync(file);\n this.fileMeta.set(parsed.id, { mtimeMs: stat.mtimeMs, size: stat.size });\n } catch {\n // derived cache; reload can recover\n }\n }\n const lastJournalEntry = journalEntries[journalEntries.length - 1] as { seq: number };\n this.head = { seq: lastJournalEntry.seq, hash: hashLine(JSON.stringify(lastJournalEntry)) };\n\n this.beforeStep?.('before-derived');\n this.revision += 1;\n this.cachedIndex = null;\n this.writeDerived();\n return prepared.map((entry) => ({\n id: entry.id,\n content_hash: entry.hash,\n deduplicated: false,\n warnings: [],\n }));\n } finally {\n lock.release();\n }\n }\n\n /**\n * Append an audit/decide line and refresh the manifest in the same lock, so a\n * journal write made outside `add`/`remove` never looks like truncation.\n */\n appendJournal(op: 'audit' | 'decide', data: Readonly<Record<string, unknown>>): void {\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n this.journal.append({ op, data });\n this.reload();\n this.writeDerived();\n this.reload();\n } finally {\n lock.release();\n }\n }\n\n /** Audit append for non-store writers (snapshot capture): refreshes the manifest head too. */\n appendAudit(data: Readonly<Record<string, unknown>>): void {\n this.appendJournal('audit', data);\n }\n\n /** Physically remove one memory (human T2): tombstone in journal, file gone. */\n purge(id: MemoryId, options: { reason: string }): { removed: boolean; proposals: number } {\n if (!isMemoryId(id)) throw new MemoryStoreError('INVALID', `\"${id}\" is not a memory id`);\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n const file = this.findMemoryFile(id);\n if (file === undefined) throw new MemoryStoreError('NOT_FOUND', `no memory file for ${id}`);\n const doc = this.docs.get(id);\n this.journal.append({\n op: 'delete',\n data: { id, purged: true, reason: options.reason, sha256: doc?.content_hash ?? '' },\n });\n rmSync(file, { force: true });\n\n let proposals = 0;\n let names: string[] = [];\n try {\n names = readdirSync(this.paths.pendingDir).filter((name) => name.endsWith('.json'));\n } catch {\n names = [];\n }\n for (const name of names) {\n const path = join(this.paths.pendingDir, name);\n try {\n const proposal = JSON.parse(readFileSync(path, 'utf8')) as { id?: string; targets?: unknown };\n if (Array.isArray(proposal.targets) && proposal.targets.includes(id)) {\n rmSync(path, { force: true });\n this.journal.append({\n op: 'audit',\n data: { event: 'proposal-invalidated', proposal: proposal.id ?? name, target: id },\n });\n proposals += 1;\n }\n } catch {\n // A corrupt pending file is left for `doctor`, not silently deleted.\n }\n }\n\n this.reload();\n this.writeDerived();\n this.reload();\n return { removed: true, proposals };\n } finally {\n lock.release();\n }\n }\n\n rebuild(): RebuildReport {\n const lock = acquireLock({\n file: this.paths.lockFile,\n config: {\n heartbeatMs: this.config.lock.heartbeat_ms,\n staleMs: this.config.lock.stale_ms,\n timeoutMs: this.config.lock.timeout_ms,\n },\n now: () => this.now().getTime(),\n });\n try {\n this.reload();\n if (this.issues.length > 0) {\n // Rebuilding derived files must not rewrite `journal_head` over a\n // truncated or broken chain: that would hide the damage the manifest\n // tripwire exists to expose.\n throw new MemoryStoreError(\n 'CONFLICT',\n `journal is inconsistent, repair it before rebuild: ${this.issues[0]}`,\n );\n }\n this.writeDerived(true);\n this.checkpoint();\n return {\n records: this.accounted.size,\n files: this.docs.size,\n quarantined: [...this.quarantined.keys()],\n journal_head: this.head,\n journal_consistent: true,\n rebuilt_index: true,\n rebuilt_catalog: true,\n };\n } finally {\n lock.release();\n }\n }\n\n /** Quarantine and journal diagnostics, used by `mem doctor`. */\n diagnostics(): {\n quarantined: ReadonlyMap<MemoryId, string>;\n issues: readonly string[];\n head: { seq: number; hash: string } | null;\n journal: JournalStats;\n reload_ms: number;\n checkpoint: { seq: number; created_at: string } | null;\n } {\n return {\n quarantined: this.quarantined,\n issues: this.issues,\n head: this.head,\n journal: this.journal.stats(),\n reload_ms: Number(this.lastReloadMs.toFixed(3)),\n checkpoint: this.checkpointState,\n };\n }\n\n private writeDerived(force = false): void {\n // Above 1000 records, coalesce O(n) manifest/catalog writes; the journal is\n // still the source of truth and the cache catches up every 50 writes.\n if (!force && this.docs.size > 1000) {\n this.dirtyDerived += 1;\n if (this.dirtyDerived < 50) {\n this.maybeCheckpoint();\n if (this.head !== null && this.head.seq % 500 === 0) this.maybeArchive();\n return;\n }\n }\n this.dirtyDerived = 0;\n const active = this.active();\n const manifest = {\n schema: 1,\n tokenizer_version: TOKENIZER_VERSION,\n built_at: this.now().toISOString(),\n journal_head: this.head,\n entries: active.map((doc) => ({\n id: doc.id,\n kind: doc.kind,\n abstract: doc.abstract,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n supersedes: doc.supersedes,\n evidence_level: doc.evidence_level,\n content_hash: doc.content_hash,\n file: doc.file_path,\n })),\n };\n writeFileAtomic(this.paths.manifestFile, `${JSON.stringify(manifest, null, 2)}\\n`);\n\n const order: Record<string, number> = { user_explicit: 0, user_confirmed: 1, observed: 2, inferred: 3 };\n const sorted = [...active].sort((left, right) => {\n const rank = (order[left.evidence_level] ?? 9) - (order[right.evidence_level] ?? 9);\n if (rank !== 0) return rank;\n if (left.valid_from !== right.valid_from) return right.valid_from.localeCompare(left.valid_from);\n return left.id.localeCompare(right.id);\n });\n const lines = ['<!-- generated by mem; do not edit -->', '', '## MEMORY', ''];\n for (const doc of sorted) lines.push(`- [${doc.kind}] ${doc.abstract} \u2014 ${doc.id}`);\n writeFileAtomic(this.paths.memoryIndexFile, `${lines.join('\\n')}\\n`);\n this.maybeCheckpoint();\n this.maybeArchive();\n }\n\n /** Force a checkpoint (maintenance/tests); returns false when journal is empty. */\n checkpoint(): boolean {\n if (this.head === null) return false;\n const full = this.journal.readAll();\n const docs = [...this.accounted.entries()].map(([id, sha256]) => ({\n id,\n sha256,\n deleted: this.deleted.has(id),\n }));\n writeCheckpoint(this.paths.home, {\n journal: {\n ...this.head,\n segment: this.journal.segments().at(-1),\n },\n docs,\n journalRoot: merkleRoot(full.hashes),\n });\n this.lastCheckpointSeq = this.head.seq;\n return true;\n }\n\n private maybeCheckpoint(force = false): void {\n if (this.head === null) return;\n if (!force && this.head.seq - this.lastCheckpointSeq < 1000) return;\n this.checkpoint();\n }\n\n private maybeArchive(): void {\n if (this.journal.stats().lines <= 50_000) return;\n if (readCheckpoint(this.paths.home).checkpoint === undefined) this.checkpoint();\n this.archiveOldSegments(true);\n }\n\n private validateInput(input: RecordInput): void {\n if (!KINDS.includes(input.kind)) {\n throw new MemoryStoreError('INVALID', `kind must be one of ${KINDS.join(', ')}`);\n }\n const projectIssue = projectProblem(input.project ?? null);\n if (projectIssue !== undefined) throw new MemoryStoreError('INVALID', projectIssue);\n const tagsIssue = tagsProblem(input.tags ?? []);\n if (tagsIssue !== undefined) throw new MemoryStoreError('INVALID', tagsIssue);\n const sourceIssue = sourceProblem(input.source ?? null);\n if (sourceIssue !== undefined) throw new MemoryStoreError('INVALID', sourceIssue);\n if (typeof input.abstract !== 'string' || input.abstract.trim() === '') {\n throw new MemoryStoreError('INVALID', 'abstract must not be empty');\n }\n if (/[\\r\\n]/.test(input.abstract)) {\n throw new MemoryStoreError('INVALID', 'abstract must be a single line');\n }\n if ([...input.abstract].length > this.config.limits.abstract_chars) {\n throw new MemoryStoreError(\n 'INVALID',\n `abstract exceeds limits.abstract_chars (${this.config.limits.abstract_chars})`,\n );\n }\n if (input.body !== undefined && [...input.body].length > this.config.limits.body_chars) {\n throw new MemoryStoreError(\n 'INVALID',\n `body exceeds limits.body_chars (${this.config.limits.body_chars})`,\n );\n }\n if ((input.evidence_level as string) === 'inferred') {\n throw new MemoryStoreError('INVALID', 'inferred content must go through a proposal');\n }\n const signatures = input.error_signatures ?? [];\n if (signatures.length > 3) throw new MemoryStoreError('INVALID', 'error_signatures allows at most 3 entries');\n for (const signature of signatures) {\n if (signature.length === 0 || [...signature].length > 80) {\n throw new MemoryStoreError('INVALID', 'each error_signatures entry must be 1..80 characters');\n }\n }\n if (input.kind === 'pitfall' && signatures.length === 0) {\n throw new MemoryStoreError('INVALID', 'a pitfall must declare at least one error_signatures entry');\n }\n const findings = scanInput({\n abstract: input.abstract,\n body: input.body,\n error_signatures: signatures,\n });\n if (findings.length > 0) {\n throw new MemoryStoreError(\n 'INVALID',\n `content rejected by scan: ${findings.map((finding) => `${finding.rule}@${finding.field}`).join(', ')}`,\n );\n }\n }\n\n private findMemoryFile(id: MemoryId): string | undefined {\n for (const kind of KINDS) {\n const file = join(this.paths.memoriesDir, kind, `${id}.md`);\n if (existsSync(file)) return file;\n }\n return undefined;\n }\n\n private findDuplicate(input: RecordInput, author: 'agent' | 'human'): MemoryDoc | undefined {\n // Content-only dedupe (user request): the date, author and evidence level\n // do not make the same text a new memory. Importing yesterday's export on\n // a new date must skip, not duplicate.\n void author;\n // The stored body always carries the file's single trailing newline.\n const body = input.body.endsWith('\\n') ? input.body : `${input.body}\\n`;\n for (const doc of this.docs.values()) {\n if (this.deleted.has(doc.id) || this.quarantined.has(doc.id)) continue;\n if (\n doc.kind === input.kind &&\n doc.abstract === input.abstract &&\n doc.body === body &&\n JSON.stringify(doc.error_signatures) === JSON.stringify(input.error_signatures ?? []) &&\n doc.supersedes.length === 0\n ) {\n return doc;\n }\n }\n return undefined;\n }\n\n private allocateId(now: Date): MemoryId {\n for (let attempt = 0; attempt < 100; attempt += 1) {\n const id = newMemoryId(now);\n const exists =\n this.docs.has(id) ||\n this.accounted.has(id) ||\n existsSync(join(this.paths.memoriesDir, 'fact', `${id}.md`)) ||\n existsSync(join(this.paths.memoriesDir, 'pitfall', `${id}.md`)) ||\n existsSync(join(this.paths.memoriesDir, 'exp', `${id}.md`));\n if (!exists) return id;\n }\n throw new MemoryStoreError('CONFLICT', 'could not allocate a unique memory id');\n }\n}\n\nfunction countPending(dir: string): number {\n try {\n return readdirSync(dir).filter((name) => name.endsWith('.json')).length;\n } catch {\n return 0;\n }\n}\n", "/**\n * Tokenizer for the in-memory index (plan v1.3 \u00A76.3).\n *\n * NFKC + lower-case; CJK as bigrams; ASCII words; code-shaped fragments keep\n * their whole form and also split on separators. The version is a cache key:\n * changing the rules must invalidate the index.\n */\n\nexport const TOKENIZER_VERSION = 1;\n\nconst CJK = /[\\u3400-\\u9fff\\uf900-\\ufaff]/;\nconst WORD = /[a-z0-9]/;\nconst WORD_BODY = /[a-z0-9_\\-.:/]/;\nconst SEPARATORS = /[-_.:/]+/;\n\nfunction isCjk(char: string): boolean {\n return CJK.test(char);\n}\n\nexport function tokenize(input: string): string[] {\n const text = input.normalize('NFKC').toLowerCase();\n const tokens: string[] = [];\n let index = 0;\n while (index < text.length) {\n const char = text[index] as string;\n if (isCjk(char)) {\n let end = index;\n while (end < text.length && isCjk(text[end] as string)) end += 1;\n const run = [...text.slice(index, end)];\n if (run.length === 1) {\n tokens.push(run[0] as string);\n } else {\n for (let at = 0; at < run.length - 1; at += 1) {\n tokens.push(`${run[at]}${run[at + 1]}`);\n }\n }\n index = end;\n continue;\n }\n if (WORD.test(char)) {\n let end = index;\n while (end < text.length && WORD_BODY.test(text[end] as string)) end += 1;\n const word = text.slice(index, end);\n if (word !== '') {\n tokens.push(word);\n if (SEPARATORS.test(word)) {\n for (const part of word.split(SEPARATORS)) {\n if (part !== '') tokens.push(part);\n }\n }\n }\n index = end;\n continue;\n }\n index += 1;\n }\n return tokens;\n}\n\n/** A compact token string for tests and diagnostics. */\nexport function tokenizeJoined(input: string): string {\n return tokenize(input).join(' ');\n}\n", "import type { Kind, MemoryDoc, MemoryId } from '../model/types.ts';\nimport { tokenize } from './tokenizer.ts';\n\n/**\n * Field-weighted BM25 over the active set (plan v1.3 \u00A76.3).\n *\n * weights: error_signatures \u00D74, abstract \u00D73, body \u00D71; k1=1.2, b=0.75.\n * A literal hit adds a bonus, so error codes and quoted strings still rank well\n * when tokenization is ambiguous. Scores are normalized to 0..1 (top hit = 1)\n * before `recall.min_score` (per-mille) is applied.\n */\n\nconst K1 = 1.2;\nconst B = 0.75;\nconst WEIGHTS = { abstract: 3, body: 1, signatures: 4 } as const;\nconst LITERAL_BONUS = { abstract: 3, body: 1, signatures: 2 } as const;\n\ninterface FieldStats {\n readonly length: number;\n readonly frequencies: ReadonlyMap<string, number>;\n}\n\nexport interface IndexedDoc {\n readonly id: MemoryId;\n readonly kind: Kind;\n readonly abstract: string;\n readonly body: string;\n readonly error_signatures: readonly string[];\n readonly valid_from: string;\n readonly valid_until: string | null;\n readonly fields: {\n readonly abstract: FieldStats;\n readonly body: FieldStats;\n readonly signatures: FieldStats;\n };\n}\n\nexport interface SearchIndex {\n readonly tokenizer_version: number;\n readonly size: number;\n readonly docs: readonly IndexedDoc[];\n readonly df: ReadonlyMap<string, number>;\n readonly averages: { readonly abstract: number; readonly body: number; readonly signatures: number };\n}\n\nfunction frequencies(tokens: readonly string[]): FieldStats {\n const map = new Map<string, number>();\n for (const token of tokens) map.set(token, (map.get(token) ?? 0) + 1);\n return { length: tokens.length, frequencies: map };\n}\n\nexport function buildIndex(docs: Iterable<MemoryDoc>, tokenizerVersion = 1): SearchIndex {\n const indexed: IndexedDoc[] = [];\n const df = new Map<string, number>();\n let abstractLength = 0;\n let bodyLength = 0;\n let signatureLength = 0;\n\n for (const doc of docs) {\n const abstractTokens = tokenize(doc.abstract);\n const bodyTokens = tokenize(doc.body);\n const signatureTokens = doc.error_signatures.flatMap((signature) => tokenize(signature));\n abstractLength += abstractTokens.length;\n bodyLength += bodyTokens.length;\n signatureLength += signatureTokens.length;\n\n const seen = new Set<string>();\n for (const token of [...abstractTokens, ...bodyTokens, ...signatureTokens]) {\n if (seen.has(token)) continue;\n seen.add(token);\n df.set(token, (df.get(token) ?? 0) + 1);\n }\n\n indexed.push({\n id: doc.id,\n kind: doc.kind,\n abstract: doc.abstract,\n body: doc.body,\n error_signatures: doc.error_signatures,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n fields: {\n abstract: frequencies(abstractTokens),\n body: frequencies(bodyTokens),\n signatures: frequencies(signatureTokens),\n },\n });\n }\n\n const size = indexed.length;\n return {\n tokenizer_version: tokenizerVersion,\n size,\n docs: indexed,\n df,\n averages: {\n abstract: size === 0 ? 0 : abstractLength / size,\n body: size === 0 ? 0 : bodyLength / size,\n signatures: size === 0 ? 0 : signatureLength / size,\n },\n };\n}\n\nfunction idf(index: SearchIndex, term: string): number {\n const df = index.df.get(term) ?? 0;\n return Math.log(1 + (index.size - df + 0.5) / (df + 0.5));\n}\n\nfunction fieldScore(\n frequencies: ReadonlyMap<string, number>,\n length: number,\n average: number,\n term: string,\n): number {\n const tf = frequencies.get(term) ?? 0;\n if (tf === 0 || average === 0) return 0;\n return (tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * length) / average));\n}\n\nexport interface SearchOptions {\n readonly limit: number;\n readonly minScorePermille: number;\n readonly kinds?: readonly Kind[];\n}\n\nexport interface SearchHit {\n readonly id: MemoryId;\n readonly score: number;\n}\n\nexport function search(index: SearchIndex, query: string, options: SearchOptions): SearchHit[] {\n const terms = [...new Set(tokenize(query))];\n if (terms.length === 0 || index.size === 0) return [];\n const literal = query.normalize('NFKC').toLowerCase().trim();\n const kindFilter = options.kinds === undefined ? undefined : new Set(options.kinds);\n\n const scored: Array<{ doc: IndexedDoc; score: number }> = [];\n for (const doc of index.docs) {\n if (kindFilter !== undefined && !kindFilter.has(doc.kind)) continue;\n let score = 0;\n for (const term of terms) {\n const weight = idf(index, term);\n score +=\n weight *\n (WEIGHTS.abstract *\n fieldScore(doc.fields.abstract.frequencies, doc.fields.abstract.length, index.averages.abstract, term) +\n WEIGHTS.body *\n fieldScore(doc.fields.body.frequencies, doc.fields.body.length, index.averages.body, term) +\n WEIGHTS.signatures *\n fieldScore(\n doc.fields.signatures.frequencies,\n doc.fields.signatures.length,\n index.averages.signatures,\n term,\n ));\n }\n if (score === 0) continue;\n if (literal !== '') {\n const normalizedAbstract = doc.abstract.normalize('NFKC').toLowerCase();\n const normalizedBody = doc.body.normalize('NFKC').toLowerCase();\n const signatureText = doc.error_signatures.join('\\n').normalize('NFKC').toLowerCase();\n if (normalizedAbstract.includes(literal)) score += LITERAL_BONUS.abstract * (idf(index, literal) + 1);\n if (normalizedBody.includes(literal)) score += LITERAL_BONUS.body;\n if (signatureText.includes(literal)) score += LITERAL_BONUS.signatures;\n }\n scored.push({ doc, score });\n }\n if (scored.length === 0) return [];\n\n const max = Math.max(...scored.map((entry) => entry.score));\n const minimum = options.minScorePermille / 1000;\n return scored\n .map((entry) => ({ doc: entry.doc, normalized: entry.score / max }))\n .filter((entry) => entry.normalized >= minimum)\n .sort((left, right) => {\n if (right.normalized !== left.normalized) return right.normalized - left.normalized;\n if (right.doc.valid_from !== left.doc.valid_from) return right.doc.valid_from.localeCompare(left.doc.valid_from);\n return left.doc.id.localeCompare(right.doc.id);\n })\n .slice(0, options.limit)\n .map((entry) => ({ id: entry.doc.id, score: Number(entry.normalized.toFixed(6)) }));\n}\n", "import { tokenize } from './tokenizer.ts';\n\n/**\n * Local vector provider seam (V4.0-S2a).\n *\n * `HashEmbeddingProvider` is deterministic and dependency-free: it hashes word\n * and character n-gram features into a fixed vector. It is a *fallback* for\n * tests, offline use and CI, not a semantic model. The ONNX provider (S2b) will\n * implement the same interface and replace the backend without changing the\n * fusion code.\n */\n\nexport interface EmbeddingProvider {\n readonly name: string;\n readonly dimensions: number;\n embed(text: string): Float32Array;\n}\n\nconst DIMENSIONS = 256;\n\nfunction hashFeature(feature: string): number {\n let hash = 2166136261;\n for (let index = 0; index < feature.length; index += 1) {\n hash ^= feature.charCodeAt(index);\n hash = Math.imul(hash, 16777619);\n }\n return hash >>> 0;\n}\n\nexport class HashEmbeddingProvider implements EmbeddingProvider {\n readonly name = 'hash-256';\n readonly dimensions = DIMENSIONS;\n\n embed(text: string): Float32Array {\n const vector = new Float32Array(DIMENSIONS);\n const tokens = tokenize(text);\n const features = [...tokens, ...tokens.map((token) => `#${token}`)];\n for (const feature of features) {\n const bucket = hashFeature(feature) % DIMENSIONS;\n vector[bucket] = (vector[bucket] ?? 0) + 1;\n }\n let norm = 0;\n for (const value of vector) norm += value * value;\n norm = Math.sqrt(norm);\n if (norm > 0) for (let index = 0; index < vector.length; index += 1) vector[index] = (vector[index] ?? 0) / norm;\n return vector;\n }\n}\n\nexport function cosine(left: Float32Array, right: Float32Array): number {\n if (left.length !== right.length) throw new Error('embedding dimensions differ');\n let dot = 0;\n for (let index = 0; index < left.length; index += 1) dot += (left[index] ?? 0) * (right[index] ?? 0);\n return Math.max(0, Math.min(1, dot));\n}\n", "import type { MemoryId } from '../model/types.ts';\n\n/** Fuse normalized lexical and vector scores; both inputs are 0..1. */\nexport function fuseScores(\n lexical: ReadonlyMap<MemoryId, number>,\n vector: ReadonlyMap<MemoryId, number>,\n embeddingWeightPermille: number,\n): Map<MemoryId, number> {\n const weight = Math.min(1000, Math.max(0, embeddingWeightPermille)) / 1000;\n const ids = new Set<MemoryId>([...lexical.keys(), ...vector.keys()]);\n const fused = new Map<MemoryId, number>();\n for (const id of ids) {\n const lexicalScore = lexical.get(id) ?? 0;\n const vectorScore = vector.get(id) ?? 0;\n fused.set(id, (1 - weight) * lexicalScore + weight * vectorScore);\n }\n return fused;\n}\n", "import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * Sidecar vector cache (V4.0-S2b).\n *\n * The plugin never runs ONNX itself. A user-installed vectorizer command reads\n * `{ texts: string[] }` from an input file and writes `{ vectors: number[][] }`\n * to an output file:\n *\n * node my-vectorizer.mjs <input.json> <output.json>\n *\n * `mem embed --apply` fills the cache; `recallAsync` asks the same command for\n * the query vector. File IPC (not stdio pipes) keeps it usable under sandboxes\n * that refuse piped child processes.\n */\n\nexport interface EmbeddingCache {\n readonly schema: 1;\n readonly provider: string;\n readonly dimensions: number;\n readonly generated_at: string;\n readonly docs: Readonly<Record<string, readonly number[]>>;\n}\n\nconst CACHE_SCHEMA = 1;\n\nexport function embeddingsFile(home: string): string {\n return join(memoryPaths(home).indexDir, 'embeddings.json');\n}\n\nexport function readEmbeddingCache(home: string): EmbeddingCache | undefined {\n try {\n const parsed = JSON.parse(readFileSync(embeddingsFile(home), 'utf8')) as Partial<EmbeddingCache>;\n if (parsed.schema !== CACHE_SCHEMA) return undefined;\n if (typeof parsed.provider !== 'string' || typeof parsed.dimensions !== 'number') return undefined;\n if (typeof parsed.generated_at !== 'string' || typeof parsed.docs !== 'object' || parsed.docs === null) {\n return undefined;\n }\n return parsed as EmbeddingCache;\n } catch {\n return undefined;\n }\n}\n\nexport function writeEmbeddingCache(home: string, cache: EmbeddingCache): void {\n writeFileAtomic(embeddingsFile(home), `${JSON.stringify(cache)}\\n`);\n}\n\nexport interface VectorizerResult {\n readonly vectors: readonly (readonly number[])[];\n readonly dimensions: number;\n}\n\nexport function vectorizerCommand(): string | undefined {\n const command = process.env.AGENT_MEMORY_VECTORIZER?.trim();\n return command === undefined || command === '' ? undefined : command;\n}\n\n/** Run the user's vectorizer over a batch of texts. */\nexport async function embedTexts(command: string, texts: readonly string[]): Promise<VectorizerResult> {\n const dir = mkdtempSync(join(tmpdir(), 'agent-memory-embed-'));\n const inputPath = join(dir, 'input.json');\n const outputPath = join(dir, 'output.json');\n try {\n writeFileSync(inputPath, JSON.stringify({ texts }));\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command, [inputPath, outputPath], {\n stdio: 'ignore',\n shell: true,\n windowsHide: true,\n });\n child.once('error', reject);\n child.once('exit', (code) => {\n if (code === 0) resolve();\n else reject(new Error(`vectorizer exited with ${code ?? 'no code'}`));\n });\n });\n const parsed = JSON.parse(readFileSync(outputPath, 'utf8')) as { vectors?: unknown };\n if (!Array.isArray(parsed.vectors) || parsed.vectors.length !== texts.length) {\n throw new Error('vectorizer output must contain one vector per text');\n }\n let dimensions = 0;\n for (const vector of parsed.vectors) {\n if (!Array.isArray(vector) || vector.some((value) => typeof value !== 'number' || !Number.isFinite(value))) {\n throw new Error('vectorizer vectors must be arrays of finite numbers');\n }\n if (dimensions === 0) dimensions = vector.length;\n if (vector.length !== dimensions) throw new Error('vectorizer vectors have inconsistent dimensions');\n }\n return { vectors: parsed.vectors as number[][], dimensions };\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n", "/**\n * Content scanning (plan v1.3 \u00A76.4). Cannot be disabled.\n *\n * Findings carry only a rule id and a field name, never the matched text, so a\n * rejection cannot echo a secret into logs or the journal.\n */\n\nexport type ScanRule = 'invisible' | 'credentials' | 'injection' | 'private_tag';\n\nexport interface ScanFinding {\n readonly rule: ScanRule;\n readonly field: string;\n}\n\nexport class ScanError extends Error {\n readonly findings: readonly ScanFinding[];\n constructor(findings: readonly ScanFinding[]) {\n super(`content rejected by scan: ${findings.map((finding) => `${finding.rule}@${finding.field}`).join(', ')}`);\n this.name = 'ScanError';\n this.findings = findings;\n }\n}\n\nconst INVISIBLE = /[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u2069\\uFEFF]|[\\u{E0000}-\\u{E007F}]/u;\nconst CREDENTIALS = [\n /sk-[A-Za-z0-9_-]{16,}/,\n /AKIA[0-9A-Z]{16}/,\n /-----BEGIN [A-Z ]*PRIVATE KEY-----/,\n /(?:postgres|postgresql|mysql|mongodb|redis):\\/\\/[^\\s]+:[^\\s]+@/i,\n];\nconst INJECTION = [\n /ignore\\s+(all\\s+)?(previous|prior|above)\\s+instructions/i,\n /\u5FFD\u7565(\u4E4B\u524D|\u4EE5\u4E0A|\u524D\u9762)(\u7684)?(\u6240\u6709)?(\u6307\u4EE4|\u6307\u793A)/,\n /disregard\\s+(all\\s+)?(previous|prior)\\s+instructions/i,\n];\nconst PRIVATE_TAG = /<private>[\\s\\S]*?<\\/private>/i;\n\nexport function scanText(field: string, text: string): ScanFinding[] {\n const findings: ScanFinding[] = [];\n if (INVISIBLE.test(text)) findings.push({ rule: 'invisible', field });\n if (CREDENTIALS.some((pattern) => pattern.test(text))) findings.push({ rule: 'credentials', field });\n if (INJECTION.some((pattern) => pattern.test(text))) findings.push({ rule: 'injection', field });\n if (PRIVATE_TAG.test(text)) findings.push({ rule: 'private_tag', field });\n return findings;\n}\n\nexport interface ScannableInput {\n readonly abstract?: string;\n readonly body?: string;\n readonly error_signatures?: readonly string[];\n readonly quote?: string;\n readonly targets?: readonly string[];\n}\n\n/** Scan every field that can reach a file, the journal or the prompt. */\nexport function scanInput(input: ScannableInput): ScanFinding[] {\n const findings: ScanFinding[] = [];\n if (input.abstract !== undefined) findings.push(...scanText('abstract', input.abstract));\n if (input.body !== undefined) findings.push(...scanText('body', input.body));\n if (input.quote !== undefined) findings.push(...scanText('quote', input.quote));\n input.error_signatures?.forEach((signature, index) =>\n findings.push(...scanText(`error_signatures[${index}]`, signature)),\n );\n input.targets?.forEach((target, index) => findings.push(...scanText(`targets[${index}]`, target)));\n return findings;\n}\n\nexport function assertClean(input: ScannableInput): void {\n const findings = scanInput(input);\n if (findings.length > 0) throw new ScanError(findings);\n}\n\n/** T1 path: `<private>\u2026</private>` is not silently stripped; it becomes redacted text. */\nexport function redactPrivate(text: string): string {\n return text.replace(PRIVATE_TAG, '[private]');\n}\n", "import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * RULES.md parser and validator (plan v1.3 \u00A74.3, \u00A79.2).\n *\n * Entry shape:\n *\n * 1. [\u673A\u5668\u95E8\u7981] one line of rule text\n * check: packages/cli/src/main.ts#commandAdd\n * test: packages/core/test/rules/rules.test.ts\n * 2. [\u6A21\u578B\u6307\u5F15] advice for the model, never a system guarantee\n * 3. [\u5E9F\u6B62] a retired entry keeps its number and is labelled\n *\n * A `[\u673A\u5668\u95E8\u7981]` entry is valid only when `check` names an existing symbol, the\n * `test` file exists, and that test file contains a `[neg]` case. `[\u6A21\u578B\u6307\u5F15]`\n * must not claim to be a guarantee.\n */\n\nexport type RuleCategory = 'machine' | 'guide' | 'revoked';\n\nexport interface Rule {\n readonly number: number;\n readonly category: RuleCategory;\n readonly text: string;\n readonly check?: string;\n readonly test?: string;\n}\n\nexport interface RulesParseResult {\n readonly rules: readonly Rule[];\n readonly errors: readonly string[];\n}\n\nconst HEADER = /^(\\d+)\\.\\s*\\[(\u673A\u5668\u95E8\u7981|\u6A21\u578B\u6307\u5F15|\u5E9F\u6B62)\\]\\s*(.*)$/;\nconst EXTRA = /^\\s+(check|test):\\s*(.+)$/;\n\nexport function parseRules(text: string): RulesParseResult {\n const normalized = (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text).replaceAll('\\r\\n', '\\n');\n const rules: Rule[] = [];\n const errors: string[] = [];\n const seen = new Set<number>();\n let current: { number: number; category: RuleCategory; text: string; check?: string; test?: string } | undefined;\n\n const flush = (): void => {\n if (current === undefined) return;\n rules.push({ ...current });\n current = undefined;\n };\n\n for (const raw of normalized.split('\\n')) {\n const line = raw.trimEnd();\n const header = HEADER.exec(line);\n if (header !== null) {\n flush();\n const number = Number(header[1]);\n const label = header[2] as '\u673A\u5668\u95E8\u7981' | '\u6A21\u578B\u6307\u5F15' | '\u5E9F\u6B62';\n if (seen.has(number)) errors.push(`rule ${number}: duplicate number`);\n seen.add(number);\n current = {\n number,\n category: label === '\u673A\u5668\u95E8\u7981' ? 'machine' : label === '\u6A21\u578B\u6307\u5F15' ? 'guide' : 'revoked',\n text: (header[3] ?? '').trim(),\n };\n continue;\n }\n if (current === undefined) continue;\n const extra = EXTRA.exec(line);\n if (extra !== null) {\n if (extra[1] === 'check') current.check = (extra[2] ?? '').trim();\n else current.test = (extra[2] ?? '').trim();\n continue;\n }\n if (line.trim() === '') continue;\n current.text = `${current.text} ${line.trim()}`.trim();\n }\n flush();\n\n for (const rule of rules) {\n if (rule.category === 'machine') {\n if (rule.check === undefined || rule.check === '') errors.push(`rule ${rule.number}: [\u673A\u5668\u95E8\u7981] needs \"check:\"`);\n if (rule.test === undefined || rule.test === '') errors.push(`rule ${rule.number}: [\u673A\u5668\u95E8\u7981] needs \"test:\"`);\n }\n if (rule.category === 'guide' && /\u4FDD\u8BC1|guarantee/i.test(rule.text)) {\n errors.push(`rule ${rule.number}: [\u6A21\u578B\u6307\u5F15] must not be described as a guarantee`);\n }\n }\n return { rules, errors };\n}\n\nexport interface RuleValidationOptions {\n /** Repository root used to resolve `check` and `test` paths. */\n readonly rootDir: string;\n}\n\n/** Resolve a `path#symbol` check and confirm the symbol appears in that file. */\nfunction checkSymbolExists(check: string, rootDir: string): boolean {\n const [path, symbol] = check.split('#');\n if (path === undefined || symbol === undefined || path === '' || symbol === '') return false;\n const file = join(rootDir, path);\n if (!existsSync(file)) return false;\n return readFileSync(file, 'utf8').includes(symbol);\n}\n\nexport function validateRules(rules: readonly Rule[], options: RuleValidationOptions): string[] {\n const errors: string[] = [];\n for (const rule of rules) {\n if (rule.category !== 'machine') continue;\n if (rule.check === undefined || !checkSymbolExists(rule.check, options.rootDir)) {\n errors.push(`rule ${rule.number}: check \"${rule.check ?? ''}\" does not name an existing symbol`);\n }\n if (rule.test === undefined) continue;\n const testFile = join(options.rootDir, rule.test);\n if (!existsSync(testFile)) {\n errors.push(`rule ${rule.number}: test file \"${rule.test}\" does not exist`);\n continue;\n }\n if (!/\\[neg\\]/.test(readFileSync(testFile, 'utf8'))) {\n errors.push(`rule ${rule.number}: test file \"${rule.test}\" has no [neg] case`);\n }\n }\n return errors;\n}\n\nexport function parseAndValidateRules(text: string, options: RuleValidationOptions): RulesParseResult {\n const parsed = parseRules(text);\n return { rules: parsed.rules, errors: [...parsed.errors, ...validateRules(parsed.rules, options)] };\n}\n\n/** Read and parse the store's RULES.md (used by `rules_list`). */\nexport function loadRules(home: string): readonly Rule[] {\n const file = memoryPaths(home).rulesFile;\n if (!existsSync(file)) return [];\n return parseRules(readFileSync(file, 'utf8')).rules;\n}\n\n/** Numbered rendering for injection; `[\u5E9F\u6B62]` is labelled but not enforceable. */\nexport function renderRules(rules: readonly Rule[], options: { includeRevoked?: boolean } = {}): string {\n const lines: string[] = [];\n for (const rule of rules) {\n if (rule.category === 'revoked' && options.includeRevoked !== true) continue;\n const label = rule.category === 'machine' ? '\u673A\u5668\u95E8\u7981' : rule.category === 'guide' ? '\u6A21\u578B\u6307\u5F15' : '\u5E9F\u6B62';\n lines.push(`${rule.number}. [${label}] ${rule.text}`);\n }\n return lines.join('\\n');\n}\n\n/** Raw RULES.md text (comments included); empty when the file is absent. */\nexport function readRulesFile(home: string): string {\n const file = memoryPaths(home).rulesFile;\n return existsSync(file) ? readFileSync(file, 'utf8') : '';\n}\n\n/**\n * Human GUI save path: validate the whole file, then write it atomically.\n * It does not seal policy.json; the caller seals with an explicit human action.\n */\nexport function saveRulesFile(home: string, text: string): void {\n const parsed = parseAndValidateRules(text, { rootDir: home });\n if (parsed.errors.length > 0) {\n throw new Error(`RULES.md rejected: ${parsed.errors.join('; ')}`);\n }\n writeFileAtomic(memoryPaths(home).rulesFile, text);\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { memoryPaths } from '../paths.ts';\nimport { writeFileAtomic } from '../fs/atomic.ts';\n\n/**\n * Frozen per-session injection snapshot (plan v1.3 \u00A76.1).\n *\n * Same session + same prompt schema => byte-identical text on every assemble,\n * even after new writes; a new session captures the current revision. At most\n * 20 snapshots are kept (oldest removed on capture).\n */\n\nexport const PROMPT_SCHEMA_VERSION = 4;\nexport const SNAPSHOT_KEEP = 20;\n\nexport interface SnapshotRecord {\n readonly session_id: string;\n readonly memory_revision: string;\n readonly prompt_schema_version: number;\n readonly created_at: string;\n readonly text: string;\n /** Per-section text so the host can register one prompt section per source. */\n readonly parts?: Readonly<Record<string, string>>;\n readonly sectionList?: readonly { readonly key: string; readonly order: number; readonly text: string }[];\n readonly health?: readonly { readonly key: string; readonly ok: boolean; readonly message?: string }[];\n}\n\nexport function snapshotPath(home: string, sessionId: string): string {\n const name = createHash('sha256').update(sessionId, 'utf8').digest('hex').slice(0, 32);\n return join(memoryPaths(home).snapshotsDir, `${name}.json`);\n}\n\nexport function readSnapshot(home: string, sessionId: string): SnapshotRecord | null {\n const file = snapshotPath(home, sessionId);\n if (!existsSync(file)) return null;\n try {\n const record = JSON.parse(readFileSync(file, 'utf8')) as SnapshotRecord;\n if (\n record.session_id !== sessionId ||\n typeof record.text !== 'string' ||\n typeof record.memory_revision !== 'string' ||\n typeof record.prompt_schema_version !== 'number'\n ) {\n return null;\n }\n return record;\n } catch {\n return null;\n }\n}\n\nexport function writeSnapshot(home: string, record: SnapshotRecord, keep = SNAPSHOT_KEEP): void {\n writeFileAtomic(snapshotPath(home, record.session_id), `${JSON.stringify(record, null, 2)}\\n`);\n pruneSnapshots(home, keep);\n}\n\n/** Keep the newest `keep` snapshot files; a snapshot is a cache, not truth. */\nexport function pruneSnapshots(home: string, keep = SNAPSHOT_KEEP): void {\n const dir = memoryPaths(home).snapshotsDir;\n let names: string[];\n try {\n names = readdirSync(dir).filter((name) => name.endsWith('.json'));\n } catch {\n return;\n }\n if (names.length <= keep) return;\n const byAge = names\n .map((name) => ({ name, mtime: statSync(join(dir, name)).mtimeMs }))\n .sort((left, right) => right.mtime - left.mtime);\n for (const entry of byAge.slice(keep)) {\n try {\n rmSync(join(dir, entry.name), { force: true });\n } catch {\n // A snapshot that cannot be removed is only wasted disk space.\n }\n }\n}\n", "import { createHash, randomBytes } from 'node:crypto';\nimport type { Config } from '../config/config.ts';\nimport type { Policy } from '../policy/policy.ts';\nimport { verifySealedFiles } from '../policy/policy.ts';\nimport type { Rule } from '../rules/rules.ts';\nimport { today } from '../model/validity.ts';\nimport type { MemoryDoc } from '../model/types.ts';\nimport { buildSections, SECTION_ORDERS, type SectionHealth, type SectionSource } from './sections.ts';\nimport { readSnapshot, writeSnapshot, PROMPT_SCHEMA_VERSION } from './snapshot.ts';\n\n/**\n * Injection assembly (plan v1.3 \u00A76.1; architecture v2 P0.5).\n *\n * Sections come from the registry (`sections.ts`): SOUL, GUIDANCE, RULES, USER,\n * then the memory catalog built here. A broken optional section degrades to a\n * visible notice (health entry) instead of failing the whole injection; sealed\n * files and store integrity remain global failures. The text is frozen per\n * session in `.state/snapshots/` and wrapped in a random delimiter.\n */\n\nexport type InjectionErrorCode = 'RULES_INVALID' | 'RULES_OVER_BUDGET' | 'OVER_BUDGET';\n\nexport class InjectionError extends Error {\n readonly code: InjectionErrorCode;\n constructor(code: InjectionErrorCode, message: string) {\n super(message);\n this.name = 'InjectionError';\n this.code = code;\n }\n}\n\nexport interface InjectionSource {\n active(date?: string): readonly MemoryDoc[];\n /** Preferred audit sink: keeps the store manifest head in sync. */\n appendAudit?(data: Record<string, unknown>): void;\n readonly journal?: { append(entry: { op: 'audit'; data: Record<string, unknown> }): unknown };\n}\n\nexport interface AssembleInput {\n readonly home: string;\n readonly config: Config;\n readonly policy: Policy;\n readonly source: InjectionSource;\n readonly sessionId: string;\n readonly asOf?: string;\n readonly now?: () => Date;\n /** Token counter; when absent, chars/2.5 and `estimated: true`. */\n readonly measure?: (text: string) => number;\n /** Test seam: fixed delimiter instead of a random 16-hex one. */\n readonly delimiter?: string;\n /** Test seam: skip snapshot persistence. */\n readonly persist?: boolean;\n /** Extension seam: extra document layers (P0.5 section registry). */\n readonly extraSections?: readonly SectionSource[];\n}\n\nexport interface InjectionBudget {\n readonly counter: 'chars' | 'tokens';\n readonly estimated: boolean;\n readonly sections: Readonly<Record<string, number>>;\n readonly total: number;\n}\n\nexport interface AssembleResult {\n readonly text: string;\n readonly memory_revision: string;\n readonly captured: boolean;\n readonly budget: InjectionBudget;\n readonly sections: readonly string[];\n readonly rules: readonly Rule[];\n /** Per-source text, one entry per source (empty when absent). */\n readonly parts: Readonly<Record<string, string>>;\n /** Rendered section list in order, so the host can register one prompt section per source. */\n readonly sectionList: readonly { readonly key: string; readonly order: number; readonly text: string }[];\n /** Per-section health; a degraded section still appears in `sectionList` as a notice. */\n readonly health: readonly SectionHealth[];\n}\n\nconst EVIDENCE_RANK: Record<string, number> = {\n user_explicit: 0,\n user_confirmed: 1,\n observed: 2,\n inferred: 3,\n};\n\nfunction charCount(text: string): number {\n return [...text].length;\n}\n\nexport function memoryRevision(docs: Iterable<MemoryDoc>): string {\n const lines = [...docs]\n .map((doc) => `${doc.id}:${doc.content_hash}`)\n .sort((left, right) => left.localeCompare(right));\n return createHash('sha256').update(lines.join('\\n'), 'utf8').digest('hex');\n}\n\nfunction catalogLines(docs: readonly MemoryDoc[]): string[] {\n const sorted = [...docs].sort((left, right) => {\n const rank = (EVIDENCE_RANK[left.evidence_level] ?? 9) - (EVIDENCE_RANK[right.evidence_level] ?? 9);\n if (rank !== 0) return rank;\n if (left.valid_from !== right.valid_from) return right.valid_from.localeCompare(left.valid_from);\n return left.id.localeCompare(right.id);\n });\n return sorted.map((doc) => `- [${doc.kind}] ${doc.abstract} \u2014 ${doc.id}`);\n}\n\nfunction fitCatalog(docs: readonly MemoryDoc[], budget: number): string {\n const lines = catalogLines(docs);\n if (lines.length === 0) return '';\n let used = 0;\n const kept: string[] = [];\n for (const line of lines) {\n const cost = charCount(line) + 1;\n if (used + cost > budget) break;\n kept.push(line);\n used += cost;\n }\n const remaining = lines.length - kept.length;\n if (remaining > 0) {\n const hint =\n docs.length > 200\n ? `- \u2026${remaining} \u6761\u672A\u5217\u51FA\uFF08\u7528 memory_recall \u68C0\u7D22\uFF09`\n : `- \u2026${remaining} \u6761\u672A\u5217\u51FA`;\n kept.push(hint);\n }\n return kept.join('\\n');\n}\n\nfunction counted(text: string, counter: 'chars' | 'tokens', measure?: (text: string) => number): number {\n if (counter === 'chars') return charCount(text);\n return measure === undefined ? Math.ceil(charCount(text) / 2.5) : measure(text);\n}\n\nexport function assemble(input: AssembleInput): AssembleResult {\n const now = input.now ?? (() => new Date());\n const date = input.asOf ?? today(now());\n\n // T2: re-check the sealed human files right before reading them, so an edit\n // after startup cannot slip into the prompt.\n verifySealedFiles({ home: input.home, policy: input.policy });\n\n const active = input.source.active(date);\n const revision = memoryRevision(active);\n\n const existing = readSnapshot(input.home, input.sessionId);\n if (\n existing !== null &&\n existing.prompt_schema_version === PROMPT_SCHEMA_VERSION &&\n existing.parts !== undefined &&\n existing.sectionList !== undefined\n ) {\n return {\n text: existing.text,\n memory_revision: existing.memory_revision,\n captured: false,\n budget: { counter: input.config.inject.counter, estimated: input.measure === undefined, sections: {}, total: 0 },\n sections: existing.sectionList.map((section) => section.key),\n rules: [],\n parts: existing.parts,\n sectionList: existing.sectionList,\n health: existing.health ?? [],\n };\n }\n\n const built = buildSections({ home: input.home, config: input.config }, input.extraSections ?? []);\n const sectionList: { key: string; order: number; text: string }[] = [...built.entries];\n const parts: Record<string, string> = {};\n for (const entry of sectionList) parts[entry.key] = entry.text;\n const rules = built.rules;\n\n const catalog = fitCatalog(active, input.config.inject.index_max_chars);\n if (catalog !== '') {\n parts.MEMORY = catalog;\n sectionList.push({ key: 'MEMORY', order: SECTION_ORDERS.MEMORY, text: catalog });\n }\n sectionList.sort((left, right) => left.order - right.order);\n\n let body = sectionList.map((section) => `## ${section.key}\\n${section.text}`).join('\\n\\n');\n const counter = input.config.inject.counter;\n let total = counted(body, counter, input.measure);\n if (total > input.config.inject.total_max_chars) {\n // Only the catalog may be trimmed further; all other sections are capped.\n const indexSection = sectionList.find((section) => section.key === 'MEMORY');\n if (indexSection === undefined) {\n throw new InjectionError('OVER_BUDGET', `injection is over inject.total_max_chars (${input.config.inject.total_max_chars})`);\n }\n const excess = total - input.config.inject.total_max_chars;\n indexSection.text = fitCatalog(active, Math.max(0, input.config.inject.index_max_chars - excess - 8));\n parts.MEMORY = indexSection.text;\n body = sectionList.map((section) => `## ${section.key}\\n${section.text}`).join('\\n\\n');\n total = counted(body, counter, input.measure);\n if (total > input.config.inject.total_max_chars) {\n throw new InjectionError('OVER_BUDGET', `injection is over inject.total_max_chars (${input.config.inject.total_max_chars})`);\n }\n }\n\n const delimiter = input.delimiter ?? randomBytes(8).toString('hex');\n const escaped = body.split(delimiter).join('<escaped>');\n const text = `<<AM-${delimiter}>>\\n${escaped}\\n<<AM-${delimiter}>>`;\n\n const sectionBudgets: Record<string, number> = {};\n for (const section of sectionList) {\n sectionBudgets[section.key] = counted(section.text, counter, input.measure);\n }\n\n const record = {\n session_id: input.sessionId,\n memory_revision: revision,\n prompt_schema_version: PROMPT_SCHEMA_VERSION,\n created_at: now().toISOString(),\n text,\n parts,\n sectionList,\n health: built.health,\n };\n if (input.persist !== false) {\n writeSnapshot(input.home, record);\n try {\n const audit = { event: 'snapshot-capture', session_id: input.sessionId };\n if (input.source.appendAudit !== undefined) {\n input.source.appendAudit(audit);\n } else {\n input.source.journal?.append({ op: 'audit', data: audit });\n }\n } catch {\n // Journal trouble is reported by the store; a snapshot is still usable.\n }\n }\n\n return {\n text,\n memory_revision: revision,\n captured: true,\n budget: {\n counter,\n estimated: counter === 'tokens' && input.measure === undefined,\n sections: sectionBudgets,\n total,\n },\n sections: sectionList.map((section) => section.key),\n rules,\n parts,\n sectionList,\n health: built.health,\n };\n}\n\n/** DSH adapter shape: one protected section, no interpolation. */\nexport function sectionPayload(result: AssembleResult, order = 100) {\n return { name: 'agent-memory', order, text: result.text, interpolate: false as const };\n}\n", "import { existsSync, readFileSync } from 'node:fs';\nimport type { Config } from '../config/config.ts';\nimport { memoryPaths } from '../paths.ts';\nimport { renderGuidance } from '../personalization/guidance.ts';\nimport { parseRules, renderRules, validateRules, type Rule } from '../rules/rules.ts';\n\n/**\n * Section registry (architecture v2, P0.5). Each injected block is one source\n * with its own order, budget and failure mode. A broken optional section only\n * degrades itself (visible notice + health entry); sealed-file and store\n * integrity checks stay outside and remain global.\n *\n * Adding a document layer later means adding one source here (or passing one\n * through `AssembleInput.extraSections`) \u2014 assemble() and the GUI do not change.\n */\n\nexport interface SectionSource {\n readonly key: string;\n readonly order: number;\n /** Hard character cap; undefined means the source enforces its own budget. */\n readonly maxChars?: number;\n /** Render the raw text (parse/validate). Throw to degrade this section. */\n readonly render?: (text: string) => string;\n readonly load: () => string;\n}\n\nexport interface SectionContext {\n readonly home: string;\n readonly config: Config;\n}\n\nexport interface SectionHealth {\n readonly key: string;\n readonly ok: boolean;\n readonly message?: string;\n}\n\nexport interface BuiltSections {\n readonly entries: readonly { key: string; order: number; text: string }[];\n readonly health: readonly SectionHealth[];\n readonly rules: readonly Rule[];\n}\n\nconst COMMENT = /<!--[\\s\\S]*?-->/g;\n\nfunction charCount(text: string): number {\n return [...text].length;\n}\n\nfunction truncate(text: string, budget: number): string {\n const points = [...text];\n if (points.length <= budget) return text;\n if (budget <= 1) return '\u2026';\n return `${points.slice(0, budget - 1).join('')}\u2026`;\n}\n\nfunction readIfExists(file: string): string {\n return existsSync(file) ? readFileSync(file, 'utf8').replace(COMMENT, '').trim() : '';\n}\n\nexport const SECTION_ORDERS = { SOUL: 100, GUIDANCE: 110, RULES: 150, USER: 200, MEMORY: 300 } as const;\n\nexport function builtinSectionSources(context: SectionContext): SectionSource[] {\n const paths = memoryPaths(context.home);\n return [\n {\n key: 'SOUL',\n order: SECTION_ORDERS.SOUL,\n maxChars: context.config.inject.persona_max_chars,\n load: () => readIfExists(paths.soulFile),\n },\n {\n key: 'GUIDANCE',\n order: SECTION_ORDERS.GUIDANCE,\n maxChars: context.config.inject.guidance_max_chars,\n load: () => renderGuidance(context.config.personalization.mode),\n },\n {\n key: 'RULES',\n order: SECTION_ORDERS.RULES,\n render: (text) => {\n const parsed = parseRules(text);\n const errors = [...parsed.errors, ...validateRules(parsed.rules, { rootDir: context.home })];\n if (errors.length > 0) throw new Error(`RULES.md rejected: ${errors.join('; ')}`);\n const rendered = renderRules(parsed.rules, { includeRevoked: false });\n if (charCount(rendered) > context.config.inject.rules_max_chars) {\n throw new Error(\n `RULES.md renders to ${charCount(rendered)} chars, over inject.rules_max_chars (${context.config.inject.rules_max_chars})`,\n );\n }\n return rendered;\n },\n load: () => readIfExists(paths.rulesFile),\n },\n {\n key: 'USER',\n order: SECTION_ORDERS.USER,\n maxChars: context.config.inject.user_max_chars,\n load: () => readIfExists(paths.userFile),\n },\n ];\n}\n\n/** Render every source, degrading only the failing one. */\nexport function buildSections(context: SectionContext, extra: readonly SectionSource[] = []): BuiltSections {\n const sources = [...builtinSectionSources(context), ...extra].sort((left, right) => left.order - right.order);\n const entries: { key: string; order: number; text: string }[] = [];\n const health: SectionHealth[] = [];\n const rules: Rule[] = [];\n\n for (const source of sources) {\n try {\n const loaded = source.load();\n const rendered = source.render === undefined ? loaded : source.render(loaded);\n const text = source.maxChars === undefined ? rendered : truncate(rendered, source.maxChars);\n if (text !== '') entries.push({ key: source.key, order: source.order, text });\n health.push({ key: source.key, ok: true });\n if (source.key === 'RULES') {\n rules.push(...parseRules(loaded).rules);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const notice = `\u26A0 \u672C\u8282\u4E0D\u53EF\u7528\uFF08${source.key}\uFF09\uFF1A${message}`.slice(0, 200);\n entries.push({ key: source.key, order: source.order, text: notice });\n health.push({ key: source.key, ok: false, message });\n }\n }\n\n return { entries, health, rules };\n}\n", "import type { PersonalizationMode } from './mode.ts';\n\n/**\n * `MEMORY_GUIDANCE` section (architecture v2, P3). Short, mode-aware instructions\n * that tell the model how to use the memory surfaces. It is injected right after\n * SOUL and kept inside the guidance budget.\n */\n\nexport function renderGuidance(mode: PersonalizationMode): string {\n const modeLine =\n mode === 'direct'\n ? '- \u81EA\u4E3B\u5224\u65AD\u5E76\u76F4\u63A5\u5199\u5165\uFF0C\u65E0\u9700\u5148\u5F81\u5F97\u540C\u610F\uFF1B\u4ECD\u5FC5\u987B\u4FDD\u7559\u51FA\u5904\u3002'\n : mode === 'readonly'\n ? '- \u53EA\u8BFB\uFF1A\u4E0D\u5F97\u65B0\u589E\u3001\u4FEE\u6539\u6216\u5220\u9664\u8BB0\u5FC6\u4E0E\u504F\u597D\uFF1B\u9700\u8981\u65F6\u628A\u5EFA\u8BAE\u4EA4\u7ED9\u7528\u6237\u3002'\n : '- \u65B0\u589E\u3001\u4FEE\u6539\u6216\u5220\u9664\u8BB0\u5FC6\u4E0E\u504F\u597D\u524D\uFF0C\u5148\u7528\u786E\u8BA4\u5361\u7247\u53D6\u5F97\u7528\u6237\u540C\u610F\uFF1B\u88AB\u62D2\u7EDD\u5C31\u4E0D\u5199\u3002';\n return [\n '## \u8BB0\u5FC6\u4E0E\u65B9\u6CD5\u590D\u7528',\n '- \u504F\u597D\u5199 USER\uFF0C\u4E8B\u5B9E\u4E0E\u7ECF\u9A8C\u5199\u8BB0\u5FC6\uFF0C\u7EA6\u5B9A\u5199 RULES\uFF0C\u53EF\u590D\u7528\u65B9\u6CD5\u7528 skills\u3002',\n '- \u4FEE\u6539\u524D\u5148\u8BFB\u6700\u65B0\u6761\u76EE\uFF1B\u66FF\u6362\u8981\u7ED9\u5B8C\u6574\u6761\u76EE\uFF0C\u907F\u514D\u91CD\u590D\u6216\u77DB\u76FE\u3002',\n '- \u53EA\u901A\u8FC7\u5DE5\u5177\u5199\u5165\uFF0C\u4E0D\u7ED5\u8FC7\uFF1B\u5199\u5165\u5FC5\u987B\u5F15\u7528\u771F\u5B9E\u4E8B\u4EF6\u51FA\u5904\u3002',\n modeLine,\n '- \u5B50 agent \u53EA\u8BFB\u3002',\n ].join('\\n');\n}\n", "import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Config } from '../config/config.ts';\nimport type { MemoryId, ProposalInput, ProposalReplacement } from '../model/types.ts';\nimport { isMemoryId, newMemoryId } from '../model/ids.ts';\nimport { assertClean, redactPrivate } from '../scan/scan.ts';\nimport type { MemoryStore } from '../store/store.ts';\nimport { writeFileAtomic } from '../fs/atomic.ts';\n\n/**\n * Proposal ledger (plan v1.3 \u00A74.6, S4). A proposal is a file under\n * `proposals/pending/`; decisions live in the journal (`op: decide`), so the\n * ledger and history never disagree.\n *\n * Accepting verifies every `base_hash` before touching the store; a failed\n * accept leaves the proposal file in place (S4.4).\n */\n\n/**\n * A replacement carries provenance bound at propose time (verified against the\n * proposing session). It is written into the record on accept, so the evidence\n * does not stop at the pending file (plan v1.3 \u00A77 \"\u8BC1\u636E\u53EF\u6838\u9A8C\").\n */\nexport type { ProposalReplacement };\n\nexport interface Proposal {\n readonly id: string;\n readonly op: 'create' | 'supersede' | 'delete';\n readonly targets: readonly MemoryId[];\n readonly base_hashes: readonly string[];\n readonly replacements: readonly ProposalReplacement[];\n readonly reason: string;\n readonly created_at: string;\n}\n\nexport class ProposalError extends Error {\n readonly code: 'INVALID' | 'NOT_FOUND' | 'CONFLICT';\n constructor(code: ProposalError['code'], message: string) {\n super(message);\n this.name = 'ProposalError';\n this.code = code;\n }\n}\n\nexport interface ProposalDeps {\n readonly store: MemoryStore;\n readonly config: Config;\n}\n\nfunction pendingDir(store: MemoryStore): string {\n return store.paths.pendingDir;\n}\n\nfunction proposalPath(store: MemoryStore, id: string): string {\n return join(pendingDir(store), `${id}.json`);\n}\n\nexport function listProposals(store: MemoryStore): Proposal[] {\n let names: string[];\n try {\n names = readdirSync(pendingDir(store)).filter((name) => name.endsWith('.json'));\n } catch {\n return [];\n }\n const proposals: Proposal[] = [];\n for (const name of names) {\n try {\n proposals.push(JSON.parse(readFileSync(join(pendingDir(store), name), 'utf8')) as Proposal);\n } catch {\n // A corrupt proposal file is not a reason to hide the others.\n }\n }\n return proposals.sort((left, right) => left.created_at.localeCompare(right.created_at));\n}\n\nexport function readProposal(store: MemoryStore, id: string): Proposal {\n const file = proposalPath(store, id);\n if (!existsSync(file)) throw new ProposalError('NOT_FOUND', `no pending proposal ${id}`);\n return JSON.parse(readFileSync(file, 'utf8')) as Proposal;\n}\n\nfunction currentHash(store: MemoryStore, id: MemoryId): string {\n const doc = store.read(id);\n return doc.content_hash;\n}\n\nexport function createProposal(deps: ProposalDeps, input: ProposalInput): Proposal {\n const { store, config } = deps;\n if (input.op === 'create') {\n if (input.replacements.length === 0) throw new ProposalError('INVALID', 'create needs replacements');\n for (const replacement of input.replacements) {\n assertClean({ abstract: replacement.abstract, body: replacement.body, error_signatures: replacement.error_signatures });\n }\n } else if (input.op === 'supersede') {\n if (input.replacements.length === 0) throw new ProposalError('INVALID', 'supersede needs replacements');\n if (input.targets.length === 0) throw new ProposalError('INVALID', 'supersede needs targets');\n const unique = new Set(input.targets);\n if (unique.size !== input.targets.length) throw new ProposalError('INVALID', 'targets must be unique');\n if (input.base_hashes.length !== input.targets.length) {\n throw new ProposalError('INVALID', 'one base_hash per target is required');\n }\n input.targets.forEach((target, index) => {\n if (!isMemoryId(target)) throw new ProposalError('INVALID', `invalid target id: ${target}`);\n const actual = currentHash(store, target);\n if (actual !== input.base_hashes[index]) {\n throw new ProposalError('CONFLICT', `base_hash for ${target} does not match the current content`);\n }\n });\n for (const replacement of input.replacements) {\n assertClean({ abstract: replacement.abstract, body: replacement.body, error_signatures: replacement.error_signatures });\n }\n } else {\n if (!isMemoryId(input.target)) throw new ProposalError('INVALID', `invalid target id: ${input.target}`);\n if (input.reason.trim() === '') throw new ProposalError('INVALID', 'a delete proposal needs a reason');\n if (currentHash(store, input.target) !== input.base_hash) {\n throw new ProposalError('CONFLICT', `base_hash for ${input.target} does not match the current content`);\n }\n assertClean({ targets: [input.target] });\n }\n\n const existing = listProposals(store);\n if (existing.length >= config.proposals.max_pending) {\n throw new ProposalError('CONFLICT', `pending proposals are at proposals.max_pending (${config.proposals.max_pending})`);\n }\n\n const proposal: Proposal = {\n id: `prop-${newMemoryId(new Date())}`,\n op: input.op,\n targets: input.op === 'create' ? [] : input.op === 'supersede' ? input.targets : [input.target],\n base_hashes: input.op === 'create' ? [] : input.op === 'supersede' ? input.base_hashes : [input.base_hash],\n replacements:\n input.op === 'delete'\n ? []\n : input.replacements.map((replacement) => ({\n ...replacement,\n abstract: redactPrivate(replacement.abstract),\n body: redactPrivate(replacement.body),\n })),\n reason: input.op === 'delete' ? input.reason : (input.reason ?? ''),\n created_at: new Date().toISOString(),\n };\n writeFileAtomic(proposalPath(store, proposal.id), `${JSON.stringify(proposal, null, 2)}\\n`);\n store.appendJournal('audit', { event: 'proposal-created', proposal: proposal.id, op: proposal.op });\n return proposal;\n}\n\nexport interface DecideInput {\n readonly id: string;\n readonly decision: 'accept' | 'reject';\n readonly reason?: string;\n}\n\n/** Apply (or reject) one proposal; the pending file is removed only on success. */\nexport function decideProposal(deps: ProposalDeps, input: DecideInput): void {\n const { store } = deps;\n const proposal = readProposal(store, input.id);\n\n if (input.decision === 'reject') {\n store.appendJournal('decide', { proposal: proposal.id, decision: 'reject', reason: input.reason ?? '' });\n rmSync(proposalPath(store, proposal.id), { force: true });\n return;\n }\n\n if (proposal.op === 'delete') {\n const target = proposal.targets[0] as MemoryId;\n const hash = proposal.base_hashes[0] as string;\n if (currentHash(store, target) !== hash) {\n throw new ProposalError('CONFLICT', `target ${target} changed since the proposal was created`);\n }\n store.remove(target, { reason: proposal.reason, baseHash: hash });\n store.journal.append({ op: 'decide', data: { proposal: proposal.id, decision: 'accept' } });\n rmSync(proposalPath(store, proposal.id), { force: true });\n return;\n }\n\n if (proposal.op === 'create') {\n store.addMany(proposal.replacements, { author: 'human', opId: `decide-${proposal.id}` });\n store.appendJournal('decide', { proposal: proposal.id, decision: 'accept' });\n rmSync(proposalPath(store, proposal.id), { force: true });\n return;\n }\n\n proposal.targets.forEach((target, index) => {\n if (currentHash(store, target) !== proposal.base_hashes[index]) {\n throw new ProposalError('CONFLICT', `target ${target} changed since the proposal was created`);\n }\n });\n store.addMany(\n proposal.replacements.map((replacement) => ({ ...replacement, supersedes: proposal.targets })),\n { author: 'human', opId: `decide-${proposal.id}` },\n );\n store.appendJournal('decide', { proposal: proposal.id, decision: 'accept' });\n rmSync(proposalPath(store, proposal.id), { force: true });\n}\n", "import { createHash } from 'node:crypto';\nimport type { ProvenanceEntry } from './model/types.ts';\n\n/**\n * Trusted source binding (plan v1.3 \u00A75.3). The model only supplies\n * `{event_seq, quote}`; the adapter resolves the real event and fills\n * `session_id` / `speaker` / `event_sha256`. A quote that is not a substring of\n * the resolved event, a missing event, or an assistant message used as evidence\n * is rejected.\n */\n\nexport interface EvidenceEvent {\n readonly seq: number;\n readonly speaker: 'user' | 'assistant' | 'tool' | 'system';\n readonly text: string;\n}\n\nexport class EvidenceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'EvidenceError';\n }\n}\n\nexport interface BindEvidenceInput {\n readonly sessionId: string;\n readonly eventSeq: number;\n readonly quote: string;\n readonly lookup: (seq: number) => EvidenceEvent | undefined;\n /** Optional caller-supplied hash; must match the resolved event text. */\n readonly expectedSha256?: string;\n}\n\nexport function bindEvidence(input: BindEvidenceInput): ProvenanceEntry {\n const event = input.lookup(input.eventSeq);\n if (event === undefined) throw new EvidenceError(`event ${input.eventSeq} does not exist in this session`);\n if (event.seq !== input.eventSeq) throw new EvidenceError('event sequence mismatch');\n if (event.speaker === 'assistant') {\n throw new EvidenceError('a model message cannot be its own evidence');\n }\n if (input.quote.length === 0 || [...input.quote].length > 160) {\n throw new EvidenceError('quote must be 1..160 characters');\n }\n if (!event.text.includes(input.quote)) {\n throw new EvidenceError('quote is not a substring of the referenced event');\n }\n const sha256 = createHash('sha256').update(event.text, 'utf8').digest('hex');\n if (input.expectedSha256 !== undefined && input.expectedSha256 !== sha256) {\n throw new EvidenceError('event hash does not match the resolved event');\n }\n return {\n session_id: input.sessionId,\n event_seq: input.eventSeq,\n speaker: event.speaker,\n quote: input.quote,\n event_sha256: sha256,\n };\n}\n", "/** Per-session T0 write budget (plan v1.3 \u00A75.4). In memory on purpose: a crash\n * resets the counter, which can only make the agent ask for a proposal sooner. */\nexport class SessionQuota {\n private readonly used = new Map<string, number>();\n private readonly limit: number;\n\n constructor(limit: number) {\n this.limit = limit;\n }\n\n /** Consume one T0 write; returns false when the session budget is exhausted. */\n consume(sessionId: string): boolean {\n const count = this.used.get(sessionId) ?? 0;\n if (count >= this.limit) return false;\n this.used.set(sessionId, count + 1);\n return true;\n }\n\n usedOf(sessionId: string): number {\n return this.used.get(sessionId) ?? 0;\n }\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { memoryPaths } from '../paths.ts';\nimport { writeFileAtomic } from '../fs/atomic.ts';\n\n/** Persisted set of rejected proposal summary hashes (never re-propose them). */\nexport function loadRejected(home: string): Set<string> {\n const file = join(memoryPaths(home).stateDir, 'distill-rejected.json');\n if (!existsSync(file)) return new Set();\n try {\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as { hashes?: unknown };\n return new Set(Array.isArray(parsed.hashes) ? parsed.hashes.filter((value): value is string => typeof value === 'string') : []);\n } catch {\n return new Set();\n }\n}\n\nexport function addRejected(home: string, hashes: readonly string[]): void {\n const set = loadRejected(home);\n for (const hash of hashes) set.add(hash);\n writeFileAtomic(\n join(memoryPaths(home).stateDir, 'distill-rejected.json'),\n `${JSON.stringify({ hashes: [...set].sort() }, null, 2)}\\n`,\n );\n}\n\n/**\n * Closeout distillation core (plan v1.3 \u00A77, S6).\n *\n * L0 is deterministic tagging over the session log; it never writes memory.\n * The model gets the L0 list plus the active catalog and must answer with a\n * strict JSON contract. Everything it returns is re-validated here: evidence is\n * resolved against real events, assistant messages cannot be their own evidence,\n * a `rule` without machine-check design is downgraded, duplicates and rejected\n * summaries disappear, and at most five proposals survive.\n */\n\nexport interface DistillEvent {\n readonly seq: number;\n readonly speaker: 'user' | 'assistant' | 'tool' | 'system';\n readonly text: string;\n}\n\nexport type L0Kind = 'repeated-error' | 'correction' | 'failure-then-success' | 'rollback';\n\nexport interface L0Signal {\n readonly kind: L0Kind;\n readonly event_seqs: readonly number[];\n readonly summary: string;\n}\n\nconst CORRECTION = /\u4E0D\u5BF9|\u9519\u4E86|\u4E0D\u662F\u8FD9\u6837|\u7EA0\u6B63|actually|correction|rather than|instead/i;\nconst ROLLBACK = /\u56DE\u6EDA|\u64A4\u9500|revert|rollback|undo/i;\nconst FAILURE = /error|failed|\u5931\u8D25|\u62A5\u9519|exception/i;\n\nexport function collectL0(events: readonly DistillEvent[]): L0Signal[] {\n const signals: L0Signal[] = [];\n const failureSeqs = events.filter((event) => event.speaker !== 'user' && FAILURE.test(event.text)).map((event) => event.seq);\n if (failureSeqs.length >= 2) {\n signals.push({\n kind: 'repeated-error',\n event_seqs: failureSeqs.slice(0, 5),\n summary: `${failureSeqs.length} \u4E2A\u5DE5\u5177\u8F93\u51FA\u5305\u542B\u9519\u8BEF/\u5931\u8D25`,\n });\n }\n const corrections = events.filter((event) => event.speaker === 'user' && CORRECTION.test(event.text));\n if (corrections.length > 0) {\n signals.push({\n kind: 'correction',\n event_seqs: corrections.map((event) => event.seq).slice(0, 5),\n summary: '\u7528\u6237\u7EA0\u6B63\u4E86\u5148\u524D\u7684\u8BF4\u6CD5\u6216\u505A\u6CD5',\n });\n }\n const failures = events.filter((event) => event.speaker === 'tool' && FAILURE.test(event.text));\n const successes = events.filter((event) => event.speaker === 'tool' && !FAILURE.test(event.text));\n if (failures.length > 0 && successes.length > 0) {\n signals.push({\n kind: 'failure-then-success',\n event_seqs: [failures[failures.length - 1]?.seq as number, successes[successes.length - 1]?.seq as number],\n summary: '\u5DE5\u5177\u5148\u5931\u8D25\u540E\u6210\u529F',\n });\n }\n const rollbacks = events.filter((event) => ROLLBACK.test(event.text));\n if (rollbacks.length > 0) {\n signals.push({\n kind: 'rollback',\n event_seqs: rollbacks.map((event) => event.seq).slice(0, 5),\n summary: '\u51FA\u73B0\u56DE\u6EDA/\u64A4\u9500',\n });\n }\n return signals;\n}\n\nexport interface CloseoutPromptInput {\n readonly l0: readonly L0Signal[];\n readonly active: readonly { readonly id: string; readonly kind: string; readonly abstract: string }[];\n readonly maxProposals: number;\n}\n\nexport function buildCloseoutPrompt(input: CloseoutPromptInput): string {\n const l0 = input.l0.length === 0 ? '\uFF08\u65E0\uFF09' : input.l0.map((signal) => `- ${signal.kind} [${signal.event_seqs.join(',')}] ${signal.summary}`).join('\\n');\n const catalog = input.active.map((doc) => `- ${doc.id} [${doc.kind}] ${doc.abstract}`).join('\\n');\n return [\n '\u4F60\u6B63\u5728\u505A Agent Memory \u7684\u6536\u5C3E\u84B8\u998F\u3002\u53EA\u8F93\u51FA\u4E00\u4E2A JSON \u5BF9\u8C61\uFF0C\u4E0D\u8981\u8F93\u51FA\u522B\u7684\u6587\u5B57\u3002',\n '',\n 'L0 \u786E\u5B9A\u6027\u7EBF\u7D22\uFF1A',\n l0,\n '',\n '\u5F53\u524D\u6D3B\u52A8\u8BB0\u5FC6\uFF08targets \u53EA\u80FD\u4ECE\u8FD9\u91CC\u9009\uFF09\uFF1A',\n catalog || '\uFF08\u7A7A\uFF09',\n '',\n `\u6700\u591A ${input.maxProposals} \u6761\u63D0\u6848\u3002JSON \u5951\u7EA6\uFF1A`,\n '{\"proposals\":[{\"op\":\"supersede\",\"targets\":[\"mem-...\"],\"reason\":\"...\",\"replacements\":[{\"kind\":\"fact|pitfall|exp\",\"abstract\":\"...\",\"body\":\"...\",\"evidence\":[{\"event_seq\":1,\"quote\":\"\u539F\u6587\u7247\u6BB5\"}]}]}]}',\n '\u6216 {\"proposals\":[],\"message\":\"\u672C\u6B21\u65E0\u65B0\u63D0\u6848\"}\u3002',\n 'evidence \u5FC5\u987B\u5F15\u7528\u771F\u5B9E\u4E8B\u4EF6\uFF1Aevent_seq \u662F\u8BE5\u4E8B\u4EF6\u5E8F\u53F7\uFF0Cquote \u5FC5\u987B\u662F\u8BE5\u4E8B\u4EF6\u539F\u6587\u7684\u5B50\u4E32\uFF1B\u52A9\u624B\u6D88\u606F\u4E0D\u80FD\u5F53\u8BC1\u636E\u3002',\n '\u6CA1\u6709\u673A\u5668\u68C0\u67E5\u8BBE\u8BA1\uFF08check/test/[neg]\uFF09\u7684\u89C4\u5219\u4E0D\u8981\u5199\u6210 rule\uFF0C\u964D\u7EA7\u4E3A pitfall \u6216 fact\u3002',\n '\u5DF2\u5426\u51B3\u7684\u6458\u8981\u3001\u4E0E\u6D3B\u52A8\u8BB0\u5FC6\u91CD\u590D\u7684\u5185\u5BB9\u4E0D\u8981\u518D\u63D0\u3002',\n ].join('\\n');\n}\n\nexport interface CloseoutCandidate {\n readonly op: 'supersede' | 'delete';\n readonly targets: readonly string[];\n readonly reason: string;\n readonly replacements: readonly {\n readonly kind: 'fact' | 'pitfall' | 'exp';\n readonly abstract: string;\n readonly body: string;\n readonly evidence: readonly { readonly event_seq: number; readonly quote: string }[];\n }[];\n}\n\nexport interface ParseDeps {\n readonly events: readonly DistillEvent[];\n readonly activeAbstracts: readonly string[];\n readonly activeIds: readonly string[];\n readonly rejectedHashes?: ReadonlySet<string>;\n readonly maxProposals?: number;\n}\n\nexport interface ParseResult {\n readonly candidates: readonly CloseoutCandidate[];\n readonly message: string | null;\n readonly errors: readonly string[];\n readonly dropped: readonly string[];\n readonly truncated: number;\n}\n\nfunction normalizedAbstract(text: string): string {\n return text.normalize('NFKC').toLowerCase().replace(/\\s+/g, ' ').trim();\n}\n\nexport function summaryHash(candidate: CloseoutCandidate): string {\n const material = [\n candidate.op,\n [...candidate.targets].sort().join(','),\n ...candidate.replacements.map((replacement) => normalizedAbstract(replacement.abstract)),\n ].join('|');\n return createHash('sha256').update(material, 'utf8').digest('hex');\n}\n\nfunction findJson(text: string): unknown {\n const start = text.indexOf('{');\n const end = text.lastIndexOf('}');\n if (start < 0 || end <= start) return undefined;\n try {\n return JSON.parse(text.slice(start, end + 1));\n } catch {\n return undefined;\n }\n}\n\n/** Validate the model's closeout answer against the real session events. */\nexport function parseCloseout(text: string, deps: ParseDeps): ParseResult {\n const errors: string[] = [];\n const dropped: string[] = [];\n const parsed = findJson(text);\n if (typeof parsed !== 'object' || parsed === null) {\n return { candidates: [], message: null, errors: ['closeout answer is not a JSON object'], dropped, truncated: 0 };\n }\n const record = parsed as { proposals?: unknown; message?: unknown };\n const emptyMessage =\n typeof record.message === 'string' &&\n record.message.trim() !== '' &&\n (record.proposals === undefined || (Array.isArray(record.proposals) && record.proposals.length === 0));\n if (emptyMessage) {\n return { candidates: [], message: (record.message as string).trim(), errors, dropped, truncated: 0 };\n }\n if (!Array.isArray(record.proposals)) {\n return { candidates: [], message: null, errors: ['proposals must be an array'], dropped, truncated: 0 };\n }\n const limit = deps.maxProposals ?? 5;\n const truncated = Math.max(0, record.proposals.length - limit);\n const candidates: CloseoutCandidate[] = [];\n const activeIds = new Set(deps.activeIds);\n const activeAbstracts = new Set(deps.activeAbstracts.map(normalizedAbstract));\n const rejected = deps.rejectedHashes ?? new Set<string>();\n const events = new Map(deps.events.map((event) => [event.seq, event]));\n\n for (const raw of record.proposals.slice(0, limit)) {\n if (typeof raw !== 'object' || raw === null) {\n dropped.push('proposal is not an object');\n continue;\n }\n const proposal = raw as {\n op?: unknown;\n targets?: unknown;\n target?: unknown;\n reason?: unknown;\n replacements?: unknown;\n };\n const op = proposal.op === 'delete' ? 'delete' : proposal.op === 'supersede' ? 'supersede' : null;\n if (op === null) {\n dropped.push('unsupported op');\n continue;\n }\n const targets = (op === 'delete' ? [proposal.target] : proposal.targets) as unknown;\n if (!Array.isArray(targets) || targets.length === 0 || !targets.every((target) => typeof target === 'string')) {\n dropped.push('targets must be memory ids');\n continue;\n }\n if (!targets.every((target) => activeIds.has(target as string))) {\n dropped.push('target is not an active memory');\n continue;\n }\n const replacementsRaw = op === 'supersede' ? proposal.replacements : [];\n if (!Array.isArray(replacementsRaw) || (op === 'supersede' && replacementsRaw.length === 0)) {\n dropped.push('supersede needs replacements');\n continue;\n }\n const replacements: CloseoutCandidate['replacements'][number][] = [];\n let failed = false;\n for (const rawReplacement of replacementsRaw) {\n if (typeof rawReplacement !== 'object' || rawReplacement === null) {\n dropped.push('replacement is not an object');\n failed = true;\n break;\n }\n const replacement = rawReplacement as {\n kind?: unknown;\n abstract?: unknown;\n body?: unknown;\n evidence?: unknown;\n };\n if (replacement.kind !== 'fact' && replacement.kind !== 'pitfall' && replacement.kind !== 'exp') {\n dropped.push('replacement kind must be fact/pitfall/exp');\n failed = true;\n break;\n }\n const abstract = typeof replacement.abstract === 'string' ? replacement.abstract : '';\n if (abstract.trim() === '' || !Array.isArray(replacement.evidence) || replacement.evidence.length === 0) {\n dropped.push('replacement needs abstract and evidence');\n failed = true;\n break;\n }\n if (activeAbstracts.has(normalizedAbstract(abstract))) {\n dropped.push(`duplicate of an active memory: ${abstract.slice(0, 24)}`);\n failed = true;\n break;\n }\n const evidence: { event_seq: number; quote: string }[] = [];\n for (const rawEvidence of replacement.evidence) {\n if (typeof rawEvidence !== 'object' || rawEvidence === null) {\n dropped.push('evidence is not an object');\n failed = true;\n break;\n }\n const item = rawEvidence as { event_seq?: unknown; quote?: unknown };\n const event = typeof item.event_seq === 'number' ? events.get(item.event_seq) : undefined;\n const quote = typeof item.quote === 'string' ? item.quote : '';\n if (event === undefined) {\n dropped.push(`evidence event ${String(item.event_seq)} does not exist`);\n failed = true;\n break;\n }\n if (event.speaker === 'assistant') {\n dropped.push('assistant message cannot be evidence');\n failed = true;\n break;\n }\n if (quote === '' || !event.text.includes(quote)) {\n dropped.push('evidence quote is not a substring of the event');\n failed = true;\n break;\n }\n if ([...quote].length > 160) {\n dropped.push('evidence quote is longer than 160 characters');\n failed = true;\n break;\n }\n evidence.push({ event_seq: event.seq, quote });\n }\n if (failed) break;\n replacements.push({\n kind: replacement.kind,\n abstract,\n body: typeof replacement.body === 'string' ? replacement.body : '',\n evidence,\n });\n }\n if (failed) continue;\n\n const candidate: CloseoutCandidate = {\n op,\n targets: targets as string[],\n reason: typeof proposal.reason === 'string' ? proposal.reason : '',\n replacements,\n };\n const hash = summaryHash(candidate);\n if (rejected.has(hash)) {\n dropped.push('already rejected');\n continue;\n }\n if (candidates.some((existing) => summaryHash(existing) === hash)) {\n dropped.push('duplicate proposal');\n continue;\n }\n candidates.push(candidate);\n }\n\n return { candidates, message: null, errors, dropped, truncated };\n}\n\n/** `rule` without machine-check design is downgraded instead of proposed as a rule. */\nexport function downgradeRule(candidate: { readonly kind: string; readonly machine_gate?: { check?: string; test?: string } }): {\n readonly action: 'keep' | 'downgrade';\n readonly to?: 'pitfall';\n} {\n if (candidate.kind !== 'rule') return { action: 'keep' };\n if (candidate.machine_gate?.check !== undefined && candidate.machine_gate.test !== undefined) {\n return { action: 'keep' };\n }\n return { action: 'downgrade', to: 'pitfall' };\n}\n\nexport type RoundState = 'open' | 'submitted' | 'disposed';\n\n/** One closeout round: exactly one submit, then dispose (success/failure/timeout). */\nexport class CloseoutRound {\n readonly id: string;\n private state: RoundState = 'open';\n private readonly expiresAt: number;\n private readonly now: () => number;\n\n constructor(options: { id?: string; timeoutMs?: number; now?: () => number } = {}) {\n this.id = options.id ?? `closeout-${Date.now().toString(36)}`;\n this.now = options.now ?? Date.now;\n this.expiresAt = this.now() + (options.timeoutMs ?? 300_000);\n }\n\n get status(): RoundState {\n if (this.state === 'open' && this.now() > this.expiresAt) this.state = 'disposed';\n return this.state;\n }\n\n submit(): { ok: true } | { ok: false; error: string } {\n if (this.status !== 'open') return { ok: false, error: `round is ${this.status}` };\n this.state = 'submitted';\n return { ok: true };\n }\n\n dispose(): void {\n this.state = 'disposed';\n }\n}\n", "import { createHash } from 'node:crypto';\nimport { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { Config } from '../config/config.ts';\nimport { loadRules } from '../rules/rules.ts';\nimport type { MemoryStore } from '../store/store.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * Operational commands (S7): export/pack, checksums, and the read-only inspect\n * report. Nothing here rewrites a memory file; export copies and hashes,\n * inspect reads.\n */\n\nexport interface ExportResult {\n readonly out: string;\n readonly files: number;\n readonly bytes: number;\n readonly sums: string;\n}\n\nconst INCLUDE = [\n 'config.toml',\n 'policy.json',\n 'SOUL.md',\n 'USER.md',\n 'RULES.md',\n 'memories',\n 'proposals',\n '.state/policy.seal.json',\n '.state/journal',\n '.state/distill-rejected.json',\n];\n\nexport function exportStore(options: { home: string; out: string }): ExportResult {\n const paths = memoryPaths(options.home);\n mkdirSync(options.out, { recursive: true });\n for (const entry of INCLUDE) {\n const source = join(paths.home, entry);\n if (!existsSync(source)) continue;\n const target = join(options.out, entry);\n cpSync(source, target, { recursive: true });\n }\n const lines: string[] = [];\n let files = 0;\n let bytes = 0;\n const walk = (dir: string, base: string): void => {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name);\n if (statSync(full).isDirectory()) {\n walk(full, base);\n continue;\n }\n const rel = relative(base, full).replaceAll('\\\\', '/');\n const data = readFileSync(full);\n lines.push(`${createHash('sha256').update(data).digest('hex')} ${rel}`);\n files += 1;\n bytes += data.length;\n }\n };\n walk(options.out, options.out);\n lines.sort();\n const sums = join(options.out, 'SHA256SUMS');\n writeFileSync(sums, `${lines.join('\\n')}\\n`, 'utf8');\n return { out: options.out, files, bytes, sums };\n}\n\nexport function verifyExport(dir: string): { ok: boolean; problems: readonly string[] } {\n const sums = join(dir, 'SHA256SUMS');\n if (!existsSync(sums)) return { ok: false, problems: ['SHA256SUMS is missing'] };\n const problems: string[] = [];\n for (const line of readFileSync(sums, 'utf8').split('\\n')) {\n if (line.trim() === '') continue;\n const match = /^([0-9a-f]{64}) {2}(.+)$/.exec(line);\n if (match === null) {\n problems.push(`malformed line: ${line.slice(0, 80)}`);\n continue;\n }\n const file = join(dir, match[2] as string);\n if (!existsSync(file)) {\n problems.push(`missing file: ${match[2]}`);\n continue;\n }\n const actual = createHash('sha256').update(readFileSync(file)).digest('hex');\n if (actual !== match[1]) problems.push(`hash mismatch: ${match[2]}`);\n }\n return { ok: problems.length === 0, problems };\n}\n\nexport interface InspectReport {\n readonly active: number;\n readonly byKind: Readonly<Record<string, number>>;\n readonly quarantined: readonly string[];\n readonly pendingProposals: number;\n readonly rules: readonly { number: number; category: string; text: string }[];\n readonly journal: readonly { seq: number; op: string; at: string; op_id: string }[];\n readonly budget: { readonly indexChars: number; readonly totalChars: number };\n readonly journalHead: { readonly seq: number; readonly hash: string } | null;\n /** Character counts of the three human-owned personalization files (0 = absent). */\n readonly personalization: { readonly soul: number; readonly user: number; readonly rules: number };\n /** Injection budgets used to flag truncation in the report. */\n readonly inject: { readonly persona_max_chars: number; readonly user_max_chars: number; readonly rules_max_chars: number };\n}\n\nfunction personalizationChars(home: string): { soul: number; user: number; rules: number } {\n const paths = memoryPaths(home);\n const charsOf = (file: string): number => {\n try {\n if (!existsSync(file)) return 0;\n // Comments are stripped before injection, so they do not count against budgets.\n return [...readFileSync(file, 'utf8').replace(/<!--[\\s\\S]*?-->/g, '')].length;\n } catch {\n return 0;\n }\n };\n return { soul: charsOf(paths.soulFile), user: charsOf(paths.userFile), rules: charsOf(paths.rulesFile) };\n}\n\nexport function inspectStore(options: {\n home: string;\n config: Config;\n store: MemoryStore;\n limit?: number;\n}): InspectReport {\n const active = options.store.active();\n const byKind: Record<string, number> = { fact: 0, pitfall: 0, exp: 0 };\n let chars = 0;\n for (const doc of active) {\n byKind[doc.kind] = (byKind[doc.kind] ?? 0) + 1;\n chars += [...doc.abstract].length + [...doc.body].length;\n }\n const journal = options.store.journal.readAll();\n const limit = options.limit ?? 10;\n return {\n active: active.length,\n byKind,\n quarantined: [...options.store.diagnostics().quarantined.keys()],\n pendingProposals: options.store.stats().pending_proposals,\n rules: loadRules(options.home).map((rule) => ({ number: rule.number, category: rule.category, text: rule.text })),\n journal: journal.entries.slice(-limit).map((entry) => ({\n seq: entry.seq,\n op: entry.op,\n at: entry.at,\n op_id: entry.op_id,\n })),\n budget: { indexChars: [...active.map((doc) => doc.abstract).join('\\n')].length, totalChars: chars },\n journalHead: journal.head,\n personalization: personalizationChars(options.home),\n inject: {\n persona_max_chars: options.config.inject.persona_max_chars,\n user_max_chars: options.config.inject.user_max_chars,\n rules_max_chars: options.config.inject.rules_max_chars,\n },\n };\n}\n", "import { existsSync, readFileSync } from 'node:fs';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { memoryPaths } from '../paths.ts';\n\n/**\n * USER.md profile entries (architecture v2, P1). One entry per paragraph,\n * separated by a line containing only `\u00A7`; comments are stripped before\n * reading/writing so the scaffold template stays inert.\n *\n * The file stays human-editable; the agent may only change it through the\n * `user_profile` tool, which requires a confirmation card and a prior read.\n */\n\nexport const PROFILE_SEPARATOR = '\u00A7';\nexport const PROFILE_MAX_CHARS = 10000;\n\nexport class ProfileError extends Error {\n readonly code: 'INVALID' | 'CONFLICT' | 'NOT_FOUND';\n constructor(code: ProfileError['code'], message: string) {\n super(message);\n this.name = 'ProfileError';\n this.code = code;\n }\n}\n\nexport interface ProfileSnapshot {\n readonly entries: readonly string[];\n readonly chars: number;\n}\n\nconst COMMENT = /<!--[\\s\\S]*?-->/g;\n\nexport function stripProfileComments(text: string): string {\n return text.replace(COMMENT, '');\n}\n\nexport function parseProfileEntries(text: string): string[] {\n const entries: string[] = [];\n let current: string[] = [];\n const flush = (): void => {\n const value = current.join('\\n').trim();\n if (value !== '') entries.push(value);\n current = [];\n };\n for (const line of stripProfileComments(text).split(/\\r?\\n/)) {\n if (line.trim() === PROFILE_SEPARATOR) {\n flush();\n continue;\n }\n current.push(line);\n }\n flush();\n return entries;\n}\n\nexport function renderProfileEntries(entries: readonly string[]): string {\n return `${entries.map((entry) => entry.trim()).join(`\\n\\n${PROFILE_SEPARATOR}\\n\\n`)}\\n`;\n}\n\nfunction profileChars(entries: readonly string[]): number {\n return [...renderProfileEntries(entries)].length;\n}\n\nexport function validateProfileEntries(entries: readonly string[]): string[] {\n const problems: string[] = [];\n entries.forEach((entry, index) => {\n const text = entry.trim();\n if (text === '') problems.push(`entry ${index + 1} is empty`);\n if (text.split(/\\r?\\n/).some((line) => line.trim() === PROFILE_SEPARATOR)) {\n problems.push(`entry ${index + 1} contains a separator line; use a new entry instead`);\n }\n });\n if (profileChars(entries) > PROFILE_MAX_CHARS) {\n problems.push(`USER.md would be ${profileChars(entries)} chars, over the ${PROFILE_MAX_CHARS}-char limit`);\n }\n return problems;\n}\n\nexport function loadProfile(home: string): ProfileSnapshot {\n const file = memoryPaths(home).userFile;\n const text = existsSync(file) ? readFileSync(file, 'utf8') : '';\n const entries = parseProfileEntries(text);\n return { entries, chars: profileChars(entries) };\n}\n\nexport function saveProfile(home: string, entries: readonly string[]): ProfileSnapshot {\n const problems = validateProfileEntries(entries);\n if (problems.length > 0) throw new ProfileError('INVALID', problems.join('; '));\n writeFileAtomic(memoryPaths(home).userFile, renderProfileEntries(entries));\n return { entries: entries.map((entry) => entry.trim()), chars: profileChars(entries) };\n}\n\n/** Literal query over entries: substring match, case-insensitive for ASCII. */\nexport function queryProfile(entries: readonly string[], query: string): string[] {\n const needle = query.trim().toLowerCase();\n if (needle === '') return [...entries];\n return entries.filter((entry) => entry.toLowerCase().includes(needle));\n}\n\n/** Find one entry by complete text or a unique literal substring. */\nexport function findProfileEntry(entries: readonly string[], oldText: string): number {\n const needle = oldText.trim();\n if (needle === '') throw new ProfileError('INVALID', 'old_text is required');\n const exact = entries.findIndex((entry) => entry === needle);\n if (exact !== -1) return exact;\n const matches = entries\n .map((entry, index) => ({ entry, index }))\n .filter((item) => item.entry.includes(needle));\n if (matches.length === 0) throw new ProfileError('NOT_FOUND', 'old_text does not match any USER entry');\n if (matches.length > 1) {\n throw new ProfileError('CONFLICT', `old_text matches ${matches.length} entries; give the complete entry`);\n }\n return (matches[0] as { index: number }).index;\n}\n", "import { existsSync } from 'node:fs';\nimport { writeFileAtomic } from '../fs/atomic.ts';\nimport { memoryPaths } from '../paths.ts';\nimport { sealPolicy } from '../policy/policy.ts';\n\n/**\n * Personalization scaffold (architecture v2, P0). Creates the three human-owned\n * files with comment-only templates, then seals SOUL/RULES (USER stays unsealed\n * by default so the agent may propose edits through a confirmation card).\n *\n * Existing files are never overwritten; templates are comments so an untouched\n * file injects nothing (assemble strips HTML comments from these files).\n */\n\nexport const SOUL_TEMPLATE = `<!--\n\u4EBA\u683C\u6458\u8981\uFF1A\u6CE8\u5165\u65F6\u53EA\u53D6\u524D 200 \u5B57\u3002\u7528\u6563\u6587\u5199\u300C\u4F60\u662F\u8C01\u3001\u600E\u4E48\u8BF4\u8BDD\u3001\u8FB9\u754C\u5728\u54EA\u300D\uFF0C\u4E0D\u8981\u5199\u4E8B\u5B9E\u6761\u76EE\u3002\n\u793A\u4F8B\uFF1A\u4F60\u7684\u89D2\u8272\u662F\u2026\u2026\uFF0C\u4EE5\u2026\u2026\u7684\u8EAB\u4EFD\u4E0E\u7528\u6237\u4EA4\u6D41\uFF1B\u8BED\u6C14\u2026\u2026\uFF1B\u4E0D\u786E\u5B9A\u65F6\u5148\u95EE\uFF0C\u4E0D\u66FF\u7528\u6237\u505A\u51B3\u5B9A\u3002\n-->\n`;\n\nexport const USER_TEMPLATE = `<!--\n\u7528\u6237\u504F\u597D\uFF1A\u4E00\u6761\u4E00\u6BB5\uFF0C\u7528\u5355\u72EC\u4E00\u884C \u00A7 \u5206\u9694\uFF1B\u5355\u6761\u5FC5\u987B\u975E\u7A7A\u4E14\u5B8C\u6574\uFF0C\u5355\u6587\u4EF6\u4E0A\u9650 10000 \u5B57\u3002\n\u53EA\u5199\u7528\u6237\u660E\u786E\u8BF4\u8FC7\u7684\u957F\u671F\u80CC\u666F\u3001\u504F\u597D\u4E0E\u534F\u4F5C\u9884\u671F\uFF1B\u4E0D\u5199\u4E34\u65F6\u8981\u6C42\uFF0C\u4E0D\u5199\u4E16\u754C\u4E8B\u5B9E\uFF08\u4E8B\u5B9E\u8FDB\u8BB0\u5FC6\u5E93\uFF09\u3002\n\u793A\u4F8B\uFF1A\n\u7528\u6237\u5E0C\u671B\u88AB\u79F0\u4E3A\u300C\u2026\u2026\u300D\u3002\n\u00A7\n\u7528\u6237\u662F\u2026\u2026\uFF0C\u4E60\u60EF\u2026\u2026\u3002\n-->\n`;\n\nexport const RULES_TEMPLATE = `<!--\n\u89C4\u5219\uFF1A\u4E00\u6761\u4E00\u4E2A\u7F16\u53F7\uFF1B[\u786C] \u89C4\u5219\u5FC5\u987B\u80FD\u88AB\u4EE3\u7801\u6216\u6D4B\u8BD5\u68C0\u67E5\uFF0C[\u8F6F] \u89C4\u5219\u53EA\u5199\u5EFA\u8BAE\u3002\n\u793A\u4F8B\uFF1A\nR1 [\u786C] \u8BB0\u5FC6\u5199\u5165\u5FC5\u987B\u8D70 memory \u5DE5\u5177\uFF0C\u7981\u6B62\u76F4\u63A5\u6539 MEMORY.md\uFF1Bcheck: <\u7B26\u53F7>\uFF1Btest: <\u6D4B\u8BD5\u6587\u4EF6>\nR2 [\u8F6F] \u56DE\u7B54\u524D\u5148\u786E\u8BA4\u5173\u952E\u4E8B\u5B9E\u3002\n-->\n`;\n\nexport interface ScaffoldResult {\n readonly created: readonly string[];\n readonly kept: readonly string[];\n readonly sealSha256: string;\n readonly sealedFiles: { readonly soul: string; readonly user: string; readonly rules: string };\n}\n\nexport function scaffoldPersonalization(options: { home: string; now?: Date }): ScaffoldResult {\n const paths = memoryPaths(options.home);\n const targets: ReadonlyArray<readonly [string, string]> = [\n [paths.soulFile, SOUL_TEMPLATE],\n [paths.userFile, USER_TEMPLATE],\n [paths.rulesFile, RULES_TEMPLATE],\n ];\n const created: string[] = [];\n const kept: string[] = [];\n for (const [file, template] of targets) {\n if (existsSync(file)) {\n kept.push(file);\n continue;\n }\n writeFileAtomic(file, template);\n created.push(file);\n }\n // Human-invoked command: sealing here is intentional and scoped to SOUL/RULES.\n const seal = sealPolicy({\n home: options.home,\n accept: true,\n ...(options.now === undefined ? {} : { now: options.now }),\n });\n return { created, kept, sealSha256: seal.sha256, sealedFiles: seal.sealedFiles };\n}\n", "import type { Config } from '../config/config.ts';\nimport { isMemoryId } from '../model/ids.ts';\nimport { loadProfile, queryProfile } from '../profile/profile.ts';\nimport { scaffoldPersonalization } from '../personalization/scaffold.ts';\nimport { loadRules } from '../rules/rules.ts';\nimport { exportStore, inspectStore } from '../ops/ops.ts';\nimport { sealPolicy } from '../policy/policy.ts';\nimport { decideProposal, listProposals, ProposalError } from '../proposals/proposals.ts';\nimport type { MemoryStore } from '../store/store.ts';\nimport type { Kind, MemoryId } from '../model/types.ts';\n\n/**\n * Human command plane (S8): the same operations the `mem` CLI exposes, but\n * callable from a host UI command (`/mem \u2026`) so a human never has to leave the\n * chat box to review, approve, or fix memories.\n *\n * Hard rule this module preserves: nothing here is reachable from a model tool.\n * `decide` stays a human-only verb; the DSH adapter registers `/mem` through\n * the commands service, which runs outside model history (ADR-0011).\n */\n\nexport interface HumanCommandDeps {\n readonly store: MemoryStore;\n readonly config: Config;\n readonly home: string;\n}\n\nexport interface HumanCommandResult {\n readonly ok: boolean;\n readonly text: string;\n}\n\nexport const HUMAN_COMMAND_HINT =\n 'proposals | decide <id> accept|reject | decide --batch accept|reject | add --kind K --abstract \"\u2026\" --body \"\u2026\" | read <id> | recall <query> | profile [\u5173\u952E\u8BCD] | inspect | scaffold | adopt <id> | delete <id> --reason \"\u2026\" | purge <id> --reason \"\u2026\" --accept | rebuild | export <dir> | seal --accept [--seal-user]';\n\nexport const HUMAN_COMMANDS = [\n 'proposals',\n 'decide',\n 'add',\n 'read',\n 'recall',\n 'profile',\n 'inspect',\n 'scaffold',\n 'adopt',\n 'delete',\n 'purge',\n 'rebuild',\n 'export',\n 'seal',\n 'help',\n] as const;\n\nconst KINDS: readonly Kind[] = ['fact', 'pitfall', 'exp'];\nconst EVIDENCE_LEVELS = ['user_explicit', 'user_confirmed', 'observed'] as const;\n/** Flags that never take a value; everything else consumes the next token. */\nconst BOOLEAN_FLAGS = new Set(['accept', 'batch', 'seal-user']);\n\ninterface Parsed {\n readonly verb: string;\n readonly positionals: readonly string[];\n readonly flags: ReadonlyMap<string, string | true>;\n}\n\n/** A small CLI-shaped tokenizer: quotes group words, `--flag=value` works. */\nfunction tokenize(line: string): string[] {\n const tokens: string[] = [];\n let current = '';\n let started = false;\n let quote: '\"' | \"'\" | undefined;\n for (let index = 0; index < line.length; index += 1) {\n const char = line[index] as string;\n if (quote !== undefined) {\n if (char === '\\\\' && index + 1 < line.length) {\n const next = line[index + 1];\n if (next === quote || next === '\\\\') {\n index += 1;\n current += next as string;\n continue;\n }\n }\n if (char === quote) {\n quote = undefined;\n continue;\n }\n current += char;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n started = true;\n continue;\n }\n if (char === ' ' || char === '\\t' || char === '\\n' || char === '\\r') {\n if (started) {\n tokens.push(current);\n current = '';\n started = false;\n }\n continue;\n }\n current += char;\n started = true;\n }\n if (quote !== undefined) throw new Error('unterminated quote in command input');\n if (started) tokens.push(current);\n return tokens;\n}\n\nfunction parseLine(line: string): Parsed {\n const tokens = tokenize(line);\n const verb = tokens[0] ?? 'help';\n const positionals: string[] = [];\n const flags = new Map<string, string | true>();\n for (let index = 1; index < tokens.length; index += 1) {\n const token = tokens[index] as string;\n if (token.startsWith('--') && token.length > 2) {\n const body = token.slice(2);\n const equals = body.indexOf('=');\n const key = equals === -1 ? body : body.slice(0, equals);\n const value = equals === -1 ? true : body.slice(equals + 1);\n flags.set(key, value);\n if (value === true && !BOOLEAN_FLAGS.has(key)) {\n const next = tokens[index + 1];\n if (next !== undefined && !next.startsWith('--')) {\n flags.set(key, next);\n index += 1;\n }\n }\n continue;\n }\n positionals.push(token);\n }\n return { verb, positionals, flags };\n}\n\nfunction textFlag(parsed: Parsed, name: string): string | undefined {\n const value = parsed.flags.get(name);\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction hasFlag(parsed: Parsed, name: string): boolean {\n return parsed.flags.has(name);\n}\n\nfunction fail(text: string): HumanCommandResult {\n return { ok: false, text };\n}\n\nfunction ok(text: string): HumanCommandResult {\n return { ok: true, text };\n}\n\nfunction usage(): string {\n return [\n '\u7528\u6CD5\uFF1A/mem ' + HUMAN_COMMAND_HINT,\n '\u672C\u8F6E\u56DE\u987E\uFF08\u751F\u6210\u5F85\u5BA1\u63D0\u6848\uFF09\uFF1A/mem-fact \u4E8B\u5B9E\u3001/mem-pitfall \u5751\u3001/mem-exp \u7ECF\u9A8C\u3002',\n '\u6240\u6709\u52A8\u4F5C\u90FD\u7531\u4F60\uFF08\u4EBA\uFF09\u53D1\u8D77\uFF0C\u4E0D\u8FDB\u6A21\u578B\u4E0A\u4E0B\u6587\uFF1B`decide` \u4E0D\u4F1A\u4EE5\u5DE5\u5177\u5F62\u5F0F\u66B4\u9732\u7ED9\u6A21\u578B\u3002',\n ].join('\\n');\n}\n\nfunction formatProposals(deps: HumanCommandDeps): HumanCommandResult {\n const proposals = listProposals(deps.store);\n if (proposals.length === 0) return ok('\u6CA1\u6709\u5F85\u5BA1\u63D0\u6848\u3002');\n const lines: string[] = [];\n for (const proposal of proposals) {\n lines.push(`${proposal.id} ${proposal.op} ${proposal.targets.join(',')} ${proposal.reason}`);\n for (const replacement of proposal.replacements) {\n lines.push(` \u2192 [${replacement.kind}] ${replacement.abstract}`);\n }\n lines.push(` \u51B3\u5B9A\uFF1A/mem decide ${proposal.id} accept | reject`);\n }\n return ok(lines.join('\\n'));\n}\n\nfunction formatRead(id: string, deps: HumanCommandDeps): HumanCommandResult {\n const doc = deps.store.read(id as MemoryId);\n const lines = [\n `${doc.kind} ${doc.id} [${doc.valid_from} .. ${doc.valid_until ?? 'open'}] author=${doc.author}`,\n `abstract: ${doc.abstract}`,\n ];\n if (doc.error_signatures.length > 0) lines.push(`signatures: ${doc.error_signatures.join(' | ')}`);\n lines.push('', doc.body.trimEnd());\n if (doc.provenance.length > 0) {\n lines.push('', 'provenance:');\n for (const entry of doc.provenance) {\n lines.push(` - ${entry.speaker} #${entry.event_seq}: ${entry.quote}`);\n }\n }\n return ok(lines.join('\\n'));\n}\n\nfunction decideOne(proposalId: string, decision: 'accept' | 'reject', deps: HumanCommandDeps): string {\n const proposal = listProposals(deps.store).find((entry) => entry.id === proposalId);\n if (proposal === undefined) throw new ProposalError('NOT_FOUND', `no pending proposal ${proposalId}`);\n decideProposal({ store: deps.store, config: deps.config }, { id: proposalId, decision });\n if (decision === 'reject') return `\u5DF2\u5426\u51B3 ${proposalId}`;\n if (proposal.op === 'delete') {\n return `\u5DF2\u91C7\u7EB3 ${proposalId}\uFF1A${proposal.targets[0] ?? ''} \u5DF2\u5931\u6548\uFF08\u6587\u4EF6\u4ECD\u53EF\u8BFB\uFF09`;\n }\n const created = deps.store\n .active()\n .find((doc) => doc.supersedes.includes(proposal.targets[0] as MemoryId));\n return `\u5DF2\u91C7\u7EB3 ${proposalId}${created === undefined ? '' : ` \u2192 \u65B0\u8BB0\u5F55 ${created.id}`}`;\n}\n\nfunction decide(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n if (hasFlag(parsed, 'batch')) {\n const decision = parsed.positionals[0];\n if (decision !== 'accept' && decision !== 'reject') {\n return fail('\u7528\u6CD5\uFF1A/mem decide --batch accept|reject');\n }\n const pending = listProposals(deps.store);\n if (pending.length === 0) return ok('\u6CA1\u6709\u5F85\u5BA1\u63D0\u6848\u3002');\n const lines: string[] = [];\n let applied = 0;\n for (const proposal of pending) {\n try {\n lines.push(decideOne(proposal.id, decision, deps));\n applied += 1;\n } catch (error) {\n lines.push(`\u5931\u8D25 ${proposal.id}\uFF1A${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return {\n ok: applied === pending.length,\n text: `${decision === 'accept' ? 'accepted' : 'rejected'} ${applied}/${pending.length}\\n${lines.join('\\n')}`,\n };\n }\n const proposalId = parsed.positionals[0];\n const decision = parsed.positionals[1];\n if (proposalId === undefined || (decision !== 'accept' && decision !== 'reject')) {\n return fail('\u7528\u6CD5\uFF1A/mem decide <id> accept|reject');\n }\n return ok(decideOne(proposalId, decision, deps));\n}\n\nfunction add(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const abstract = textFlag(parsed, 'abstract');\n if (abstract === undefined || abstract.trim() === '') {\n return fail('\u7528\u6CD5\uFF1A/mem add --abstract \"\u2026\" [--kind fact|pitfall|exp] [--body \"\u2026\"]');\n }\n const kind = (textFlag(parsed, 'kind') ?? 'fact') as Kind;\n if (!KINDS.includes(kind)) return fail(`--kind \u5FC5\u987B\u662F ${KINDS.join(', ')} \u4E4B\u4E00`);\n const evidenceLevel = (textFlag(parsed, 'evidence-level') ?? 'user_explicit') as string;\n if (!EVIDENCE_LEVELS.includes(evidenceLevel as (typeof EVIDENCE_LEVELS)[number])) {\n return fail(`--evidence-level \u5FC5\u987B\u662F ${EVIDENCE_LEVELS.join(', ')} \u4E4B\u4E00`);\n }\n const signatureText = textFlag(parsed, 'signature') ?? textFlag(parsed, 'error-signature');\n const errorSignatures =\n signatureText === undefined ? [] : signatureText.split(',').map((part) => part.trim()).filter((part) => part !== '');\n const validFrom = textFlag(parsed, 'valid-from');\n const result = deps.store.add(\n {\n kind,\n abstract,\n body: textFlag(parsed, 'body') ?? '',\n evidence_level: evidenceLevel as 'user_explicit' | 'user_confirmed' | 'observed',\n error_signatures: errorSignatures,\n ...(validFrom === undefined ? {} : { valid_from: validFrom }),\n },\n { author: 'human' },\n );\n return ok(`${result.deduplicated ? '\u5DF2\u6709\u540C\u5185\u5BB9\u8BB0\u5F55' : '\u5DF2\u5199\u5165'} ${result.id}`);\n}\n\nfunction recall(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const query = parsed.positionals.slice(0).join(' ');\n if (query.trim() === '') return fail('\u7528\u6CD5\uFF1A/mem recall <query> [--kind fact|pitfall|exp] [--limit N]');\n const kind = textFlag(parsed, 'kind');\n if (kind !== undefined && !KINDS.includes(kind as Kind)) return fail(`--kind \u5FC5\u987B\u662F ${KINDS.join(', ')} \u4E4B\u4E00`);\n const limitText = textFlag(parsed, 'limit');\n const limit = limitText === undefined ? undefined : Number(limitText);\n if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) return fail('--limit \u5FC5\u987B\u662F\u6B63\u6574\u6570');\n const result = deps.store.recall(query, {\n ...(limit === undefined ? {} : { limit }),\n ...(kind === undefined ? {} : { kinds: [kind as Kind] }),\n });\n if (result.hits.length === 0) return ok('\u6CA1\u6709\u5339\u914D\u3002');\n return ok(result.hits.map((hit) => `- [${hit.kind}] ${hit.abstract} \u2014 ${hit.id}`).join('\\n'));\n}\n\nfunction inspect(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const limitText = textFlag(parsed, 'limit');\n const limit = limitText === undefined ? 10 : Number(limitText);\n if (!Number.isSafeInteger(limit) || limit < 1) return fail('--limit \u5FC5\u987B\u662F\u6B63\u6574\u6570');\n const report = inspectStore({ home: deps.home, config: deps.config, store: deps.store, limit });\n const lines = [\n `active ${report.active} (${Object.entries(report.byKind).map(([kind, count]) => `${kind} ${count}`).join(', ')})`,\n `pending proposals ${report.pendingProposals} \u00B7 quarantined ${report.quarantined.length}`,\n `journal head ${report.journalHead === null ? '(none)' : `#${report.journalHead.seq} ${report.journalHead.hash.slice(0, 12)}`}`,\n `rules ${loadRules(deps.home).length}`,\n `budget index ${report.budget.indexChars} \u00B7 total ${report.budget.totalChars}`,\n `personalization SOUL ${report.personalization.soul || '0'} \u00B7 USER ${report.personalization.user || '0'} \u00B7 RULES ${report.personalization.rules || '0'} chars`,\n ];\n if (report.personalization.soul > report.inject.persona_max_chars) {\n lines.push(`\u26A0 SOUL.md ${report.personalization.soul} \u5B57\uFF0C\u8D85\u8FC7\u6CE8\u5165\u4E0A\u9650 ${report.inject.persona_max_chars}\uFF0C\u6CE8\u5165\u65F6\u4F1A\u88AB\u622A\u65AD`);\n }\n if (report.personalization.user > report.inject.user_max_chars) {\n lines.push(`\u26A0 USER.md ${report.personalization.user} \u5B57\uFF0C\u8D85\u8FC7\u6CE8\u5165\u4E0A\u9650 ${report.inject.user_max_chars}\uFF0C\u6CE8\u5165\u65F6\u4F1A\u88AB\u622A\u65AD`);\n }\n if (report.personalization.rules > report.inject.rules_max_chars) {\n lines.push(`\u26A0 RULES.md ${report.personalization.rules} \u5B57\uFF0C\u8D85\u8FC7\u6CE8\u5165\u4E0A\u9650 ${report.inject.rules_max_chars}\uFF0C\u6CE8\u5165\u4F1A\u76F4\u63A5\u62A5\u9519`);\n }\n return ok(lines.join('\\n'));\n}\n\nfunction adopt(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const id = parsed.positionals[0];\n if (id === undefined || !isMemoryId(id)) return fail('\u7528\u6CD5\uFF1A/mem adopt <mem-YYYYMMDD-xxxxxxxx>');\n const result = deps.store.adopt(id);\n return ok(`\u5DF2\u627F\u8BA4 ${result.id}\uFF08\u54C8\u5E0C\u5DF2\u8BB0\u8D26\uFF09`);\n}\n\nfunction remove(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const id = parsed.positionals[0];\n const reason = textFlag(parsed, 'reason');\n if (id === undefined || reason === undefined || reason.trim() === '') {\n return fail('\u7528\u6CD5\uFF1A/mem delete <id> --reason \"\u2026\"');\n }\n const result = deps.store.remove(id as MemoryId, { reason });\n return ok(`\u5DF2\u5220\u9664 ${result.id}\uFF08\u6587\u4EF6\u4FDD\u7559\uFF0C\u53EF read \u8FFD\u6EAF\uFF09`);\n}\n\nfunction purge(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const id = parsed.positionals[0];\n const reason = textFlag(parsed, 'reason') ?? 'purge';\n if (id === undefined) return fail('\u7528\u6CD5\uFF1A/mem purge <id> --reason \"\u2026\" --accept');\n if (!hasFlag(parsed, 'accept')) return fail('purge \u9700\u8981 --accept \u786E\u8BA4\uFF08\u4F1A\u5220\u9664\u6587\u4EF6\uFF09');\n if (!isMemoryId(id)) return fail(`\"${id}\" \u4E0D\u662F\u8BB0\u5FC6 id`);\n const result = deps.store.purge(id as MemoryId, { reason });\n return ok(`\u5DF2\u6E05\u9664 ${id}\uFF08\u5893\u7891\u5DF2\u5199\u5165 journal\uFF0C\u4F5C\u5E9F ${result.proposals} \u4E2A\u5F85\u5BA1\u63D0\u6848\uFF09`);\n}\n\nfunction rebuild(deps: HumanCommandDeps): HumanCommandResult {\n const report = deps.store.rebuild();\n return ok(`\u5DF2\u91CD\u5EFA\u7D22\u5F15\uFF1A${report.files} \u4E2A\u6587\u4EF6\uFF0Cjournal head ${report.journal_head === null ? '(none)' : `#${report.journal_head.seq}`}`);\n}\n\nfunction exportStoreCommand(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const out = parsed.positionals[0];\n if (out === undefined) return fail('\u7528\u6CD5\uFF1A/mem export <dir>');\n const result = exportStore({ home: deps.home, out });\n return ok(`\u5DF2\u5BFC\u51FA ${result.files} \u4E2A\u6587\u4EF6\uFF08${result.bytes} bytes\uFF09\u5230 ${result.out}\\n\u6821\u9A8C\u6E05\u5355\uFF1A${result.sums}`);\n}\n\nfunction seal(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n if (!hasFlag(parsed, 'accept')) return fail('seal \u9700\u8981 --accept \u786E\u8BA4\uFF08\u4F1A\u91CD\u5199\u5C01\u5B58\u54C8\u5E0C\uFF09');\n const result = sealPolicy({\n home: deps.home,\n accept: true,\n sealUser: hasFlag(parsed, 'seal-user'),\n });\n const sealed = [result.sealedFiles.soul, result.sealedFiles.user, result.sealedFiles.rules].filter(\n (value) => value !== '',\n ).length;\n return ok(\n `\u5DF2\u91CD\u65B0\u5C01\u5B58\uFF1A${result.sealPath}\\nsha256: ${result.sha256}\\n\u4EBA\u5DE5\u6587\u4EF6\uFF1A${sealed}` +\n (result.sealedFiles.user === '' ? '\uFF08USER.md \u672A\u5C01\u5B58\uFF0C\u5141\u8BB8 agent \u63D0\u8BAE\u4FEE\u6539\uFF09' : ''),\n );\n}\n\nfunction profile(parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const snapshot = loadProfile(deps.home);\n const query = parsed.positionals.join(' ');\n const entries = query.trim() === '' ? [...snapshot.entries] : queryProfile(snapshot.entries, query);\n const warning =\n snapshot.chars > deps.config.inject.user_max_chars\n ? `\\n\u26A0 USER.md ${snapshot.chars} \u5B57\uFF0C\u8D85\u8FC7\u6CE8\u5165\u4E0A\u9650 ${deps.config.inject.user_max_chars}\uFF0C\u6CE8\u5165\u65F6\u4F1A\u88AB\u622A\u65AD`\n : '';\n if (entries.length === 0) return ok(`USER.md \u6CA1\u6709\u5339\u914D\u7684\u6761\u76EE\u3002${warning}`);\n return ok(\n `USER.md\uFF1A${snapshot.entries.length} \u6761 / ${snapshot.chars} \u5B57${warning}\\n` +\n entries.map((entry, index) => `${index + 1}. ${entry}`).join('\\n\\n'),\n );\n}\n\nfunction scaffold(_parsed: Parsed, deps: HumanCommandDeps): HumanCommandResult {\n const result = scaffoldPersonalization({ home: deps.home });\n const lines = [`\u5DF2\u91CD\u65B0\u5C01\u5B58\uFF1A${result.sealSha256}`];\n if (result.created.length > 0) lines.push(`\u65B0\u5EFA\uFF1A${result.created.map((file) => file.split(/[\\\\/]/).pop()).join('\u3001')}`);\n if (result.kept.length > 0) lines.push(`\u4FDD\u7559\uFF1A${result.kept.map((file) => file.split(/[\\\\/]/).pop()).join('\u3001')}`);\n lines.push('\u7F16\u8F91\u540E\u8FD0\u884C /mem seal --accept \u751F\u6548\uFF1BUSER.md \u9ED8\u8BA4\u4E0D\u5C01\u5B58\u3002');\n return ok(lines.join('\\n'));\n}\n\n/** Execute one `/mem \u2026` line. Never throws: every failure comes back as text. */\nexport function runHumanCommand(deps: HumanCommandDeps, line: string): HumanCommandResult {\n try {\n const parsed = parseLine(line.trim());\n switch (parsed.verb) {\n case 'help':\n return ok(usage());\n case 'proposals':\n return formatProposals(deps);\n case 'decide':\n return decide(parsed, deps);\n case 'add':\n return add(parsed, deps);\n case 'read': {\n const id = parsed.positionals[0];\n if (id === undefined) return fail('\u7528\u6CD5\uFF1A/mem read <id>');\n return formatRead(id, deps);\n }\n case 'recall':\n return recall(parsed, deps);\n case 'profile':\n return profile(parsed, deps);\n case 'inspect':\n return inspect(parsed, deps);\n case 'scaffold':\n return scaffold(parsed, deps);\n case 'adopt':\n return adopt(parsed, deps);\n case 'delete':\n return remove(parsed, deps);\n case 'purge':\n return purge(parsed, deps);\n case 'rebuild':\n return rebuild(deps);\n case 'export':\n return exportStoreCommand(parsed, deps);\n case 'seal':\n return seal(parsed, deps);\n default:\n return fail(`\u672A\u77E5\u5B50\u547D\u4EE4 ${parsed.verb}\\n${usage()}`);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`\u5931\u8D25\uFF1A${message}`);\n }\n}\n", "import type { Kind } from '../model/types.ts';\nimport type { MemoryStore } from '../store/store.ts';\n\n/**\n * Import an `agent-memory-export-v1` bundle (the JSON produced by the GUI\n * export button or `mem export`). Memory content is re-added through the store\n * so locks, validation, journaling and dedupe stay in one place.\n *\n * - Duplicate content (same content_hash) is skipped, not duplicated.\n * - Imported records are authored by the human doing the import; provenance is\n * carried as-is (the source sessions may not exist on this machine, so the\n * evidence can show as unverifiable rather than being rewritten).\n * - Pending proposals are not imported: a proposal must target a live record\n * in this store, and silently recreating one would bypass the human queue.\n */\n\nexport interface ImportReport {\n readonly imported: number;\n readonly skipped: number;\n readonly failed: readonly { readonly abstract: string; readonly error: string }[];\n readonly ignored_proposals: number;\n}\n\nexport interface ImportMemory {\n readonly kind: string;\n readonly abstract: string;\n readonly body?: string;\n readonly project?: string | null;\n readonly tags?: readonly string[];\n readonly relations?: readonly unknown[];\n readonly source?: { readonly type?: unknown; readonly id?: unknown } | null;\n readonly valid_from?: string;\n readonly error_signatures?: readonly string[];\n readonly evidence_level?: string;\n readonly provenance?: readonly unknown[];\n}\n\nconst KINDS: readonly Kind[] = ['fact', 'pitfall', 'exp'];\nconst LEVELS = new Set(['user_explicit', 'user_confirmed', 'observed']);\n\nexport function importBundle(store: MemoryStore, bundle: unknown): ImportReport {\n if (typeof bundle !== 'object' || bundle === null) throw new Error('bundle must be an object');\n const record = bundle as { format?: unknown; memories?: unknown; proposals?: unknown };\n if (record.format !== 'agent-memory-export-v1' && record.format !== 'agent-memory-export-v2') {\n throw new Error('unsupported bundle format (expected agent-memory-export-v1 or v2)');\n }\n if (!Array.isArray(record.memories)) throw new Error('bundle.memories must be an array');\n\n let imported = 0;\n let skipped = 0;\n const failed: { abstract: string; error: string }[] = [];\n\n for (const raw of record.memories as ImportMemory[]) {\n const abstract = typeof raw?.abstract === 'string' ? raw.abstract : '';\n try {\n if (typeof raw !== 'object' || raw === null) throw new Error('entry must be an object');\n if (typeof raw.kind !== 'string' || !KINDS.includes(raw.kind as Kind)) {\n throw new Error(`kind must be one of ${KINDS.join(', ')}`);\n }\n if (abstract.trim() === '') throw new Error('abstract is required');\n const body = typeof raw.body === 'string' ? raw.body : '';\n const evidenceLevel = typeof raw.evidence_level === 'string' && LEVELS.has(raw.evidence_level)\n ? (raw.evidence_level as 'user_explicit' | 'user_confirmed' | 'observed')\n : 'observed';\n const provenance = Array.isArray(raw.provenance) ? raw.provenance : [];\n const result = store.add(\n {\n kind: raw.kind as Kind,\n abstract,\n body,\n ...(typeof raw.project === 'string' || raw.project === null ? { project: raw.project } : {}),\n ...(Array.isArray(raw.tags)\n ? { tags: raw.tags.filter((entry): entry is string => typeof entry === 'string') }\n : {}),\n ...(Array.isArray(raw.relations)\n ? {\n relations: raw.relations.filter(\n (entry): entry is { type: 'relates_to' | 'derived_from'; target: string } =>\n typeof entry === 'object' &&\n entry !== null &&\n typeof (entry as { type?: unknown }).type === 'string' &&\n typeof (entry as { target?: unknown }).target === 'string',\n ),\n }\n : {}),\n ...(typeof raw.source === 'object' &&\n raw.source !== null &&\n typeof raw.source.type === 'string' &&\n typeof raw.source.id === 'string'\n ? { source: { type: raw.source.type, id: raw.source.id } }\n : {}),\n evidence_level: evidenceLevel,\n ...(typeof raw.valid_from === 'string' ? { valid_from: raw.valid_from } : {}),\n ...(Array.isArray(raw.error_signatures)\n ? { error_signatures: raw.error_signatures.filter((entry): entry is string => typeof entry === 'string') }\n : {}),\n },\n { author: 'human', provenance: provenance as never },\n );\n if (result.deduplicated) skipped += 1;\n else imported += 1;\n } catch (error) {\n failed.push({ abstract: abstract || '(no abstract)', error: error instanceof Error ? error.message : String(error) });\n }\n }\n\n return {\n imported,\n skipped,\n failed,\n ignored_proposals: Array.isArray(record.proposals) ? record.proposals.length : 0,\n };\n}\n", "import { SessionQuota } from '../../core/src/service/quota.ts';\n\n/**\n * Tool surface (plan v1.3 \u00A75.2, \u00A75.4; ADR-0012). Strict schemas, no field names\n * that could smuggle a path or a session; `decide` is never a tool.\n *\n * `memory_review` shows a human button card and then runs the `/mem decide \u2026`\n * command; the verdict comes from the card, never from the model.\n *\n * `registerTools` takes a service object so the adapter stays free of file I/O;\n * the real DSH wiring passes the core-backed service in.\n */\n\nexport const TOOL_NAMES = [\n 'memory_recall',\n 'memory_read',\n 'memory_record',\n 'memory_propose',\n 'memory_review',\n 'memory_context',\n 'rules_list',\n] as const;\nexport type ToolName = (typeof TOOL_NAMES)[number];\n\nconst FORBIDDEN_FIELDS = new Set(['path', 'target', 'session', 'session_id', 'approve']);\n\nfunction objectSchema(properties: Record<string, unknown>, required: string[] = []) {\n return { type: 'object', properties, required, additionalProperties: false };\n}\n\nexport const TOOL_SCHEMAS: Readonly<Record<ToolName, unknown>> = {\n memory_recall: objectSchema(\n {\n query: { type: 'string', minLength: 1 },\n limit: { type: 'integer', minimum: 1 },\n kind: { type: 'string', enum: ['fact', 'pitfall', 'exp'] },\n },\n ['query'],\n ),\n memory_read: objectSchema({ id: { type: 'string' } }, ['id']),\n memory_record: objectSchema(\n {\n kind: { type: 'string', enum: ['fact', 'pitfall', 'exp'] },\n abstract: { type: 'string' },\n body: { type: 'string' },\n evidence: {\n type: 'array',\n minItems: 1,\n items: objectSchema(\n { event_seq: { type: 'integer', minimum: 0 }, quote: { type: 'string' } },\n ['event_seq', 'quote'],\n ),\n },\n valid_from: { type: 'string' },\n project: { type: 'string' },\n tags: { type: 'array', items: { type: 'string' }, maxItems: 8 },\n error_signatures: { type: 'array', items: { type: 'string' }, maxItems: 3 },\n },\n ['kind', 'abstract', 'body', 'evidence'],\n ),\n memory_propose: objectSchema(\n {\n op: { type: 'string', enum: ['create', 'supersede', 'delete'] },\n ids: { type: 'array', items: { type: 'string' }, minItems: 1 },\n base_hashes: { type: 'array', items: { type: 'string' } },\n replacements: {\n type: 'array',\n minItems: 1,\n items: objectSchema(\n {\n kind: { type: 'string', enum: ['fact', 'pitfall', 'exp'] },\n abstract: { type: 'string', minLength: 1 },\n body: { type: 'string' },\n evidence: {\n type: 'array',\n minItems: 1,\n items: objectSchema(\n { event_seq: { type: 'integer', minimum: 0 }, quote: { type: 'string' } },\n ['event_seq', 'quote'],\n ),\n },\n valid_from: { type: 'string' },\n project: { type: 'string' },\n tags: { type: 'array', items: { type: 'string' }, maxItems: 8 },\n error_signatures: { type: 'array', items: { type: 'string' }, maxItems: 3 },\n },\n ['kind', 'abstract', 'body', 'evidence'],\n ),\n },\n reason: { type: 'string' },\n },\n ['op'],\n ),\n memory_review: objectSchema({ id: { type: 'string' } }),\n memory_context: objectSchema({ limit: { type: 'integer', minimum: 1, maximum: 50 } }, []),\n rules_list: objectSchema({}, []),\n};\n\nexport class ToolInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ToolInputError';\n }\n}\n\nfunction forbiddenKeys(value: unknown, path = ''): string[] {\n if (typeof value !== 'object' || value === null) return [];\n if (Array.isArray(value)) return value.flatMap((entry, index) => forbiddenKeys(entry, `${path}[${index}]`));\n const hits: string[] = [];\n for (const [key, child] of Object.entries(value)) {\n if (FORBIDDEN_FIELDS.has(key)) hits.push(`${path}${key}`.replace(/^\\./, ''));\n hits.push(...forbiddenKeys(child, `${path}${key}.`));\n }\n return hits;\n}\n\n/** Schema check used by tests and execute; returns [] when the args are usable. */\nexport function validateToolArgs(name: ToolName, args: unknown): string[] {\n if (typeof args !== 'object' || args === null || Array.isArray(args)) return ['arguments must be an object'];\n const schema = TOOL_SCHEMAS[name] as { properties: Record<string, unknown>; required: string[] };\n const record = args as Record<string, unknown>;\n const problems: string[] = [];\n const forbidden = forbiddenKeys(record);\n if (forbidden.length > 0) problems.push(`forbidden field: ${forbidden.join(', ')}`);\n for (const key of Object.keys(record)) {\n if (!(key in schema.properties)) problems.push(`unknown field: ${key}`);\n }\n for (const key of schema.required) {\n if (!(key in record)) problems.push(`missing field: ${key}`);\n }\n if (name === 'memory_read') {\n if (typeof record.id !== 'string' || !/^mem-\\d{8}-[0-9a-f]{8}$/.test(record.id)) {\n problems.push('id must be a memory id');\n }\n }\n if (name === 'memory_record') {\n if (record.kind === 'pitfall') {\n const signatures = record.error_signatures;\n if (!Array.isArray(signatures) || signatures.length === 0) {\n problems.push('a pitfall needs error_signatures');\n }\n }\n const evidence = record.evidence;\n if (!Array.isArray(evidence) || evidence.length === 0) problems.push('evidence is required');\n }\n if (name === 'memory_review') {\n if (record.id !== undefined && (typeof record.id !== 'string' || !/^prop-mem-\\d{8}-[0-9a-f]{8}$/.test(record.id))) {\n problems.push('id must be a proposal id');\n }\n }\n if (name === 'memory_propose') {\n if (record.op === 'delete' && (typeof record.reason !== 'string' || record.reason.trim() === '')) {\n problems.push('a delete proposal needs reason');\n }\n if (record.op === 'create' || record.op === 'supersede') {\n const replacements = record.replacements;\n if (!Array.isArray(replacements) || replacements.length === 0) {\n problems.push(`a ${record.op} proposal needs replacements`);\n } else {\n replacements.forEach((replacement, index) => {\n problems.push(...replacementProblems(replacement, `replacements[${index}]`));\n });\n }\n }\n if (record.op !== 'create') {\n if (!Array.isArray(record.ids) || record.ids.length === 0) problems.push('ids are required');\n if (!Array.isArray(record.base_hashes) || record.base_hashes.length === 0) {\n problems.push('base_hashes are required');\n }\n }\n if (Array.isArray(record.base_hashes) && Array.isArray(record.ids)) {\n if (record.base_hashes.length !== record.ids.length) problems.push('one base_hash per id is required');\n }\n }\n return problems;\n}\n\nconst KINDS = new Set(['fact', 'pitfall', 'exp']);\n\nfunction replacementProblems(replacement: unknown, path: string): string[] {\n if (typeof replacement !== 'object' || replacement === null || Array.isArray(replacement)) {\n return [`${path} must be an object`];\n }\n const item = replacement as Record<string, unknown>;\n const problems: string[] = [];\n if (typeof item.kind !== 'string' || !KINDS.has(item.kind)) problems.push(`${path}.kind must be fact|pitfall|exp`);\n if (typeof item.abstract !== 'string' || item.abstract.trim() === '') problems.push(`${path}.abstract is required`);\n if (typeof item.body !== 'string') problems.push(`${path}.body is required`);\n if (item.kind === 'pitfall') {\n const signatures = item.error_signatures;\n if (!Array.isArray(signatures) || signatures.length === 0) problems.push(`${path} pitfall needs error_signatures`);\n }\n const evidence = item.evidence;\n if (!Array.isArray(evidence) || evidence.length === 0) {\n problems.push(`${path}.evidence is required`);\n return problems;\n }\n evidence.forEach((entry, index) => {\n if (typeof entry !== 'object' || entry === null) {\n problems.push(`${path}.evidence[${index}] must be an object`);\n return;\n }\n const evidenceItem = entry as Record<string, unknown>;\n if (!Number.isInteger(evidenceItem.event_seq) || (evidenceItem.event_seq as number) < 0) {\n problems.push(`${path}.evidence[${index}].event_seq must be a non-negative integer`);\n }\n if (typeof evidenceItem.quote !== 'string' || evidenceItem.quote === '') {\n problems.push(`${path}.evidence[${index}].quote is required`);\n }\n });\n return problems;\n}\n\nexport interface ToolService {\n readonly config: { readonly quota: { readonly t0_per_session: number } };\n /** Assistant write mode from `personalization.mode`. */\n readonly mode: 'confirm' | 'direct' | 'readonly';\n recall(input: { query: string; limit?: number; kind?: string }): unknown;\n read(id: string): unknown;\n record(input: unknown, actor: TrustedActor, exec?: unknown): unknown;\n propose(input: unknown, actor: TrustedActor, exec?: unknown): unknown;\n context(exec?: unknown, limit?: number): unknown;\n rules(): unknown;\n}\n\n/**\n * Host-side review card hooks (ADR-0012). `memory_propose` opens the card right\n * after a proposal is stored; `memory_review` re-opens it for a deferred one.\n * The hook turns the click into `/mem decide \u2026` and returns the outcome.\n */\nexport interface ToolHooks {\n readonly reviewProposal?: (proposal: unknown, exec?: unknown) => Promise<unknown>;\n readonly reviewPending?: (proposalId: string | undefined, exec?: unknown) => Promise<unknown>;\n}\n\nexport interface TrustedActor {\n readonly sessionId: string;\n readonly delegationDepth: number;\n}\n\n/** Capability groups (architecture v2 P0.5): preset/GUI/MCP compose these. */\nexport type CapabilityGroup = 'facts.read' | 'facts.write' | 'proposals.review' | 'rules.read';\n\nexport function capabilitiesFor(\n mode: 'confirm' | 'direct' | 'readonly',\n delegationDepth: number,\n): readonly CapabilityGroup[] {\n const capabilities: CapabilityGroup[] = ['facts.read', 'rules.read'];\n if (delegationDepth === 0) {\n capabilities.push('proposals.review');\n if (mode !== 'readonly') capabilities.push('facts.write');\n }\n return capabilities;\n}\n\nexport interface ToolRegistry {\n register(definition: unknown): unknown;\n}\n\nexport interface RegisteredTool {\n readonly names: readonly ToolName[];\n}\n\n/**\n * Register read tools always and write tools only for a top-level agent. The\n * quota (if supplied) rejects the (limit+1)-th T0 write in one session.\n */\nexport function registerTools(\n ctx: { readonly tools: ToolRegistry },\n service: ToolService,\n actor: TrustedActor,\n quota: SessionQuota = new SessionQuota(service.config.quota.t0_per_session),\n hooks: ToolHooks = {},\n): RegisteredTool {\n const capabilities = new Set(capabilitiesFor(service.mode, actor.delegationDepth));\n const names: ToolName[] = ['memory_recall', 'memory_read', 'memory_context', 'rules_list'];\n if (capabilities.has('proposals.review')) names.push('memory_review');\n if (capabilities.has('facts.write')) names.push('memory_record', 'memory_propose');\n\n/** Tool copy is human-facing; Chinese is the project's default (user preference). */\nconst TOOL_DESCRIPTIONS: Readonly<Record<ToolName, string>> = {\n memory_recall: '\u68C0\u7D22\u957F\u671F\u8BB0\u5FC6\uFF1A\u6309\u67E5\u8BE2\u8FD4\u56DE\u76F8\u5173\u6458\u8981\u4E0E\u8BB0\u5FC6\u7F16\u53F7',\n memory_read: '\u8BFB\u53D6\u4E00\u6761\u8BB0\u5FC6\u7684\u5168\u6587\u3001\u51FA\u5904\u4E0E\u72B6\u6001',\n memory_record: '\u5199\u5165\u4E00\u6761\u65B0\u8BB0\u5FC6\uFF08\u5FC5\u987B\u7ED9\u51FA\u771F\u5B9E\u4E8B\u4EF6\u51FA\u5904\uFF09',\n memory_propose: '\u63D0\u51FA\u8BB0\u5FC6\u4FEE\u8BA2\u6216\u5220\u9664\u63D0\u6848\uFF0C\u7B49\u5F85\u4EBA\u786E\u8BA4',\n memory_review: '\u4E3A\u5F85\u5BA1\u63D0\u6848\u5F39\u51FA\u4E2D\u6587\u5BA1\u6279\u5361\u7247',\n memory_context: '\u67E5\u770B\u5F53\u524D\u4F1A\u8BDD\u6700\u8FD1\u4E8B\u4EF6\uFF0C\u53D6\u5F97\u53EF\u7528\u4E8E\u51FA\u5904\u7684 event_seq',\n rules_list: '\u5217\u51FA\u5F53\u524D\u751F\u6548\u7684\u89C4\u5219',\n};\n\n const execute = (name: ToolName, handler: (args: Record<string, unknown>, exec?: unknown) => unknown) => ({\n name,\n description: TOOL_DESCRIPTIONS[name],\n parameters: TOOL_SCHEMAS[name],\n output: {\n schema: { type: 'object' },\n render: (_args: unknown, value: unknown) => {\n const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);\n // Point the human at the review paths; `decide` itself stays out of the\n // tool surface (ADR-0011/0012).\n const candidate = typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {};\n const proposal = (candidate.proposal as { id?: unknown } | undefined) ?? candidate;\n const review = candidate.review as { decision?: unknown } | undefined;\n const proposalId = name === 'memory_propose' && review === undefined ? proposal.id : undefined;\n const hint =\n typeof proposalId === 'string'\n ? `\\n\\n\u4EBA\u5728\u804A\u5929\u6846\u51B3\u5B9A\uFF1A/mem decide ${proposalId} accept \u6216 reject\uFF1B\u4E5F\u53EF\u8C03\u7528 memory_review \u91CD\u65B0\u5F39\u51FA\u5361\u7247`\n : '';\n return [{ type: 'text', text: text + hint }];\n },\n },\n execute: async (args: unknown, exec?: unknown) => {\n const problems = validateToolArgs(name, args);\n if (problems.length > 0) throw new ToolInputError(problems.join('; '));\n return handler(args as Record<string, unknown>, exec);\n },\n });\n\n const handlers: Record<string, (args: Record<string, unknown>, exec?: unknown) => unknown> = {\n memory_recall: (args) =>\n service.recall({\n query: String(args.query),\n ...(typeof args.limit === 'number' ? { limit: args.limit } : {}),\n ...(typeof args.kind === 'string' ? { kind: args.kind } : {}),\n }),\n memory_read: (args) => service.read(String(args.id)),\n memory_record: (args, exec) => {\n if (service.mode === 'readonly') {\n throw new ToolInputError('\u5F53\u524D\u4E3A readonly \u6A21\u5F0F\uFF1A\u53EA\u80FD\u8BFB\u53D6\u8BB0\u5FC6\uFF0C\u4E0D\u80FD\u5199\u5165');\n }\n if (!quota.consume(actor.sessionId)) {\n throw new ToolInputError('T0 write quota is exhausted for this session; use memory_propose instead');\n }\n const { evidence, ...rest } = args;\n return service.record({ ...rest, evidence }, actor, exec);\n },\n memory_propose: async (args, exec) => {\n if (service.mode === 'readonly') {\n throw new ToolInputError('\u5F53\u524D\u4E3A readonly \u6A21\u5F0F\uFF1A\u53EA\u80FD\u8BFB\u53D6\u8BB0\u5FC6\uFF0C\u4E0D\u80FD\u63D0\u51FA\u4FEE\u6539');\n }\n const proposal = (await service.propose(args, actor, exec)) as { id?: string };\n if (hooks.reviewProposal === undefined) return proposal;\n const review = await hooks.reviewProposal(proposal, exec);\n return { proposal, review };\n },\n memory_review: async (args, exec) => {\n if (hooks.reviewPending === undefined) {\n throw new ToolInputError('proposal review is unavailable in this host');\n }\n return hooks.reviewPending(typeof args.id === 'string' ? args.id : undefined, exec);\n },\n memory_context: (args, exec) =>\n service.context(exec, typeof args.limit === 'number' ? args.limit : undefined),\n rules_list: () => service.rules(),\n };\n\n for (const name of names) {\n ctx.tools.register(execute(name, handlers[name] as (args: Record<string, unknown>, exec?: unknown) => unknown));\n }\n return { names };\n}\n", "import type { Config } from '../../core/src/config/config.ts';\nimport type { Proposal } from '../../core/src/proposals/proposals.ts';\nimport { runHumanCommand, type HumanCommandResult } from '../../core/src/human/command.ts';\nimport type { MemoryStore } from '../../core/src/store/store.ts';\n\n/**\n * S9 review card: turn a pending memory proposal into a Chinese button card\n * through the host `userQuestions` service, then translate the human's click\n * into the SAME `/mem decide \u2026` command line the chat command plane uses and\n * execute it through the host `commands` service.\n *\n * The model never sees or supplies the verdict: the card's answer comes from a\n * human UI, and `decide` is still not a tool (ADR-0012).\n */\n\nexport const REVIEW_LABELS = {\n accept: '\u91C7\u7EB3',\n reject: '\u9A73\u56DE',\n defer: '\u6682\u4E0D\u5904\u7406',\n} as const;\n\nexport type ReviewDecision = 'accept' | 'reject' | 'defer';\n\nexport interface ReviewQuestionOption {\n readonly label: string;\n readonly description: string;\n}\n\nexport interface ReviewQuestion {\n readonly id: string;\n readonly header: string;\n readonly question: string;\n readonly detail: string;\n readonly options: readonly ReviewQuestionOption[];\n}\n\nexport interface ReviewAnswer {\n readonly answers: readonly {\n readonly id: string;\n readonly selected: readonly string[];\n readonly custom?: string;\n }[];\n}\n\nexport interface UserQuestionsLike {\n ask(request: unknown): Promise<ReviewAnswer>;\n}\n\nexport interface CommandsExecutorLike {\n execute?(\n agent: unknown,\n line: string,\n attachments: readonly unknown[],\n signal: AbortSignal,\n ): Promise<{ readonly result: { readonly kind?: string; readonly text?: string } } | undefined>;\n}\n\nexport interface ReviewExecLike {\n readonly agent?: unknown;\n readonly signal?: AbortSignal;\n readonly callId?: string;\n}\n\nexport interface ReviewDeps {\n readonly store: MemoryStore;\n readonly config: Config;\n readonly home: string;\n readonly userQuestions?: UserQuestionsLike;\n readonly commands?: CommandsExecutorLike;\n}\n\nexport interface ReviewOutcome {\n readonly decision: ReviewDecision;\n readonly command?: string;\n readonly result?: HumanCommandResult;\n readonly message: string;\n}\n\n/** The card copy: proposal content first, then the three choices. */\nexport function buildReviewQuestion(proposal: Proposal): ReviewQuestion {\n const lines: string[] = [];\n const verb = proposal.op === 'supersede' ? '\u66FF\u4EE3' : '\u5220\u9664';\n lines.push(`**\u63D0\u6848**\uFF1A\\`${proposal.id}\\`\uFF08${verb}\uFF09`);\n lines.push(`**\u76EE\u6807**\uFF1A${proposal.targets.join('\u3001')}`);\n if (proposal.reason.trim() !== '') lines.push(`**\u7406\u7531**\uFF1A${formatBody(proposal.reason)}`);\n for (const replacement of proposal.replacements) {\n lines.push('', `### [${replacement.kind}] ${replacement.abstract}`);\n if (replacement.body.trim() !== '') lines.push('', formatBody(replacement.body));\n const provenance = replacement.provenance ?? [];\n if (provenance.length > 0) {\n const first = provenance[0] as { session_id: string; event_seq: number; quote: string };\n lines.push(\n '',\n `**\u51FA\u5904**\uFF1A${provenance.length} \u6761\uFF08${first.session_id} #${first.event_seq}\u300C${first.quote}\u300D\uFF09`,\n );\n }\n }\n lines.push('', '\u91C7\u7EB3\u540E\u5199\u5165 journal \u5E76\u4F7F\u76EE\u6807\u8BB0\u5F55\u5931\u6548\uFF1B\u9A73\u56DE\u4FDD\u7559\u539F\u8BB0\u5F55\uFF1B\u6682\u4E0D\u5904\u7406\u5219\u63D0\u6848\u7EE7\u7EED\u5F85\u5BA1\u3002');\n return {\n id: proposal.id,\n header: '\u8BB0\u5FC6\u63D0\u6848',\n question: `\u662F\u5426\u91C7\u7EB3\u63D0\u6848 ${proposal.id}\uFF1F`,\n detail: lines.join('\\n'),\n options: [\n { label: REVIEW_LABELS.accept, description: '\u5E94\u7528\u66FF\u6362\uFF0C\u5199\u5165 journal\uFF0C\u76EE\u6807\u8BB0\u5F55\u5931\u6548' },\n { label: REVIEW_LABELS.reject, description: '\u4FDD\u7559\u539F\u8BB0\u5F55\uFF0C\u63D0\u6848\u4F5C\u5E9F\u5E76\u8BB0\u5165 journal' },\n { label: REVIEW_LABELS.defer, description: '\u4FDD\u7559\u63D0\u6848\uFF0C\u7A0D\u540E\u518D\u51B3\u5B9A' },\n ],\n };\n}\n\n/**\n * Card typography: put enumerations (`1)` `2\uFF09` `3\u3001`) on their own lines and\n * render them as an ordered list, so a body that was written inline is readable\n * in the card instead of one long paragraph.\n */\nexport function formatBody(text: string): string {\n const source = text.trim();\n if (source === '') return '';\n const broken = source.replace(/(?<![\\p{L}\\p{N}])\\s*(?=\\d{1,2}[)\uFF09]\\s?)/gu, '\\n');\n return broken\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line !== '')\n .map((line) => line.replace(/^(\\d{1,2})[)\uFF09]\\s*/, '$1. '))\n .join('\\n');\n}\n\n/** Map the human's answer to a decision; unknown text defers. */\nexport function decisionFromAnswer(answer: ReviewAnswer): ReviewDecision {\n const item = answer.answers[0];\n if (item === undefined) return 'defer';\n const chosen = item.selected[0] ?? item.custom?.trim() ?? '';\n if (chosen === REVIEW_LABELS.accept) return 'accept';\n if (chosen === REVIEW_LABELS.reject) return 'reject';\n return 'defer';\n}\n\n/** The command line the click becomes; `undefined` when the human deferred. */\nexport function commandForDecision(proposalId: string, decision: ReviewDecision): string | undefined {\n if (decision === 'defer') return undefined;\n return `/mem decide ${proposalId} ${decision}`;\n}\n\nasync function executeCommandLine(\n deps: ReviewDeps,\n agent: unknown,\n line: string,\n signal: AbortSignal | undefined,\n): Promise<HumanCommandResult> {\n if (deps.commands !== undefined && typeof deps.commands.execute === 'function') {\n const execution = await deps.commands.execute(agent, line, [], signal ?? new AbortController().signal);\n if (execution !== undefined) {\n const kind = execution.result.kind === 'success' ? 'success' : 'error';\n return { ok: kind === 'success', text: execution.result.text ?? '' };\n }\n }\n return runHumanCommand({ store: deps.store, config: deps.config, home: deps.home }, line);\n}\n\n/** Show one card, then run the corresponding `/mem` command on the human's click. */\nexport async function reviewProposal(\n deps: ReviewDeps,\n proposal: Proposal,\n exec: ReviewExecLike | undefined,\n): Promise<ReviewOutcome> {\n if (deps.userQuestions === undefined) {\n return { decision: 'defer', message: '\u5F53\u524D\u73AF\u5883\u6CA1\u6709\u4EA4\u4E92\u754C\u9762\uFF0C\u63D0\u6848\u4FDD\u7559\u5F85\u51B3\u5B9A' };\n }\n if (exec?.agent === undefined) {\n return { decision: 'defer', message: '\u9700\u8981\u6D3B\u52A8\u4F1A\u8BDD\u624D\u80FD\u5F39\u51FA\u5BA1\u6279\u5361\u7247\uFF0C\u63D0\u6848\u4FDD\u7559\u5F85\u51B3\u5B9A' };\n }\n const question = buildReviewQuestion(proposal);\n const answer = await deps.userQuestions.ask({\n questions: [question],\n agent: exec.agent,\n ...(exec.signal === undefined ? {} : { signal: exec.signal }),\n ...(exec.callId === undefined ? {} : { wait: { callId: exec.callId } }),\n });\n const decision = decisionFromAnswer(answer);\n const line = commandForDecision(proposal.id, decision);\n if (line === undefined) {\n return { decision, message: '\u5DF2\u6682\u7F13\uFF0C\u63D0\u6848\u7EE7\u7EED\u5F85\u5BA1' };\n }\n const result = await executeCommandLine(deps, exec.agent, line, exec.signal);\n return { decision, command: line, result, message: result.text };\n}\n", "import {\n loadProfile,\n ProfileError,\n queryProfile,\n saveProfile,\n findProfileEntry,\n validateProfileEntries,\n PROFILE_MAX_CHARS,\n} from '../../core/src/index.ts';\nimport type { MemoryStore } from '../../core/src/store/store.ts';\nimport type { UserQuestionsLike } from './review.ts';\n\n/**\n * `user_profile` tool (architecture v2, P1). The agent may read USER.md freely;\n * a write requires (1) a read earlier in the same session and (2) a human\n * confirmation card. The file stays human-editable; SOUL/RULES stay sealed.\n */\n\nexport const USER_PROFILE_TOOL = 'user_profile';\n\nexport const PROFILE_LABELS = { confirm: '\u786E\u8BA4', cancel: '\u53D6\u6D88' } as const;\n\nexport interface ProfileToolDeps {\n readonly home: string;\n readonly store: Pick<MemoryStore, 'appendAudit'>;\n readonly resolveQuestions: () => UserQuestionsLike | undefined;\n /** Assistant write mode from `personalization.mode`. */\n readonly mode: 'confirm' | 'direct' | 'readonly';\n /** Sessions that already read USER.md; writes require an entry here. */\n readonly readSessions: Set<string>;\n}\n\nexport interface ProfileToolInput {\n readonly op: 'read' | 'add' | 'replace' | 'remove';\n readonly query?: string;\n readonly content?: string;\n readonly old_text?: string;\n}\n\ninterface ExecLike {\n readonly agent?: { readonly session?: { readonly id?: string }; followup?: unknown };\n readonly signal?: AbortSignal;\n readonly callId?: string;\n}\n\nexport interface RegisteredProfileTool {\n readonly name: string;\n readonly description: string;\n readonly parameters: unknown;\n readonly output: unknown;\n execute(args: unknown, exec?: unknown): Promise<unknown>;\n}\n\nfunction fail(message: string): never {\n throw new Error(message);\n}\n\nfunction sessionOf(exec: unknown): string {\n const execLike = exec as ExecLike | undefined;\n return execLike?.agent?.session?.id ?? 'unknown-session';\n}\n\nfunction buildQuestion(action: string, current: readonly string[], proposed: readonly string[], content: string) {\n const lines = [\n `**\u52A8\u4F5C**\uFF1A${action}`,\n '',\n '**\u5F53\u524D USER.md**\uFF1A',\n current.length === 0 ? '\uFF08\u7A7A\uFF09' : current.map((entry, index) => `${index + 1}. ${entry}`).join('\\n'),\n '',\n '**\u4FEE\u6539\u540E**\uFF1A',\n proposed.map((entry, index) => `${index + 1}. ${entry}`).join('\\n'),\n '',\n `\uFF08\u5355\u6587\u4EF6\u4E0A\u9650 ${PROFILE_MAX_CHARS} \u5B57\uFF1B\u786E\u8BA4\u540E\u5199\u5165 USER.md\uFF09`,\n ];\n return {\n id: 'user_profile',\n header: '\u7528\u6237\u504F\u597D\u66F4\u65B0',\n question: '\u662F\u5426\u628A\u8FD9\u6761\u4FEE\u6539\u5199\u5165 USER.md\uFF1F',\n detail: lines.join('\\n'),\n options: [\n { label: '\u786E\u8BA4', description: '\u5199\u5165 USER.md\uFF0C\u7ACB\u5373\u751F\u6548\uFF08\u4E0B\u4E00\u8F6E\u6CE8\u5165\u53EF\u89C1\uFF09' },\n { label: '\u53D6\u6D88', description: '\u4E0D\u4FEE\u6539\u6587\u4EF6' },\n ],\n actions: content,\n };\n}\n\nexport function profileParameters(): unknown {\n return {\n type: 'object',\n properties: {\n op: { type: 'string', enum: ['read', 'add', 'replace', 'remove'] },\n query: { type: 'string', description: 'read: literal keyword; omit to list every entry' },\n content: { type: 'string', description: 'add/replace: one complete entry' },\n old_text: { type: 'string', description: 'replace/remove: complete old entry or a unique literal substring' },\n },\n required: ['op'],\n additionalProperties: false,\n };\n}\n\nexport async function executeUserProfile(\n deps: ProfileToolDeps,\n args: unknown,\n exec: unknown,\n): Promise<unknown> {\n const input = args as ProfileToolInput;\n const session = sessionOf(exec);\n const snapshot = loadProfile(deps.home);\n\n if (input.op === 'read') {\n const entries = input.query === undefined || input.query.trim() === ''\n ? [...snapshot.entries]\n : queryProfile(snapshot.entries, input.query);\n deps.readSessions.add(session);\n return { entries, total: snapshot.entries.length, chars: snapshot.chars, limit: PROFILE_MAX_CHARS };\n }\n\n if (!deps.readSessions.has(session)) {\n fail('\u5148\u8BFB\u53D6 USER.md\uFF08user_profile op=read\uFF09\uFF0C\u518D\u4FEE\u6539');\n }\n if (deps.mode === 'readonly') {\n fail('\u5F53\u524D\u4E3A readonly \u6A21\u5F0F\uFF1A\u53EA\u80FD\u8BFB\u53D6\u504F\u597D\uFF0C\u4E0D\u80FD\u4FEE\u6539');\n }\n\n let proposed: string[];\n let action: string;\n let content = '';\n if (input.op === 'add') {\n if (typeof input.content !== 'string' || input.content.trim() === '') fail('add \u9700\u8981 content\uFF08\u5B8C\u6574\u6761\u76EE\uFF09');\n content = input.content.trim();\n proposed = [...snapshot.entries, content];\n action = '\u65B0\u589E\u4E00\u6761\u504F\u597D';\n } else {\n if (typeof input.old_text !== 'string' || input.old_text.trim() === '') fail(`${input.op} \u9700\u8981 old_text`);\n const index = findProfileEntry(snapshot.entries, input.old_text);\n if (input.op === 'remove') {\n proposed = snapshot.entries.filter((_, position) => position !== index);\n action = '\u5220\u9664\u4E00\u6761\u504F\u597D';\n } else {\n if (typeof input.content !== 'string' || input.content.trim() === '') fail('replace \u9700\u8981 content\uFF08\u5B8C\u6574\u65B0\u6761\u76EE\uFF09');\n content = input.content.trim();\n proposed = snapshot.entries.map((entry, position) => (position === index ? content : entry));\n action = '\u66FF\u6362\u4E00\u6761\u504F\u597D';\n }\n }\n const problems = validateProfileEntries(proposed);\n if (problems.length > 0) fail(problems.join('; '));\n\n if (deps.mode === 'confirm') {\n const questions = deps.resolveQuestions();\n if (questions === undefined) fail('\u5F53\u524D\u73AF\u5883\u6CA1\u6709\u4EA4\u4E92\u754C\u9762\uFF0C\u65E0\u6CD5\u786E\u8BA4 USER.md \u4FEE\u6539');\n if (session === 'unknown-session') fail('\u9700\u8981\u6D3B\u52A8\u4F1A\u8BDD\u624D\u80FD\u786E\u8BA4 USER.md \u4FEE\u6539');\n const question = buildQuestion(action, snapshot.entries, proposed, content);\n const answer = await questions.ask({\n questions: [question],\n agent: (exec as ExecLike | undefined)?.agent,\n ...(((exec as ExecLike | undefined)?.signal === undefined)\n ? {}\n : { signal: (exec as ExecLike).signal }),\n ...(((exec as ExecLike | undefined)?.callId === undefined)\n ? {}\n : { wait: { callId: (exec as ExecLike).callId } }),\n });\n const chosen = answer.answers[0]?.selected[0] ?? answer.answers[0]?.custom?.trim() ?? '';\n if (chosen !== PROFILE_LABELS.confirm) {\n return { ok: false, cancelled: true, entries: snapshot.entries };\n }\n }\n\n const saved = saveProfile(deps.home, proposed);\n deps.store.appendAudit({ event: 'user-profile', action: input.op, entries: saved.entries.length, chars: saved.chars });\n return { ok: true, action: input.op, entries: saved.entries, chars: saved.chars };\n}\n\n/** Register `user_profile` on the host tool registry (top-level agents only). */\nexport function registerUserProfileTool(\n ctx: { readonly tools: { register(definition: unknown): unknown } },\n deps: ProfileToolDeps,\n): void {\n ctx.tools.register({\n name: USER_PROFILE_TOOL,\n description: 'Agent Memory\uFF1A\u8BFB\u53D6\u6216\u4FEE\u6539 USER.md \u504F\u597D\u6761\u76EE\uFF08\u4FEE\u6539\u9700\u4EBA\u786E\u8BA4\uFF09',\n parameters: profileParameters(),\n output: {\n schema: { type: 'object' },\n render: (_args: unknown, value: unknown) => [\n { type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) },\n ],\n },\n execute: async (args: unknown, exec?: unknown) => executeUserProfile(deps, args, exec),\n });\n}\n\nexport { ProfileError };\n", "/**\n * Session-history tools (architecture v2, P2). These are thin, read-only\n * wrappers over the host's native `sessionQuery` service (SQLite FTS5 index\n * included), so the model can search prior conversations without a second\n * index of our own.\n */\n\nexport const SESSION_TOOL_NAMES = [\n 'session_search',\n 'session_event_search',\n 'session_event_read',\n 'session_event_trace',\n 'session_trace',\n] as const;\nexport type SessionToolName = (typeof SESSION_TOOL_NAMES)[number];\n\nexport interface SessionQueryLike {\n searchSessions?(request: { query: string; limit?: number }): Promise<{ items: readonly unknown[] }>;\n searchEvents?(request: { sessionId: string; query: string; limit?: number }): Promise<{ items: readonly unknown[] }>;\n readEvent?(request: {\n sessionId: string;\n seq: number;\n before?: number;\n after?: number;\n }): Promise<Record<string, unknown>>;\n traceEvent?(request: { sessionId: string; seq: number }): Promise<Record<string, unknown>>;\n traceSession?(sessionId: string): Promise<Record<string, unknown>>;\n}\n\nexport interface SessionToolDeps {\n readonly resolveQuery: () => SessionQueryLike | undefined;\n readonly sessionId: string;\n}\n\ninterface ExecLike {\n readonly agent?: { readonly session?: { readonly id?: string } };\n}\n\nconst SNIPPET_MAX = 500;\nconst TEXT_MAX = 4000;\n\nfunction clip(text: string, max: number): string {\n const points = [...text];\n return points.length <= max ? text : `${points.slice(0, max).join('')}\u2026`;\n}\n\nfunction textOf(data: unknown): string {\n if (typeof data !== 'object' || data === null) return '';\n const record = data as { content?: unknown; text?: unknown; message?: unknown };\n if (typeof record.content === 'string') return record.content;\n if (Array.isArray(record.content)) {\n return record.content\n .map((block) =>\n typeof block === 'object' && block !== null && typeof (block as { text?: unknown }).text === 'string'\n ? (block as { text: string }).text\n : '',\n )\n .filter((text) => text !== '')\n .join('\\n');\n }\n if (typeof record.text === 'string') return record.text;\n if (typeof record.message === 'object' && record.message !== null) return textOf(record.message);\n return '';\n}\n\nfunction sessionIdOf(deps: SessionToolDeps, exec: unknown): string {\n const execLike = exec as ExecLike | undefined;\n return execLike?.agent?.session?.id ?? deps.sessionId;\n}\n\nfunction serviceOrFail(deps: SessionToolDeps): SessionQueryLike {\n const query = deps.resolveQuery();\n if (query === undefined) {\n throw new Error('host session query service is unavailable in this composition');\n }\n return query;\n}\n\nfunction limitOf(value: unknown, fallback = 5): number {\n return typeof value === 'number' && Number.isInteger(value) && value >= 1 ? Math.min(value, 10) : fallback;\n}\n\nfunction integerOf(value: unknown, name: string): number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new Error(`${name} must be a non-negative integer`);\n }\n return value;\n}\n\nfunction summarizeEvent(item: unknown): Record<string, unknown> {\n const record = (item ?? {}) as Record<string, unknown>;\n const sessionId = (record.sessionId ?? record.session_id ?? '') as string;\n return {\n session_id: sessionId,\n seq: record.seq,\n type: record.type,\n snippet: typeof record.snippet === 'string' ? clip(record.snippet, SNIPPET_MAX) : undefined,\n };\n}\n\nexport interface RegisteredSessionTool {\n readonly name: SessionToolName;\n readonly description: string;\n readonly parameters: unknown;\n readonly output: unknown;\n execute(args: unknown, exec?: unknown): Promise<unknown>;\n}\n\nfunction definition(\n name: SessionToolName,\n description: string,\n properties: Record<string, unknown>,\n required: string[],\n handler: (args: Record<string, unknown>, exec?: unknown) => Promise<unknown>,\n): RegisteredSessionTool {\n return {\n name,\n description,\n parameters: { type: 'object', properties, required, additionalProperties: false },\n output: {\n schema: { type: 'object' },\n render: (_args: unknown, value: unknown) => [\n { type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) },\n ],\n },\n execute: async (args: unknown, exec?: unknown) => {\n if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new Error('arguments must be an object');\n const record = args as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!(key in properties)) throw new Error(`unknown field: ${key}`);\n }\n for (const key of required) {\n if (!(key in record)) throw new Error(`missing field: ${key}`);\n }\n return handler(record, exec);\n },\n };\n}\n\nexport function sessionToolDefinitions(deps: SessionToolDeps): RegisteredSessionTool[] {\n return [\n definition(\n 'session_search',\n 'Agent Memory\uFF1A\u8DE8\u4F1A\u8BDD\u5168\u6587\u68C0\u7D22\uFF0C\u6BCF\u4E2A\u4F1A\u8BDD\u8FD4\u56DE\u6700\u5339\u914D\u7684\u4E00\u6761',\n {\n query: { type: 'string', minLength: 1 },\n limit: { type: 'integer', minimum: 1, maximum: 10 },\n },\n ['query'],\n async (args) => {\n const query = serviceOrFail(deps);\n const page = await query.searchSessions?.({\n query: String(args.query),\n limit: limitOf(args.limit),\n });\n return {\n results: (page?.items ?? []).map((item) => {\n const hit = item as { bestMatch?: unknown; header?: { id?: string; title?: string } };\n const best = summarizeEvent(hit.bestMatch);\n return {\n session_id: hit.header?.id ?? best.session_id,\n title: hit.header?.title,\n seq: best.seq,\n snippet: best.snippet,\n };\n }),\n };\n },\n ),\n definition(\n 'session_event_search',\n 'Agent Memory\uFF1A\u5728\u5355\u4E2A\u4F1A\u8BDD\u5185\u5168\u6587\u68C0\u7D22\u4E8B\u4EF6\uFF08\u9ED8\u8BA4\u5F53\u524D\u4F1A\u8BDD\uFF09',\n {\n query: { type: 'string', minLength: 1 },\n session_id: { type: 'string' },\n limit: { type: 'integer', minimum: 1, maximum: 10 },\n },\n ['query'],\n async (args, exec) => {\n const query = serviceOrFail(deps);\n const page = await query.searchEvents?.({\n sessionId: typeof args.session_id === 'string' ? args.session_id : sessionIdOf(deps, exec),\n query: String(args.query),\n limit: limitOf(args.limit),\n });\n return { results: (page?.items ?? []).map(summarizeEvent) };\n },\n ),\n definition(\n 'session_event_read',\n 'Agent Memory\uFF1A\u8BFB\u53D6\u4E00\u6761\u4E8B\u4EF6\u7684\u5B8C\u6574\u539F\u6587\u4E0E\u524D\u540E\u82E5\u5E72\u6761\u7A97\u53E3',\n {\n seq: { type: 'integer', minimum: 0 },\n session_id: { type: 'string' },\n before: { type: 'integer', minimum: 0, maximum: 5 },\n after: { type: 'integer', minimum: 0, maximum: 5 },\n },\n ['seq'],\n async (args, exec) => {\n const query = serviceOrFail(deps);\n const seq = integerOf(args.seq, 'seq');\n const window = await query.readEvent?.({\n sessionId: typeof args.session_id === 'string' ? args.session_id : sessionIdOf(deps, exec),\n seq,\n before: typeof args.before === 'number' ? args.before : 1,\n after: typeof args.after === 'number' ? args.after : 1,\n });\n const target = (window?.target ?? {}) as Record<string, unknown>;\n return {\n session_id: typeof args.session_id === 'string' ? args.session_id : sessionIdOf(deps, exec),\n seq: target.seq,\n type: target.type,\n text: clip(textOf(target.data), TEXT_MAX),\n start_seq: window?.startSeq,\n end_seq: window?.endSeq,\n };\n },\n ),\n definition(\n 'session_event_trace',\n 'Agent Memory\uFF1A\u67E5\u770B\u4E00\u6761\u4E8B\u4EF6\u7684\u66FF\u6362\u94FE\u4E0E\u5F15\u7528\u6765\u6E90',\n {\n seq: { type: 'integer', minimum: 0 },\n session_id: { type: 'string' },\n },\n ['seq'],\n async (args, exec) => {\n const query = serviceOrFail(deps);\n const seq = integerOf(args.seq, 'seq');\n const trace = await query.traceEvent?.({\n sessionId: typeof args.session_id === 'string' ? args.session_id : sessionIdOf(deps, exec),\n seq,\n });\n return {\n target: trace?.target,\n replaced_by: trace?.replacedBy,\n replacement_chain: trace?.replacementChain,\n replaced_event_seqs: trace?.replacedEventSeqs,\n cited_source_seqs: trace?.citedSourceSeqs,\n };\n },\n ),\n definition(\n 'session_trace',\n 'Agent Memory\uFF1A\u67E5\u770B\u4F1A\u8BDD\u8C31\u7CFB\uFF08\u7956\u5148\u4E0E\u540E\u4EE3\uFF0C\u9ED8\u8BA4\u5F53\u524D\u4F1A\u8BDD\uFF09',\n { session_id: { type: 'string' } },\n [],\n async (args, exec) => {\n const query = serviceOrFail(deps);\n const target = typeof args.session_id === 'string' ? args.session_id : sessionIdOf(deps, exec);\n const trace = await query.traceSession?.(target);\n return { session_id: target, ...(trace ?? {}) };\n },\n ),\n ];\n}\n\nexport function registerSessionTools(\n ctx: { readonly tools: { register(definition: unknown): unknown } },\n deps: SessionToolDeps,\n): void {\n for (const tool of sessionToolDefinitions(deps)) ctx.tools.register(tool);\n}\n", "import {\n createProposal,\n createProject,\n decideProposal,\n deleteProject,\n importBundle,\n listProjects,\n listProposals,\n loadProfile,\n memoryPaths,\n readRulesFile,\n saveProfile,\n saveRulesFile,\n sealPolicy,\n} from '../../core/src/index.ts';\nimport type { Config } from '../../core/src/config/config.ts';\nimport type { MemoryDoc, MemoryId } from '../../core/src/model/types.ts';\nimport type { MemoryStore } from '../../core/src/store/store.ts';\n\n/**\n * V2 GUI data plane. P1 projections are read-only; P2 adds human write routes\n * that reuse the existing proposal + decision pipeline and journal. No file\n * I/O here beyond the core API.\n */\n\nconst KIND_ORDER = ['fact', 'pitfall', 'exp'] as const;\nconst KIND_LABEL: Record<string, string> = { fact: '\u4E8B\u5B9E', pitfall: '\u5751', exp: '\u7ECF\u9A8C' };\nconst KIND_PREFIX: Record<string, string> = { fact: 'F', pitfall: 'P', exp: 'E' };\n\nfunction byDateDesc(left: MemoryDoc, right: MemoryDoc): number {\n // Sort by the date the UI shows (valid_from), not import/creation time:\n // restored entries keep their original date and must not jump to the top.\n if (left.valid_from !== right.valid_from) return right.valid_from.localeCompare(left.valid_from);\n if (left.created_at !== right.created_at) return right.created_at.localeCompare(left.created_at);\n return right.id.localeCompare(left.id);\n}\n\n/** Stable human-readable serial: F-01, P-02, \u2026 in date-desc order within a kind. */\nexport function serialsFor(docs: readonly MemoryDoc[]): ReadonlyMap<MemoryId, string> {\n const serials = new Map<MemoryId, string>();\n for (const kind of KIND_ORDER) {\n const sorted = docs.filter((doc) => doc.kind === kind).sort(byDateDesc);\n sorted.forEach((doc, index) => {\n serials.set(doc.id, `${KIND_PREFIX[kind]}-${String(index + 1).padStart(2, '0')}`);\n });\n }\n return serials;\n}\n\n/** Human-facing summary: whitespace collapsed, hard cap of 12 characters. */\nexport function summarize(text: string, limit = 12): string {\n const clean = text.replace(/\\s+/g, ' ').trim();\n const points = [...clean];\n return points.length <= limit ? clean : points.slice(0, limit).join('');\n}\n\n/** Existing memory: `F-01 \u4E2D\u6587\u4F18\u5148\u504F\u597D`; new content: just the summary. */\nexport function displayName(serial: string, abstract: string): string {\n const text = summarize(abstract);\n return serial === '' ? text : `${serial} ${text}`;\n}\n\n/** Human GUI \"new memory\": content-only dedupe applies, audit marks the GUI. */\nexport function createGui(\n store: MemoryStore,\n input: {\n kind: string;\n abstract: string;\n body?: string;\n valid_from?: string;\n error_signatures?: readonly string[];\n },\n) {\n if (!KIND_ORDER.includes(input.kind as (typeof KIND_ORDER)[number])) {\n throw new Error(`kind must be one of ${KIND_ORDER.join(', ')}`);\n }\n const abstract = typeof input.abstract === 'string' ? input.abstract.trim() : '';\n if (abstract === '') throw new Error('abstract is required');\n const result = store.add(\n {\n kind: input.kind as (typeof KIND_ORDER)[number],\n abstract,\n body: typeof input.body === 'string' ? input.body : '',\n evidence_level: 'user_explicit',\n ...(typeof input.valid_from === 'string' && input.valid_from !== ''\n ? { valid_from: input.valid_from }\n : {}),\n ...(Array.isArray(input.error_signatures)\n ? { error_signatures: input.error_signatures.filter((entry): entry is string => typeof entry === 'string') }\n : {}),\n },\n { author: 'human' },\n );\n store.appendJournal('audit', {\n event: 'gui-create',\n id: result.id,\n deduplicated: result.deduplicated,\n });\n const serial = serialsFor(store.active()).get(result.id) ?? '';\n return {\n id: result.id,\n deduplicated: result.deduplicated,\n display: displayName(serial, abstract),\n };\n}\n\nexport interface SummarySuggestion {\n readonly id: string;\n readonly text: string;\n readonly category: string;\n readonly basis: readonly string[];\n readonly confidence: '\u9AD8' | '\u4E2D' | '\u4F4E';\n}\n\n/**\n * Deterministic \"\u6574\u7406\u8BB0\u5FC6\" projection. Read-only: it never writes RULES.\n * Suggestions are candidate model-guide lines; a human must select them and\n * still press save in the RULES editor.\n */\nexport function summarizeGui(store: MemoryStore) {\n const docs = store.active();\n const serials = serialsFor(docs);\n const byKind = { fact: 0, pitfall: 0, exp: 0 };\n for (const doc of docs) byKind[doc.kind] += 1;\n\n const sorted = [...docs].sort(byDateDesc);\n const recent = sorted.slice(0, 5).map((doc) => ({\n serial: serials.get(doc.id) ?? '',\n kind: doc.kind,\n abstract: doc.abstract,\n }));\n\n const signatures = new Map<string, { count: number; ids: string[] }>();\n for (const doc of docs) {\n if (doc.kind !== 'pitfall') continue;\n for (const signature of doc.error_signatures) {\n const entry = signatures.get(signature) ?? { count: 0, ids: [] };\n entry.count += 1;\n entry.ids.push(doc.id);\n signatures.set(signature, entry);\n }\n }\n const topSignatures = [...signatures.entries()]\n .map(([signature, entry]) => ({\n signature,\n count: entry.count,\n basis: entry.ids.map((id) => serials.get(id) ?? ''),\n }))\n .sort((left, right) => right.count - left.count || left.signature.localeCompare(right.signature))\n .slice(0, 5);\n\n const suggestions: SummarySuggestion[] = [];\n for (const item of topSignatures) {\n if (item.count < 2) continue;\n suggestions.push({\n id: `sig-${suggestions.length + 1}`,\n text: `\u9047\u5230\u300C${item.signature}\u300D\u65F6\uFF0C\u5148\u6309\u5DF2\u6709\u7ECF\u9A8C\u6392\u67E5\uFF0C\u907F\u514D\u91CD\u590D\u8E29\u5751\u3002`,\n category: '\u6A21\u578B\u6307\u5F15',\n basis: item.basis,\n confidence: '\u9AD8',\n });\n }\n if (suggestions.length === 0) {\n suggestions.push({\n id: 'generic-1',\n text: '\u65B0\u589E\u8BB0\u5FC6\u524D\u5148\u68C0\u7D22\u662F\u5426\u5DF2\u6709\u540C\u7C7B\u7ED3\u8BBA\uFF0C\u907F\u514D\u91CD\u590D\u8BB0\u5F55\u3002',\n category: '\u6A21\u578B\u6307\u5F15',\n basis: recent.slice(0, 3).map((entry) => entry.serial).filter((serial) => serial !== ''),\n confidence: '\u4E2D',\n });\n }\n\n return {\n total: docs.length,\n by_kind: byKind,\n recent,\n top_signatures: topSignatures,\n suggestions: suggestions.slice(0, 8),\n };\n}\n\n/** Path only: the GUI never reads or writes SOUL.md. */\nexport function soulPathGui(home: string): { path: string; hint: string } {\n return {\n path: memoryPaths(home).soulFile,\n hint: '\u6B64\u6587\u4EF6\u53EA\u7531\u4F60\u7F16\u8F91\uFF1B\u672C\u63D2\u4EF6\u4E0D\u8BFB\u53D6\u3001\u4E0D\u4FEE\u6539\u5B83\u7684\u5185\u5BB9\u3002\u4FEE\u6539\u540E\u70B9\u4E0B\u65B9\u300C\u4E00\u952E\u5C01\u5B58\u300D\u3002',\n };\n}\n\n/**\n * Human GUI seal: the click is the explicit acceptance. Sealing hashes the\n * sealed files but never returns or edits their contents.\n */\nexport function sealGui(home: string, store: MemoryStore) {\n const result = sealPolicy({ home, accept: true });\n store.appendJournal('audit', { event: 'gui-seal', sha256: result.sha256 });\n return { sealed: true, sha256: result.sha256 };\n}\n\nfunction summary(doc: MemoryDoc, serial: string) {\n return {\n serial,\n display: displayName(serial, doc.abstract),\n id: doc.id,\n kind: doc.kind,\n abstract: doc.abstract,\n project: doc.project ?? null,\n tags: doc.tags ?? [],\n relations: doc.relations ?? [],\n source: doc.source ?? null,\n author: doc.author,\n valid_from: doc.valid_from,\n valid_until: doc.valid_until,\n evidence_level: doc.evidence_level,\n created_at: doc.created_at,\n supersedes: doc.supersedes,\n };\n}\n\nexport function buildList(store: MemoryStore) {\n const active = store.active();\n const serials = serialsFor(active);\n const groups = KIND_ORDER.map((kind) => ({\n kind,\n label: KIND_LABEL[kind] ?? kind,\n items: active\n .filter((doc) => doc.kind === kind)\n .sort(byDateDesc)\n .map((doc) => summary(doc, serials.get(doc.id) ?? '')),\n }));\n return {\n total: active.length,\n pending: store.stats().pending_proposals,\n groups,\n };\n}\n\nexport function buildItem(store: MemoryStore, id: string) {\n const doc = store.read(id as MemoryId);\n const serial = serialsFor(store.active()).get(doc.id) ?? '';\n return {\n ...summary(doc, serial),\n body: doc.body,\n error_signatures: doc.error_signatures,\n provenance: doc.provenance,\n content_hash: doc.content_hash,\n };\n}\n\nexport async function buildSearch(store: MemoryStore, query: string, limit = 20) {\n const result = await store.recallAsync(query, { limit });\n const serials = serialsFor(store.active());\n return {\n query,\n hits: result.hits.map((hit) => ({\n serial: serials.get(hit.id) ?? '',\n id: hit.id,\n kind: hit.kind,\n abstract: hit.abstract,\n score: hit.score,\n provenance_verifiable: hit.provenance_verifiable,\n })),\n warnings: result.warnings,\n };\n}\n\nexport interface GraphNode {\n readonly id: string;\n readonly serial: string;\n readonly display: string;\n readonly kind: string;\n readonly project: string;\n readonly tags: readonly string[];\n readonly relations: readonly { type: string; target: string }[];\n readonly supersedes: readonly string[];\n readonly valid_from: string;\n}\n\nexport interface GraphProject {\n readonly name: string;\n readonly count: number;\n readonly last_updated: string | null;\n}\n\n/** Read-only worktree projection (S4): projects, memory nodes and three edge types. */\nexport function buildGraph(store: MemoryStore, home: string) {\n const active = store.active();\n const serials = serialsFor(active);\n const registered = listProjects(home).map((project) => project.name);\n const registeredSet = new Set(registered);\n const effectiveProject = (doc: MemoryDoc): string =>\n doc.project !== null && doc.project !== undefined && registeredSet.has(doc.project) ? doc.project : '\u672A\u5F52\u7C7B';\n const names = new Set(registered);\n for (const doc of active) names.add(effectiveProject(doc));\n const projects: GraphProject[] = [...names].map((name) => {\n const docs = active.filter((doc) => effectiveProject(doc) === name);\n const last = docs.map((doc) => doc.valid_from).sort().at(-1) ?? null;\n return { name, count: docs.length, last_updated: last };\n });\n projects.sort((left, right) => right.count - left.count || left.name.localeCompare(right.name));\n\n const limited = active\n .slice()\n .sort((left, right) => right.valid_from.localeCompare(left.valid_from) || right.created_at.localeCompare(left.created_at))\n .slice(0, 200);\n const ids = new Set(limited.map((doc) => doc.id));\n const nodes: GraphNode[] = limited.map((doc) => {\n const serial = serials.get(doc.id) ?? '';\n return {\n id: doc.id,\n serial,\n display: displayName(serial, doc.abstract),\n kind: doc.kind,\n project: effectiveProject(doc),\n tags: doc.tags ?? [],\n relations: (doc.relations ?? []).map((relation) => ({ type: relation.type, target: relation.target })),\n supersedes: doc.supersedes,\n valid_from: doc.valid_from,\n };\n });\n const edges: { from: string; to: string; type: string }[] = [];\n for (const doc of limited) {\n for (const target of doc.supersedes) {\n if (ids.has(target)) edges.push({ from: doc.id, to: target, type: 'supersedes' });\n }\n for (const relation of doc.relations ?? []) {\n if (ids.has(relation.target)) edges.push({ from: doc.id, to: relation.target, type: relation.type });\n }\n }\n const conflicts: { a: string; b: string; project: string; reason: string }[] = [];\n for (let left = 0; left < limited.length; left += 1) {\n for (let right = left + 1; right < limited.length; right += 1) {\n const a = limited[left] as MemoryDoc;\n const b = limited[right] as MemoryDoc;\n if (effectiveProject(a) !== effectiveProject(b)) continue;\n const shared = (a.tags ?? []).some((tag) => (b.tags ?? []).includes(tag));\n if (!shared) continue;\n const charsA = new Set([...a.abstract.replace(/\\s+/g, '')]);\n const charsB = new Set([...b.abstract.replace(/\\s+/g, '')]);\n let overlap = 0;\n for (const char of charsA) if (charsB.has(char)) overlap += 1;\n const similarity = overlap / Math.max(1, new Set([...charsA, ...charsB]).size);\n if (similarity >= 0.8) {\n conflicts.push({ a: a.id, b: b.id, project: effectiveProject(a), reason: '\u540C\u9879\u76EE\u540C\u6807\u7B7E\u4E14\u6458\u8981\u9AD8\u5EA6\u91CD\u53E0' });\n }\n }\n }\n return {\n schema: 1,\n generated_at: new Date().toISOString(),\n truncated: active.length > limited.length,\n projects,\n nodes,\n edges,\n conflicts,\n };\n}\n\nexport function exportBundle(store: MemoryStore) { const active = store.active();\n const serials = serialsFor(active);\n const memories = active\n .slice()\n .sort(byDateDesc)\n .map((doc) => ({\n ...summary(doc, serials.get(doc.id) ?? ''),\n body: doc.body,\n error_signatures: doc.error_signatures,\n provenance: doc.provenance,\n content_hash: doc.content_hash,\n }));\n return {\n format: 'agent-memory-export-v2',\n exported_at: new Date().toISOString(),\n memories,\n proposals: listProposals(store).map((proposal) => ({\n id: proposal.id,\n op: proposal.op,\n targets: proposal.targets,\n reason: proposal.reason,\n created_at: proposal.created_at,\n })),\n };\n}\n\nexport interface GuiRouteDeps {\n readonly store: MemoryStore;\n readonly home: string;\n readonly mode: string;\n readonly modules: readonly { name: string; ok: boolean; error?: string }[];\n readonly config: Config;\n}\n\n/** Pending proposals with display serials and target abstracts. */\nexport function buildProposals(store: MemoryStore) {\n const serials = serialsFor(store.active());\n const abstractOf = (id: string): string => {\n try {\n return store.read(id as MemoryId).abstract;\n } catch {\n return '\uFF08\u5DF2\u4E0D\u5B58\u5728\uFF09';\n }\n };\n return listProposals(store).map((proposal) => ({\n id: proposal.id,\n op: proposal.op,\n reason: proposal.reason,\n created_at: proposal.created_at,\n targets: proposal.targets.map((id) => {\n const serial = serials.get(id) ?? '';\n const abstract = abstractOf(id);\n return { id, serial, abstract, display: displayName(serial, abstract) };\n }),\n replacements: proposal.replacements.map((replacement) => ({\n kind: replacement.kind,\n abstract: replacement.abstract,\n display: summarize(replacement.abstract),\n body: replacement.body,\n })),\n }));\n}\n\n/** Human GUI decision: same proposal pipeline as `/mem decide`, audited as GUI. */\nexport function decideGui(\n store: MemoryStore,\n config: Config,\n id: string,\n decision: 'accept' | 'reject',\n note?: string,\n): void {\n decideProposal({ store, config }, { id, decision, ...(note === undefined ? {} : { reason: note }) });\n store.appendJournal('audit', { event: 'gui-decide', proposal: id, decision });\n}\n\n/**\n * Human GUI revise: create the supersede proposal, then accept it in the same\n * human action. Provenance survives from the old record; the decision line is\n * the GUI confirmation.\n */\nexport function reviseGui(\n store: MemoryStore,\n config: Config,\n id: string,\n input: { abstract: string; body: string },\n): void {\n const target = store.read(id as MemoryId);\n const proposal = createProposal(\n { store, config },\n {\n op: 'supersede',\n targets: [id],\n base_hashes: [target.content_hash],\n reason: '\u56FE\u5F62\u754C\u9762\u4FEE\u8BA2',\n replacements: [\n {\n kind: target.kind,\n abstract: input.abstract,\n body: input.body,\n evidence_level: 'user_confirmed',\n error_signatures: target.error_signatures,\n provenance: target.provenance,\n },\n ],\n },\n );\n decideProposal({ store, config }, { id: proposal.id, decision: 'accept' });\n store.appendJournal('audit', { event: 'gui-revise', target: id, proposal: proposal.id });\n}\n\n/** Human GUI delete: delete proposal + immediate acceptance. */\n/**\n * Human GUI delete is a hard delete: the memory file is removed and pending\n * proposals targeting it are invalidated. Superseded ancestors are removed in\n * the same action, otherwise purging the revision would revive the old version.\n * The journal keeps a delete line with the reason and content hash only \u2014 no\n * body, no recoverable copy.\n */\nexport function deleteGui(store: MemoryStore, config: Config, id: string, reason = '\u56FE\u5F62\u754C\u9762\u5220\u9664'): void {\n void config;\n const target = store.read(id as MemoryId);\n const ids: string[] = [id];\n const collect = (docId: string): void => {\n if (ids.includes(docId)) return;\n ids.push(docId);\n try {\n for (const parent of store.read(docId as MemoryId).supersedes) collect(parent);\n } catch {\n // An already-purged ancestor is skipped; the visible one is still removed.\n }\n };\n for (const parent of target.supersedes) collect(parent);\n\n let proposals = 0;\n for (const each of ids) {\n try {\n proposals += store.purge(each as MemoryId, { reason }).proposals;\n } catch {\n // Missing files are fine; the goal is that none of these ids stay active.\n }\n }\n store.appendJournal('audit', { event: 'gui-purge', target: id, removed: ids.length, proposals });\n}\n\nexport function readProfileGui(home: string) {\n const profile = loadProfile(home);\n return { entries: [...profile.entries], chars: profile.chars };\n}\n\nexport function saveProfileGui(home: string, store: MemoryStore, entries: readonly string[]) {\n const profile = saveProfile(home, entries);\n store.appendJournal('audit', { event: 'gui-profile', entries: profile.entries.length });\n return profile;\n}\n\nexport function readRulesGui(home: string) {\n return { text: readRulesFile(home) };\n}\n\n/**\n * Human GUI RULES write. Only reachable from the GUI route (no model tool and\n * no CLI command), validates first, then seals policy with the human click as\n * the explicit acceptance.\n */\nexport function saveRulesGui(home: string, store: MemoryStore, text: string) {\n saveRulesFile(home, text);\n const sealed = sealPolicy({ home, accept: true });\n store.appendJournal('audit', { event: 'gui-rules', sha256: sealed.sha256 });\n return { sealed: true };\n}\n\n\nexport interface GuiConnection {\n readonly fetch?: { register(route: unknown): unknown };\n}\n\nfunction json(value: unknown, status = 200): Response {\n return new Response(JSON.stringify(value), {\n status,\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n 'x-agent-memory-api-version': '1',\n },\n });\n}\n\nfunction errorResponse(message: string, status = 400): Response {\n return json({ ok: false, error: message }, status);\n}\n\nasync function readJson(request: Request): Promise<Record<string, unknown>> {\n try {\n const value = (await request.json()) as unknown;\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\n/** Register the P1 read-only routes (paths own their full `/api` prefix). */\nexport function guiRoutes(deps: GuiRouteDeps): unknown[] {\n const status = {\n path: '/api/agent-memory/status',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => {\n const stats = deps.store.stats();\n return json({\n ok: true,\n home: deps.home,\n active: stats.active,\n pending: stats.pending_proposals,\n journal_head: stats.journal_head,\n mode: deps.mode,\n modules: deps.modules,\n });\n },\n };\n\n const list = {\n path: '/api/agent-memory/list',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => json(buildList(deps.store)),\n };\n\n const graph = {\n path: '/api/agent-memory/graph',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => json(buildGraph(deps.store, deps.home)),\n };\n\n const projects = {\n path: '/api/agent-memory/projects',\n methods: ['GET', 'POST', 'DELETE'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n if (request.method === 'GET') return json({ projects: listProjects(deps.home) });\n if (request.method === 'DELETE') {\n const name = new URL(request.url).searchParams.get('name') ?? '';\n if (name === '') return errorResponse('name is required');\n return deleteProject(deps.home, name) ? json({ ok: true }) : errorResponse('project not found', 404);\n }\n const body = await readJson(request);\n if (typeof body.name !== 'string' || body.name.trim() === '') return errorResponse('name is required');\n try {\n const project = createProject({\n home: deps.home,\n name: body.name,\n ...(typeof body.description === 'string' ? { description: body.description } : {}),\n });\n return json({ project });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const moveProject = {\n path: '/api/agent-memory/projects/move',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n if (!Array.isArray(body.ids) || body.ids.some((id) => typeof id !== 'string')) {\n return errorResponse('ids must be a string array');\n }\n if (body.project !== null && typeof body.project !== 'string') {\n return errorResponse('project must be a string or null');\n }\n const target = body.project as string | null;\n if (target !== null && !listProjects(deps.home).some((project) => project.name === target)) {\n return errorResponse(`unknown project: ${target}`, 409);\n }\n try {\n const result = deps.store.moveProjects(body.ids as string[], target);\n return json({ ok: true, ...result });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const meta = {\n path: '/api/agent-memory/meta',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n if (typeof body.id !== 'string' || body.id === '') return errorResponse('id is required');\n if (body.tags !== undefined && (!Array.isArray(body.tags) || body.tags.some((tag) => typeof tag !== 'string'))) {\n return errorResponse('tags must be a string array');\n }\n if (\n body.relations !== undefined &&\n (!Array.isArray(body.relations) ||\n body.relations.some(\n (relation) =>\n typeof relation !== 'object' ||\n relation === null ||\n typeof (relation as { type?: unknown }).type !== 'string' ||\n typeof (relation as { target?: unknown }).target !== 'string',\n ))\n ) {\n return errorResponse('relations must be {type,target} objects');\n }\n try {\n const doc = deps.store.updateMeta(body.id, {\n ...(body.tags === undefined ? {} : { tags: body.tags as string[] }),\n ...(body.relations === undefined\n ? {}\n : { relations: body.relations as { type: 'relates_to' | 'derived_from'; target: string }[] }),\n });\n return json({ ok: true, id: doc.id, project: doc.project ?? null, tags: doc.tags ?? [], relations: doc.relations ?? [] });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const item = {\n path: '/api/agent-memory/item',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const id = new URL(request.url).searchParams.get('id') ?? '';\n if (!/^mem-\\d{8}-[0-9a-f]{8}$/.test(id)) return errorResponse('id must be a memory id');\n try {\n return json(buildItem(deps.store, id));\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 404);\n }\n },\n };\n\n const search = {\n path: '/api/agent-memory/search',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const query = (new URL(request.url).searchParams.get('q') ?? '').trim();\n if (query === '') return errorResponse('q is required');\n return json(await buildSearch(deps.store, query));\n },\n };\n\n const exportRoute = {\n path: '/api/agent-memory/export',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => {\n const body = JSON.stringify(exportBundle(deps.store), null, 2);\n return new Response(body, {\n status: 200,\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'content-disposition': `attachment; filename=\"agent-memory-${new Date().toISOString().slice(0, 10)}.json\"`,\n 'cache-control': 'no-store',\n },\n });\n },\n };\n\n const proposalsRoute = {\n path: '/api/agent-memory/proposals',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => json(buildProposals(deps.store)),\n };\n\n const decideRoute = {\n path: '/api/agent-memory/proposals/decide',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n const id = typeof body.id === 'string' ? body.id : '';\n const decision = body.decision === 'accept' || body.decision === 'reject' ? body.decision : null;\n if (id === '' || decision === null) return errorResponse('id and decision are required');\n try {\n decideGui(deps.store, deps.config, id, decision, typeof body.note === 'string' ? body.note : undefined);\n return json({ ok: true });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const reviseRoute = {\n path: '/api/agent-memory/revise',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n const id = typeof body.id === 'string' ? body.id : '';\n const abstract = typeof body.abstract === 'string' ? body.abstract.trim() : '';\n const text = typeof body.body === 'string' ? body.body : '';\n if (id === '' || abstract === '') return errorResponse('id and abstract are required');\n try {\n reviseGui(deps.store, deps.config, id, { abstract, body: text });\n return json({ ok: true });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const deleteRoute = {\n path: '/api/agent-memory/delete',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n const id = typeof body.id === 'string' ? body.id : '';\n if (id === '') return errorResponse('id is required');\n try {\n deleteGui(deps.store, deps.config, id);\n return json({ ok: true });\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const importRoute = {\n path: '/api/agent-memory/import',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n try {\n const report = importBundle(deps.store, body);\n deps.store.appendJournal('audit', {\n event: 'gui-import',\n imported: report.imported,\n skipped: report.skipped,\n failed: report.failed.length,\n });\n return json(report);\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error));\n }\n },\n };\n\n const createRoute = {\n path: '/api/agent-memory/create',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n const body = await readJson(request);\n try {\n return json(\n createGui(deps.store, {\n kind: typeof body.kind === 'string' ? body.kind : '',\n abstract: typeof body.abstract === 'string' ? body.abstract : '',\n ...(typeof body.body === 'string' ? { body: body.body } : {}),\n ...(typeof body.valid_from === 'string' ? { valid_from: body.valid_from } : {}),\n ...(Array.isArray(body.error_signatures)\n ? { error_signatures: body.error_signatures.filter((entry): entry is string => typeof entry === 'string') }\n : {}),\n }),\n );\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error));\n }\n },\n };\n\n const summarizeRoute = {\n path: '/api/agent-memory/summarize',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => json(summarizeGui(deps.store)),\n };\n\n const soulPathRoute = {\n path: '/api/agent-memory/soul-path',\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => json(soulPathGui(deps.home)),\n };\n\n const sealRoute = {\n path: '/api/agent-memory/policy/seal',\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async () => {\n try {\n return json(sealGui(deps.home, deps.store));\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n const profileRoute = {\n path: '/api/agent-memory/profile',\n methods: ['GET', 'POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n if (request.method === 'GET') return json(readProfileGui(deps.home));\n const body = await readJson(request);\n const entries = Array.isArray(body.entries)\n ? body.entries.filter((entry): entry is string => typeof entry === 'string')\n : null;\n if (entries === null) return errorResponse('entries must be a string array');\n try {\n return json(saveProfileGui(deps.home, deps.store, entries));\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error));\n }\n },\n };\n\n const rulesRoute = {\n path: '/api/agent-memory/rules',\n methods: ['GET', 'POST'],\n requestBody: 'buffered',\n fetch: async (request: Request) => {\n if (request.method === 'GET') return json(readRulesGui(deps.home));\n const body = await readJson(request);\n const text = typeof body.text === 'string' ? body.text : null;\n if (text === null) return errorResponse('text is required');\n try {\n return json(saveRulesGui(deps.home, deps.store, text));\n } catch (error) {\n return errorResponse(error instanceof Error ? error.message : String(error), 409);\n }\n },\n };\n\n return [\n status,\n list,\n graph,\n projects,\n moveProject,\n meta,\n item,\n search,\n exportRoute,\n proposalsRoute,\n decideRoute,\n reviseRoute,\n deleteRoute,\n importRoute,\n createRoute,\n summarizeRoute,\n soulPathRoute,\n sealRoute,\n profileRoute,\n rulesRoute,\n ];\n}\n\nexport function registerGuiRoutes(\n connection: GuiConnection,\n deps: GuiRouteDeps,\n effect: ((install: () => unknown, label?: string) => unknown) | undefined,\n): void {\n if (connection.fetch === undefined) return;\n const install = (): void => {\n for (const route of guiRoutes(deps)) connection.fetch?.register(route);\n };\n if (effect !== undefined) effect(install, 'agent-memory: gui routes');\n else install();\n}\n", "import {\n assemble,\n bindEvidence,\n createProposal,\n loadRules,\n MemoryStore,\n startup,\n type Kind,\n type ProposalInput,\n type ProposalReplacement,\n type Runtime,\n} from '../../core/src/index.ts';\nimport type { EvidenceEvent } from '../../core/src/actor.ts';\nimport type { ToolService } from './tools.ts';\n\n/**\n * Host-side service used by the plugin tools (S4).\n *\n * The adapter may only call core; all file I/O happens inside `MemoryStore`.\n * Evidence binding goes through the host's durable session store\n * (`ctx.sessionPersistence.open(id, 'read').read(seq, 1)`), so the model can\n * only cite events that really exist in the calling session.\n */\n\nexport interface SessionEventLike {\n readonly type: string;\n readonly seq: number;\n readonly data: unknown;\n}\n\nexport interface SessionHandleLike {\n read(offset?: number, length?: number): Promise<{ events: readonly SessionEventLike[] }>;\n close(): Promise<void>;\n}\n\nexport interface SessionPersistenceLike {\n open(id: string, access: 'read'): Promise<SessionHandleLike>;\n}\n\n/** Live session store (`ctx.sessions`), the sanctioned fallback in \u00A75.3. */\nexport interface SessionLike {\n readonly seq?: number;\n eventAt(seq: number): SessionEventLike | undefined;\n}\n\nexport interface SessionStoreLike {\n get(id: string): SessionLike | undefined;\n}\n\nexport interface HostSessionContext {\n readonly sessionId: string;\n readonly persistence?: SessionPersistenceLike;\n readonly sessions?: SessionStoreLike;\n}\n\nexport interface PromptSectionLike {\n readonly name: string;\n readonly order: number;\n readonly text: string;\n readonly interpolate: false;\n}\n\nexport interface HostService extends ToolService {\n readonly store: MemoryStore;\n readonly runtime: Runtime;\n readonly home: string;\n readonly mode: 'confirm' | 'direct' | 'readonly';\n readonly session: HostSessionContext;\n assembleSection(sessionId?: string): PromptSectionLike;\n /** One prompt section per human/maintained source, in injection order. */\n assembleSections(sessionId?: string): PromptSectionLike[];\n}\n\ninterface ToolExecLike {\n readonly agent?: { readonly session?: { readonly id?: string } };\n}\n\nfunction speakerOf(type: string): 'user' | 'assistant' | 'tool' | 'system' {\n if (type.startsWith('assistant')) return 'assistant';\n if (type.startsWith('tool')) return 'tool';\n if (type.startsWith('system')) return 'system';\n return 'user';\n}\n\nfunction textOf(data: unknown): string {\n if (typeof data !== 'object' || data === null) return '';\n const record = data as { content?: unknown; text?: unknown; message?: unknown };\n if (typeof record.content === 'string') return record.content;\n if (Array.isArray(record.content)) {\n return record.content\n .map((block) =>\n typeof block === 'object' && block !== null && typeof (block as { text?: unknown }).text === 'string'\n ? ((block as { text: string }).text)\n : '',\n )\n .filter((text) => text !== '')\n .join('\\n');\n }\n if (typeof record.text === 'string') return record.text;\n if (typeof record.message === 'object' && record.message !== null) return textOf(record.message);\n return '';\n}\n\nexport function openHostService(\n home: string,\n session: HostSessionContext,\n options: { readonly onFailure?: (error: unknown) => void } = {},\n): HostService | null {\n let runtime: Runtime;\n try {\n runtime = startup({ home });\n } catch (error) {\n // The host keeps running with the probe fallback, but the failure must not\n // disappear: the caller surfaces it (repair command included) to the model.\n options.onFailure?.(error);\n return null;\n }\n const store = new MemoryStore({ home, config: runtime.config });\n\n const lookupEvent = async (sessionId: string, seq: number): Promise<EvidenceEvent> => {\n // Live session fallback is sanctioned by plan \u00A75.3; it is also what desktop\n // compositions expose (`ctx.sessions`) when the durable service is absent.\n const live = session.sessions?.get(sessionId);\n if (live !== undefined) {\n const event = live.eventAt(seq);\n if (event === undefined || event.seq !== seq) {\n throw new Error(`event ${seq} does not exist in this session`);\n }\n return { seq: event.seq, speaker: speakerOf(event.type), text: textOf(event.data) };\n }\n if (session.persistence === undefined) {\n throw new Error('trusted source binding is unavailable in this host session');\n }\n const handle = await session.persistence.open(sessionId, 'read');\n try {\n const { events } = await handle.read(seq, 1);\n const event = events[0];\n if (event === undefined || event.seq !== seq) throw new Error(`event ${seq} does not exist in this session`);\n return { seq: event.seq, speaker: speakerOf(event.type), text: textOf(event.data) };\n } finally {\n await handle.close();\n }\n };\n\n return {\n store,\n runtime,\n home,\n mode: runtime.config.personalization.mode,\n session,\n config: runtime.config,\n async recall(input) {\n return store.recallAsync(input.query, {\n ...(input.limit === undefined ? {} : { limit: input.limit }),\n ...(input.kind === undefined ? {} : { kinds: [input.kind as Kind] }),\n });\n },\n read(id) {\n return store.read(id);\n },\n async record(input, actor, exec?: unknown) {\n const execLike = exec as ToolExecLike | undefined;\n const sessionId = execLike?.agent?.session?.id ?? actor.sessionId;\n const raw = input as {\n kind: Kind;\n abstract: string;\n body: string;\n valid_from?: string;\n project?: string;\n tags?: readonly string[];\n error_signatures?: readonly string[];\n evidence: readonly { event_seq: number; quote: string }[];\n };\n const provenance = [];\n for (const entry of raw.evidence) {\n const event = await lookupEvent(sessionId, entry.event_seq);\n provenance.push(\n bindEvidence({\n sessionId,\n eventSeq: entry.event_seq,\n quote: entry.quote,\n lookup: () => event,\n }),\n );\n }\n return store.add(\n {\n kind: raw.kind,\n abstract: raw.abstract,\n body: raw.body,\n evidence_level: 'observed',\n ...(raw.valid_from === undefined ? {} : { valid_from: raw.valid_from }),\n ...(raw.project === undefined ? {} : { project: raw.project }),\n ...(raw.tags === undefined ? {} : { tags: raw.tags }),\n ...(raw.error_signatures === undefined ? {} : { error_signatures: raw.error_signatures }),\n },\n { author: 'agent', provenance },\n );\n },\n context(exec, limit = 10) {\n const execLike = exec as ToolExecLike | undefined;\n const sessionId = execLike?.agent?.session?.id ?? session.sessionId;\n const live = session.sessions?.get(sessionId);\n if (live === undefined) return { events: [] };\n const events: Array<{ seq: number; speaker: string; preview: string }> = [];\n const end = live.seq ?? 0;\n for (let seq = 0; seq < end; seq += 1) {\n const event = live.eventAt(seq);\n if (event === undefined) continue;\n if (event.type !== 'user/message' && event.type !== 'system/message' && event.type !== 'tool/result') {\n continue;\n }\n const text = textOf(event.data);\n if (text === '') continue;\n events.push({ seq: event.seq, speaker: speakerOf(event.type), preview: text.slice(0, 120) });\n }\n return { events: events.slice(-limit) };\n },\n async propose(input, actor, exec?: unknown) {\n const execLike = exec as ToolExecLike | undefined;\n const sessionId = execLike?.agent?.session?.id ?? actor.sessionId;\n const raw = input as {\n op: 'create' | 'supersede' | 'delete';\n ids?: readonly string[];\n base_hashes?: readonly string[];\n replacements?: readonly {\n kind: Kind;\n abstract: string;\n body: string;\n evidence_level?: 'user_explicit' | 'user_confirmed' | 'observed';\n valid_from?: string;\n project?: string;\n tags?: readonly string[];\n error_signatures?: readonly string[];\n evidence?: readonly { event_seq: number; quote: string }[];\n }[];\n reason?: string;\n };\n const replacements: ProposalReplacement[] = [];\n for (const replacement of raw.replacements ?? []) {\n const provenance = [];\n for (const entry of replacement.evidence ?? []) {\n const event = await lookupEvent(sessionId, entry.event_seq);\n provenance.push(\n bindEvidence({\n sessionId,\n eventSeq: entry.event_seq,\n quote: entry.quote,\n lookup: () => event,\n }),\n );\n }\n replacements.push({\n kind: replacement.kind,\n abstract: replacement.abstract,\n body: replacement.body,\n evidence_level: replacement.evidence_level ?? 'observed',\n ...(replacement.valid_from === undefined ? {} : { valid_from: replacement.valid_from }),\n ...(replacement.project === undefined ? {} : { project: replacement.project }),\n ...(replacement.tags === undefined ? {} : { tags: replacement.tags }),\n ...(replacement.error_signatures === undefined\n ? {}\n : { error_signatures: replacement.error_signatures }),\n provenance,\n });\n }\n const proposalInput: ProposalInput =\n raw.op === 'delete'\n ? {\n op: 'delete',\n target: (raw.ids ?? [])[0] as string,\n base_hash: (raw.base_hashes ?? [])[0] as string,\n reason: raw.reason ?? 'agent proposal',\n }\n : raw.op === 'create'\n ? {\n op: 'create',\n replacements,\n ...(raw.reason === undefined ? {} : { reason: raw.reason }),\n }\n : {\n op: 'supersede',\n targets: raw.ids ?? [],\n base_hashes: raw.base_hashes ?? [],\n replacements,\n ...(raw.reason === undefined ? {} : { reason: raw.reason }),\n };\n return createProposal({ store, config: runtime.config }, proposalInput);\n },\n rules() {\n return { rules: loadRules(home) };\n },\n assembleSection(sessionId = session.sessionId) {\n const result = assemble({\n home,\n config: runtime.config,\n policy: runtime.policy,\n source: store,\n sessionId,\n });\n return { name: 'agent-memory' as const, order: 100, text: result.text, interpolate: false as const };\n },\n assembleSections(sessionId = session.sessionId) {\n const result = assemble({\n home,\n config: runtime.config,\n policy: runtime.policy,\n source: store,\n sessionId,\n });\n return result.sectionList.map((section) => ({\n name: `agent-memory:${section.key.toLowerCase()}`,\n order: section.order,\n text: section.text,\n interpolate: false as const,\n }));\n },\n };\n}\n"],
|
|
5
|
+
"mappings": ";AAcA,SAAS,kBAAkB;;;ACkBpB,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAA0B,SAAiB,OAA2B,CAAC,GAAG;AACpF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU,KAAK,WAAW,CAAC;AAChC,SAAK,OAAO,KAAK;AACjB,SAAK,aAAa,KAAK;AACvB,SAAK,OAAO,KAAK,QAAQ,CAAC;AAC1B,SAAK,aAAa,KAAK;AAAA,EACzB;AAAA;AAAA,EAGA,SAAiB;AACf,UAAM,QAAQ,CAAC,gCAAgC,KAAK,IAAI,MAAM,KAAK,OAAO,EAAE;AAC5E,QAAI,KAAK,eAAe,OAAW,OAAM,KAAK,WAAW,KAAK,UAAU,EAAE;AAC1E,eAAW,UAAU,KAAK,QAAS,OAAM,KAAK,OAAO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ject", "recall", "join", "isAbsolute", "resolve", "createHash", "readFileSync", "name", "createHash", "readFileSync", "name", "seal", "sha256", "sha256", "readFileSync", "existsSync", "name", "existsSync", "readFileSync", "TIMESTAMP", "existsSync", "readFileSync", "name", "name", "project", "name", "createHash", "randomBytes", "existsSync", "readFileSync", "writeFileSync", "createHash", "existsSync", "readFileSync", "randomBytes", "writeFileSync", "randomBytes", "closeSync", "fsyncSync", "openSync", "readFileSync", "statSync", "writeFileSync", "readFileSync", "statSync", "openSync", "fsyncSync", "closeSync", "randomBytes", "randomBytes", "createHash", "closeSync", "existsSync", "fsyncSync", "mkdirSync", "openSync", "readFileSync", "statSync", "writeSync", "join", "name", "existsSync", "readdirSync", "readFileSync", "rmSync", "statSync", "writeFileSync", "createHash", "join", "frequencies", "normalizedAbstract", "readFileSync", "rmSync", "writeFileSync", "join", "join", "readFileSync", "join", "writeFileSync", "resolve", "readFileSync", "rmSync", "KINDS", "DATE", "join", "readdirSync", "name", "statSync", "readFileSync", "createHash", "writeFileSync", "rmSync", "existsSync", "resolve", "sha256", "existsSync", "readFileSync", "join", "join", "existsSync", "readFileSync", "createHash", "existsSync", "readFileSync", "readdirSync", "rmSync", "statSync", "join", "name", "createHash", "join", "existsSync", "readFileSync", "readdirSync", "statSync", "rmSync", "createHash", "randomBytes", "existsSync", "readFileSync", "existsSync", "readFileSync", "charCount", "createHash", "randomBytes", "existsSync", "readdirSync", "readFileSync", "rmSync", "join", "join", "readdirSync", "name", "readFileSync", "existsSync", "rmSync", "createHash", "sha256", "createHash", "existsSync", "readFileSync", "join", "join", "existsSync", "readFileSync", "createHash", "createHash", "existsSync", "mkdirSync", "readFileSync", "readdirSync", "statSync", "writeFileSync", "join", "mkdirSync", "join", "existsSync", "walk", "name", "readdirSync", "statSync", "readFileSync", "createHash", "writeFileSync", "existsSync", "readFileSync", "existsSync", "readFileSync", "COMMENT", "existsSync", "readFileSync", "existsSync", "existsSync", "seal", "KINDS", "tokenize", "name", "fail", "decision", "KINDS", "name", "KINDS", "service", "fail", "name", "name", "profile", "search", "textOf", "name", "commands", "definition", "entry"]
|
|
7
7
|
}
|