@remnic/core 9.3.696 → 9.3.698
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/access-boundary.d.ts +1 -1
- package/dist/access-boundary.js +20 -20
- package/dist/access-cli.js +44 -44
- package/dist/access-http.d.ts +1 -1
- package/dist/access-http.js +23 -23
- package/dist/access-mcp.d.ts +1 -1
- package/dist/access-mcp.js +22 -22
- package/dist/access-operations.d.ts +1 -1
- package/dist/access-operations.js +21 -21
- package/dist/{access-service-BqBQeUJd.d.ts → access-service-DftqtNUy.d.ts} +10 -0
- package/dist/access-service.d.ts +1 -1
- package/dist/access-service.js +19 -19
- package/dist/access-surface-catalog.d.ts +1 -1
- package/dist/active-recall.js +1 -1
- package/dist/{auto-sync-PFW2NJZY.js → auto-sync-3AAP25FV.js} +5 -5
- package/dist/briefing.js +7 -7
- package/dist/calibration.js +2 -2
- package/dist/causal-behavior.js +2 -2
- package/dist/causal-chain.js +2 -2
- package/dist/causal-consolidation.js +10 -10
- package/dist/causal-retrieval.js +2 -2
- package/dist/causal-trajectory-graph.js +2 -2
- package/dist/causal-trajectory.js +1 -1
- package/dist/{chunk-YOZNTNNA.js → chunk-2K64VH66.js} +2 -2
- package/dist/{chunk-NLZO5NO6.js → chunk-2KJG6ZZK.js} +2 -2
- package/dist/{chunk-3P2XEQSV.js → chunk-2ULWWAQH.js} +2 -2
- package/dist/{chunk-EK6FYL2E.js → chunk-3LSSFCB4.js} +13 -13
- package/dist/chunk-3LSSFCB4.js.map +1 -0
- package/dist/{chunk-3PG3H5TD.js → chunk-4EX5WZ4M.js} +2 -2
- package/dist/chunk-4EX5WZ4M.js.map +1 -0
- package/dist/{chunk-LM6JB2EG.js → chunk-4NFVPDIL.js} +2 -2
- package/dist/{chunk-5TYA4OCF.js → chunk-5J4OL7TJ.js} +2 -2
- package/dist/chunk-5J4OL7TJ.js.map +1 -0
- package/dist/{chunk-J45OCIVH.js → chunk-A62RAIBN.js} +2 -2
- package/dist/{chunk-XXA6T3O4.js → chunk-ANZLT74L.js} +2 -2
- package/dist/{chunk-MNFAGE5D.js → chunk-COEZR6F5.js} +2 -2
- package/dist/{chunk-HKET3ZOI.js → chunk-CQ4PGFMC.js} +3 -3
- package/dist/{chunk-SPVIG2R3.js → chunk-E6GOVHHJ.js} +10 -10
- package/dist/{chunk-XWT4JXXA.js → chunk-EZWQZYLK.js} +2 -2
- package/dist/{chunk-5AT62NQH.js → chunk-FEB7W5JG.js} +104 -16
- package/dist/chunk-FEB7W5JG.js.map +1 -0
- package/dist/{chunk-QJM2XAJD.js → chunk-FN2SM5SN.js} +5 -5
- package/dist/{chunk-Q6ZHGGNJ.js → chunk-FSEQXHEZ.js} +2 -2
- package/dist/{chunk-32XTY2DQ.js → chunk-HZ5DRA4Q.js} +44 -44
- package/dist/{chunk-XUNQLJT2.js → chunk-IZ5E6ZTK.js} +4 -4
- package/dist/{chunk-RWST6NOL.js → chunk-JYVD2XZ4.js} +52 -52
- package/dist/chunk-JYVD2XZ4.js.map +1 -0
- package/dist/{chunk-YGKUAX2B.js → chunk-KF74X62T.js} +4 -4
- package/dist/{chunk-JMAKCWJ3.js → chunk-LIWU4QI6.js} +5 -5
- package/dist/{chunk-Q7SFJURX.js → chunk-M4DQWUKX.js} +2 -2
- package/dist/{chunk-AF6DSAWD.js → chunk-MRX6S22R.js} +2 -2
- package/dist/{chunk-FZMH66NT.js → chunk-N55RJT4N.js} +2 -2
- package/dist/{chunk-RK6F44Y6.js → chunk-N7RWREIQ.js} +2 -2
- package/dist/chunk-N7RWREIQ.js.map +1 -0
- package/dist/{chunk-W54EAJT4.js → chunk-PJIHCOGV.js} +2 -2
- package/dist/{chunk-WR6KFJKA.js → chunk-RC3CNIPK.js} +2 -2
- package/dist/{chunk-MOBRVKWE.js → chunk-RIC5U67B.js} +10 -10
- package/dist/{chunk-EC3A6M43.js → chunk-RTN2BLZM.js} +2 -2
- package/dist/{chunk-G663XUEG.js → chunk-SIDSEXUG.js} +2 -2
- package/dist/{chunk-52QIAN76.js → chunk-SJQ4HY3E.js} +2 -2
- package/dist/{chunk-JJT3AGL4.js → chunk-TH7WMHVK.js} +2 -2
- package/dist/{chunk-4NNDJOAO.js → chunk-UDDSC6PO.js} +8 -8
- package/dist/{chunk-TT7BJWGI.js → chunk-VKJHM6PL.js} +2 -2
- package/dist/{chunk-N4PD5IY3.js → chunk-XFG3PVZE.js} +53 -33
- package/dist/chunk-XFG3PVZE.js.map +1 -0
- package/dist/{chunk-NFMDHE45.js → chunk-XL5RSHZP.js} +2 -2
- package/dist/{chunk-3LYJIA76.js → chunk-YN4ZT4CW.js} +1 -1
- package/dist/{chunk-IF362TF6.js → chunk-YOI3ELXF.js} +2 -2
- package/dist/{chunk-6GAUF4OU.js → chunk-YY2HGKWR.js} +2 -2
- package/dist/{cli-DBDgdvh9.d.ts → cli-DUMkkdLl.d.ts} +1 -1
- package/dist/{codex-cli-fallback.js → cli-fallback.js} +2 -2
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +38 -38
- package/dist/compounding/engine.js +7 -7
- package/dist/config.js +1 -1
- package/dist/connectors/codex-materialize-runner.js +7 -7
- package/dist/connectors/index.js +7 -7
- package/dist/entity-retrieval.js +7 -7
- package/dist/extraction-faithfulness.d.ts +23 -3
- package/dist/extraction-faithfulness.js +3 -3
- package/dist/extraction-judge.js +3 -3
- package/dist/extraction.js +4 -4
- package/dist/fallback-llm.js +2 -2
- package/dist/{graph-edge-decay-JLOF3YW4.js → graph-edge-decay-D7OESCBR.js} +3 -3
- package/dist/graph-snapshot.js +3 -3
- package/dist/graph.js +2 -2
- package/dist/index.d.ts +4 -4
- package/dist/index.js +80 -80
- package/dist/maintenance/memory-governance.js +7 -7
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +7 -7
- package/dist/maintenance/rebuild-memory-projection.js +8 -8
- package/dist/mcp-memory-inspector-app.d.ts +1 -1
- package/dist/namespaces/migrate.js +8 -8
- package/dist/namespaces/storage.js +7 -7
- package/dist/operator-toolkit.js +15 -15
- package/dist/orchestration/maintenance.js +9 -9
- package/dist/orchestrator.js +35 -35
- package/dist/recall-planner-llm.js +2 -2
- package/dist/resume-bundles.js +2 -2
- package/dist/schemas.d.ts +22 -22
- package/dist/semantic-consolidation.js +8 -8
- package/dist/semantic-rule-promotion.js +7 -7
- package/dist/semantic-rule-verifier.js +7 -7
- package/dist/storage.js +6 -6
- package/dist/summarizer.js +3 -3
- package/dist/{codex-thread-key.js → thread-key.js} +2 -2
- package/dist/transfer/types.d.ts +12 -12
- package/dist/verified-recall.js +7 -7
- package/package.json +18 -18
- package/src/access-service.ts +17 -0
- package/src/coding/session-delta-surfaces.test.ts +185 -1
- package/src/coding/session-delta-surfaces.ts +30 -1
- package/src/coding/session-delta.test.ts +46 -0
- package/src/coding/session-delta.ts +18 -1
- package/src/config.test.ts +32 -0
- package/src/config.ts +12 -12
- package/src/extraction-faithfulness.test.ts +149 -5
- package/src/extraction-faithfulness.ts +195 -21
- package/src/fallback-llm.test.ts +1 -1
- package/src/fallback-llm.ts +1 -1
- package/src/index.ts +2 -2
- package/src/orchestrator.ts +1 -1
- package/dist/chunk-3PG3H5TD.js.map +0 -1
- package/dist/chunk-5AT62NQH.js.map +0 -1
- package/dist/chunk-5TYA4OCF.js.map +0 -1
- package/dist/chunk-EK6FYL2E.js.map +0 -1
- package/dist/chunk-N4PD5IY3.js.map +0 -1
- package/dist/chunk-RK6F44Y6.js.map +0 -1
- package/dist/chunk-RWST6NOL.js.map +0 -1
- /package/dist/{auto-sync-PFW2NJZY.js.map → auto-sync-3AAP25FV.js.map} +0 -0
- /package/dist/{chunk-YOZNTNNA.js.map → chunk-2K64VH66.js.map} +0 -0
- /package/dist/{chunk-NLZO5NO6.js.map → chunk-2KJG6ZZK.js.map} +0 -0
- /package/dist/{chunk-3P2XEQSV.js.map → chunk-2ULWWAQH.js.map} +0 -0
- /package/dist/{chunk-LM6JB2EG.js.map → chunk-4NFVPDIL.js.map} +0 -0
- /package/dist/{chunk-J45OCIVH.js.map → chunk-A62RAIBN.js.map} +0 -0
- /package/dist/{chunk-XXA6T3O4.js.map → chunk-ANZLT74L.js.map} +0 -0
- /package/dist/{chunk-MNFAGE5D.js.map → chunk-COEZR6F5.js.map} +0 -0
- /package/dist/{chunk-HKET3ZOI.js.map → chunk-CQ4PGFMC.js.map} +0 -0
- /package/dist/{chunk-SPVIG2R3.js.map → chunk-E6GOVHHJ.js.map} +0 -0
- /package/dist/{chunk-XWT4JXXA.js.map → chunk-EZWQZYLK.js.map} +0 -0
- /package/dist/{chunk-QJM2XAJD.js.map → chunk-FN2SM5SN.js.map} +0 -0
- /package/dist/{chunk-Q6ZHGGNJ.js.map → chunk-FSEQXHEZ.js.map} +0 -0
- /package/dist/{chunk-32XTY2DQ.js.map → chunk-HZ5DRA4Q.js.map} +0 -0
- /package/dist/{chunk-XUNQLJT2.js.map → chunk-IZ5E6ZTK.js.map} +0 -0
- /package/dist/{chunk-YGKUAX2B.js.map → chunk-KF74X62T.js.map} +0 -0
- /package/dist/{chunk-JMAKCWJ3.js.map → chunk-LIWU4QI6.js.map} +0 -0
- /package/dist/{chunk-Q7SFJURX.js.map → chunk-M4DQWUKX.js.map} +0 -0
- /package/dist/{chunk-AF6DSAWD.js.map → chunk-MRX6S22R.js.map} +0 -0
- /package/dist/{chunk-FZMH66NT.js.map → chunk-N55RJT4N.js.map} +0 -0
- /package/dist/{chunk-W54EAJT4.js.map → chunk-PJIHCOGV.js.map} +0 -0
- /package/dist/{chunk-WR6KFJKA.js.map → chunk-RC3CNIPK.js.map} +0 -0
- /package/dist/{chunk-MOBRVKWE.js.map → chunk-RIC5U67B.js.map} +0 -0
- /package/dist/{chunk-EC3A6M43.js.map → chunk-RTN2BLZM.js.map} +0 -0
- /package/dist/{chunk-G663XUEG.js.map → chunk-SIDSEXUG.js.map} +0 -0
- /package/dist/{chunk-52QIAN76.js.map → chunk-SJQ4HY3E.js.map} +0 -0
- /package/dist/{chunk-JJT3AGL4.js.map → chunk-TH7WMHVK.js.map} +0 -0
- /package/dist/{chunk-4NNDJOAO.js.map → chunk-UDDSC6PO.js.map} +0 -0
- /package/dist/{chunk-TT7BJWGI.js.map → chunk-VKJHM6PL.js.map} +0 -0
- /package/dist/{chunk-NFMDHE45.js.map → chunk-XL5RSHZP.js.map} +0 -0
- /package/dist/{chunk-3LYJIA76.js.map → chunk-YN4ZT4CW.js.map} +0 -0
- /package/dist/{chunk-IF362TF6.js.map → chunk-YOI3ELXF.js.map} +0 -0
- /package/dist/{chunk-6GAUF4OU.js.map → chunk-YY2HGKWR.js.map} +0 -0
- /package/dist/{codex-cli-fallback.d.ts → cli-fallback.d.ts} +0 -0
- /package/dist/{codex-cli-fallback.js.map → cli-fallback.js.map} +0 -0
- /package/dist/{graph-edge-decay-JLOF3YW4.js.map → graph-edge-decay-D7OESCBR.js.map} +0 -0
- /package/dist/{codex-thread-key.d.ts → thread-key.d.ts} +0 -0
- /package/dist/{codex-thread-key.js.map → thread-key.js.map} +0 -0
- /package/src/{codex-cli-fallback.ts → cli-fallback.ts} +0 -0
- /package/src/{codex-thread-key.ts → thread-key.ts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/thread-key.ts"],"sourcesContent":["export const CODEX_THREAD_KEY_PREFIX = \"codex-thread:\";\n"],"mappings":";AAAO,IAAM,0BAA0B;","names":[]}
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-7FL4CNPV.js";
|
|
4
4
|
import {
|
|
5
5
|
resolveCausalTrajectoryStoreDir
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-YN4ZT4CW.js";
|
|
7
7
|
import {
|
|
8
8
|
log
|
|
9
9
|
} from "./chunk-NU3CSQ4H.js";
|
|
@@ -339,4 +339,4 @@ export {
|
|
|
339
339
|
scoreStitchCandidate,
|
|
340
340
|
stitchCausalChain
|
|
341
341
|
};
|
|
342
|
-
//# sourceMappingURL=chunk-
|
|
342
|
+
//# sourceMappingURL=chunk-4NFVPDIL.js.map
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
} from "./chunk-RGMVMVMF.js";
|
|
16
16
|
import {
|
|
17
17
|
callCodexCliFallback
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-N7RWREIQ.js";
|
|
19
19
|
import {
|
|
20
20
|
expandTildePath
|
|
21
21
|
} from "./chunk-EYIEWJNI.js";
|
|
@@ -698,4 +698,4 @@ export {
|
|
|
698
698
|
fallbackLlmRuntimeContextFromConfig,
|
|
699
699
|
FallbackLlmClient
|
|
700
700
|
};
|
|
701
|
-
//# sourceMappingURL=chunk-
|
|
701
|
+
//# sourceMappingURL=chunk-5J4OL7TJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/fallback-llm.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport path from \"node:path\";\nimport type { AgentPersonaModelConfig, GatewayConfig, ModelProviderConfig, PluginConfig } from \"./types.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\nimport {\n buildChatCompletionTemperature,\n buildChatCompletionTokenLimit,\n shouldAssumeOpenAiChatCompletions,\n} from \"./openai-chat-compat.js\";\nimport {\n resolveProviderApiKey,\n getGatewayRuntimeAuthForModel,\n type GetRuntimeAuthForModelFn,\n type ResolveApiKeyFn,\n} from \"./resolve-provider-secret.js\";\nimport { loadModelsJsonProviders } from \"./models-json.js\";\nimport { callCodexCliFallback } from \"./cli-fallback.js\";\nimport { resolveHomeDir } from \"./runtime/env.js\";\nimport { expandTildePath } from \"./utils/path.js\";\n\nexport interface FallbackLlmOptions {\n temperature?: number;\n maxTokens?: number;\n timeoutMs?: number;\n signal?: AbortSignal;\n /** Explicit \"provider/model\" override to try before the configured chain. */\n model?: string;\n /** Explicit model chain override to use instead of the configured agent/default chain. */\n modelChain?: AgentPersonaModelConfig;\n /** Override which agent persona's model chain to use (by ID from agents.list[]). */\n agentId?: string;\n}\n\nexport interface FallbackLlmAvailabilityOptions {\n agentId?: string;\n modelChain?: AgentPersonaModelConfig;\n}\n\n/**\n * Resolve the gateway routing options Remnic's background tasks should pass to\n * FallbackLlmClient — extraction, fact/profile/identity consolidation,\n * summarization, calibration, and causal/semantic consolidation. Single source\n * of truth so every task path stays consistent and can't diverge (gotcha #22):\n * in gateway mode an explicit `taskModelChain` wins over the gateway agent\n * persona; otherwise the persona (if any) is used. Returns `{}` in plugin mode\n * because the chain resolves through gateway providers only. Issue #1365.\n */\nexport function gatewayTaskChainOptions(\n config: Pick<PluginConfig, \"modelSource\" | \"taskModelChain\" | \"gatewayAgentId\">,\n): Pick<FallbackLlmOptions, \"modelChain\" | \"agentId\"> {\n if (config.modelSource !== \"gateway\") return {};\n if (config.taskModelChain) return { modelChain: config.taskModelChain };\n return config.gatewayAgentId ? { agentId: config.gatewayAgentId } : {};\n}\n\nexport interface FallbackLlmResponse {\n content: string;\n modelUsed: string;\n usage?: {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n };\n}\n\nexport interface FallbackLlmRuntimeContext {\n agentDir?: string;\n getRuntimeAuthForModel?: GetRuntimeAuthForModelFn | null;\n resolveApiKeyForProvider?: ResolveApiKeyFn | null;\n workspaceDir?: string;\n}\n\nexport function fallbackLlmRuntimeContextFromConfig(\n config: Pick<\n GatewayBackedRuntimeConfig,\n \"providerApiKeyResolver\" | \"runtimeAuthForModelResolver\" | \"workspaceDir\"\n >,\n overrides: FallbackLlmRuntimeContext = {},\n): FallbackLlmRuntimeContext {\n return {\n workspaceDir: config.workspaceDir,\n resolveApiKeyForProvider: config.providerApiKeyResolver,\n getRuntimeAuthForModel: config.runtimeAuthForModelResolver,\n ...overrides,\n };\n}\n\ntype GatewayBackedRuntimeConfig = {\n providerApiKeyResolver?: ResolveApiKeyFn | null;\n runtimeAuthForModelResolver?: GetRuntimeAuthForModelFn | null;\n workspaceDir?: string;\n};\n\ninterface ModelRef {\n providerId: string;\n modelId: string;\n providerConfig: ModelProviderConfig;\n modelString: string;\n}\n\nconst PROVIDER_ALIASES: Record<string, readonly string[]> = {\n \"openai-codex\": [\"codex\"],\n codex: [\"openai-codex\"],\n \"claude-cli\": [\"anthropic\"],\n};\n\nconst LEGACY_PROVIDER_IDS = new Set([\"openai-codex\", \"claude-cli\"]);\n\nconst MANAGED_SECRETREF_MARKER = [\"secretref\", \"managed\"].join(\"-\");\nconst PROVIDER_API_KEY_FIELD = [\"api\", \"Key\"].join(\"\") as keyof ModelProviderConfig;\n\n/**\n * Built-in provider fallbacks for providers that are commonly configured via\n * OAuth or gateway-managed auth rather than an explicit apiKey in\n * openclaw.json. These entries let resolveProviderConfig() succeed so the\n * chain proceeds to tryModel() → resolveRuntimeAuth(), which is where the\n * gateway's native OAuth token exchange happens.\n *\n * Without these, OAuth-only providers like `openai` are rejected with\n * \"provider not found\" before runtime auth is ever attempted.\n */\nconst BUILT_IN_PROVIDER_FALLBACKS: Record<string, ModelProviderConfig> = {\n anthropic: {\n baseUrl: \"https://api.anthropic.com/v1\",\n api: \"anthropic-messages\",\n models: [],\n [PROVIDER_API_KEY_FIELD]: MANAGED_SECRETREF_MARKER,\n },\n openai: {\n baseUrl: \"https://api.openai.com/v1\",\n api: \"openai-responses\",\n models: [],\n [PROVIDER_API_KEY_FIELD]: MANAGED_SECRETREF_MARKER,\n },\n};\n\n/**\n * Generic fallback LLM client that uses the gateway's default AI configuration\n * and walks through the full fallback chain (primary + fallbacks).\n * Supports OpenAI and Anthropic API formats.\n */\nexport class FallbackLlmClient {\n private gatewayConfig: GatewayConfig | undefined;\n private runtimeContext: FallbackLlmRuntimeContext;\n\n constructor(\n gatewayConfig?: GatewayConfig,\n runtimeContext: FallbackLlmRuntimeContext = {},\n ) {\n this.gatewayConfig = gatewayConfig;\n this.runtimeContext = {\n ...runtimeContext,\n workspaceDir:\n normalizeRuntimePath(runtimeContext.workspaceDir) ??\n readGatewayWorkspaceDir(gatewayConfig) ??\n defaultOpenClawWorkspaceDir(),\n };\n }\n\n /**\n * Check if fallback is available (gateway config has at least one model).\n */\n isAvailable(agentIdOrOptions?: string | FallbackLlmAvailabilityOptions): boolean {\n const options = typeof agentIdOrOptions === \"string\"\n ? { agentId: agentIdOrOptions }\n : (agentIdOrOptions ?? {});\n const models = this.getModelChain(options.agentId, undefined, options.modelChain);\n return models.length > 0;\n }\n\n /**\n * Make a chat completion request using the gateway's default AI chain.\n * Tries primary first, then each fallback in order.\n * When agentId is provided, uses that agent persona's model chain instead of defaults.\n */\n async chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: FallbackLlmOptions = {},\n ): Promise<FallbackLlmResponse | null> {\n const models = this.getModelChain(options.agentId, options.model, options.modelChain);\n if (models.length === 0) {\n log.warn(\"fallback LLM: no models configured in gateway\");\n return null;\n }\n\n const runChain = async (\n runOptions: FallbackLlmOptions,\n ): Promise<FallbackLlmResponse | null> => {\n // Try each model in the chain\n for (let i = 0; i < models.length; i++) {\n if (runOptions.signal?.aborted) {\n throw abortReason(runOptions.signal);\n }\n const model = models[i];\n const isFallback = i > 0;\n\n try {\n const result = await this.tryModel(model, messages, runOptions);\n if (result) {\n if (isFallback) {\n log.debug(`fallback LLM: succeeded using ${model.modelString} (fallback ${i})`);\n }\n return {\n content: result.content,\n modelUsed: model.modelString,\n usage: result.usage,\n };\n }\n } catch (err) {\n if (runOptions.signal?.aborted) {\n throw abortReason(runOptions.signal);\n }\n const errorMsg = err instanceof Error ? err.message : String(err);\n log.debug(`fallback LLM: ${model.modelString} failed (${errorMsg}), trying next...`);\n // Continue to next model in chain\n }\n }\n\n log.warn(`fallback LLM: all ${models.length} models in chain failed`);\n return null;\n };\n\n if (typeof options.timeoutMs === \"number\") {\n if (options.timeoutMs <= 0) {\n log.warn(\"fallback LLM: timed out before request started\");\n return null;\n }\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined;\n const controller = new AbortController();\n const onCallerAbort = (): void => {\n controller.abort(abortReason(options.signal));\n };\n options.signal?.addEventListener(\"abort\", onCallerAbort, { once: true });\n if (options.signal?.aborted) {\n onCallerAbort();\n }\n const timedOptions = { ...options, signal: controller.signal };\n const chain = runChain(timedOptions);\n chain.catch(() => {});\n try {\n return await Promise.race([\n chain,\n new Promise<null>((resolve) => {\n timeoutHandle = setTimeout(() => {\n log.warn(`fallback LLM: timed out after ${options.timeoutMs}ms`);\n controller.abort(\n new Error(`fallback LLM timed out after ${options.timeoutMs}ms`),\n );\n resolve(null);\n }, options.timeoutMs);\n }),\n ]);\n } finally {\n if (timeoutHandle) clearTimeout(timeoutHandle);\n options.signal?.removeEventListener(\"abort\", onCallerAbort);\n }\n }\n\n return await runChain(options);\n }\n\n /**\n * Make a request with structured output (Zod schema).\n * Returns parsed JSON or null on failure.\n */\n async parseWithSchema<T>(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n schema: { parse: (data: unknown) => T },\n options: FallbackLlmOptions = {},\n ): Promise<T | null> {\n const detailed = await this.parseWithSchemaDetailed(messages, schema, options);\n return detailed?.result ?? null;\n }\n\n /**\n * Like parseWithSchema but also returns the model that was used,\n * so callers can emit accurate trace events.\n */\n async parseWithSchemaDetailed<T>(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n schema: { parse: (data: unknown) => T },\n options: FallbackLlmOptions = {},\n ): Promise<{ result: T; modelUsed: string } | null> {\n const response = await this.chatCompletion(messages, options);\n if (!response?.content) return null;\n\n try {\n const candidates = extractJsonCandidates(response.content);\n for (const c of candidates) {\n try {\n const parsed = JSON.parse(c);\n return { result: schema.parse(parsed), modelUsed: response.modelUsed };\n } catch {\n // keep trying other candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"fallback LLM: failed to parse structured output:\", err);\n return null;\n }\n }\n\n /**\n * Get the full model chain from gateway config.\n * Returns array of models in order: [primary, fallback1, fallback2, ...]\n *\n * When modelChainOverride is provided, uses it instead of any configured\n * agent/default chain. Otherwise, when agentId is provided, looks up the\n * matching entry in agents.list[] and uses that persona's model chain.\n * Falls back to agents.defaults.model if agentId is not found or not provided.\n */\n private getModelChain(\n agentId?: string,\n modelOverride?: string,\n modelChainOverride?: AgentPersonaModelConfig,\n ): ModelRef[] {\n const chain: ModelRef[] = [];\n const providers = this.gatewayConfig?.models?.providers ?? {};\n\n // Resolve the model config: explicit task chain, agent persona chain, or global defaults\n let modelConfig: AgentPersonaModelConfig | undefined;\n\n if (modelChainOverride?.primary) {\n modelConfig = modelChainOverride;\n log.debug(\"fallback LLM: using explicit model chain override\");\n } else if (modelChainOverride) {\n log.warn(\"fallback LLM: ignoring explicit model chain override without primary model\");\n }\n\n if (!modelConfig && agentId) {\n const persona = this.gatewayConfig?.agents?.list?.find(\n (a) => a.id === agentId,\n );\n if (persona?.model) {\n modelConfig = persona.model;\n log.debug(`fallback LLM: using agent persona \"${agentId}\" model chain`);\n } else {\n log.warn(\n `fallback LLM: agent persona \"${agentId}\" not found or has no model config, falling back to defaults`,\n );\n }\n }\n\n if (!modelConfig) {\n modelConfig = this.gatewayConfig?.agents?.defaults?.model;\n }\n\n // Build list of model strings: primary + fallbacks\n const modelStrings: string[] = [];\n\n const addModelString = (value: unknown): void => {\n if (typeof value !== \"string\") return;\n const trimmed = value.trim();\n if (trimmed.length > 0 && !modelStrings.includes(trimmed)) {\n modelStrings.push(trimmed);\n }\n };\n\n addModelString(modelOverride);\n addModelString(modelConfig?.primary);\n\n if (Array.isArray(modelConfig?.fallbacks)) {\n for (const fb of modelConfig.fallbacks) {\n addModelString(fb);\n }\n }\n\n // Parse each model string and look up provider config\n for (const modelString of modelStrings) {\n const modelRef = this.parseModelString(modelString, providers);\n if (modelRef) {\n chain.push(modelRef);\n }\n }\n\n // Implicit last-resort: when a task-specific modelChain override is active,\n // append the gateway default model so a stale or exhausted taskModelChain\n // never leaves the chain empty — Remnic should never be the reason a chat is\n // interrupted by a flush failure. Keyed on `modelChainOverride?.primary` —\n // the SAME activation condition chain resolution uses above — so a\n // primary-less override (e.g. {}) that falls through to a persona/default\n // chain does NOT get the default appended (gotcha #39). Issue #1365 / PR #1370.\n if (modelChainOverride?.primary && modelStrings.length > 0) {\n // Append the FULL gateway default chain (primary + fallbacks), not just\n // the primary — if the default primary is also unreachable, a listed\n // default fallback may still succeed (cursor review #1425).\n const defaults = this.gatewayConfig?.agents?.defaults?.model;\n const defaultStrings: string[] = [\n ...(typeof defaults?.primary === \"string\" ? [defaults.primary] : []),\n ...(Array.isArray(defaults?.fallbacks) ? defaults.fallbacks : []),\n ];\n for (const candidate of defaultStrings) {\n if (typeof candidate !== \"string\") continue;\n const trimmed = candidate.trim();\n if (trimmed.length === 0 || modelStrings.includes(trimmed)) continue;\n const defaultRef = this.parseModelString(trimmed, providers);\n if (defaultRef) {\n chain.push(defaultRef);\n modelStrings.push(trimmed); // keep dedupe correct for later default fallbacks\n log.debug(\n `fallback LLM: appended gateway default model \"${trimmed}\" as implicit last resort`,\n );\n }\n }\n }\n\n return chain;\n }\n\n /**\n * Parse a \"provider/model\" string and look up its config.\n */\n private parseModelString(\n modelString: string,\n providers: Record<string, ModelProviderConfig>,\n ): ModelRef | null {\n // Parse \"provider/model\" format (e.g., \"openai/gpt-5.5\", \"anthropic/claude-opus-4-6\")\n const parts = modelString.split(\"/\");\n if (parts.length < 2) {\n log.warn(`fallback LLM: invalid model format: ${modelString}`);\n return null;\n }\n\n const requestedProviderId = parts[0];\n const modelId = parts.slice(1).join(\"/\"); // Handle cases like \"openai/gpt-5.5\"\n\n // Respect the active gateway config first so profile-local overrides and\n // credentials win. Fall back to the materialized models.json only when\n // the provider is absent from the loaded config (for built-in providers\n // registered by the gateway at runtime).\n const resolvedProvider = this.resolveProviderConfig(requestedProviderId, providers);\n const providerConfig = resolvedProvider?.config;\n if (!providerConfig) {\n log.warn(\n `fallback LLM: provider not found: ${requestedProviderId} ` +\n `(tried: ${this.providerResolutionCandidates(requestedProviderId).join(\", \")})`,\n );\n return null;\n }\n\n return {\n providerId: resolvedProvider.providerId,\n modelId,\n providerConfig,\n modelString,\n };\n }\n\n private resolveProviderConfig(\n providerId: string,\n providers: Record<string, ModelProviderConfig>,\n ): { providerId: string; config: ModelProviderConfig } | null {\n const candidates = this.providerResolutionCandidates(providerId);\n const aliasCandidates = candidates.filter((candidate) => candidate !== providerId);\n const fallbackCandidates = LEGACY_PROVIDER_IDS.has(providerId)\n ? [...aliasCandidates, providerId]\n : [providerId, ...aliasCandidates];\n for (const candidate of candidates) {\n const config = providers[candidate];\n if (config) {\n if (candidate !== providerId) {\n log.debug(`fallback LLM: provider \"${providerId}\" resolved via alias \"${candidate}\"`);\n }\n return { providerId: candidate, config };\n }\n }\n for (const candidate of fallbackCandidates) {\n const config = this.resolveFromModelsJson(candidate);\n if (config) {\n if (candidate !== providerId) {\n log.debug(`fallback LLM: provider \"${providerId}\" resolved via models.json alias \"${candidate}\"`);\n }\n return { providerId: candidate, config };\n }\n const builtInConfig = BUILT_IN_PROVIDER_FALLBACKS[candidate];\n if (builtInConfig) {\n if (candidate === providerId) {\n log.debug(`fallback LLM: provider \"${providerId}\" resolved from built-in defaults`);\n return { providerId, config: builtInConfig };\n }\n log.debug(`fallback LLM: provider \"${providerId}\" resolved via built-in alias \"${candidate}\"`);\n return { providerId: candidate, config: builtInConfig };\n }\n }\n return null;\n }\n\n private providerResolutionCandidates(providerId: string): string[] {\n const candidates = [providerId, ...(PROVIDER_ALIASES[providerId] ?? [])];\n return [...new Set(candidates)];\n }\n\n /**\n * Look up a provider from the gateway's materialized models.json, which\n * contains all providers including built-in ones (openai-codex, google-vertex,\n * etc.) that aren't in the user's openclaw.json but are registered by\n * gateway plugins. Returns null if the provider isn't found there either.\n */\n private resolveFromModelsJson(providerId: string): ModelProviderConfig | null {\n const allProviders = loadModelsJsonProviders();\n const config = allProviders[providerId];\n if (config) {\n log.debug(`fallback LLM: resolved provider \"${providerId}\" from models.json (api: ${config.api ?? \"default\"})`);\n return config;\n }\n return null;\n }\n\n /**\n * Try to call a single model.\n *\n * Uses the gateway's native getRuntimeAuthForModel when available — this\n * handles all provider-specific auth transforms (OAuth token exchange,\n * base URL overrides for codex/copilot/etc.) through the same codepath\n * the gateway itself uses. Falls back to resolveProviderApiKey for\n * simpler providers or when the runtime module isn't loaded.\n */\n private async tryModel(\n model: ModelRef,\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: FallbackLlmOptions,\n ): Promise<{ content: string; usage?: FallbackLlmResponse[\"usage\"] } | null> {\n // Try the gateway's native runtime auth first — it handles all provider-\n // specific transforms (OAuth exchange, base URL rewrite, etc.)\n const runtimeAuth = model.providerConfig.api === \"codex-cli\"\n ? null\n : await this.resolveRuntimeAuth(model);\n const effectiveBaseUrl = runtimeAuth?.baseUrl ?? model.providerConfig.baseUrl;\n const resolvedApiKey = runtimeAuth?.apiKey\n ?? (\n model.providerConfig.api === \"codex-cli\" && model.providerConfig.apiKey === undefined\n ? undefined\n : await this.resolveFallbackApiKey(model)\n );\n\n // If the raw key looks like an unresolved secret ref and resolution fails,\n // skip this provider entirely so the chain falls through to the next.\n const rawKey = model.providerConfig.apiKey;\n const needsResolution = rawKey === \"secretref-managed\"\n || (typeof rawKey === \"object\" && rawKey !== null);\n if (needsResolution && !resolvedApiKey) {\n throw new Error(`API key for provider \"${model.providerId}\" could not be resolved from secret ref`);\n }\n\n const effectiveConfig: ModelProviderConfig = {\n ...model.providerConfig,\n baseUrl: effectiveBaseUrl,\n ...(resolvedApiKey ? { apiKey: resolvedApiKey } : {}),\n };\n\n if (model.providerConfig.api === \"anthropic-messages\") {\n return await this.callAnthropic(effectiveConfig, model.modelId, messages, options);\n }\n\n if (model.providerConfig.api === \"codex-cli\") {\n return await callCodexCliFallback(\n effectiveConfig,\n model.modelId,\n messages,\n { timeoutMs: options.timeoutMs, signal: options.signal },\n );\n }\n\n if (model.providerConfig.api === \"ollama-chat\") {\n return await this.callOllamaChat(effectiveConfig, model.modelId, messages, options);\n }\n\n if (\n model.providerConfig.api === \"openai-responses\" ||\n model.providerConfig.api === \"openai-codex-responses\" ||\n model.providerConfig.api === \"azure-openai-responses\"\n ) {\n return await this.callOpenAIResponses(\n effectiveConfig,\n model.modelId,\n messages,\n options,\n );\n }\n\n // For OpenAI-compatible chat-completions APIs (openai-completions,\n // ollama, etc.) and unknown formats, use chat completions — the gateway's\n // runtime auth resolver returns request-ready base URL and credentials for\n // most providers.\n return await this.callOpenAI(\n effectiveConfig,\n model.modelId,\n messages,\n options,\n shouldAssumeOpenAiChatCompletions(effectiveConfig.baseUrl),\n );\n }\n\n /**\n * Resolve request-ready auth through the gateway's native runtime, which\n * handles provider-specific transforms (OAuth token exchange for codex/copilot,\n * base URL rewrite, etc.). Returns null if the runtime isn't available.\n */\n private async resolveRuntimeAuth(\n model: ModelRef,\n ): Promise<{ apiKey?: string; baseUrl?: string } | null> {\n try {\n const getRuntimeAuth = await getGatewayRuntimeAuthForModel({\n getRuntimeAuthForModel: this.runtimeContext.getRuntimeAuthForModel,\n });\n if (!getRuntimeAuth) return null;\n\n const result = await getRuntimeAuth({\n model: {\n provider: model.providerId,\n id: model.modelId,\n api: model.providerConfig.api,\n baseUrl: model.providerConfig.baseUrl,\n },\n cfg: this.gatewayConfig,\n workspaceDir: this.runtimeContext.workspaceDir,\n });\n\n if (result?.apiKey || result?.baseUrl) {\n log.debug(\n `fallback LLM: resolved runtime auth for \"${model.modelString}\" (source: ${result.source ?? \"unknown\"}, mode: ${result.mode ?? \"unknown\"})`,\n );\n return { apiKey: result.apiKey, baseUrl: result.baseUrl };\n }\n } catch (err) {\n log.debug(\n `fallback LLM: gateway runtime auth failed for \"${model.modelString}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return null;\n }\n\n /**\n * Resolve API key through the existing provider-level resolution (env vars,\n * secret refs, etc.). Used as fallback when gateway runtime auth isn't available.\n */\n private async resolveFallbackApiKey(model: ModelRef): Promise<string | undefined> {\n return resolveProviderApiKey(\n model.providerId,\n model.providerConfig.apiKey,\n this.gatewayConfig,\n this.runtimeContext.agentDir,\n {\n resolveApiKeyForProvider: this.runtimeContext.resolveApiKeyForProvider,\n },\n );\n }\n\n /**\n * Call OpenAI-compatible API.\n */\n private async callOpenAI(\n config: ModelProviderConfig,\n modelId: string,\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: FallbackLlmOptions,\n assumeOpenAI: boolean,\n ): Promise<{ content: string; usage?: FallbackLlmResponse[\"usage\"] } | null> {\n const base = config.baseUrl.replace(/\\/$/, \"\");\n const url = base.endsWith(\"/v1\")\n ? `${base}/chat/completions`\n : `${base}/v1/chat/completions`;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n\n // Handle auth — apiKey is already resolved to a string by tryModel()\n if (config.apiKey && typeof config.apiKey === \"string\") {\n if (config.authHeader !== false) {\n headers[\"Authorization\"] = `Bearer ${config.apiKey}`;\n }\n }\n\n const body = {\n model: modelId,\n messages,\n ...buildChatCompletionTemperature(modelId, options.temperature ?? 0.3, {\n assumeOpenAI,\n }),\n ...buildChatCompletionTokenLimit(modelId, options.maxTokens ?? 4096, {\n assumeOpenAI,\n }),\n };\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n signal: options.signal,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${response.status} ${error}`);\n }\n\n const data = (await response.json()) as {\n choices: Array<{\n message: {\n content: string;\n };\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n };\n\n const content = data.choices?.[0]?.message?.content;\n if (!content) {\n throw new Error(\"Empty response from OpenAI API\");\n }\n\n return {\n content,\n usage: data.usage\n ? {\n inputTokens: data.usage.prompt_tokens,\n outputTokens: data.usage.completion_tokens,\n totalTokens: data.usage.total_tokens,\n }\n : undefined,\n };\n }\n\n /**\n * Call Ollama's native /api/chat transport. This lets benchmark-isolated\n * gateway configs route Remnic's own internal LLM calls to Ollama Cloud\n * without requiring an OpenAI-compatible shim.\n */\n private async callOllamaChat(\n config: ModelProviderConfig,\n modelId: string,\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: FallbackLlmOptions,\n ): Promise<{ content: string; usage?: FallbackLlmResponse[\"usage\"] } | null> {\n const base = config.baseUrl.replace(/\\/$/, \"\");\n const url = base.endsWith(\"/api\") ? `${base}/chat` : `${base}/api/chat`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n if (config.apiKey && typeof config.apiKey === \"string\" && config.authHeader !== false) {\n headers.Authorization = `Bearer ${config.apiKey}`;\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n signal: options.signal,\n body: JSON.stringify({\n model: modelId,\n messages,\n stream: false,\n ...(config.disableThinking ? { think: false } : {}),\n options: {\n temperature: options.temperature ?? 0.3,\n num_predict: options.maxTokens ?? 4096,\n },\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Ollama API error: ${response.status} ${error}`);\n }\n\n const data = (await response.json()) as {\n message?: { content?: string };\n response?: string;\n prompt_eval_count?: number;\n eval_count?: number;\n };\n const content = data.message?.content ?? data.response;\n if (!content) {\n throw new Error(\"Empty response from Ollama API\");\n }\n\n const inputTokens = data.prompt_eval_count ?? 0;\n const outputTokens = data.eval_count ?? 0;\n return {\n content,\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n },\n };\n }\n\n /**\n * Call an OpenAI-compatible Responses API.\n */\n private async callOpenAIResponses(\n config: ModelProviderConfig,\n modelId: string,\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: FallbackLlmOptions,\n ): Promise<{ content: string; usage?: FallbackLlmResponse[\"usage\"] } | null> {\n const base = config.baseUrl.replace(/\\/$/, \"\");\n const url = base.endsWith(\"/v1\")\n ? `${base}/responses`\n : `${base}/v1/responses`;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n\n if (config.apiKey && typeof config.apiKey === \"string\" && config.authHeader !== false) {\n headers[\"Authorization\"] = `Bearer ${config.apiKey}`;\n }\n\n const instructions = messages\n .filter((message) => message.role === \"system\")\n .map((message) => message.content)\n .join(\"\\n\\n\")\n .trim();\n const input = messages\n .filter((message) => message.role !== \"system\")\n .map((message) => ({\n role: message.role,\n content: [{\n type: message.role === \"assistant\" ? \"output_text\" : \"input_text\",\n text: message.content,\n }],\n }));\n\n const body: Record<string, unknown> = {\n model: modelId,\n input,\n max_output_tokens: Math.max(0, Math.floor(options.maxTokens ?? 4096)),\n ...buildChatCompletionTemperature(modelId, options.temperature ?? 0.3, {\n assumeOpenAI: shouldAssumeOpenAiChatCompletions(config.baseUrl),\n }),\n };\n if (instructions.length > 0) {\n body.instructions = instructions;\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n signal: options.signal,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI Responses API error: ${response.status} ${error}`);\n }\n\n const data = (await response.json()) as {\n output_text?: string;\n output?: Array<{\n type?: string;\n text?: string;\n content?: Array<{\n type?: string;\n text?: string;\n }>;\n }>;\n usage?: {\n input_tokens?: number;\n output_tokens?: number;\n total_tokens?: number;\n };\n };\n\n const outputText = extractResponsesOutputText(data);\n if (!outputText) {\n throw new Error(\"Empty response from OpenAI Responses API\");\n }\n\n return {\n content: outputText,\n usage: data.usage\n ? {\n inputTokens: data.usage.input_tokens,\n outputTokens: data.usage.output_tokens,\n totalTokens: data.usage.total_tokens,\n }\n : undefined,\n };\n }\n\n /**\n * Call Anthropic Messages API.\n */\n private async callAnthropic(\n config: ModelProviderConfig,\n modelId: string,\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: FallbackLlmOptions,\n ): Promise<{ content: string; usage?: FallbackLlmResponse[\"usage\"] } | null> {\n const base = config.baseUrl.replace(/\\/$/, \"\");\n const url = base.endsWith(\"/v1\")\n ? `${base}/messages`\n : `${base}/v1/messages`;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"anthropic-version\": \"2023-06-01\",\n ...config.headers,\n };\n\n // Handle auth - Anthropic uses x-api-key header (apiKey resolved by tryModel)\n if (config.apiKey && typeof config.apiKey === \"string\") {\n headers[\"x-api-key\"] = config.apiKey;\n }\n\n // Extract system message (Anthropic handles it separately)\n const systemMessage = messages.find((m) => m.role === \"system\")?.content;\n const nonSystemMessages = messages.filter((m) => m.role !== \"system\");\n\n // Convert messages to Anthropic format\n const anthropicMessages = nonSystemMessages.map((m) => ({\n role: m.role,\n content: m.content,\n }));\n\n const body: Record<string, unknown> = {\n model: modelId,\n messages: anthropicMessages,\n max_tokens: options.maxTokens ?? 4096,\n temperature: options.temperature ?? 0.3,\n };\n\n if (systemMessage) {\n body.system = systemMessage;\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n signal: options.signal,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Anthropic API error: ${response.status} ${error}`);\n }\n\n const data = (await response.json()) as {\n content: Array<{\n type: string;\n text: string;\n }>;\n usage?: {\n input_tokens?: number;\n output_tokens?: number;\n };\n };\n\n const content = data.content?.[0]?.text;\n if (!content) {\n throw new Error(\"Empty response from Anthropic API\");\n }\n\n return {\n content,\n usage: data.usage\n ? {\n inputTokens: data.usage.input_tokens,\n outputTokens: data.usage.output_tokens,\n totalTokens: (data.usage.input_tokens ?? 0) + (data.usage.output_tokens ?? 0),\n }\n : undefined,\n };\n }\n}\n\nfunction abortReason(signal: AbortSignal | undefined): Error {\n const reason = signal?.reason;\n return reason instanceof Error ? reason : new Error(\"fallback LLM request aborted\");\n}\n\nfunction normalizeRuntimePath(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? expandTildePath(trimmed) : undefined;\n}\n\nfunction readGatewayWorkspaceDir(gatewayConfig: GatewayConfig | undefined): string | undefined {\n if (!gatewayConfig || typeof gatewayConfig !== \"object\") return undefined;\n const raw = gatewayConfig as Record<string, unknown>;\n return (\n normalizeRuntimePath(raw.workspaceDir) ??\n normalizeRuntimePath(raw.workspacePath) ??\n normalizeRuntimePath(raw.workspace)\n );\n}\n\nfunction defaultOpenClawWorkspaceDir(): string {\n return path.join(resolveHomeDir(), \".openclaw\", \"workspace\");\n}\n\nfunction extractResponsesOutputText(data: {\n output_text?: string;\n output?: Array<{\n type?: string;\n text?: string;\n content?: Array<{\n type?: string;\n text?: string;\n }>;\n }>;\n}): string | null {\n if (typeof data.output_text === \"string\" && data.output_text.trim().length > 0) {\n return data.output_text;\n }\n\n const chunks: string[] = [];\n for (const item of data.output ?? []) {\n if (typeof item.text === \"string\" && item.text.trim().length > 0) {\n chunks.push(item.text);\n }\n for (const part of item.content ?? []) {\n if (\n (part.type === \"output_text\" || part.type === \"text\") &&\n typeof part.text === \"string\" &&\n part.text.trim().length > 0\n ) {\n chunks.push(part.text);\n }\n }\n }\n\n const joined = chunks.join(\"\\n\").trim();\n return joined.length > 0 ? joined : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AA8CV,SAAS,wBACd,QACoD;AACpD,MAAI,OAAO,gBAAgB,UAAW,QAAO,CAAC;AAC9C,MAAI,OAAO,eAAgB,QAAO,EAAE,YAAY,OAAO,eAAe;AACtE,SAAO,OAAO,iBAAiB,EAAE,SAAS,OAAO,eAAe,IAAI,CAAC;AACvE;AAmBO,SAAS,oCACd,QAIA,YAAuC,CAAC,GACb;AAC3B,SAAO;AAAA,IACL,cAAc,OAAO;AAAA,IACrB,0BAA0B,OAAO;AAAA,IACjC,wBAAwB,OAAO;AAAA,IAC/B,GAAG;AAAA,EACL;AACF;AAeA,IAAM,mBAAsD;AAAA,EAC1D,gBAAgB,CAAC,OAAO;AAAA,EACxB,OAAO,CAAC,cAAc;AAAA,EACtB,cAAc,CAAC,WAAW;AAC5B;AAEA,IAAM,sBAAsB,oBAAI,IA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E,SAAS,GAAG;AAC9E,WAAO,KAAK;AAAA,EACd;AAEA,QAAM,SAAmB,CAAC;AAC1B,aAAW,QAAQ,KAAK,UAAU,CAAC,GAAG;AACpC,QAAI,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,KAAK,EAAE,SAAS,GAAG;AAChE,aAAO,KAAK,KAAK,IAAI;AAAA,IACvB;AACA,eAAW,QAAQ,KAAK,WAAW,CAAC,GAAG;AACrC,WACG,KAAK,SAAS,iBAAiB,KAAK,SAAS,WAC9C,OAAO,KAAK,SAAS,YACrB,KAAK,KAAK,KAAK,EAAE,SAAS,GAC1B;AACA,eAAO,KAAK,KAAK,IAAI;AAAA,MACvB;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAS,OAAO,KAAK,IAAI,EAAE,KAAK;AACtC,SAAO,OAAO,SAAS,IAAI,SAAS;AACtC;","names":[]}
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-SFQ6QNL7.js";
|
|
7
7
|
import {
|
|
8
8
|
StorageManager
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-RIC5U67B.js";
|
|
10
10
|
import {
|
|
11
11
|
buildLifecycleEventsForMemory,
|
|
12
12
|
sortMemoryLifecycleEvents
|
|
@@ -74,4 +74,4 @@ export {
|
|
|
74
74
|
backupExistingLedger,
|
|
75
75
|
rebuildMemoryLifecycleLedger
|
|
76
76
|
};
|
|
77
|
-
//# sourceMappingURL=chunk-
|
|
77
|
+
//# sourceMappingURL=chunk-A62RAIBN.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
StorageManager
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-RIC5U67B.js";
|
|
4
4
|
import {
|
|
5
5
|
assertPathInsideRoot
|
|
6
6
|
} from "./chunk-5GPPACXK.js";
|
|
@@ -751,4 +751,4 @@ export {
|
|
|
751
751
|
listMemoryGovernanceRuns,
|
|
752
752
|
readMemoryGovernanceRunArtifact
|
|
753
753
|
};
|
|
754
|
-
//# sourceMappingURL=chunk-
|
|
754
|
+
//# sourceMappingURL=chunk-ANZLT74L.js.map
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
compareEntityTimestamps,
|
|
6
6
|
normalizeEntityName
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-RIC5U67B.js";
|
|
8
8
|
import {
|
|
9
9
|
sanitizeMemoryContent
|
|
10
10
|
} from "./chunk-FVQJYWH7.js";
|
|
@@ -679,4 +679,4 @@ export {
|
|
|
679
679
|
entityIndexVersion,
|
|
680
680
|
entityRecentTranscriptLookbackHours
|
|
681
681
|
};
|
|
682
|
-
//# sourceMappingURL=chunk-
|
|
682
|
+
//# sourceMappingURL=chunk-COEZR6F5.js.map
|
|
@@ -3,12 +3,12 @@ import {
|
|
|
3
3
|
} from "./chunk-JI6HWBYL.js";
|
|
4
4
|
import {
|
|
5
5
|
defineOperation
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-XL5RSHZP.js";
|
|
7
7
|
import {
|
|
8
8
|
DECISION_SUBCOMMANDS,
|
|
9
9
|
DELTA_SUBCOMMANDS,
|
|
10
10
|
isCodegraphToolName
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-XFG3PVZE.js";
|
|
12
12
|
|
|
13
13
|
// src/access-operations.ts
|
|
14
14
|
import { z } from "zod";
|
|
@@ -378,4 +378,4 @@ export {
|
|
|
378
378
|
codegraphIngestTracesOperation,
|
|
379
379
|
REGISTERED_OPERATIONS
|
|
380
380
|
};
|
|
381
|
-
//# sourceMappingURL=chunk-
|
|
381
|
+
//# sourceMappingURL=chunk-CQ4PGFMC.js.map
|
|
@@ -10,17 +10,10 @@ import {
|
|
|
10
10
|
import {
|
|
11
11
|
listMemoryGovernanceRuns,
|
|
12
12
|
readMemoryGovernanceRunArtifact
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-ANZLT74L.js";
|
|
14
14
|
import {
|
|
15
15
|
StorageManager
|
|
16
|
-
} from "./chunk-
|
|
17
|
-
import {
|
|
18
|
-
MEMORY_LIFECYCLE_EVENT_SORT_ORDER,
|
|
19
|
-
buildLifecycleEventsForMemory,
|
|
20
|
-
inferMemoryStatus,
|
|
21
|
-
sortMemoryLifecycleEvents,
|
|
22
|
-
toMemoryPathRel
|
|
23
|
-
} from "./chunk-RULE4VG5.js";
|
|
16
|
+
} from "./chunk-RIC5U67B.js";
|
|
24
17
|
import {
|
|
25
18
|
normalizeProjectionPreview,
|
|
26
19
|
normalizeProjectionTags
|
|
@@ -39,6 +32,13 @@ import {
|
|
|
39
32
|
import {
|
|
40
33
|
openBetterSqlite3
|
|
41
34
|
} from "./chunk-6KYMPV2O.js";
|
|
35
|
+
import {
|
|
36
|
+
MEMORY_LIFECYCLE_EVENT_SORT_ORDER,
|
|
37
|
+
buildLifecycleEventsForMemory,
|
|
38
|
+
inferMemoryStatus,
|
|
39
|
+
sortMemoryLifecycleEvents,
|
|
40
|
+
toMemoryPathRel
|
|
41
|
+
} from "./chunk-RULE4VG5.js";
|
|
42
42
|
|
|
43
43
|
// src/maintenance/rebuild-memory-projection.ts
|
|
44
44
|
import path from "path";
|
|
@@ -929,4 +929,4 @@ export {
|
|
|
929
929
|
verifyMemoryProjection,
|
|
930
930
|
repairMemoryProjection
|
|
931
931
|
};
|
|
932
|
-
//# sourceMappingURL=chunk-
|
|
932
|
+
//# sourceMappingURL=chunk-E6GOVHHJ.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
StorageManager,
|
|
3
3
|
normalizeEntityName
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-RIC5U67B.js";
|
|
5
5
|
import {
|
|
6
6
|
extractJsonCandidates
|
|
7
7
|
} from "./chunk-RGMVMVMF.js";
|
|
@@ -870,4 +870,4 @@ export {
|
|
|
870
870
|
resolveBriefingSaveDir,
|
|
871
871
|
briefingFilename
|
|
872
872
|
};
|
|
873
|
-
//# sourceMappingURL=chunk-
|
|
873
|
+
//# sourceMappingURL=chunk-EZWQZYLK.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
gatewayTaskChainOptions
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-5J4OL7TJ.js";
|
|
4
4
|
import {
|
|
5
5
|
extractJsonCandidates
|
|
6
6
|
} from "./chunk-RGMVMVMF.js";
|
|
@@ -372,9 +372,15 @@ function overlapCoefficient(a, b) {
|
|
|
372
372
|
return intersection / small.size;
|
|
373
373
|
}
|
|
374
374
|
var LOCATE_QUOTE_MIN_OVERLAP = 0.3;
|
|
375
|
-
function extractContextWindow(sourceText, quote, contextChars) {
|
|
375
|
+
function extractContextWindow(sourceText, quote, contextChars, matchedOffset) {
|
|
376
376
|
if (!sourceText || !quote || !(contextChars > 0)) return void 0;
|
|
377
|
-
|
|
377
|
+
let idx;
|
|
378
|
+
if (matchedOffset !== void 0 && matchedOffset >= 0) {
|
|
379
|
+
const at = sourceText.indexOf(quote, matchedOffset);
|
|
380
|
+
idx = at >= 0 ? at : sourceText.indexOf(quote);
|
|
381
|
+
} else {
|
|
382
|
+
idx = sourceText.indexOf(quote);
|
|
383
|
+
}
|
|
378
384
|
if (idx < 0) return void 0;
|
|
379
385
|
const quoteEnd = idx + quote.length;
|
|
380
386
|
const center = Math.floor((idx + quoteEnd) / 2);
|
|
@@ -385,23 +391,96 @@ function extractContextWindow(sourceText, quote, contextChars) {
|
|
|
385
391
|
const window = sourceText.slice(start, end).trim();
|
|
386
392
|
return window.length > 0 ? window : void 0;
|
|
387
393
|
}
|
|
394
|
+
function splitSourceCandidates(sourceText) {
|
|
395
|
+
const candidates = [];
|
|
396
|
+
const re = /(?<=[.!?])\s+|\n+/g;
|
|
397
|
+
let lastEnd = 0;
|
|
398
|
+
let m;
|
|
399
|
+
while ((m = re.exec(sourceText)) !== null) {
|
|
400
|
+
pushCandidate(candidates, sourceText, lastEnd, m.index);
|
|
401
|
+
lastEnd = re.lastIndex;
|
|
402
|
+
}
|
|
403
|
+
pushCandidate(candidates, sourceText, lastEnd, sourceText.length);
|
|
404
|
+
return candidates;
|
|
405
|
+
}
|
|
406
|
+
function pushCandidate(out, source, begin, end) {
|
|
407
|
+
const seg = source.slice(begin, end);
|
|
408
|
+
const leadingWS = seg.length - seg.trimStart().length;
|
|
409
|
+
const trimmed = seg.trim();
|
|
410
|
+
if (trimmed.length > 0) {
|
|
411
|
+
out.push({ text: trimmed, start: begin + leadingWS });
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
function locateMatchedTokens(factTokens, candidate) {
|
|
415
|
+
const lower = candidate.toLowerCase();
|
|
416
|
+
const wordRe = /[a-z0-9]+/g;
|
|
417
|
+
const positions = [];
|
|
418
|
+
let m;
|
|
419
|
+
while ((m = wordRe.exec(lower)) !== null) {
|
|
420
|
+
const word = m[0];
|
|
421
|
+
if (word.length <= 1) continue;
|
|
422
|
+
if (STOPWORDS.has(word)) continue;
|
|
423
|
+
if (factTokens.has(crudeStem(word))) {
|
|
424
|
+
positions.push(m.index);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return positions;
|
|
428
|
+
}
|
|
429
|
+
function boundedWindow(text, matchedPositions, maxChars) {
|
|
430
|
+
if (matchedPositions.length === 0) {
|
|
431
|
+
const end2 = Math.min(text.length, maxChars);
|
|
432
|
+
return { text: text.slice(0, end2), start: 0 };
|
|
433
|
+
}
|
|
434
|
+
let bestAnchor = matchedPositions[0];
|
|
435
|
+
let bestCount = 0;
|
|
436
|
+
let bestLast = bestAnchor;
|
|
437
|
+
let j = 0;
|
|
438
|
+
for (let i = 0; i < matchedPositions.length; i++) {
|
|
439
|
+
const anchor = matchedPositions[i];
|
|
440
|
+
const winEnd = anchor + maxChars;
|
|
441
|
+
if (j < i) j = i;
|
|
442
|
+
while (j + 1 < matchedPositions.length && matchedPositions[j + 1] < winEnd) {
|
|
443
|
+
j++;
|
|
444
|
+
}
|
|
445
|
+
const count = j - i + 1;
|
|
446
|
+
if (count > bestCount) {
|
|
447
|
+
bestCount = count;
|
|
448
|
+
bestAnchor = anchor;
|
|
449
|
+
bestLast = matchedPositions[j];
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
const center = Math.floor((bestAnchor + bestLast) / 2);
|
|
453
|
+
const half = Math.floor(maxChars / 2);
|
|
454
|
+
let start = Math.max(0, center - half);
|
|
455
|
+
const end = Math.min(text.length, start + maxChars);
|
|
456
|
+
start = Math.max(0, end - maxChars);
|
|
457
|
+
return { text: text.slice(start, end), start };
|
|
458
|
+
}
|
|
388
459
|
function locateFactQuote(factText, sourceText, maxQuoteChars = 600) {
|
|
389
460
|
if (!factText || !sourceText) return void 0;
|
|
390
461
|
const factTokens = tokenize(factText);
|
|
391
462
|
if (factTokens.size === 0) return void 0;
|
|
392
|
-
const candidates =
|
|
393
|
-
for (const sentence of sourceText.split(/(?<=[.!?])\s+|\n+/)) {
|
|
394
|
-
const s = sentence.trim();
|
|
395
|
-
if (s.length > 0) candidates.push(s);
|
|
396
|
-
}
|
|
463
|
+
const candidates = splitSourceCandidates(sourceText);
|
|
397
464
|
if (candidates.length === 0) return void 0;
|
|
398
465
|
let best = null;
|
|
399
|
-
for (
|
|
400
|
-
const
|
|
401
|
-
|
|
466
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
467
|
+
const candidate = candidates[i];
|
|
468
|
+
const score = overlapCoefficient(factTokens, tokenize(candidate.text));
|
|
469
|
+
const prevText = i > 0 ? candidates[i - 1].text : "";
|
|
470
|
+
const contextText = prevText ? `${prevText} ${candidate.text}` : candidate.text;
|
|
471
|
+
const contextScore = overlapCoefficient(factTokens, tokenize(contextText));
|
|
472
|
+
if (!best || score > best.score || score === best.score && contextScore > best.contextScore) {
|
|
473
|
+
best = { candidate, score, contextScore };
|
|
474
|
+
}
|
|
402
475
|
}
|
|
403
476
|
if (!best || best.score < LOCATE_QUOTE_MIN_OVERLAP) return void 0;
|
|
404
|
-
|
|
477
|
+
const { text, start } = best.candidate;
|
|
478
|
+
if (text.length <= maxQuoteChars) {
|
|
479
|
+
return { quote: text, offset: start };
|
|
480
|
+
}
|
|
481
|
+
const matched = locateMatchedTokens(factTokens, text);
|
|
482
|
+
const win = boundedWindow(text, matched, maxQuoteChars);
|
|
483
|
+
return { quote: win.text, offset: start + win.start };
|
|
405
484
|
}
|
|
406
485
|
async function runFaithfulnessGateBatch(facts, mode, config, localLlm, fallbackLlm, counters, sourceText = "") {
|
|
407
486
|
const inputs = [];
|
|
@@ -411,12 +490,21 @@ async function runFaithfulnessGateBatch(facts, mode, config, localLlm, fallbackL
|
|
|
411
490
|
const sources = Array.isArray(f.sources) ? f.sources : [];
|
|
412
491
|
const sourceQuotes = sources.map((s) => s && typeof s.quote === "string" ? s.quote.trim() : "").filter((q) => q.length > 0);
|
|
413
492
|
const usingFallbackLocator = sourceQuotes.length === 0;
|
|
414
|
-
|
|
415
|
-
|
|
493
|
+
let quote;
|
|
494
|
+
let matchedOffset;
|
|
495
|
+
if (sourceQuotes.length > 0) {
|
|
496
|
+
quote = sourceQuotes.join("\n");
|
|
497
|
+
} else {
|
|
498
|
+
const located = locateFactQuote(f.content, sourceText);
|
|
499
|
+
if (!located) continue;
|
|
500
|
+
quote = located.quote;
|
|
501
|
+
matchedOffset = located.offset;
|
|
502
|
+
}
|
|
416
503
|
const fallbackContext = usingFallbackLocator ? extractContextWindow(
|
|
417
504
|
sourceText,
|
|
418
505
|
quote,
|
|
419
|
-
config.extractionFaithfulnessContextChars
|
|
506
|
+
config.extractionFaithfulnessContextChars,
|
|
507
|
+
matchedOffset
|
|
420
508
|
) : void 0;
|
|
421
509
|
inputs.push({
|
|
422
510
|
factIndex: fi,
|
|
@@ -550,4 +638,4 @@ export {
|
|
|
550
638
|
serializeFaithfulnessFields,
|
|
551
639
|
parseFaithfulnessField
|
|
552
640
|
};
|
|
553
|
-
//# sourceMappingURL=chunk-
|
|
641
|
+
//# sourceMappingURL=chunk-FEB7W5JG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/extraction-faithfulness.ts"],"sourcesContent":["/**\n * Extraction faithfulness gate — entailment verification of extracted\n * facts against their verified source spans (issue #1576).\n *\n * Part of #1572 (glass-box memory). Depends on #1575 (provenance spans).\n * Improved later by #1585 (fine-tuned local gate model).\n *\n * Unlike the extraction-judge (#376), which gates on fact-worthiness\n * (\"is this worth remembering?\"), this module gates on faithfulness\n * (\"is this fact actually supported by what was said?\"). Hallucinated\n * or mis-paraphrased extractions become durable memories, get recalled\n * with confidence, and poison downstream answers — the highest-severity\n * accuracy failure a memory system can have.\n *\n * Design constraints:\n * - Tagged results only — a backend failure is distinguishable from a\n * genuine verdict (rule 34 / checklist §22: never conflate \"empty\"\n * with \"failed\").\n * - The gate consumes the QUOTE, not the whole conversation — passing\n * full turns re-introduces the hallucination surface you're guarding\n * and blows the latency budget.\n * - No module-level state — batch queues hang off the orchestrator\n * instance (rule 11).\n * - Byte-identical pre-feature pipeline when mode is \"off\" (rule 39).\n * - Graceful degradation — a backend failure never blocks writes\n * (checklist §4); the fact proceeds with verdict \"unchecked\".\n * - Never mutate mw_*\\/trust fields — faithfulness is its own\n * frontmatter island consumed by #1577.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { log } from \"./logger.js\";\nimport type { PluginConfig, MemoryFrontmatter, FaithfulnessFrontmatter } from \"./types.js\";\nimport type { LocalLlmClient } from \"./local-llm.js\";\nimport { type FallbackLlmClient, gatewayTaskChainOptions } from \"./fallback-llm.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\n\n// Re-export for callers importing from this module.\nexport type { FaithfulnessFrontmatter } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * The three entailment verdicts. \"unchecked\" is NOT a member of this union —\n * it lives only in the frontmatter to mark facts that bypassed the gate\n * (backend failure, no span, mode=off). A real verdict is always one of\n * these three.\n */\nexport type FaithfulnessVerdict = \"entailed\" | \"contradicted\" | \"unsupported\";\n\n/**\n * Failure codes for tagged-error results. Each is distinguishable so callers\n * and telemetry can tell \"no span available\" from \"the backend was down\".\n */\nexport type FaithfulnessFailureCode =\n | \"no_span\"\n | \"backend_unavailable\"\n | \"malformed_output\"\n | \"timeout\";\n\n/**\n * Tagged result — success carries the verdict + model + optional rationale;\n * failure carries only the error code. Never conflate the two (rule 34).\n */\nexport type FaithfulnessResult =\n | { ok: true; verdict: FaithfulnessVerdict; model: string; rationale?: string }\n | { ok: false; error: { code: FaithfulnessFailureCode } };\n\n/**\n * Input for a single faithfulness check. The quote is the verified span from\n * #1575; context is optional surrounding turn text (bounded by\n * faithfulnessContextChars).\n */\nexport interface FaithfulnessCheckInput {\n factText: string;\n quote: string;\n context?: string;\n}\n\n/**\n * Shape persisted to frontmatter (issue #1576). Serialized as a single JSON\n * line so it round-trips through the existing YAML parser without special\n * handling.\n *\n * `verdict: \"unchecked\"` marks a fact that entered the gate but could not be\n * evaluated (backend failure, timeout). It is distinct from the field being\n * absent (which means the gate was off entirely or the fact predates #1576).\n */\n\n// ---------------------------------------------------------------------------\n// Sealed prompt (hash lets #1573-style caching key on it)\n// ---------------------------------------------------------------------------\n\nconst FAITHFULNESS_SYSTEM_PROMPT = `You are a faithfulness verifier for a memory system. Given a QUOTE from the source conversation and an extracted FACT, determine whether the FACT is supported by the QUOTE.\n\nRules:\n- \"entailed\" — the FACT directly follows from the QUOTE (paraphrase is OK).\n- \"contradicted\" — the FACT asserts something the QUOTE directly negates.\n- \"unsupported\" — the FACT introduces information not present in the QUOTE.\n\nAnswer with a JSON array. Each element: {\"index\": <int>, \"verdict\": \"entailed\"|\"contradicted\"|\"unsupported\", \"rationale\": \"<one sentence>\"}.\n\nExamples:\nQUOTE: \"I've been using Vim for about ten years now.\"\nFACT: \"The user has used Vim for approximately a decade.\"\n{\"index\": 0, \"verdict\": \"entailed\", \"rationale\": \"Paraphrase of the same duration.\"}\n\nQUOTE: \"I've been using Vim for about ten years now.\"\nFACT: \"The user prefers Emacs.\"\n{\"index\": 0, \"verdict\": \"unsupported\", \"rationale\": \"QUOTE mentions Vim, not Emacs.\"}\n\nQUOTE: \"I stopped drinking coffee last month.\"\nFACT: \"The user drinks coffee regularly.\"\n{\"index\": 0, \"verdict\": \"contradicted\", \"rationale\": \"QUOTE says they stopped; FACT claims the opposite.\"}`;\n\n/**\n * SHA-256 hash of the sealed system prompt. Cache keys and prompt-version\n * telemetry include this so a prompt change is detectable (#1573-style\n * caching can invalidate stale entries).\n */\nexport const FAITHFULNESS_PROMPT_HASH = createHash(\"sha256\")\n .update(FAITHFULNESS_SYSTEM_PROMPT)\n .digest(\"hex\");\n\n// ---------------------------------------------------------------------------\n// Prompt construction\n// ---------------------------------------------------------------------------\n\n/**\n * Build the user-prompt payload for a batch of (fact, quote) pairs.\n * Each pair is numbered so the LLM's response can be correlated back.\n *\n * Context (when provided) is included after the quote, clearly delimited,\n * so the model knows it is supplementary — not the primary evidence.\n */\nfunction buildBatchPrompt(inputs: FaithfulnessCheckInput[], contextChars: number): string {\n const parts: string[] = [];\n for (let i = 0; i < inputs.length; i++) {\n const inp = inputs[i];\n if (!inp) continue;\n // The QUOTE is the primary entailment evidence and is already bounded\n // upstream (provenance.maxQuoteChars / locateFactQuote). Send it whole\n // so the verifier never judges entailment on a truncated span. Only the\n // supplementary CONTEXT is bounded by contextChars (the config's \"window\n // around the quote\" semantics — cursor review).\n parts.push(`--- Item ${i} ---\nQUOTE: \"${inp.quote}\"`);\n if (inp.context && inp.context.trim().length > 0) {\n parts.push(`CONTEXT: \"${inp.context.slice(0, contextChars)}\"`);\n }\n parts.push(`FACT: \"${inp.factText}\"\n\nRespond with the JSON array entry for index ${i}.`);\n }\n parts.push(`\\nRespond now with a single JSON array covering indexes 0–${inputs.length - 1}.`);\n return parts.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Response parsing\n// ---------------------------------------------------------------------------\n\nconst VALID_VERDICTS = new Set<string>([\"entailed\", \"contradicted\", \"unsupported\"]);\n\n/**\n * Parsed LLM response entry — validated shape.\n */\ninterface ParsedFaithfulnessEntry {\n index: number;\n verdict: FaithfulnessVerdict;\n rationale?: string;\n}\n\n/**\n * Parse the LLM response into a map of index → entry. Returns null when the\n * response is unparseable (rules 13/18: malformed output → tagged error,\n * never a crash).\n *\n * Accepts both a bare JSON array and a JSON array embedded in surrounding\n * text (the `extractJsonCandidates` helper handles fenced blocks and\n * code-block-wrapped JSON).\n */\nexport function parseFaithfulnessResponse(\n raw: string,\n expectedCount: number,\n): Map<number, ParsedFaithfulnessEntry> | null {\n if (!raw || typeof raw !== \"string\" || raw.trim().length === 0) {\n return null;\n }\n\n const candidates = extractJsonCandidates(raw);\n for (const candidate of candidates) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(candidate);\n } catch {\n continue;\n }\n const map = parseEntries(parsed, expectedCount);\n if (map) return map;\n }\n\n // Last resort: the model may have returned bare objects without array\n // wrapping — try parsing the whole thing as a single entry.\n try {\n const single = JSON.parse(raw.trim());\n const map = parseEntries([single], expectedCount);\n if (map) return map;\n } catch {\n // fall through\n }\n\n return null;\n}\n\nfunction parseEntries(\n data: unknown,\n expectedCount: number,\n): Map<number, ParsedFaithfulnessEntry> | null {\n if (!Array.isArray(data)) {\n // Accept object-wrapped arrays — {\"results\":[...]}, {\"verdicts\":[...]},\n // {\"entries\":[...]}, {\"facts\":[...]} — a common JSON-object prompt shape the\n // extraction-judge parser already accepts. Rejecting them marked the whole\n // batch malformed_output; in enforce mode those facts then wrote as ACTIVE\n // (gate bypass — codex Ob4RO).\n if (data && typeof data === \"object\") {\n for (const key of [\"results\", \"verdicts\", \"entries\", \"facts\"]) {\n const inner = (data as Record<string, unknown>)[key];\n if (Array.isArray(inner)) return parseEntries(inner, expectedCount);\n }\n }\n return null;\n }\n const map = new Map<number, ParsedFaithfulnessEntry>();\n for (const entry of data) {\n if (!entry || typeof entry !== \"object\") continue;\n const obj = entry as Record<string, unknown>;\n const idx = typeof obj.index === \"number\" ? obj.index : undefined;\n if (idx === undefined || idx < 0 || idx >= expectedCount) continue;\n const verdictRaw = typeof obj.verdict === \"string\" ? obj.verdict : undefined;\n if (!verdictRaw || !VALID_VERDICTS.has(verdictRaw)) continue;\n const rationale =\n typeof obj.rationale === \"string\" && obj.rationale.trim().length > 0\n ? obj.rationale.trim().slice(0, 500)\n : undefined;\n map.set(idx, {\n index: idx,\n verdict: verdictRaw as FaithfulnessVerdict,\n rationale,\n });\n }\n return map.size > 0 ? map : null;\n}\n\n// ---------------------------------------------------------------------------\n// LLM call helper\n// ---------------------------------------------------------------------------\n\ninterface LlmCallResult {\n content: string | null;\n modelUsed: string | null;\n}\n\n/**\n * Call the model routing chain (local → fallback) with the faithfulness\n * classification prompt. Mirrors `callJudgeLlm` in extraction-judge.ts so\n * the same routing, model-override, and gateway-chain logic applies.\n *\n * Returns the raw content string and the model that produced it, or\n * `{ content: null, modelUsed: null }` when every backend is unavailable.\n */\nasync function callFaithfulnessLlm(\n systemPrompt: string,\n userPrompt: string,\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<LlmCallResult> {\n const messages: Array<{ role: \"system\" | \"user\"; content: string }> = [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: userPrompt },\n ];\n\n const modelOverride = config.extractionFaithfulnessModel || undefined;\n\n // Skip the local backend when (a) modelSource is \"gateway\", or (b) a\n // faithfulness model override is set. The local client always sends\n // config.localLlmModel and silently ignores options.model, so a local\n // success would run the wrong model and prevent the override from ever\n // reaching the gateway. Routing straight to the gateway honors the\n // override (codex review PRRT_kwDORJXyws6ObYQ8).\n const skipLocal = config.modelSource === \"gateway\" || Boolean(modelOverride);\n const gatewayChain = gatewayTaskChainOptions(config);\n\n let modelUsed: string | null = null;\n\n // Try local LLM first (only when no override routes the call to gateway).\n // The local client uses its OWN per-attempt AbortController keyed on\n // `timeoutMs` (it does not read options.signal — see LocalLlmChatCompletionOptions),\n // so the batch `signal` is not forwarded here; `timeoutMs` bounds each local\n // attempt instead. The batch AbortController still governs the fallback path,\n // which DOES honor the signal. (Matches extraction-judge.ts, which also passes\n // no signal to the local client.)\n if (localLlm && !skipLocal) {\n try {\n const result = await callLocalLlm(localLlm, messages, {\n temperature: 0.1,\n maxTokens: 2048,\n responseFormat: { type: \"json_object\" },\n timeoutMs,\n operation: \"extraction-faithfulness\",\n });\n if (result.content) {\n return { content: result.content, modelUsed: result.modelUsed ?? \"local\" };\n }\n } catch (err) {\n log.debug(\n `extraction-faithfulness: local LLM failed, trying fallback: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n // Try fallback LLM\n if (fallbackLlm) {\n try {\n const result = await fallbackLlm.chatCompletion(\n messages as Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n {\n temperature: 0.1,\n maxTokens: 2048,\n timeoutMs,\n ...(modelOverride ? { model: modelOverride } : {}),\n ...gatewayChain,\n ...(signal ? { signal } : {}),\n },\n );\n if (result?.content) {\n return { content: result.content, modelUsed: result.modelUsed ?? \"fallback\" };\n }\n } catch (err) {\n log.debug(\n `extraction-faithfulness: fallback LLM failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n return { content: null, modelUsed: null };\n}\n\n/**\n * Call the local LLM's chatCompletion through a narrow, typed interface.\n * LocalLlmClient.chatCompletion accepts an options bag that includes an\n * `operation` discriminator; we forward it so the client can route\n * appropriately.\n */\ninterface LocalLlmCallOptions {\n temperature: number;\n maxTokens: number;\n responseFormat?: { type: string };\n timeoutMs: number;\n operation: string;\n}\n\ninterface LocalLlmCallResponse {\n content: string | null;\n modelUsed?: string;\n}\n\nasync function callLocalLlm(\n client: LocalLlmClient,\n messages: Array<{ role: \"system\" | \"user\"; content: string }>,\n options: LocalLlmCallOptions,\n): Promise<LocalLlmCallResponse> {\n // LocalLlmClient.chatCompletion returns { content: string } — we use a\n // typed call signature so no `any` leaks. The local client does not\n // expose modelUsed, so we return \"local\" as the model identifier.\n const result = await client.chatCompletion(messages, options);\n return {\n content: result?.content ?? null,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Core batch check\n// ---------------------------------------------------------------------------\n\n/**\n * Result of a batch faithfulness check — per-input results plus timing.\n */\nexport interface FaithfulnessBatchResult {\n results: FaithfulnessResult[];\n /** Wall-clock duration of the LLM call (0 when backend was not called). */\n elapsedMs: number;\n}\n\n/**\n * Evaluate a batch of (fact, quote) pairs for faithfulness.\n *\n * - Calls the LLM once with all pairs (bounded by `inputs.length`).\n * - On timeout → every input gets `{ ok: false, code: \"timeout\" }`.\n * - On backend unavailable → `{ ok: false, code: \"backend_unavailable\" }`.\n * - On malformed output → `{ ok: false, code: \"malformed_output\" }`.\n * - Inputs with empty quotes get `{ ok: false, code: \"no_span\" }` and are\n * NOT sent to the LLM.\n *\n * No module-level state: the caller (orchestrator) owns any caches.\n */\nexport async function checkFaithfulnessBatch(\n inputs: FaithfulnessCheckInput[],\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n): Promise<FaithfulnessBatchResult> {\n const timeoutMs =\n typeof config.extractionFaithfulnessTimeoutMs === \"number\" &&\n Number.isFinite(config.extractionFaithfulnessTimeoutMs) &&\n config.extractionFaithfulnessTimeoutMs > 0\n ? config.extractionFaithfulnessTimeoutMs\n : 8000;\n\n const contextChars =\n typeof config.extractionFaithfulnessContextChars === \"number\" &&\n Number.isFinite(config.extractionFaithfulnessContextChars) &&\n config.extractionFaithfulnessContextChars > 0\n ? config.extractionFaithfulnessContextChars\n : 400;\n\n // Partition: inputs with a real quote vs. inputs without one.\n const results: FaithfulnessResult[] = new Array(inputs.length);\n const checkableIndices: number[] = [];\n const checkableInputs: FaithfulnessCheckInput[] = [];\n\n for (let i = 0; i < inputs.length; i++) {\n const inp = inputs[i];\n if (!inp || !inp.quote || inp.quote.trim().length === 0) {\n results[i] = { ok: false, error: { code: \"no_span\" } };\n } else if (!inp.factText || inp.factText.trim().length === 0) {\n results[i] = { ok: false, error: { code: \"no_span\" } };\n } else {\n checkableIndices.push(i);\n checkableInputs.push(inp);\n }\n }\n\n if (checkableInputs.length === 0) {\n return { results, elapsedMs: 0 };\n }\n\n const userPrompt = buildBatchPrompt(checkableInputs, contextChars);\n const startedAt = Date.now();\n\n let timedOut = false;\n const controller = new AbortController();\n // Race the LLM call against the budget so the batch fails open at\n // `timeoutMs` regardless of which backend is in flight. The local backend\n // ignores the batch AbortSignal (it aborts each attempt via its own\n // controller keyed on `timeoutMs`), so awaiting callFaithfulnessLlm directly\n // could block past the budget on a slow/retrying local verifier. The timer\n // both aborts the fallback (which honors the signal) and resolves the race\n // so the batch returns promptly; the in-flight local call aborts on its own\n // per-attempt timeoutMs. (codex review PRRT_kwDORJXyws6ObgMJ.)\n // Manual deferred instead of Promise.withResolvers (ES2024) — plugin-openclaw's\n // standalone tsconfig targets ES2022 lib and this module is reachable from its\n // type graph, so withResolvers would TS2550 there.\n let resolveTimeout!: (value: true) => void;\n const racedTimeout = new Promise<true>((resolve) => {\n resolveTimeout = resolve;\n });\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n resolveTimeout(true);\n }, timeoutMs);\n\n try {\n const callPromise = callFaithfulnessLlm(\n FAITHFULNESS_SYSTEM_PROMPT,\n userPrompt,\n config,\n localLlm,\n fallbackLlm,\n timeoutMs,\n controller.signal,\n );\n const settled = await Promise.race([\n callPromise.then(\n (r) => ({ done: true as const, result: r }),\n // An unexpected throw is treated as \"no content\" (backend_unavailable)\n // so the race never rejects and the outer catch is the final safety net.\n () => ({ done: true as const, result: { content: null, modelUsed: null } }),\n ),\n racedTimeout.then(() => ({ done: false as const })),\n ]);\n const elapsedMs = Date.now() - startedAt;\n\n if (!settled.done) {\n // The budget elapsed before any backend returned content. Fail open as\n // timeout; the orphaned callPromise resolves/rejects harmlessly (the\n // fallback was aborted; the local client aborts on its own timeoutMs).\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"timeout\" } };\n }\n return { results, elapsedMs };\n }\n\n const llmResult = settled.result;\n\n // Cursor review: if the LLM returned usable content, use it even when\n // the abort timer raced — a response that lands just as the timer fires\n // has real verdicts. Only fall back to timeout errors when there is no\n // content to parse (the call genuinely did not complete in time).\n if (timedOut && !llmResult.content) {\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"timeout\" } };\n }\n return { results, elapsedMs };\n }\n\n if (!llmResult.content) {\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"backend_unavailable\" } };\n }\n return { results, elapsedMs };\n }\n\n const parsed = parseFaithfulnessResponse(llmResult.content, checkableInputs.length);\n if (!parsed) {\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"malformed_output\" } };\n }\n return { results, elapsedMs };\n }\n\n for (let j = 0; j < checkableIndices.length; j++) {\n const inputIdx = checkableIndices[j];\n if (inputIdx === undefined) continue;\n const entry = parsed.get(j);\n if (entry) {\n results[inputIdx] = {\n ok: true,\n verdict: entry.verdict,\n model: llmResult.modelUsed ?? \"unknown\",\n ...(entry.rationale ? { rationale: entry.rationale } : {}),\n };\n } else {\n // LLM response was missing this index\n results[inputIdx] = { ok: false, error: { code: \"malformed_output\" } };\n }\n }\n\n return { results, elapsedMs };\n } catch (err) {\n const elapsedMs = Date.now() - startedAt;\n if (timedOut || isAbortError(err)) {\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"timeout\" } };\n }\n return { results, elapsedMs };\n }\n log.warn(\n `extraction-faithfulness: batch check threw unexpectedly: ${err instanceof Error ? err.message : String(err)}`,\n );\n for (const idx of checkableIndices) {\n results[idx] = { ok: false, error: { code: \"backend_unavailable\" } };\n }\n return { results, elapsedMs };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const maybe = err as { name?: string; message?: string };\n return (\n maybe.name === \"AbortError\" ||\n maybe.message === \"This operation was aborted\" ||\n maybe.message === \"The operation was aborted\"\n );\n}\n\n\n// ---------------------------------------------------------------------------\n// Extraction-path orchestration helpers (issue #1576)\n//\n// These wrap checkFaithfulnessBatch + verdict application so the orchestrator\n// holds only thin delegation (ground rule 4: god files gain thin wiring only).\n// The core algorithm lives above; these are call-site glue.\n// ---------------------------------------------------------------------------\n\n/**\n * Telemetry counters for the faithfulness gate. Hang off the orchestrator\n * instance (rule 11: no module-level state) and surface via console_state so\n * `remnic doctor` renders the verdict distribution.\n */\nexport interface FaithfulnessGateCounters {\n entailed: number;\n contradicted: number;\n unsupported: number;\n unchecked: number;\n skippedNoSpan: number;\n}\n\n/**\n * Create a fresh zeroed counters object. Callers store it on the orchestrator\n * instance and pass it by reference to the gate helpers, which mutate it.\n */\nexport function createFaithfulnessCounters(): FaithfulnessGateCounters {\n return { entailed: 0, contradicted: 0, unsupported: 0, unchecked: 0, skippedNoSpan: 0 };\n}\n\n/**\n * Structural slice of an extracted fact that the gate reads. Kept loose so\n * this pure module does not depend on the full `ExtractedFact` type.\n */\nexport interface FaithfulnessGateFact {\n content: string;\n sources?: { quote?: string }[];\n}\n\n/**\n * Run the faithfulness batch over a list of extracted facts and return a map\n * keyed by the ORIGINAL fact index → result. Facts without a usable verified\n * source span are omitted from the batch (they are tagged `skipped_no_span`\n * at apply time, never gated — don't punish legacy data). Updates `counters`\n * for console_state telemetry.\n *\n * Fail-open: any pipeline error is caught, logged, and an empty map returned\n * so the caller records `unchecked`/`skipped_no_span` and proceeds — a gate\n * outage must never block memory writes (checklist §4).\n */\n// Common English stopwords — filtered before overlap scoring so function\n// words (the, a, is, ...) don't dilute the signal between a fact and its\n// source sentence.\nconst STOPWORDS = new Set([\n \"the\",\"a\",\"an\",\"and\",\"or\",\"but\",\"is\",\"are\",\"was\",\"were\",\"be\",\"been\",\"being\",\n \"to\",\"of\",\"in\",\"on\",\"at\",\"for\",\"with\",\"from\",\"by\",\"as\",\"it\",\"its\",\"this\",\"that\",\n \"these\",\"those\",\"i\",\"you\",\"he\",\"she\",\"we\",\"they\",\"my\",\"your\",\"his\",\"her\",\"our\",\"their\",\n \"has\",\"have\",\"had\",\"do\",\"does\",\"did\",\"will\",\"would\",\"can\",\"could\",\"should\",\"not\",\"no\",\n \"s\",\"very\",\"really\",\"just\",\"so\",\"than\",\"then\",\"there\",\"here\",\"about\",\"into\",\"over\",\"under\",\n]);\n\n/**\n * Crude stemmer: strip common suffixes so \"prefers\"/\"prefer\",\n * \"using\"/\"use\", \"started\"/\"start\" collapse to one token. Not a real\n * stemmer — just enough to raise recall for the interim locator (#1575 will\n * replace this with NLI-verified spans).\n */\nfunction crudeStem(word: string): string {\n if (word.length > 5 && word.endsWith(\"ing\")) return word.slice(0, -3);\n if (word.length > 4 && word.endsWith(\"ed\")) return word.slice(0, -2);\n if (word.length > 3 && (word.endsWith(\"s\")) && !word.endsWith(\"ss\")) return word.slice(0, -1);\n return word;\n}\n\n/**\n * Tokenize text into a lowercase, stopword-filtered, crudely-stemmed token\n * set for overlap scoring.\n */\nfunction tokenize(text: string): Set<string> {\n const tokens = new Set<string>();\n for (const raw of text.toLowerCase().split(/[^a-z0-9]+/)) {\n if (raw.length <= 1) continue;\n if (STOPWORDS.has(raw)) continue;\n tokens.add(crudeStem(raw));\n }\n return tokens;\n}\n\n/**\n * Overlap coefficient: |A ∩ B| / min(|A|, |B|). Robust for paraphrase\n * matching where a short fact paraphrases a longer source sentence — a short\n * fact fully supported by a long sentence scores high, unrelated text scores 0.\n */\nfunction overlapCoefficient(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 || b.size === 0) return 0;\n let intersection = 0;\n const [small, large] = a.size <= b.size ? [a, b] : [b, a];\n for (const t of small) if (large.has(t)) intersection++;\n return intersection / small.size;\n}\n\n/**\n * Minimum overlap for a located quote to be trusted as the fact's source span.\n * Below this the fact is treated as having no located span (skipped_no_span)\n * rather than judged against an unrelated sentence.\n */\nconst LOCATE_QUOTE_MIN_OVERLAP = 0.3;\n\n/**\n * Locate the best-matching verbatim span (sentence) from the source turn text\n * for an extracted fact, by token overlap. Returns the quote when a confident\n * match is found, `undefined` otherwise (the gate then records\n * skipped_no_span — never judged against an unrelated span).\n *\n * This is the interim source-text locator that makes the gate functional on\n * real extraction output (where #1575 has not yet attached per-fact\n * `sources`). It produces a genuine located quote per fact so the gate\n * consumes a span, not the whole conversation (issue #1576 design constraint).\n * #1575's NLI-verified per-fact locator will replace this when it lands.\n */\n/**\n * Extract a bounded window of `sourceText` centered on the located `quote`,\n * bounded by `contextChars` (the config's \"window around the quote\" semantics).\n *\n * Used by the fallback-locator path in `runFaithfulnessGateBatch` so the\n * verifier sees surrounding turn text — without it,\n * `extractionFaithfulnessContextChars` is effectively ignored in the\n * production path (codex review PRRT_kwDORJXyws6OblI1). Returns undefined when\n * the quote is absent from sourceText (e.g. it was truncated by maxQuoteChars).\n */\nexport function extractContextWindow(\n sourceText: string,\n quote: string,\n contextChars: number,\n /**\n * Character offset of `quote` within `sourceText` (from `locateFactQuote`).\n * When the quote string appears more than once — e.g. repeated anaphoric\n * lines after different entities — pass the matched occurrence's offset so\n * the context window centers on the actual match, not the first occurrence\n * (issue #1633, codex PRRT_kwDORJXyws6ObzwI). Defaults to the first\n * occurrence via indexOf for backward compatibility.\n */\n matchedOffset?: number,\n): string | undefined {\n if (!sourceText || !quote || !(contextChars > 0)) return undefined;\n let idx: number;\n if (matchedOffset !== undefined && matchedOffset >= 0) {\n const at = sourceText.indexOf(quote, matchedOffset);\n // Fall back to the first occurrence if the matched offset is stale (e.g.\n // the quote was bounded and is not a literal substring at that offset).\n idx = at >= 0 ? at : sourceText.indexOf(quote);\n } else {\n idx = sourceText.indexOf(quote);\n }\n if (idx < 0) return undefined;\n const quoteEnd = idx + quote.length;\n const center = Math.floor((idx + quoteEnd) / 2);\n const half = Math.floor(contextChars / 2);\n let start = Math.max(0, center - half);\n const end = Math.min(sourceText.length, start + contextChars);\n // Re-anchor start so the window uses the full budget when end clamped.\n start = Math.max(0, end - contextChars);\n const window = sourceText.slice(start, end).trim();\n return window.length > 0 ? window : undefined;\n}\n\n/**\n * A located fallback quote plus the offset it begins at in the source text.\n * `offset` lets `extractContextWindow` disambiguate repeated occurrences of\n * the same quote string (issue #1633).\n */\nexport interface LocatedQuote {\n /** Verbatim source span, centered on the matched terms when truncated. */\n quote: string;\n /** Character offset of `quote` within sourceText. */\n offset: number;\n}\n\ninterface SourceCandidate {\n /** Trimmed candidate text. */\n text: string;\n /** Character offset of `text` within the source string. */\n start: number;\n}\n\n/**\n * Split source text into candidate spans (sentences, then line segments as a\n * fallback for transcripts without sentence punctuation), tracking each\n * candidate's start offset so repeated occurrences can be disambiguated\n * (issue #1633).\n */\nfunction splitSourceCandidates(sourceText: string): SourceCandidate[] {\n const candidates: SourceCandidate[] = [];\n const re = /(?<=[.!?])\\s+|\\n+/g;\n let lastEnd = 0;\n let m: RegExpExecArray | null;\n while ((m = re.exec(sourceText)) !== null) {\n pushCandidate(candidates, sourceText, lastEnd, m.index);\n lastEnd = re.lastIndex;\n }\n pushCandidate(candidates, sourceText, lastEnd, sourceText.length);\n return candidates;\n}\n\nfunction pushCandidate(\n out: SourceCandidate[],\n source: string,\n begin: number,\n end: number,\n): void {\n const seg = source.slice(begin, end);\n const leadingWS = seg.length - seg.trimStart().length;\n const trimmed = seg.trim();\n if (trimmed.length > 0) {\n out.push({ text: trimmed, start: begin + leadingWS });\n }\n}\n\n/**\n * Locate the start offsets of fact-token matches inside a candidate. Used by\n * `locateFactQuote` to build a bounded window that is guaranteed to contain\n * real evidence (issue #1633, codex PRRT_kwDORJXyws6Obrwe / PRRT_kwDORJXyws6Oce-O).\n */\nfunction locateMatchedTokens(factTokens: Set<string>, candidate: string): number[] {\n const lower = candidate.toLowerCase();\n const wordRe = /[a-z0-9]+/g;\n const positions: number[] = [];\n let m: RegExpExecArray | null;\n while ((m = wordRe.exec(lower)) !== null) {\n const word = m[0];\n if (word.length <= 1) continue;\n if (STOPWORDS.has(word)) continue;\n if (factTokens.has(crudeStem(word))) {\n positions.push(m.index);\n }\n }\n return positions;\n}\n\n/**\n * Build a bounded window of `maxChars` from `text` that contains the densest\n * cluster of matched-token positions. Slides a maxChars-wide window anchored\n * at each matched token and keeps the one that captures the most matches\n * (tiebreak: earliest anchor). This guarantees the window includes real\n * evidence even when the matched span is wider than `maxChars` (e.g. fact\n * tokens at both ends of a long sentence with filler between). Centering on\n * the densest cluster's midpoint then uses any leftover budget as leading and\n * trailing context. Returns the window text and its start offset within `text`\n * so callers can translate the in-candidate offset back to a source-text offset.\n */\nfunction boundedWindow(\n text: string,\n matchedPositions: number[],\n maxChars: number,\n): { text: string; start: number } {\n if (matchedPositions.length === 0) {\n // Defensive: overlap scoring accepted the candidate but no individual\n // token matched (e.g. all matches were stopwords). Fall back to prefix.\n const end = Math.min(text.length, maxChars);\n return { text: text.slice(0, end), start: 0 };\n }\n // matchedPositions is sorted ascending (the regex scans left-to-right), so a\n // two-pointer sliding window finds the densest maxChars-wide cluster in O(n)\n // instead of O(n^2). This matters when a long unpunctuated candidate carries\n // many repeats of a fact token (pasted logs, minified text) — thousands of\n // positions would otherwise stall extraction before the LLM call (codex\n // PRRT_kwDORJXyws6Ocih3).\n let bestAnchor = matchedPositions[0]!;\n let bestCount = 0;\n let bestLast = bestAnchor;\n let j = 0;\n for (let i = 0; i < matchedPositions.length; i++) {\n const anchor = matchedPositions[i]!;\n const winEnd = anchor + maxChars;\n if (j < i) j = i;\n while (j + 1 < matchedPositions.length && matchedPositions[j + 1]! < winEnd) {\n j++;\n }\n const count = j - i + 1;\n if (count > bestCount) {\n bestCount = count;\n bestAnchor = anchor;\n bestLast = matchedPositions[j]!;\n }\n }\n // The densest cluster [bestAnchor, bestLast] fits within maxChars by\n // construction; center a maxChars window on its midpoint, clamped to text.\n const center = Math.floor((bestAnchor + bestLast) / 2);\n const half = Math.floor(maxChars / 2);\n let start = Math.max(0, center - half);\n const end = Math.min(text.length, start + maxChars);\n // Re-anchor start so the window uses the full budget when end clamped.\n start = Math.max(0, end - maxChars);\n return { text: text.slice(start, end), start };\n}\n\nexport function locateFactQuote(\n factText: string,\n sourceText: string,\n maxQuoteChars = 600,\n): LocatedQuote | undefined {\n if (!factText || !sourceText) return undefined;\n const factTokens = tokenize(factText);\n if (factTokens.size === 0) return undefined;\n const candidates = splitSourceCandidates(sourceText);\n if (candidates.length === 0) return undefined;\n // Pick the best-overlap candidate. Tiebreak equal own-overlap scores by a\n // \"context\" score that includes the immediately PRECEDING candidate's text,\n // so a repeated anaphoric line (\"It launched in March\") resolves to the\n // occurrence whose neighbor names the fact's entity (issue #1633, codex\n // PRRT_kwDORJXyws6Oce-S). Without this tiebreak the first occurrence wins\n // even when the second is the one the fact refers to.\n let best: { candidate: SourceCandidate; score: number; contextScore: number } | null = null;\n for (let i = 0; i < candidates.length; i++) {\n const candidate = candidates[i]!;\n const score = overlapCoefficient(factTokens, tokenize(candidate.text));\n const prevText = i > 0 ? candidates[i - 1]!.text : \"\";\n const contextText = prevText ? `${prevText} ${candidate.text}` : candidate.text;\n const contextScore = overlapCoefficient(factTokens, tokenize(contextText));\n if (\n !best ||\n score > best.score ||\n (score === best.score && contextScore > best.contextScore)\n ) {\n best = { candidate, score, contextScore };\n }\n }\n if (!best || best.score < LOCATE_QUOTE_MIN_OVERLAP) return undefined;\n const { text, start } = best.candidate;\n if (text.length <= maxQuoteChars) {\n return { quote: text, offset: start };\n }\n // Build a bounded window around the densest cluster of matched terms instead\n // of returning the first maxQuoteChars prefix (issue #1633). Returning the\n // prefix drops supporting words that fall after char ~600, routing\n // actually-entailed facts to pending_review in enforce mode.\n const matched = locateMatchedTokens(factTokens, text);\n const win = boundedWindow(text, matched, maxQuoteChars);\n return { quote: win.text, offset: start + win.start };\n}\nexport async function runFaithfulnessGateBatch(\n facts: readonly FaithfulnessGateFact[],\n mode: \"shadow\" | \"enforce\",\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n counters: FaithfulnessGateCounters,\n /**\n * The verbatim source turn text the facts were extracted from. When a fact\n * has no #1575 `sources`, locateFactQuote finds a fallback span here so the\n * gate runs on real extraction output. May be empty (replay/import paths\n * with no source turns) — facts then get skipped_no_span.\n */\n sourceText = \"\",\n): Promise<Map<number, FaithfulnessResult> | null> {\n // Phase 1 — build the checkable inputs. This is pure (no LLM, no throw):\n // locateFactQuote and the source/span selection never reject. Keeping it\n // outside the try lets the catch walk the same inputs to tag a pipeline\n // failure as \"unchecked\" rather than dropping it on the floor.\n const inputs: { factIndex: number; input: FaithfulnessCheckInput }[] = [];\n for (let fi = 0; fi < facts.length; fi++) {\n const f = facts[fi];\n if (!f || typeof f.content !== \"string\" || !f.content.trim()) continue;\n // Prefer #1575 verified spans; fall back to a located quote from the\n // source turn text so the gate runs even before per-fact sources are\n // attached. Without either, the fact is skipped_no_span (never gated).\n // A composite fact may be supported by multiple adjacent spans — collect\n // every valid source quote so the verifier sees the full evidence, not\n // just sources[0] (codex review PRRT_kwDORJXyws6ObYQ_).\n const sources = Array.isArray(f.sources) ? f.sources : [];\n const sourceQuotes = sources\n .map((s) => (s && typeof s.quote === \"string\" ? s.quote.trim() : \"\"))\n .filter((q) => q.length > 0);\n const usingFallbackLocator = sourceQuotes.length === 0;\n let quote: string;\n let matchedOffset: number | undefined;\n if (sourceQuotes.length > 0) {\n quote = sourceQuotes.join(\"\\n\");\n } else {\n // Fallback locator returns the matched span AND its offset so the\n // context window centers on the occurrence that actually matched the\n // fact, not the first indexOf hit (issue #1633).\n const located = locateFactQuote(f.content, sourceText);\n if (!located) continue; // no located span — applyFaithfulnessVerdict tags skipped_no_span\n quote = located.quote;\n matchedOffset = located.offset;\n }\n // Pass source context into the verifier so extractionFaithfulnessContextChars\n // actually applies in the fallback-locator path (codex P2\n // PRRT_kwDORJXyws6OblI1). #1575 verified spans already carry full evidence,\n // so context is only synthesized for the fallback locator.\n const fallbackContext =\n usingFallbackLocator\n ? extractContextWindow(\n sourceText,\n quote,\n config.extractionFaithfulnessContextChars,\n matchedOffset,\n )\n : undefined;\n inputs.push({\n factIndex: fi,\n input: {\n factText: f.content,\n quote,\n ...(fallbackContext ? { context: fallbackContext } : {}),\n },\n });\n }\n const resultsByFactIndex = new Map<number, FaithfulnessResult>();\n if (inputs.length === 0) return resultsByFactIndex;\n try {\n const batch = await checkFaithfulnessBatch(\n inputs.map((x) => x.input),\n config,\n localLlm,\n fallbackLlm,\n );\n for (let j = 0; j < inputs.length; j++) {\n const entry = inputs[j];\n if (entry) resultsByFactIndex.set(entry.factIndex, batch.results[j]!);\n }\n // Verdict-distribution counters are bumped in applyFaithfulnessVerdict\n // (at the per-fact apply point), NOT here, so console_state reflects\n // facts that actually reached verdict application — not facts later\n // dropped by dedup, importance, or judge gates (cursor review).\n log.info(\n `extraction-faithfulness[${mode}]: ${inputs.length} facts checked, ${batch.elapsedMs}ms`,\n );\n } catch (err) {\n // Fail-open: a pipeline error never blocks writes (checklist §4). Tag each\n // checkable fact as backend_unavailable so applyFaithfulnessVerdict records\n // \"unchecked\" (issue spec: backend failure → unchecked). Returning null\n // here would make a shadow/enforce batch failure indistinguishable from\n // gate-off, losing the telemetry signal (cursor review). Facts with no\n // located span stay absent → skipped_no_span at apply time.\n log.warn(\n `extraction-faithfulness: pipeline error, tagging ${inputs.length} checkable facts as unchecked (fail-open): ${err instanceof Error ? err.message : String(err)}`,\n );\n for (const { factIndex } of inputs) {\n resultsByFactIndex.set(factIndex, { ok: false, error: { code: \"backend_unavailable\" } });\n }\n }\n return resultsByFactIndex;\n}\n\n/**\n * Apply a pre-computed faithfulness verdict to a single fact, producing the\n * frontmatter record + an optional enforce-mode `pending_review` status.\n *\n * - `resultsByFactIndex` null (gate off) → nothing (rule 39: byte-identical).\n * - fact has no entry (no verified span) → `skipped_no_span`, never gated.\n * - backend failure (`ok: false`) → `unchecked`, fact proceeds (checklist §4).\n * - enforce + unsupported/contradicted → `pending_review` (memory persists,\n * enters the review queue, never silently dropped).\n *\n * Mutates `counters.skippedNoSpan` for facts without a span.\n */\nexport function applyFaithfulnessVerdict(\n resultsByFactIndex: Map<number, FaithfulnessResult> | null,\n factLoopIndex: number,\n mode: \"off\" | \"shadow\" | \"enforce\",\n factContent: string,\n counters: FaithfulnessGateCounters,\n): {\n faithfulness: FaithfulnessFrontmatter | undefined;\n enforceStatus: \"pending_review\" | undefined;\n} {\n if (!resultsByFactIndex) {\n return { faithfulness: undefined, enforceStatus: undefined };\n }\n const result = resultsByFactIndex.get(factLoopIndex);\n if (!result) {\n // No result for this fact index — it had no verified source span.\n counters.skippedNoSpan++;\n return {\n faithfulness: { verdict: \"skipped_no_span\", at: new Date().toISOString() },\n enforceStatus: undefined,\n };\n }\n if (result.ok) {\n if (result.verdict === \"entailed\") counters.entailed++;\n else if (result.verdict === \"contradicted\") counters.contradicted++;\n else if (result.verdict === \"unsupported\") counters.unsupported++;\n const fm: FaithfulnessFrontmatter = {\n verdict: result.verdict,\n ...(result.model ? { model: result.model } : {}),\n ...(result.rationale ? { rationale: result.rationale } : {}),\n at: new Date().toISOString(),\n };\n let enforceStatus: \"pending_review\" | undefined;\n if (\n mode === \"enforce\" &&\n (result.verdict === \"unsupported\" || result.verdict === \"contradicted\")\n ) {\n enforceStatus = \"pending_review\";\n log.info(\n `extraction-faithfulness[enforce]: routing \"${factContent.slice(0, 60)}…\" to pending_review (verdict=${result.verdict})`,\n );\n }\n return { faithfulness: fm, enforceStatus };\n }\n // Backend failure — record as unchecked, fact proceeds (graceful degradation).\n counters.unchecked++;\n return {\n faithfulness: { verdict: \"unchecked\", at: new Date().toISOString() },\n enforceStatus: undefined,\n };\n}\n// ---------------------------------------------------------------------------\n// Frontmatter serialization (single-line JSON, like provenance sources)\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical key order for the serialized `faithfulness` frontmatter field.\n * Deterministic emission (rule 38).\n */\nconst FAITHFULNESS_KEY_ORDER = [\"verdict\", \"model\", \"rationale\", \"at\"] as const;\n\n/**\n * Serialize the `faithfulness` frontmatter field as a single JSON line,\n * appended to `lines`. Called from `serializeFrontmatter` in storage.ts.\n *\n * Contract: when `fm.faithfulness` is absent, no line is emitted — the\n * memory round-trips byte-identical to pre-#1576 behavior (rule 39).\n */\nexport function serializeFaithfulnessFields(fm: MemoryFrontmatter, lines: string[]): void {\n if (!fm.faithfulness) return;\n const fm2 = fm.faithfulness;\n const canonical: Record<string, unknown> = {};\n for (const key of FAITHFULNESS_KEY_ORDER) {\n const val = fm2[key];\n if (val !== undefined && val !== null && val !== \"\") {\n canonical[key] = val;\n }\n }\n // verdict is always present on a valid FaithfulnessFrontmatter\n if (!canonical.verdict) return;\n lines.push(`faithfulness: ${JSON.stringify(canonical)}`);\n}\n\n/**\n * Parse the `faithfulness` frontmatter line from its single-line JSON form.\n * Returns `undefined` for missing, blank, or corrupt values so a malformed\n * frontmatter never poisons downstream readers (rule 34 spirit).\n */\nexport function parseFaithfulnessField(\n raw: string | undefined,\n): FaithfulnessFrontmatter | undefined {\n if (!raw || typeof raw !== \"string\" || raw.trim().length === 0) return undefined;\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return undefined;\n const obj = parsed as Record<string, unknown>;\n const verdictRaw = typeof obj.verdict === \"string\" ? obj.verdict : undefined;\n if (!verdictRaw) return undefined;\n const validVerdicts = new Set([\n \"entailed\",\n \"contradicted\",\n \"unsupported\",\n \"unchecked\",\n \"skipped_no_span\",\n ]);\n if (!validVerdicts.has(verdictRaw)) return undefined;\n const result: FaithfulnessFrontmatter = {\n verdict: verdictRaw as FaithfulnessFrontmatter[\"verdict\"],\n };\n if (typeof obj.model === \"string\" && obj.model.length > 0) {\n result.model = obj.model;\n }\n if (typeof obj.rationale === \"string\" && obj.rationale.length > 0) {\n result.rationale = obj.rationale.slice(0, 500);\n }\n if (typeof obj.at === \"string\" && obj.at.length > 0) {\n result.at = obj.at;\n }\n return result;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;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