@caupulican/pi-adaptative 0.80.100 → 0.80.102

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.
Files changed (122) hide show
  1. package/CHANGELOG.md +190 -0
  2. package/dist/core/agent-session.d.ts +72 -0
  3. package/dist/core/agent-session.d.ts.map +1 -1
  4. package/dist/core/agent-session.js +437 -46
  5. package/dist/core/agent-session.js.map +1 -1
  6. package/dist/core/autonomy/envelope-enforcement.d.ts +5 -0
  7. package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
  8. package/dist/core/autonomy/envelope-enforcement.js +28 -4
  9. package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
  10. package/dist/core/autonomy/path-scope.d.ts.map +1 -1
  11. package/dist/core/autonomy/path-scope.js +33 -2
  12. package/dist/core/autonomy/path-scope.js.map +1 -1
  13. package/dist/core/bash-executor.d.ts.map +1 -1
  14. package/dist/core/bash-executor.js +15 -7
  15. package/dist/core/bash-executor.js.map +1 -1
  16. package/dist/core/context/brain-curator.d.ts +10 -0
  17. package/dist/core/context/brain-curator.d.ts.map +1 -1
  18. package/dist/core/context/brain-curator.js +19 -2
  19. package/dist/core/context/brain-curator.js.map +1 -1
  20. package/dist/core/context-gc.d.ts +8 -3
  21. package/dist/core/context-gc.d.ts.map +1 -1
  22. package/dist/core/context-gc.js +5 -0
  23. package/dist/core/context-gc.js.map +1 -1
  24. package/dist/core/delegation/worker-actions.d.ts +0 -10
  25. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  26. package/dist/core/delegation/worker-actions.js +5 -7
  27. package/dist/core/delegation/worker-actions.js.map +1 -1
  28. package/dist/core/delegation/worker-result.d.ts +6 -0
  29. package/dist/core/delegation/worker-result.d.ts.map +1 -1
  30. package/dist/core/delegation/worker-result.js +10 -4
  31. package/dist/core/delegation/worker-result.js.map +1 -1
  32. package/dist/core/delegation/worker-runner.d.ts +3 -0
  33. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  34. package/dist/core/delegation/worker-runner.js +6 -1
  35. package/dist/core/delegation/worker-runner.js.map +1 -1
  36. package/dist/core/doctor.d.ts +66 -0
  37. package/dist/core/doctor.d.ts.map +1 -0
  38. package/dist/core/doctor.js +144 -0
  39. package/dist/core/doctor.js.map +1 -0
  40. package/dist/core/learning/learning-audit.d.ts +13 -1
  41. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  42. package/dist/core/learning/learning-audit.js +22 -1
  43. package/dist/core/learning/learning-audit.js.map +1 -1
  44. package/dist/core/learning/learning-gate.d.ts +3 -0
  45. package/dist/core/learning/learning-gate.d.ts.map +1 -1
  46. package/dist/core/learning/learning-gate.js +13 -4
  47. package/dist/core/learning/learning-gate.js.map +1 -1
  48. package/dist/core/models/local-registration.d.ts +2 -0
  49. package/dist/core/models/local-registration.d.ts.map +1 -1
  50. package/dist/core/models/local-registration.js +2 -1
  51. package/dist/core/models/local-registration.js.map +1 -1
  52. package/dist/core/models/local-runtime.d.ts +76 -2
  53. package/dist/core/models/local-runtime.d.ts.map +1 -1
  54. package/dist/core/models/local-runtime.js +233 -21
  55. package/dist/core/models/local-runtime.js.map +1 -1
  56. package/dist/core/profile-resource-selection.d.ts +15 -3
  57. package/dist/core/profile-resource-selection.d.ts.map +1 -1
  58. package/dist/core/profile-resource-selection.js +19 -9
  59. package/dist/core/profile-resource-selection.js.map +1 -1
  60. package/dist/core/resource-loader.d.ts +20 -0
  61. package/dist/core/resource-loader.d.ts.map +1 -1
  62. package/dist/core/resource-loader.js +42 -16
  63. package/dist/core/resource-loader.js.map +1 -1
  64. package/dist/core/settings-manager.d.ts +30 -0
  65. package/dist/core/settings-manager.d.ts.map +1 -1
  66. package/dist/core/settings-manager.js +65 -3
  67. package/dist/core/settings-manager.js.map +1 -1
  68. package/dist/core/skills.d.ts +14 -0
  69. package/dist/core/skills.d.ts.map +1 -1
  70. package/dist/core/skills.js +8 -0
  71. package/dist/core/skills.js.map +1 -1
  72. package/dist/core/tools/fff-search-backend.d.ts +34 -1
  73. package/dist/core/tools/fff-search-backend.d.ts.map +1 -1
  74. package/dist/core/tools/fff-search-backend.js +43 -4
  75. package/dist/core/tools/fff-search-backend.js.map +1 -1
  76. package/dist/core/tools/find.d.ts +16 -0
  77. package/dist/core/tools/find.d.ts.map +1 -1
  78. package/dist/core/tools/find.js +17 -3
  79. package/dist/core/tools/find.js.map +1 -1
  80. package/dist/core/tools/grep.d.ts +20 -0
  81. package/dist/core/tools/grep.d.ts.map +1 -1
  82. package/dist/core/tools/grep.js +15 -3
  83. package/dist/core/tools/grep.js.map +1 -1
  84. package/dist/main.d.ts.map +1 -1
  85. package/dist/main.js +17 -0
  86. package/dist/main.js.map +1 -1
  87. package/dist/modes/interactive/components/fitness-role-selector.d.ts +6 -2
  88. package/dist/modes/interactive/components/fitness-role-selector.d.ts.map +1 -1
  89. package/dist/modes/interactive/components/fitness-role-selector.js +55 -45
  90. package/dist/modes/interactive/components/fitness-role-selector.js.map +1 -1
  91. package/dist/modes/interactive/components/model-suggestion-selector.d.ts +13 -0
  92. package/dist/modes/interactive/components/model-suggestion-selector.d.ts.map +1 -0
  93. package/dist/modes/interactive/components/model-suggestion-selector.js +40 -0
  94. package/dist/modes/interactive/components/model-suggestion-selector.js.map +1 -0
  95. package/dist/modes/interactive/components/profile-resource-editor.d.ts +3 -0
  96. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  97. package/dist/modes/interactive/components/profile-resource-editor.js +16 -2
  98. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  99. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  100. package/dist/modes/interactive/components/settings-selector.js +98 -0
  101. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  102. package/dist/modes/interactive/interactive-mode.d.ts +8 -1
  103. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  104. package/dist/modes/interactive/interactive-mode.js +50 -12
  105. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  106. package/dist/utils/safe-write-stream.d.ts +8 -0
  107. package/dist/utils/safe-write-stream.d.ts.map +1 -1
  108. package/dist/utils/safe-write-stream.js +32 -0
  109. package/dist/utils/safe-write-stream.js.map +1 -1
  110. package/dist/utils/tools-manager.d.ts +92 -2
  111. package/dist/utils/tools-manager.d.ts.map +1 -1
  112. package/dist/utils/tools-manager.js +172 -32
  113. package/dist/utils/tools-manager.js.map +1 -1
  114. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  115. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  116. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  117. package/examples/extensions/sandbox/package-lock.json +2 -2
  118. package/examples/extensions/sandbox/package.json +1 -1
  119. package/examples/extensions/with-deps/package-lock.json +2 -2
  120. package/examples/extensions/with-deps/package.json +1 -1
  121. package/npm-shrinkwrap.json +12 -36
  122. package/package.json +4 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doctor.js","sourceRoot":"","sources":["../../src/core/doctor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EACN,YAAY,EACZ,oBAAoB,EAEpB,wBAAwB,EACxB,WAAW,EACX,2BAA2B,EAC3B,YAAY,GAEZ,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAgE1D,MAAM,cAAc,GAAe;IAClC,2BAA2B;IAC3B,oBAAoB;IACpB,wBAAwB;IACxB,SAAS,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC;IAClC,YAAY,EAAE,GAAG,EAAE,CAAC,YAAY,EAAE;IAClC,YAAY;IACZ,aAAa,EAAE,IAAI,aAAa,CAAC,EAAE,QAAQ,EAAE,WAAW,EAAE,EAAE,CAAC;CAC7D,CAAC;AAEF,MAAM,aAAa,GAAG;IACrB,oGAAoG;IACpG,4CAA4C;I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CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IAClH,CAAC;AAAA,CACD","sourcesContent":["import chalk from \"chalk\";\nimport { getAgentDir } from \"../config.ts\";\nimport {\n\tdetectPython,\n\tensureFffNodePackage,\n\ttype FffInstallOutcome,\n\tgetLastFffInstallOutcome,\n\tgetToolPath,\n\tloadAvailableFffNodePackage,\n\tprobeVersion,\n\ttype SystemToolStatus,\n} from \"../utils/tools-manager.ts\";\nimport { OllamaRuntime } from \"./models/local-runtime.ts\";\n\n/**\n * Environment doctor: verifies required tooling and installs what it safely\n * can, instead of leaving provisioning entirely to lazy first-use (the exact\n * gap behind \"ran `pi-adaptative update` on another machine and fff-node\n * never got installed\" -- see fff-lazy-install.test.ts/fff-search-tools.test.ts\n * for the underlying lazy-install fix; this module is the proactive half).\n *\n * Two tool kinds, two different postures:\n * - \"managed\": pi already owns the install path (fff-node into\n * ~/.pi/agent/bin via tools-manager.ts's ensureFffNodePackage). The doctor\n * actually attempts the install when missing.\n * - \"system\": pi does not own the install (ripgrep, ollama, python). GUIDE\n * MODE only -- exact manual steps are reported, never executed, never\n * `curl | sh`, never `sudo`. This matches the harness's deliberate\n * no-silent-installer stance for tooling outside its own managed bin dir.\n */\n\nexport type DoctorToolKind = \"managed\" | \"system\";\n\nexport interface DoctorCheck {\n\t/** Stable identifier, e.g. \"fff-node\", \"ripgrep\", \"ollama\", \"python\". */\n\tid: string;\n\t/** Human-readable label for the report. */\n\tlabel: string;\n\tkind: DoctorToolKind;\n\tpresent: boolean;\n\t/** Version/path/status summary, present or not. */\n\tdetail?: string;\n\t/** Only set for a \"managed\" tool: whether an install was just attempted. */\n\tinstallAttempted?: boolean;\n\t/** Only set for a \"system\" tool that's missing: exact manual steps, never executed. */\n\tguide?: string[];\n}\n\nexport interface DoctorReport {\n\tchecks: DoctorCheck[];\n}\n\n/** Minimal slice of OllamaRuntime the doctor needs -- lets tests inject a fake without touching the real runtime. */\nexport type DoctorOllamaRuntime = Pick<OllamaRuntime, \"detect\" | \"installGuide\">;\n\nexport interface DoctorDeps {\n\tloadAvailableFffNodePackage: () => unknown | undefined;\n\tensureFffNodePackage: (silent?: boolean) => Promise<unknown | undefined>;\n\tgetLastFffInstallOutcome: () => FffInstallOutcome | undefined;\n\tgetRgPath: () => string | null;\n\tdetectPython: () => SystemToolStatus;\n\t/** Best-effort `<command> --version` probe; undefined if it can't be run. Used only to enrich a status line, never for presence detection. */\n\tprobeVersion: (command: string, versionArgs?: readonly string[]) => string | undefined;\n\tollamaRuntime: DoctorOllamaRuntime;\n}\n\nexport interface RunDoctorOptions {\n\t/**\n\t * Whether the fff-node managed install (if one is attempted) stays quiet.\n\t * Default true, matching runUpdatePreflight's existing background\n\t * behavior. The interactive `doctor` command passes `false` so a\n\t * multi-second install doesn't read as a silent hang.\n\t */\n\tsilent?: boolean;\n}\n\nconst realDoctorDeps: DoctorDeps = {\n\tloadAvailableFffNodePackage,\n\tensureFffNodePackage,\n\tgetLastFffInstallOutcome,\n\tgetRgPath: () => getToolPath(\"rg\"),\n\tdetectPython: () => detectPython(),\n\tprobeVersion,\n\tollamaRuntime: new OllamaRuntime({ agentDir: getAgentDir() }),\n};\n\nconst RIPGREP_GUIDE = [\n\t\"ripgrep (rg) was not found. Pi never runs installers itself -- manual steps (user-level, no sudo):\",\n\t\" - macOS (Homebrew): brew install ripgrep\",\n\t\" - Debian/Ubuntu: apt install ripgrep\",\n\t\" - Arch: pacman -S ripgrep\",\n\t\" - Or download a release: https://github.com/BurntSushi/ripgrep/releases\",\n];\n\nconst PYTHON_GUIDE = [\n\t\"python3 was not found. Pi never runs installers itself -- manual steps (user-level, no sudo):\",\n\t\" - macOS (Homebrew): brew install python3\",\n\t\" - Debian/Ubuntu: apt install python3\",\n\t\" - Arch: pacman -S python\",\n\t\" - Or download from https://www.python.org/downloads/\",\n];\n\nfunction describeFffOutcome(outcome: FffInstallOutcome | undefined): string {\n\tswitch (outcome?.status) {\n\t\tcase \"already-available\":\n\t\t\treturn \"already available\";\n\t\tcase \"installed\":\n\t\t\treturn \"installed just now\";\n\t\tcase \"offline\":\n\t\t\treturn \"offline mode enabled, skipped\";\n\t\tcase \"unsupported-platform\":\n\t\t\treturn \"no native build for this platform\";\n\t\tcase \"install-failed\":\n\t\t\treturn `install failed: ${outcome.reason}`;\n\t\tdefault:\n\t\t\treturn \"unavailable\";\n\t}\n}\n\n/** First line only -- a compiled-features/build-flags tail (e.g. rg --version) is noise in a one-line status report. */\nfunction firstLine(text: string | undefined): string | undefined {\n\treturn text?.split(\"\\n\")[0];\n}\n\n/** MANAGED tool: pi owns this install path, so the doctor actually attempts it when missing. */\nasync function checkFffNode(deps: DoctorDeps, silent: boolean): Promise<DoctorCheck> {\n\t// Delegate entirely to ensureFffNodePackage rather than re-deriving \"is it\n\t// already there\" here: that function (and its offline/unsupported-platform/\n\t// cooldown handling, see tools-manager.ts) is the single source of truth for\n\t// whether an install should even be attempted -- the doctor must not\n\t// duplicate or second-guess that logic, only report its outcome honestly.\n\tconst installed = await deps.ensureFffNodePackage(silent);\n\tconst outcome = deps.getLastFffInstallOutcome();\n\treturn {\n\t\tid: \"fff-node\",\n\t\tlabel: \"FFF native search (@ff-labs/fff-node)\",\n\t\tkind: \"managed\",\n\t\tpresent: Boolean(installed),\n\t\tinstallAttempted: outcome !== undefined && outcome.status !== \"already-available\",\n\t\tdetail: describeFffOutcome(outcome),\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor. */\nfunction checkRipgrep(deps: DoctorDeps): DoctorCheck {\n\tconst path = deps.getRgPath();\n\tif (!path) {\n\t\treturn { id: \"ripgrep\", label: \"ripgrep (rg)\", kind: \"system\", present: false, guide: RIPGREP_GUIDE };\n\t}\n\tconst version = firstLine(deps.probeVersion(path));\n\treturn {\n\t\tid: \"ripgrep\",\n\t\tlabel: \"ripgrep (rg)\",\n\t\tkind: \"system\",\n\t\tpresent: true,\n\t\tdetail: version ? `${path} (${version})` : path,\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor (OllamaRuntime.installGuide() is itself already guide-mode-only). */\nasync function checkOllama(deps: DoctorDeps): Promise<DoctorCheck> {\n\tconst status = await deps.ollamaRuntime.detect();\n\tif (!status.binaryPath) {\n\t\treturn {\n\t\t\tid: \"ollama\",\n\t\t\tlabel: \"Ollama (local model runtime)\",\n\t\t\tkind: \"system\",\n\t\t\tpresent: false,\n\t\t\tguide: deps.ollamaRuntime.installGuide(),\n\t\t};\n\t}\n\tconst version = firstLine(deps.probeVersion(status.binaryPath));\n\tconst versionSuffix = version ? `, ${version}` : \"\";\n\treturn {\n\t\tid: \"ollama\",\n\t\tlabel: \"Ollama (local model runtime)\",\n\t\tkind: \"system\",\n\t\tpresent: true,\n\t\tdetail: `binary: ${status.binaryPath} [${status.binarySource}]${versionSuffix}; server: ${status.serverUp ? \"up\" : \"down\"} at ${status.serverUrl}`,\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor. */\nfunction checkPython(deps: DoctorDeps): DoctorCheck {\n\tconst status = deps.detectPython();\n\tif (!status.present) {\n\t\treturn { id: \"python\", label: \"Python (python3)\", kind: \"system\", present: false, guide: PYTHON_GUIDE };\n\t}\n\tconst detail = status.version ? `${status.command} (${status.version})` : status.command;\n\treturn { id: \"python\", label: \"Python (python3)\", kind: \"system\", present: true, detail };\n}\n\nexport async function runDoctor(\n\tdeps: DoctorDeps = realDoctorDeps,\n\toptions: RunDoctorOptions = {},\n): Promise<DoctorReport> {\n\tconst silent = options.silent ?? true;\n\tconst [fffNode, ollama] = await Promise.all([checkFffNode(deps, silent), checkOllama(deps)]);\n\treturn { checks: [fffNode, checkRipgrep(deps), ollama, checkPython(deps)] };\n}\n\nexport function formatDoctorReport(report: DoctorReport): string {\n\tconst lines: string[] = [];\n\tfor (const check of report.checks) {\n\t\tconst status = check.present ? chalk.green(\"[OK]\") : chalk.yellow(\"[MISSING]\");\n\t\tconst detail = check.detail ? ` -- ${check.detail}` : \"\";\n\t\tlines.push(`${status} ${check.label}${detail}`);\n\t\tif (!check.present && check.guide) {\n\t\t\tfor (const guideLine of check.guide) lines.push(` ${guideLine}`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Best-effort preflight meant to be called right after `pi-adaptative update`\n * succeeds. Must never fail the update itself: any error here is swallowed\n * and reported as a skipped check, not surfaced as an update failure.\n */\nexport async function runUpdatePreflight(): Promise<void> {\n\ttry {\n\t\tconst report = await runDoctor();\n\t\tconsole.log(`\\n${formatDoctorReport(report)}\\n`);\n\t} catch (error) {\n\t\tconsole.log(chalk.dim(`(environment check skipped: ${error instanceof Error ? error.message : String(error)})`));\n\t}\n}\n"]}
@@ -17,7 +17,11 @@ export interface LearningRollbackPlan {
17
17
  previous?: string;
18
18
  instructions: string;
19
19
  }
20
- export type LearningAuditAction = "apply" | "propose" | "rollback";
20
+ export type LearningAuditAction = "apply" | "apply_failed" | "propose" | "rollback";
21
+ /** reasonCode for an "apply_failed" audit — distinct from the gate's own reasonCode (e.g.
22
+ * "eligible_auto_apply") so the record is honest about WHERE it stopped: the gate approved the
23
+ * write, but the write tool refused it after the fact. */
24
+ export declare const APPLY_WRITE_REFUSED_REASON_CODE = "apply_write_refused";
21
25
  export interface LearningAuditRecord {
22
26
  id: string;
23
27
  proposalId: string;
@@ -32,6 +36,14 @@ export interface LearningAuditRecord {
32
36
  createdAt: string;
33
37
  }
34
38
  export declare function proposalFromReflectionWrite(write: ReflectionWrite, proposalId: string): DurableChangeProposal;
39
+ /**
40
+ * Contradiction count a reflection write carries against existing durable knowledge. A
41
+ * `memory_replace`/`memory_remove` is only emitted when the reflection engine CONFRONTS an existing
42
+ * fact (it supersedes or deletes it) — that supersession is the gate's contradiction signal, so such
43
+ * a write must route through approval rather than silently overwriting prior memory. A `memory_add`
44
+ * or `promote_skill` is purely additive and contradicts nothing.
45
+ */
46
+ export declare function contradictionsForReflectionWrite(write: ReflectionWrite): number;
35
47
  export declare function rollbackPlanForReflectionWrite(write: ReflectionWrite): LearningRollbackPlan;
36
48
  export declare function isLearningAuditRecord(value: unknown): value is LearningAuditRecord;
37
49
  export declare function cloneLearningAuditRecordForStorage(record: LearningAuditRecord): LearningAuditRecord;
@@ -1 +1 @@
1
- {"version":3,"file":"learning-audit.d.ts","sourceRoot":"","sources":["../../../src/core/learning/learning-audit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,KAAK,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AACpF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D;;;;;GAKG;AAEH,MAAM,MAAM,oBAAoB,GAAG,eAAe,GAAG,gBAAgB,GAAG,YAAY,GAAG,eAAe,CAAC;AAEvG,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,oBAAoB,CAAC;IAC3B,sGAAsG;IACtG,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,MAAM,mBAAmB,GAAG,OAAO,GAAG,SAAS,GAAG,UAAU,CAAC;AAEnE,MAAM,WAAW,mBAAmB;IACnC,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,kBAAkB,CAAC;IAC1B,MAAM,EAAE,mBAAmB,CAAC;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAChC,oFAAoF;IACpF,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;CAClB;AAeD,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,GAAG,qBAAqB,CAO7G;AAED,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,eAAe,GAAG,oBAAoB,CA4B3F;AA8BD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,mBAAmB,CAYlF;AAED,wBAAgB,kCAAkC,CAAC,MAAM,EAAE,mBAAmB,GAAG,mBAAmB,CAMnG;AAED,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAE3D,MAAM,WAAW,4BAA4B;IAC5C,OAAO,EAAE,CAAC,CAAC;IACX,MAAM,EAAE,mBAAmB,CAAC;CAC5B;AAED,wBAAgB,2BAA2B,CAC1C,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,mBAAmB,CAAC,EACzD,MAAM,EAAE,mBAAmB,GACzB,MAAM,CAMR;AAQD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,mBAAmB,EAAE,CAmBjG","sourcesContent":["import type { LearningDecision } from \"../autonomy/contracts.ts\";\nimport type { SessionEntry, SessionManager } from \"../session-manager.ts\";\nimport type { DurableChangeLayer, DurableChangeProposal } from \"./learning-gate.ts\";\nimport type { ReflectionWrite } from \"./reflection-engine.ts\";\n\n/**\n * Audit + rollback metadata for durable learning changes. Every reflection-sourced write that the\n * learning policy applies (or converts to a proposal) leaves one of these records in the session\n * log, so `/autonomy diagnostics` can explain what changed, why, and how to undo it — and\n * `rollbackLearningWrite` can execute the inverse operation.\n */\n\nexport type LearningRollbackKind = \"memory_remove\" | \"memory_restore\" | \"memory_add\" | \"archive_skill\";\n\nexport interface LearningRollbackPlan {\n\tkind: LearningRollbackKind;\n\t/** Text currently present because of the change (to remove/replace), or the skill name to archive. */\n\ttarget?: string;\n\t/** Original text to restore (memory_restore/memory_add). */\n\tprevious?: string;\n\tinstructions: string;\n}\n\nexport type LearningAuditAction = \"apply\" | \"propose\" | \"rollback\";\n\nexport interface LearningAuditRecord {\n\tid: string;\n\tproposalId: string;\n\tlayer: DurableChangeLayer;\n\taction: LearningAuditAction;\n\tsummary: string;\n\treasonCode: string;\n\tdecision: LearningDecision;\n\trollback?: LearningRollbackPlan;\n\t/** For action \"rollback\": the audit id of the applied change this record undoes. */\n\trollbackOf?: string;\n\tcreatedAt: string;\n}\n\nfunction describeWrite(write: ReflectionWrite): string {\n\tswitch (write.kind) {\n\t\tcase \"memory_add\":\n\t\t\treturn `Add ${write.section} memory: ${write.text}`;\n\t\tcase \"memory_replace\":\n\t\t\treturn `Replace memory \"${write.target}\" with \"${write.text}\"`;\n\t\tcase \"memory_remove\":\n\t\t\treturn `Remove memory: ${write.target}`;\n\t\tcase \"promote_skill\":\n\t\t\treturn `Promote skill \"${write.name}\": ${write.description}`;\n\t}\n}\n\nexport function proposalFromReflectionWrite(write: ReflectionWrite, proposalId: string): DurableChangeProposal {\n\treturn {\n\t\tid: proposalId,\n\t\tlayer: write.kind === \"promote_skill\" ? \"skill\" : \"memory\",\n\t\tsummary: describeWrite(write),\n\t\trollbackPlan: rollbackPlanForReflectionWrite(write).instructions,\n\t};\n}\n\nexport function rollbackPlanForReflectionWrite(write: ReflectionWrite): LearningRollbackPlan {\n\tswitch (write.kind) {\n\t\tcase \"memory_add\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_remove\",\n\t\t\t\ttarget: write.text,\n\t\t\t\tinstructions: `Remove the added ${write.section} memory text.`,\n\t\t\t};\n\t\tcase \"memory_replace\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_restore\",\n\t\t\t\ttarget: write.text,\n\t\t\t\tprevious: write.target,\n\t\t\t\tinstructions: \"Replace the new memory text with the original text it overwrote.\",\n\t\t\t};\n\t\tcase \"memory_remove\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_add\",\n\t\t\t\tprevious: write.target,\n\t\t\t\tinstructions: \"Re-add the removed text to the MEMORY file (it may originally have lived in USER).\",\n\t\t\t};\n\t\tcase \"promote_skill\":\n\t\t\treturn {\n\t\t\t\tkind: \"archive_skill\",\n\t\t\t\ttarget: write.name,\n\t\t\t\tinstructions: \"Archive the promoted skill so it no longer loads.\",\n\t\t\t};\n\t}\n}\n\nconst AUDIT_ACTIONS: readonly string[] = [\"apply\", \"propose\", \"rollback\"];\nconst ROLLBACK_KINDS: readonly string[] = [\"memory_remove\", \"memory_restore\", \"memory_add\", \"archive_skill\"];\nconst LAYERS: readonly string[] = [\"memory\", \"skill\", \"prompt\", \"extension\", \"tool\", \"script\", \"settings\", \"source\"];\n\nfunction isOptionalString(value: unknown): boolean {\n\treturn value === undefined || typeof value === \"string\";\n}\n\nfunction isLearningRollbackPlan(value: unknown): value is LearningRollbackPlan {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst plan = value as Record<string, unknown>;\n\tif (typeof plan.kind !== \"string\" || !ROLLBACK_KINDS.includes(plan.kind)) return false;\n\tif (!isOptionalString(plan.target) || !isOptionalString(plan.previous)) return false;\n\treturn typeof plan.instructions === \"string\";\n}\n\nfunction isLearningDecisionShape(value: unknown): value is LearningDecision {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst decision = value as Record<string, unknown>;\n\treturn (\n\t\t(decision.kind === \"no-op\" || decision.kind === \"proposal\" || decision.kind === \"apply\") &&\n\t\ttypeof decision.reasonCode === \"string\" &&\n\t\ttypeof decision.confidence === \"number\" &&\n\t\ttypeof decision.summary === \"string\" &&\n\t\ttypeof decision.requiresApproval === \"boolean\"\n\t);\n}\n\nexport function isLearningAuditRecord(value: unknown): value is LearningAuditRecord {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst record = value as Record<string, unknown>;\n\tif (typeof record.id !== \"string\" || record.id.length === 0) return false;\n\tif (typeof record.proposalId !== \"string\") return false;\n\tif (typeof record.layer !== \"string\" || !LAYERS.includes(record.layer)) return false;\n\tif (typeof record.action !== \"string\" || !AUDIT_ACTIONS.includes(record.action)) return false;\n\tif (typeof record.summary !== \"string\" || typeof record.reasonCode !== \"string\") return false;\n\tif (!isLearningDecisionShape(record.decision)) return false;\n\tif (record.rollback !== undefined && !isLearningRollbackPlan(record.rollback)) return false;\n\tif (!isOptionalString(record.rollbackOf)) return false;\n\treturn typeof record.createdAt === \"string\";\n}\n\nexport function cloneLearningAuditRecordForStorage(record: LearningAuditRecord): LearningAuditRecord {\n\treturn {\n\t\t...record,\n\t\tdecision: { ...record.decision },\n\t\t...(record.rollback ? { rollback: { ...record.rollback } } : {}),\n\t};\n}\n\nexport const LEARNING_AUDIT_CUSTOM_TYPE = \"learning_audit\";\n\nexport interface LearningAuditSnapshotPayload {\n\tversion: 1;\n\trecord: LearningAuditRecord;\n}\n\nexport function appendLearningAuditSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\trecord: LearningAuditRecord,\n): string {\n\tconst payload: LearningAuditSnapshotPayload = {\n\t\tversion: 1,\n\t\trecord: cloneLearningAuditRecordForStorage(record),\n\t};\n\treturn sessionManager.appendCustomEntry(LEARNING_AUDIT_CUSTOM_TYPE, payload);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function getLearningAuditSnapshots(entries: readonly SessionEntry[]): LearningAuditRecord[] {\n\tconst records: LearningAuditRecord[] = [];\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== LEARNING_AUDIT_CUSTOM_TYPE) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst payload = entry.data;\n\t\tif (!isPlainRecord(payload)) continue;\n\t\tif (payload.version !== 1) continue;\n\t\tif (!(\"record\" in payload)) continue;\n\t\tconst record = payload.record;\n\t\tif (isLearningAuditRecord(record)) {\n\t\t\trecords.push(cloneLearningAuditRecordForStorage(record));\n\t\t}\n\t}\n\n\treturn records;\n}\n"]}
1
+ {"version":3,"file":"learning-audit.d.ts","sourceRoot":"","sources":["../../../src/core/learning/learning-audit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,KAAK,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AACpF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D;;;;;GAKG;AAEH,MAAM,MAAM,oBAAoB,GAAG,eAAe,GAAG,gBAAgB,GAAG,YAAY,GAAG,eAAe,CAAC;AAEvG,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,oBAAoB,CAAC;IAC3B,sGAAsG;IACtG,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;CACrB;AAKD,MAAM,MAAM,mBAAmB,GAAG,OAAO,GAAG,cAAc,GAAG,SAAS,GAAG,UAAU,CAAC;AAEpF;;0DAE0D;AAC1D,eAAO,MAAM,+BAA+B,wBAAwB,CAAC;AAErE,MAAM,WAAW,mBAAmB;IACnC,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,kBAAkB,CAAC;IAC1B,MAAM,EAAE,mBAAmB,CAAC;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAChC,oFAAoF;IACpF,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;CAClB;AAeD,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,GAAG,qBAAqB,CAO7G;AAED;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,CAS/E;AAED,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,eAAe,GAAG,oBAAoB,CA4B3F;AA8BD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,mBAAmB,CAYlF;AAED,wBAAgB,kCAAkC,CAAC,MAAM,EAAE,mBAAmB,GAAG,mBAAmB,CAMnG;AAED,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAE3D,MAAM,WAAW,4BAA4B;IAC5C,OAAO,EAAE,CAAC,CAAC;IACX,MAAM,EAAE,mBAAmB,CAAC;CAC5B;AAED,wBAAgB,2BAA2B,CAC1C,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,mBAAmB,CAAC,EACzD,MAAM,EAAE,mBAAmB,GACzB,MAAM,CAMR;AAQD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,mBAAmB,EAAE,CAmBjG","sourcesContent":["import type { LearningDecision } from \"../autonomy/contracts.ts\";\nimport type { SessionEntry, SessionManager } from \"../session-manager.ts\";\nimport type { DurableChangeLayer, DurableChangeProposal } from \"./learning-gate.ts\";\nimport type { ReflectionWrite } from \"./reflection-engine.ts\";\n\n/**\n * Audit + rollback metadata for durable learning changes. Every reflection-sourced write that the\n * learning policy applies (or converts to a proposal) leaves one of these records in the session\n * log, so `/autonomy diagnostics` can explain what changed, why, and how to undo it — and\n * `rollbackLearningWrite` can execute the inverse operation.\n */\n\nexport type LearningRollbackKind = \"memory_remove\" | \"memory_restore\" | \"memory_add\" | \"archive_skill\";\n\nexport interface LearningRollbackPlan {\n\tkind: LearningRollbackKind;\n\t/** Text currently present because of the change (to remove/replace), or the skill name to archive. */\n\ttarget?: string;\n\t/** Original text to restore (memory_restore/memory_add). */\n\tprevious?: string;\n\tinstructions: string;\n}\n\n// \"apply_failed\" is distinct from \"apply\": the gate decided to apply, but the underlying write tool\n// (e.g. the memory tool) refused it (budget exceeded, drift, threat) without throwing. It must never\n// be treated as \"apply\" by a rollback-eligibility check — there is nothing durable to undo.\nexport type LearningAuditAction = \"apply\" | \"apply_failed\" | \"propose\" | \"rollback\";\n\n/** reasonCode for an \"apply_failed\" audit — distinct from the gate's own reasonCode (e.g.\n * \"eligible_auto_apply\") so the record is honest about WHERE it stopped: the gate approved the\n * write, but the write tool refused it after the fact. */\nexport const APPLY_WRITE_REFUSED_REASON_CODE = \"apply_write_refused\";\n\nexport interface LearningAuditRecord {\n\tid: string;\n\tproposalId: string;\n\tlayer: DurableChangeLayer;\n\taction: LearningAuditAction;\n\tsummary: string;\n\treasonCode: string;\n\tdecision: LearningDecision;\n\trollback?: LearningRollbackPlan;\n\t/** For action \"rollback\": the audit id of the applied change this record undoes. */\n\trollbackOf?: string;\n\tcreatedAt: string;\n}\n\nfunction describeWrite(write: ReflectionWrite): string {\n\tswitch (write.kind) {\n\t\tcase \"memory_add\":\n\t\t\treturn `Add ${write.section} memory: ${write.text}`;\n\t\tcase \"memory_replace\":\n\t\t\treturn `Replace memory \"${write.target}\" with \"${write.text}\"`;\n\t\tcase \"memory_remove\":\n\t\t\treturn `Remove memory: ${write.target}`;\n\t\tcase \"promote_skill\":\n\t\t\treturn `Promote skill \"${write.name}\": ${write.description}`;\n\t}\n}\n\nexport function proposalFromReflectionWrite(write: ReflectionWrite, proposalId: string): DurableChangeProposal {\n\treturn {\n\t\tid: proposalId,\n\t\tlayer: write.kind === \"promote_skill\" ? \"skill\" : \"memory\",\n\t\tsummary: describeWrite(write),\n\t\trollbackPlan: rollbackPlanForReflectionWrite(write).instructions,\n\t};\n}\n\n/**\n * Contradiction count a reflection write carries against existing durable knowledge. A\n * `memory_replace`/`memory_remove` is only emitted when the reflection engine CONFRONTS an existing\n * fact (it supersedes or deletes it) — that supersession is the gate's contradiction signal, so such\n * a write must route through approval rather than silently overwriting prior memory. A `memory_add`\n * or `promote_skill` is purely additive and contradicts nothing.\n */\nexport function contradictionsForReflectionWrite(write: ReflectionWrite): number {\n\tswitch (write.kind) {\n\t\tcase \"memory_replace\":\n\t\tcase \"memory_remove\":\n\t\t\treturn 1;\n\t\tcase \"memory_add\":\n\t\tcase \"promote_skill\":\n\t\t\treturn 0;\n\t}\n}\n\nexport function rollbackPlanForReflectionWrite(write: ReflectionWrite): LearningRollbackPlan {\n\tswitch (write.kind) {\n\t\tcase \"memory_add\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_remove\",\n\t\t\t\ttarget: write.text,\n\t\t\t\tinstructions: `Remove the added ${write.section} memory text.`,\n\t\t\t};\n\t\tcase \"memory_replace\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_restore\",\n\t\t\t\ttarget: write.text,\n\t\t\t\tprevious: write.target,\n\t\t\t\tinstructions: \"Replace the new memory text with the original text it overwrote.\",\n\t\t\t};\n\t\tcase \"memory_remove\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_add\",\n\t\t\t\tprevious: write.target,\n\t\t\t\tinstructions: \"Re-add the removed text to the MEMORY file (it may originally have lived in USER).\",\n\t\t\t};\n\t\tcase \"promote_skill\":\n\t\t\treturn {\n\t\t\t\tkind: \"archive_skill\",\n\t\t\t\ttarget: write.name,\n\t\t\t\tinstructions: \"Archive the promoted skill so it no longer loads.\",\n\t\t\t};\n\t}\n}\n\nconst AUDIT_ACTIONS: readonly string[] = [\"apply\", \"apply_failed\", \"propose\", \"rollback\"];\nconst ROLLBACK_KINDS: readonly string[] = [\"memory_remove\", \"memory_restore\", \"memory_add\", \"archive_skill\"];\nconst LAYERS: readonly string[] = [\"memory\", \"skill\", \"prompt\", \"extension\", \"tool\", \"script\", \"settings\", \"source\"];\n\nfunction isOptionalString(value: unknown): boolean {\n\treturn value === undefined || typeof value === \"string\";\n}\n\nfunction isLearningRollbackPlan(value: unknown): value is LearningRollbackPlan {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst plan = value as Record<string, unknown>;\n\tif (typeof plan.kind !== \"string\" || !ROLLBACK_KINDS.includes(plan.kind)) return false;\n\tif (!isOptionalString(plan.target) || !isOptionalString(plan.previous)) return false;\n\treturn typeof plan.instructions === \"string\";\n}\n\nfunction isLearningDecisionShape(value: unknown): value is LearningDecision {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst decision = value as Record<string, unknown>;\n\treturn (\n\t\t(decision.kind === \"no-op\" || decision.kind === \"proposal\" || decision.kind === \"apply\") &&\n\t\ttypeof decision.reasonCode === \"string\" &&\n\t\ttypeof decision.confidence === \"number\" &&\n\t\ttypeof decision.summary === \"string\" &&\n\t\ttypeof decision.requiresApproval === \"boolean\"\n\t);\n}\n\nexport function isLearningAuditRecord(value: unknown): value is LearningAuditRecord {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst record = value as Record<string, unknown>;\n\tif (typeof record.id !== \"string\" || record.id.length === 0) return false;\n\tif (typeof record.proposalId !== \"string\") return false;\n\tif (typeof record.layer !== \"string\" || !LAYERS.includes(record.layer)) return false;\n\tif (typeof record.action !== \"string\" || !AUDIT_ACTIONS.includes(record.action)) return false;\n\tif (typeof record.summary !== \"string\" || typeof record.reasonCode !== \"string\") return false;\n\tif (!isLearningDecisionShape(record.decision)) return false;\n\tif (record.rollback !== undefined && !isLearningRollbackPlan(record.rollback)) return false;\n\tif (!isOptionalString(record.rollbackOf)) return false;\n\treturn typeof record.createdAt === \"string\";\n}\n\nexport function cloneLearningAuditRecordForStorage(record: LearningAuditRecord): LearningAuditRecord {\n\treturn {\n\t\t...record,\n\t\tdecision: { ...record.decision },\n\t\t...(record.rollback ? { rollback: { ...record.rollback } } : {}),\n\t};\n}\n\nexport const LEARNING_AUDIT_CUSTOM_TYPE = \"learning_audit\";\n\nexport interface LearningAuditSnapshotPayload {\n\tversion: 1;\n\trecord: LearningAuditRecord;\n}\n\nexport function appendLearningAuditSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\trecord: LearningAuditRecord,\n): string {\n\tconst payload: LearningAuditSnapshotPayload = {\n\t\tversion: 1,\n\t\trecord: cloneLearningAuditRecordForStorage(record),\n\t};\n\treturn sessionManager.appendCustomEntry(LEARNING_AUDIT_CUSTOM_TYPE, payload);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function getLearningAuditSnapshots(entries: readonly SessionEntry[]): LearningAuditRecord[] {\n\tconst records: LearningAuditRecord[] = [];\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== LEARNING_AUDIT_CUSTOM_TYPE) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst payload = entry.data;\n\t\tif (!isPlainRecord(payload)) continue;\n\t\tif (payload.version !== 1) continue;\n\t\tif (!(\"record\" in payload)) continue;\n\t\tconst record = payload.record;\n\t\tif (isLearningAuditRecord(record)) {\n\t\t\trecords.push(cloneLearningAuditRecordForStorage(record));\n\t\t}\n\t}\n\n\treturn records;\n}\n"]}
@@ -1,3 +1,7 @@
1
+ /** reasonCode for an "apply_failed" audit — distinct from the gate's own reasonCode (e.g.
2
+ * "eligible_auto_apply") so the record is honest about WHERE it stopped: the gate approved the
3
+ * write, but the write tool refused it after the fact. */
4
+ export const APPLY_WRITE_REFUSED_REASON_CODE = "apply_write_refused";
1
5
  function describeWrite(write) {
2
6
  switch (write.kind) {
3
7
  case "memory_add":
@@ -18,6 +22,23 @@ export function proposalFromReflectionWrite(write, proposalId) {
18
22
  rollbackPlan: rollbackPlanForReflectionWrite(write).instructions,
19
23
  };
20
24
  }
25
+ /**
26
+ * Contradiction count a reflection write carries against existing durable knowledge. A
27
+ * `memory_replace`/`memory_remove` is only emitted when the reflection engine CONFRONTS an existing
28
+ * fact (it supersedes or deletes it) — that supersession is the gate's contradiction signal, so such
29
+ * a write must route through approval rather than silently overwriting prior memory. A `memory_add`
30
+ * or `promote_skill` is purely additive and contradicts nothing.
31
+ */
32
+ export function contradictionsForReflectionWrite(write) {
33
+ switch (write.kind) {
34
+ case "memory_replace":
35
+ case "memory_remove":
36
+ return 1;
37
+ case "memory_add":
38
+ case "promote_skill":
39
+ return 0;
40
+ }
41
+ }
21
42
  export function rollbackPlanForReflectionWrite(write) {
22
43
  switch (write.kind) {
23
44
  case "memory_add":
@@ -47,7 +68,7 @@ export function rollbackPlanForReflectionWrite(write) {
47
68
  };
48
69
  }
49
70
  }
50
- const AUDIT_ACTIONS = ["apply", "propose", "rollback"];
71
+ const AUDIT_ACTIONS = ["apply", "apply_failed", "propose", "rollback"];
51
72
  const ROLLBACK_KINDS = ["memory_remove", "memory_restore", "memory_add", "archive_skill"];
52
73
  const LAYERS = ["memory", "skill", "prompt", "extension", "tool", "script", "settings", "source"];
53
74
  function isOptionalString(value) {
@@ -1 +1 @@
1
- {"version":3,"file":"learning-audit.js","sourceRoot":"","sources":["../../../src/core/learning/learning-audit.ts"],"names":[],"mappings":"AAuCA,SAAS,aAAa,CAAC,KAAsB,EAAU;IACtD,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,YAAY;YAChB,OAAO,OAAO,KAAK,CAAC,OAAO,YAAY,KAAK,CAAC,IAAI,EAAE,CAAC;QACrD,KAAK,gBAAgB;YACpB,OAAO,mBAAmB,KAAK,CAAC,MAAM,WAAW,KAAK,CAAC,IAAI,GAAG,CAAC;QAChE,KAAK,eAAe;YACnB,OAAO,kBAAkB,KAAK,CAAC,MAAM,EAAE,CAAC;QACzC,KAAK,eAAe;YACnB,OAAO,kBAAkB,KAAK,CAAC,IAAI,MAAM,KAAK,CAAC,WAAW,EAAE,CAAC;IAC/D,CAAC;AAAA,CACD;AAED,MAAM,UAAU,2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AAO,KAAK,CAAC;YAAE,SAAS;QACpC,IAAI,CAAC,CAAC,QAAQ,IAAI,OAAO,CAAC;YAAE,SAAS;QACrC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC9B,IAAI,qBAAqB,CAAC,MAAM,CAAC,EAAE,CAAC;YACnC,OAAO,CAAC,IAAI,CAAC,kCAAkC,CAAC,MAAM,CAAC,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;IAED,OAAO,OAAO,CAAC;AAAA,CACf","sourcesContent":["import type { LearningDecision } from \"../autonomy/contracts.ts\";\nimport type { SessionEntry, SessionManager } from \"../session-manager.ts\";\nimport type { DurableChangeLayer, DurableChangeProposal } from \"./learning-gate.ts\";\nimport type { ReflectionWrite } from \"./reflection-engine.ts\";\n\n/**\n * Audit + rollback metadata for durable learning changes. Every reflection-sourced write that the\n * learning policy applies (or converts to a proposal) leaves one of these records in the session\n * log, so `/autonomy diagnostics` can explain what changed, why, and how to undo it — and\n * `rollbackLearningWrite` can execute the inverse operation.\n */\n\nexport type LearningRollbackKind = \"memory_remove\" | \"memory_restore\" | \"memory_add\" | \"archive_skill\";\n\nexport interface LearningRollbackPlan {\n\tkind: LearningRollbackKind;\n\t/** Text currently present because of the change (to remove/replace), or the skill name to archive. */\n\ttarget?: string;\n\t/** Original text to restore (memory_restore/memory_add). */\n\tprevious?: string;\n\tinstructions: string;\n}\n\nexport type LearningAuditAction = \"apply\" | \"propose\" | \"rollback\";\n\nexport interface LearningAuditRecord {\n\tid: string;\n\tproposalId: string;\n\tlayer: DurableChangeLayer;\n\taction: LearningAuditAction;\n\tsummary: string;\n\treasonCode: string;\n\tdecision: LearningDecision;\n\trollback?: LearningRollbackPlan;\n\t/** For action \"rollback\": the audit id of the applied change this record undoes. */\n\trollbackOf?: string;\n\tcreatedAt: string;\n}\n\nfunction describeWrite(write: ReflectionWrite): string {\n\tswitch (write.kind) {\n\t\tcase \"memory_add\":\n\t\t\treturn `Add ${write.section} memory: ${write.text}`;\n\t\tcase \"memory_replace\":\n\t\t\treturn `Replace memory \"${write.target}\" with \"${write.text}\"`;\n\t\tcase \"memory_remove\":\n\t\t\treturn `Remove memory: ${write.target}`;\n\t\tcase \"promote_skill\":\n\t\t\treturn `Promote skill \"${write.name}\": ${write.description}`;\n\t}\n}\n\nexport function proposalFromReflectionWrite(write: ReflectionWrite, proposalId: string): DurableChangeProposal {\n\treturn {\n\t\tid: proposalId,\n\t\tlayer: write.kind === \"promote_skill\" ? \"skill\" : \"memory\",\n\t\tsummary: describeWrite(write),\n\t\trollbackPlan: rollbackPlanForReflectionWrite(write).instructions,\n\t};\n}\n\nexport function rollbackPlanForReflectionWrite(write: ReflectionWrite): LearningRollbackPlan {\n\tswitch (write.kind) {\n\t\tcase \"memory_add\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_remove\",\n\t\t\t\ttarget: write.text,\n\t\t\t\tinstructions: `Remove the added ${write.section} memory text.`,\n\t\t\t};\n\t\tcase \"memory_replace\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_restore\",\n\t\t\t\ttarget: write.text,\n\t\t\t\tprevious: write.target,\n\t\t\t\tinstructions: \"Replace the new memory text with the original text it overwrote.\",\n\t\t\t};\n\t\tcase \"memory_remove\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_add\",\n\t\t\t\tprevious: write.target,\n\t\t\t\tinstructions: \"Re-add the removed text to the MEMORY file (it may originally have lived in USER).\",\n\t\t\t};\n\t\tcase \"promote_skill\":\n\t\t\treturn {\n\t\t\t\tkind: \"archive_skill\",\n\t\t\t\ttarget: write.name,\n\t\t\t\tinstructions: \"Archive the promoted skill so it no longer loads.\",\n\t\t\t};\n\t}\n}\n\nconst AUDIT_ACTIONS: readonly string[] = [\"apply\", \"propose\", \"rollback\"];\nconst ROLLBACK_KINDS: readonly string[] = [\"memory_remove\", \"memory_restore\", \"memory_add\", \"archive_skill\"];\nconst LAYERS: readonly string[] = [\"memory\", \"skill\", \"prompt\", \"extension\", \"tool\", \"script\", \"settings\", \"source\"];\n\nfunction isOptionalString(value: unknown): boolean {\n\treturn value === undefined || typeof value === \"string\";\n}\n\nfunction isLearningRollbackPlan(value: unknown): value is LearningRollbackPlan {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst plan = value as Record<string, unknown>;\n\tif (typeof plan.kind !== \"string\" || !ROLLBACK_KINDS.includes(plan.kind)) return false;\n\tif (!isOptionalString(plan.target) || !isOptionalString(plan.previous)) return false;\n\treturn typeof plan.instructions === \"string\";\n}\n\nfunction isLearningDecisionShape(value: unknown): value is LearningDecision {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst decision = value as Record<string, unknown>;\n\treturn (\n\t\t(decision.kind === \"no-op\" || decision.kind === \"proposal\" || decision.kind === \"apply\") &&\n\t\ttypeof decision.reasonCode === \"string\" &&\n\t\ttypeof decision.confidence === \"number\" &&\n\t\ttypeof decision.summary === \"string\" &&\n\t\ttypeof decision.requiresApproval === \"boolean\"\n\t);\n}\n\nexport function isLearningAuditRecord(value: unknown): value is LearningAuditRecord {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst record = value as Record<string, unknown>;\n\tif (typeof record.id !== \"string\" || record.id.length === 0) return false;\n\tif (typeof record.proposalId !== \"string\") return false;\n\tif (typeof record.layer !== \"string\" || !LAYERS.includes(record.layer)) return false;\n\tif (typeof record.action !== \"string\" || !AUDIT_ACTIONS.includes(record.action)) return false;\n\tif (typeof record.summary !== \"string\" || typeof record.reasonCode !== \"string\") return false;\n\tif (!isLearningDecisionShape(record.decision)) return false;\n\tif (record.rollback !== undefined && !isLearningRollbackPlan(record.rollback)) return false;\n\tif (!isOptionalString(record.rollbackOf)) return false;\n\treturn typeof record.createdAt === \"string\";\n}\n\nexport function cloneLearningAuditRecordForStorage(record: LearningAuditRecord): LearningAuditRecord {\n\treturn {\n\t\t...record,\n\t\tdecision: { ...record.decision },\n\t\t...(record.rollback ? { rollback: { ...record.rollback } } : {}),\n\t};\n}\n\nexport const LEARNING_AUDIT_CUSTOM_TYPE = \"learning_audit\";\n\nexport interface LearningAuditSnapshotPayload {\n\tversion: 1;\n\trecord: LearningAuditRecord;\n}\n\nexport function appendLearningAuditSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\trecord: LearningAuditRecord,\n): string {\n\tconst payload: LearningAuditSnapshotPayload = {\n\t\tversion: 1,\n\t\trecord: cloneLearningAuditRecordForStorage(record),\n\t};\n\treturn sessionManager.appendCustomEntry(LEARNING_AUDIT_CUSTOM_TYPE, payload);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function getLearningAuditSnapshots(entries: readonly SessionEntry[]): LearningAuditRecord[] {\n\tconst records: LearningAuditRecord[] = [];\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== LEARNING_AUDIT_CUSTOM_TYPE) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst payload = entry.data;\n\t\tif (!isPlainRecord(payload)) continue;\n\t\tif (payload.version !== 1) continue;\n\t\tif (!(\"record\" in payload)) continue;\n\t\tconst record = payload.record;\n\t\tif (isLearningAuditRecord(record)) {\n\t\t\trecords.push(cloneLearningAuditRecordForStorage(record));\n\t\t}\n\t}\n\n\treturn records;\n}\n"]}
1
+ {"version":3,"file":"learning-audit.js","sourceRoot":"","sources":["../../../src/core/learning/learning-audit.ts"],"names":[],"mappings":"AA4BA;;0DAE0D;AAC1D,MAAM,CAAC,MAAM,+BAA+B,GAAG,qBAAqB,CAAC;AAgBrE,SAAS,aAAa,CAAC,KAAsB,EAAU;IACtD,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,YAAY;YAChB,OAAO,OAAO,KAAK,CAAC,OAAO,YAAY,KAAK,CAAC,IAAI,EAA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AAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9E,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,SAAS,KAAK,IAAI,CAAC;AAAA,CAC5D;AAED,MAAM,UAAU,yBAAyB,CAAC,OAAgC,EAAyB;IAClG,MAAM,OAAO,GAA0B,EAAE,CAAC;IAE1C,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,UAAU,KAAK,0BAA0B,EAAE,CAAC;YAChF,SAAS;QACV,CAAC;QAED,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC;QAC3B,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC;YAAE,SAAS;QACtC,IAAI,OAAO,CAAC,OAAO,KAAK,CAAC;YAAE,SAAS;QACpC,IAAI,CAAC,CAAC,QAAQ,IAAI,OAAO,CAAC;YAAE,SAAS;QACrC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC9B,IAAI,qBAAqB,CAAC,MAAM,CAAC,EAAE,CAAC;YACnC,OAAO,CAAC,IAAI,CAAC,kCAAkC,CAAC,MAAM,CAAC,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;IAED,OAAO,OAAO,CAAC;AAAA,CACf","sourcesContent":["import type { LearningDecision } from \"../autonomy/contracts.ts\";\nimport type { SessionEntry, SessionManager } from \"../session-manager.ts\";\nimport type { DurableChangeLayer, DurableChangeProposal } from \"./learning-gate.ts\";\nimport type { ReflectionWrite } from \"./reflection-engine.ts\";\n\n/**\n * Audit + rollback metadata for durable learning changes. Every reflection-sourced write that the\n * learning policy applies (or converts to a proposal) leaves one of these records in the session\n * log, so `/autonomy diagnostics` can explain what changed, why, and how to undo it — and\n * `rollbackLearningWrite` can execute the inverse operation.\n */\n\nexport type LearningRollbackKind = \"memory_remove\" | \"memory_restore\" | \"memory_add\" | \"archive_skill\";\n\nexport interface LearningRollbackPlan {\n\tkind: LearningRollbackKind;\n\t/** Text currently present because of the change (to remove/replace), or the skill name to archive. */\n\ttarget?: string;\n\t/** Original text to restore (memory_restore/memory_add). */\n\tprevious?: string;\n\tinstructions: string;\n}\n\n// \"apply_failed\" is distinct from \"apply\": the gate decided to apply, but the underlying write tool\n// (e.g. the memory tool) refused it (budget exceeded, drift, threat) without throwing. It must never\n// be treated as \"apply\" by a rollback-eligibility check — there is nothing durable to undo.\nexport type LearningAuditAction = \"apply\" | \"apply_failed\" | \"propose\" | \"rollback\";\n\n/** reasonCode for an \"apply_failed\" audit — distinct from the gate's own reasonCode (e.g.\n * \"eligible_auto_apply\") so the record is honest about WHERE it stopped: the gate approved the\n * write, but the write tool refused it after the fact. */\nexport const APPLY_WRITE_REFUSED_REASON_CODE = \"apply_write_refused\";\n\nexport interface LearningAuditRecord {\n\tid: string;\n\tproposalId: string;\n\tlayer: DurableChangeLayer;\n\taction: LearningAuditAction;\n\tsummary: string;\n\treasonCode: string;\n\tdecision: LearningDecision;\n\trollback?: LearningRollbackPlan;\n\t/** For action \"rollback\": the audit id of the applied change this record undoes. */\n\trollbackOf?: string;\n\tcreatedAt: string;\n}\n\nfunction describeWrite(write: ReflectionWrite): string {\n\tswitch (write.kind) {\n\t\tcase \"memory_add\":\n\t\t\treturn `Add ${write.section} memory: ${write.text}`;\n\t\tcase \"memory_replace\":\n\t\t\treturn `Replace memory \"${write.target}\" with \"${write.text}\"`;\n\t\tcase \"memory_remove\":\n\t\t\treturn `Remove memory: ${write.target}`;\n\t\tcase \"promote_skill\":\n\t\t\treturn `Promote skill \"${write.name}\": ${write.description}`;\n\t}\n}\n\nexport function proposalFromReflectionWrite(write: ReflectionWrite, proposalId: string): DurableChangeProposal {\n\treturn {\n\t\tid: proposalId,\n\t\tlayer: write.kind === \"promote_skill\" ? \"skill\" : \"memory\",\n\t\tsummary: describeWrite(write),\n\t\trollbackPlan: rollbackPlanForReflectionWrite(write).instructions,\n\t};\n}\n\n/**\n * Contradiction count a reflection write carries against existing durable knowledge. A\n * `memory_replace`/`memory_remove` is only emitted when the reflection engine CONFRONTS an existing\n * fact (it supersedes or deletes it) — that supersession is the gate's contradiction signal, so such\n * a write must route through approval rather than silently overwriting prior memory. A `memory_add`\n * or `promote_skill` is purely additive and contradicts nothing.\n */\nexport function contradictionsForReflectionWrite(write: ReflectionWrite): number {\n\tswitch (write.kind) {\n\t\tcase \"memory_replace\":\n\t\tcase \"memory_remove\":\n\t\t\treturn 1;\n\t\tcase \"memory_add\":\n\t\tcase \"promote_skill\":\n\t\t\treturn 0;\n\t}\n}\n\nexport function rollbackPlanForReflectionWrite(write: ReflectionWrite): LearningRollbackPlan {\n\tswitch (write.kind) {\n\t\tcase \"memory_add\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_remove\",\n\t\t\t\ttarget: write.text,\n\t\t\t\tinstructions: `Remove the added ${write.section} memory text.`,\n\t\t\t};\n\t\tcase \"memory_replace\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_restore\",\n\t\t\t\ttarget: write.text,\n\t\t\t\tprevious: write.target,\n\t\t\t\tinstructions: \"Replace the new memory text with the original text it overwrote.\",\n\t\t\t};\n\t\tcase \"memory_remove\":\n\t\t\treturn {\n\t\t\t\tkind: \"memory_add\",\n\t\t\t\tprevious: write.target,\n\t\t\t\tinstructions: \"Re-add the removed text to the MEMORY file (it may originally have lived in USER).\",\n\t\t\t};\n\t\tcase \"promote_skill\":\n\t\t\treturn {\n\t\t\t\tkind: \"archive_skill\",\n\t\t\t\ttarget: write.name,\n\t\t\t\tinstructions: \"Archive the promoted skill so it no longer loads.\",\n\t\t\t};\n\t}\n}\n\nconst AUDIT_ACTIONS: readonly string[] = [\"apply\", \"apply_failed\", \"propose\", \"rollback\"];\nconst ROLLBACK_KINDS: readonly string[] = [\"memory_remove\", \"memory_restore\", \"memory_add\", \"archive_skill\"];\nconst LAYERS: readonly string[] = [\"memory\", \"skill\", \"prompt\", \"extension\", \"tool\", \"script\", \"settings\", \"source\"];\n\nfunction isOptionalString(value: unknown): boolean {\n\treturn value === undefined || typeof value === \"string\";\n}\n\nfunction isLearningRollbackPlan(value: unknown): value is LearningRollbackPlan {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst plan = value as Record<string, unknown>;\n\tif (typeof plan.kind !== \"string\" || !ROLLBACK_KINDS.includes(plan.kind)) return false;\n\tif (!isOptionalString(plan.target) || !isOptionalString(plan.previous)) return false;\n\treturn typeof plan.instructions === \"string\";\n}\n\nfunction isLearningDecisionShape(value: unknown): value is LearningDecision {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst decision = value as Record<string, unknown>;\n\treturn (\n\t\t(decision.kind === \"no-op\" || decision.kind === \"proposal\" || decision.kind === \"apply\") &&\n\t\ttypeof decision.reasonCode === \"string\" &&\n\t\ttypeof decision.confidence === \"number\" &&\n\t\ttypeof decision.summary === \"string\" &&\n\t\ttypeof decision.requiresApproval === \"boolean\"\n\t);\n}\n\nexport function isLearningAuditRecord(value: unknown): value is LearningAuditRecord {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst record = value as Record<string, unknown>;\n\tif (typeof record.id !== \"string\" || record.id.length === 0) return false;\n\tif (typeof record.proposalId !== \"string\") return false;\n\tif (typeof record.layer !== \"string\" || !LAYERS.includes(record.layer)) return false;\n\tif (typeof record.action !== \"string\" || !AUDIT_ACTIONS.includes(record.action)) return false;\n\tif (typeof record.summary !== \"string\" || typeof record.reasonCode !== \"string\") return false;\n\tif (!isLearningDecisionShape(record.decision)) return false;\n\tif (record.rollback !== undefined && !isLearningRollbackPlan(record.rollback)) return false;\n\tif (!isOptionalString(record.rollbackOf)) return false;\n\treturn typeof record.createdAt === \"string\";\n}\n\nexport function cloneLearningAuditRecordForStorage(record: LearningAuditRecord): LearningAuditRecord {\n\treturn {\n\t\t...record,\n\t\tdecision: { ...record.decision },\n\t\t...(record.rollback ? { rollback: { ...record.rollback } } : {}),\n\t};\n}\n\nexport const LEARNING_AUDIT_CUSTOM_TYPE = \"learning_audit\";\n\nexport interface LearningAuditSnapshotPayload {\n\tversion: 1;\n\trecord: LearningAuditRecord;\n}\n\nexport function appendLearningAuditSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\trecord: LearningAuditRecord,\n): string {\n\tconst payload: LearningAuditSnapshotPayload = {\n\t\tversion: 1,\n\t\trecord: cloneLearningAuditRecordForStorage(record),\n\t};\n\treturn sessionManager.appendCustomEntry(LEARNING_AUDIT_CUSTOM_TYPE, payload);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function getLearningAuditSnapshots(entries: readonly SessionEntry[]): LearningAuditRecord[] {\n\tconst records: LearningAuditRecord[] = [];\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== LEARNING_AUDIT_CUSTOM_TYPE) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst payload = entry.data;\n\t\tif (!isPlainRecord(payload)) continue;\n\t\tif (payload.version !== 1) continue;\n\t\tif (!(\"record\" in payload)) continue;\n\t\tconst record = payload.record;\n\t\tif (isLearningAuditRecord(record)) {\n\t\t\trecords.push(cloneLearningAuditRecordForStorage(record));\n\t\t}\n\t}\n\n\treturn records;\n}\n"]}
@@ -15,6 +15,9 @@ export interface LearningGateSettings {
15
15
  allowedAutoApplyLayers: readonly DurableChangeLayer[];
16
16
  requireRollbackPlan?: boolean;
17
17
  requireEvidence?: boolean;
18
+ /** default: false — a memory_replace/memory_remove (supersedes/deletes an existing fact) stays an
19
+ * approval-gated proposal even when otherwise eligible, unless explicitly opted in. */
20
+ autoApplySupersessions?: boolean;
18
21
  }
19
22
  export declare function evaluateLearningDecision(args: {
20
23
  proposal: DurableChangeProposal;
@@ -1 +1 @@
1
- {"version":3,"file":"learning-gate.d.ts","sourceRoot":"","sources":["../../../src/core/learning/learning-gate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,MAAM,MAAM,kBAAkB,GAC3B,QAAQ,GACR,OAAO,GACP,QAAQ,GACR,WAAW,GACX,MAAM,GACN,QAAQ,GACR,UAAU,GACV,QAAQ,CAAC;AAEZ,MAAM,WAAW,qBAAqB;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,kBAAkB,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,oBAAoB;IACpC,OAAO,EAAE,OAAO,CAAC;IACjB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,eAAe,EAAE,MAAM,CAAC;IACxB,sBAAsB,EAAE,SAAS,kBAAkB,EAAE,CAAC;IACtD,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AA2BD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE;IAC9C,QAAQ,EAAE,qBAAqB,CAAC;IAChC,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,GAAG,CAAC,EAAE,MAAM,CAAC;CACb,GAAG,gBAAgB,CA2GnB;AAQD,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,gBAAgB,CAc5E;AAED,wBAAgB,+BAA+B,CAAC,QAAQ,EAAE,gBAAgB,GAAG,gBAAgB,CAS5F","sourcesContent":["import type { LearningDecision } from \"../autonomy/contracts.ts\";\n\nexport type DurableChangeLayer =\n\t| \"memory\"\n\t| \"skill\"\n\t| \"prompt\"\n\t| \"extension\"\n\t| \"tool\"\n\t| \"script\"\n\t| \"settings\"\n\t| \"source\";\n\nexport interface DurableChangeProposal {\n\tid: string;\n\tlayer: DurableChangeLayer;\n\tsummary: string;\n\tevidenceIds?: readonly string[];\n\trollbackPlan?: string;\n}\n\nexport interface LearningGateSettings {\n\tenabled: boolean;\n\tautoApplyEnabled: boolean;\n\tconfidenceThreshold: number;\n\tminObservations: number;\n\tallowedAutoApplyLayers: readonly DurableChangeLayer[];\n\trequireRollbackPlan?: boolean;\n\trequireEvidence?: boolean;\n}\n\nconst MAX_DECISION_SUMMARY_LENGTH = 240;\n\nfunction boundedDecisionSummary(summary: string): string {\n\tif (summary.length <= MAX_DECISION_SUMMARY_LENGTH) return summary;\n\treturn `${summary.slice(0, MAX_DECISION_SUMMARY_LENGTH - 1)}…`;\n}\n\nfunction learningDecision(args: {\n\tkind: LearningDecision[\"kind\"];\n\treasonCode: string;\n\tconfidence: number;\n\tsummary: string;\n\trequiresApproval: boolean;\n\tcreatedAt?: string;\n}): LearningDecision {\n\treturn {\n\t\tkind: args.kind,\n\t\treasonCode: args.reasonCode,\n\t\tconfidence: args.confidence,\n\t\tsummary: boundedDecisionSummary(args.summary),\n\t\trequiresApproval: args.requiresApproval,\n\t\tcreatedAt: args.createdAt,\n\t};\n}\n\nexport function evaluateLearningDecision(args: {\n\tproposal: DurableChangeProposal;\n\tconfidence: number;\n\tobservations: number;\n\tcontradictions: number;\n\tsettings: LearningGateSettings;\n\tnow?: string;\n}): LearningDecision {\n\tconst { proposal, confidence, observations, contradictions, settings, now } = args;\n\n\tif (!settings.enabled) {\n\t\treturn learningDecision({\n\t\t\tkind: \"no-op\",\n\t\t\treasonCode: \"learning_disabled\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: false,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (contradictions > 0) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"contradictions_present\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (confidence < settings.confidenceThreshold) {\n\t\tconst hasEvidence = !!(proposal.evidenceIds && proposal.evidenceIds.length > 0);\n\t\treturn learningDecision({\n\t\t\tkind: hasEvidence ? \"proposal\" : \"no-op\",\n\t\t\treasonCode: \"below_confidence_threshold\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: hasEvidence,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (observations < settings.minObservations) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"insufficient_observations\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (settings.requireEvidence) {\n\t\tconst hasEvidence = !!(proposal.evidenceIds && proposal.evidenceIds.length > 0);\n\t\tif (!hasEvidence) {\n\t\t\treturn learningDecision({\n\t\t\t\tkind: \"proposal\",\n\t\t\t\treasonCode: \"missing_evidence\",\n\t\t\t\tconfidence,\n\t\t\t\tsummary: proposal.summary,\n\t\t\t\trequiresApproval: true,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (settings.requireRollbackPlan) {\n\t\tconst hasRollback = proposal.rollbackPlan !== undefined && proposal.rollbackPlan.trim().length > 0;\n\t\tif (!hasRollback) {\n\t\t\treturn learningDecision({\n\t\t\t\tkind: \"proposal\",\n\t\t\t\treasonCode: \"missing_rollback_plan\",\n\t\t\t\tconfidence,\n\t\t\t\tsummary: proposal.summary,\n\t\t\t\trequiresApproval: true,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (!settings.autoApplyEnabled) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"auto_apply_disabled\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tconst isAllowed = settings.allowedAutoApplyLayers.includes(proposal.layer);\n\tif (!isAllowed) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"layer_not_allowed_for_auto_apply\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\treturn learningDecision({\n\t\tkind: \"apply\",\n\t\treasonCode: \"eligible_auto_apply\",\n\t\tconfidence,\n\t\tsummary: proposal.summary,\n\t\trequiresApproval: false,\n\t\tcreatedAt: now,\n\t});\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function isLearningDecision(value: unknown): value is LearningDecision {\n\tif (!isPlainRecord(value)) return false;\n\n\tif (typeof value.kind !== \"string\" || ![\"no-op\", \"proposal\", \"apply\"].includes(value.kind)) {\n\t\treturn false;\n\t}\n\n\tif (typeof value.reasonCode !== \"string\") return false;\n\tif (typeof value.confidence !== \"number\" || !Number.isFinite(value.confidence)) return false;\n\tif (typeof value.summary !== \"string\") return false;\n\tif (typeof value.requiresApproval !== \"boolean\") return false;\n\tif (value.createdAt !== undefined && typeof value.createdAt !== \"string\") return false;\n\n\treturn true;\n}\n\nexport function cloneLearningDecisionForStorage(decision: LearningDecision): LearningDecision {\n\treturn {\n\t\tkind: decision.kind,\n\t\treasonCode: decision.reasonCode,\n\t\tconfidence: decision.confidence,\n\t\tsummary: decision.summary,\n\t\trequiresApproval: decision.requiresApproval,\n\t\tcreatedAt: decision.createdAt,\n\t};\n}\n"]}
1
+ {"version":3,"file":"learning-gate.d.ts","sourceRoot":"","sources":["../../../src/core/learning/learning-gate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,MAAM,MAAM,kBAAkB,GAC3B,QAAQ,GACR,OAAO,GACP,QAAQ,GACR,WAAW,GACX,MAAM,GACN,QAAQ,GACR,UAAU,GACV,QAAQ,CAAC;AAEZ,MAAM,WAAW,qBAAqB;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,kBAAkB,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,oBAAoB;IACpC,OAAO,EAAE,OAAO,CAAC;IACjB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,eAAe,EAAE,MAAM,CAAC;IACxB,sBAAsB,EAAE,SAAS,kBAAkB,EAAE,CAAC;IACtD,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;2FACuF;IACvF,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACjC;AA2BD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE;IAC9C,QAAQ,EAAE,qBAAqB,CAAC;IAChC,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,GAAG,CAAC,EAAE,MAAM,CAAC;CACb,GAAG,gBAAgB,CAoHnB;AAQD,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,gBAAgB,CAc5E;AAED,wBAAgB,+BAA+B,CAAC,QAAQ,EAAE,gBAAgB,GAAG,gBAAgB,CAS5F","sourcesContent":["import type { LearningDecision } from \"../autonomy/contracts.ts\";\n\nexport type DurableChangeLayer =\n\t| \"memory\"\n\t| \"skill\"\n\t| \"prompt\"\n\t| \"extension\"\n\t| \"tool\"\n\t| \"script\"\n\t| \"settings\"\n\t| \"source\";\n\nexport interface DurableChangeProposal {\n\tid: string;\n\tlayer: DurableChangeLayer;\n\tsummary: string;\n\tevidenceIds?: readonly string[];\n\trollbackPlan?: string;\n}\n\nexport interface LearningGateSettings {\n\tenabled: boolean;\n\tautoApplyEnabled: boolean;\n\tconfidenceThreshold: number;\n\tminObservations: number;\n\tallowedAutoApplyLayers: readonly DurableChangeLayer[];\n\trequireRollbackPlan?: boolean;\n\trequireEvidence?: boolean;\n\t/** default: false — a memory_replace/memory_remove (supersedes/deletes an existing fact) stays an\n\t * approval-gated proposal even when otherwise eligible, unless explicitly opted in. */\n\tautoApplySupersessions?: boolean;\n}\n\nconst MAX_DECISION_SUMMARY_LENGTH = 240;\n\nfunction boundedDecisionSummary(summary: string): string {\n\tif (summary.length <= MAX_DECISION_SUMMARY_LENGTH) return summary;\n\treturn `${summary.slice(0, MAX_DECISION_SUMMARY_LENGTH - 1)}…`;\n}\n\nfunction learningDecision(args: {\n\tkind: LearningDecision[\"kind\"];\n\treasonCode: string;\n\tconfidence: number;\n\tsummary: string;\n\trequiresApproval: boolean;\n\tcreatedAt?: string;\n}): LearningDecision {\n\treturn {\n\t\tkind: args.kind,\n\t\treasonCode: args.reasonCode,\n\t\tconfidence: args.confidence,\n\t\tsummary: boundedDecisionSummary(args.summary),\n\t\trequiresApproval: args.requiresApproval,\n\t\tcreatedAt: args.createdAt,\n\t};\n}\n\nexport function evaluateLearningDecision(args: {\n\tproposal: DurableChangeProposal;\n\tconfidence: number;\n\tobservations: number;\n\tcontradictions: number;\n\tsettings: LearningGateSettings;\n\tnow?: string;\n}): LearningDecision {\n\tconst { proposal, confidence, observations, contradictions, settings, now } = args;\n\n\tif (!settings.enabled) {\n\t\treturn learningDecision({\n\t\t\tkind: \"no-op\",\n\t\t\treasonCode: \"learning_disabled\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: false,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\t// A replace/remove supersedes or deletes an existing fact — the reflection engine's\n\t// confront-before-write conflict signal — so by default it routes through approval rather than\n\t// silently overwriting prior memory. With `autoApplySupersessions` opted in, that signal no longer\n\t// short-circuits the decision outright: it FALLS THROUGH to the standard eligibility chain below,\n\t// so a supersession auto-applies only when everything else (threshold/observations/evidence/\n\t// rollback/autoApplyEnabled/layer) also passes.\n\tif (contradictions > 0 && !settings.autoApplySupersessions) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"contradictions_present\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (confidence < settings.confidenceThreshold) {\n\t\t// Below-threshold confidence degrades to an approval-gated proposal, never a silent no-op:\n\t\t// learning stays fail-closed (it can only auto-apply above the threshold) while remaining\n\t\t// VISIBLE and audited. A silent no-op here disabled learning entirely under stock settings\n\t\t// (reflectionSourceConfidence < confidenceThreshold, reflection writes carrying no evidenceIds).\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"below_confidence_threshold\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (observations < settings.minObservations) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"insufficient_observations\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (settings.requireEvidence) {\n\t\tconst hasEvidence = !!(proposal.evidenceIds && proposal.evidenceIds.length > 0);\n\t\tif (!hasEvidence) {\n\t\t\treturn learningDecision({\n\t\t\t\tkind: \"proposal\",\n\t\t\t\treasonCode: \"missing_evidence\",\n\t\t\t\tconfidence,\n\t\t\t\tsummary: proposal.summary,\n\t\t\t\trequiresApproval: true,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (settings.requireRollbackPlan) {\n\t\tconst hasRollback = proposal.rollbackPlan !== undefined && proposal.rollbackPlan.trim().length > 0;\n\t\tif (!hasRollback) {\n\t\t\treturn learningDecision({\n\t\t\t\tkind: \"proposal\",\n\t\t\t\treasonCode: \"missing_rollback_plan\",\n\t\t\t\tconfidence,\n\t\t\t\tsummary: proposal.summary,\n\t\t\t\trequiresApproval: true,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (!settings.autoApplyEnabled) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"auto_apply_disabled\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tconst isAllowed = settings.allowedAutoApplyLayers.includes(proposal.layer);\n\tif (!isAllowed) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"layer_not_allowed_for_auto_apply\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\treturn learningDecision({\n\t\tkind: \"apply\",\n\t\treasonCode: \"eligible_auto_apply\",\n\t\tconfidence,\n\t\tsummary: proposal.summary,\n\t\trequiresApproval: false,\n\t\tcreatedAt: now,\n\t});\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function isLearningDecision(value: unknown): value is LearningDecision {\n\tif (!isPlainRecord(value)) return false;\n\n\tif (typeof value.kind !== \"string\" || ![\"no-op\", \"proposal\", \"apply\"].includes(value.kind)) {\n\t\treturn false;\n\t}\n\n\tif (typeof value.reasonCode !== \"string\") return false;\n\tif (typeof value.confidence !== \"number\" || !Number.isFinite(value.confidence)) return false;\n\tif (typeof value.summary !== \"string\") return false;\n\tif (typeof value.requiresApproval !== \"boolean\") return false;\n\tif (value.createdAt !== undefined && typeof value.createdAt !== \"string\") return false;\n\n\treturn true;\n}\n\nexport function cloneLearningDecisionForStorage(decision: LearningDecision): LearningDecision {\n\treturn {\n\t\tkind: decision.kind,\n\t\treasonCode: decision.reasonCode,\n\t\tconfidence: decision.confidence,\n\t\tsummary: decision.summary,\n\t\trequiresApproval: decision.requiresApproval,\n\t\tcreatedAt: decision.createdAt,\n\t};\n}\n"]}
@@ -26,7 +26,13 @@ export function evaluateLearningDecision(args) {
26
26
  createdAt: now,
27
27
  });
28
28
  }
29
- if (contradictions > 0) {
29
+ // A replace/remove supersedes or deletes an existing fact — the reflection engine's
30
+ // confront-before-write conflict signal — so by default it routes through approval rather than
31
+ // silently overwriting prior memory. With `autoApplySupersessions` opted in, that signal no longer
32
+ // short-circuits the decision outright: it FALLS THROUGH to the standard eligibility chain below,
33
+ // so a supersession auto-applies only when everything else (threshold/observations/evidence/
34
+ // rollback/autoApplyEnabled/layer) also passes.
35
+ if (contradictions > 0 && !settings.autoApplySupersessions) {
30
36
  return learningDecision({
31
37
  kind: "proposal",
32
38
  reasonCode: "contradictions_present",
@@ -37,13 +43,16 @@ export function evaluateLearningDecision(args) {
37
43
  });
38
44
  }
39
45
  if (confidence < settings.confidenceThreshold) {
40
- const hasEvidence = !!(proposal.evidenceIds && proposal.evidenceIds.length > 0);
46
+ // Below-threshold confidence degrades to an approval-gated proposal, never a silent no-op:
47
+ // learning stays fail-closed (it can only auto-apply above the threshold) while remaining
48
+ // VISIBLE and audited. A silent no-op here disabled learning entirely under stock settings
49
+ // (reflectionSourceConfidence < confidenceThreshold, reflection writes carrying no evidenceIds).
41
50
  return learningDecision({
42
- kind: hasEvidence ? "proposal" : "no-op",
51
+ kind: "proposal",
43
52
  reasonCode: "below_confidence_threshold",
44
53
  confidence,
45
54
  summary: proposal.summary,
46
- requiresApproval: hasEvidence,
55
+ requiresApproval: true,
47
56
  createdAt: now,
48
57
  });
49
58
  }
@@ -1 +1 @@
1
- {"version":3,"file":"learning-gate.js","sourceRoot":"","sources":["../../../src/core/learning/learning-gate.ts"],"names":[],"mappings":"AA8BA,MAAM,2BAA2B,GAAG,GAAG,CAAC;AAExC,SAAS,sBAAsB,CAAC,OAAe,EAAU;IACxD,IAAI,OAAO,CAAC,MAAM,IAAI,2BAA2B;QAAE,OAAO,OAAO,CAAC;IAClE,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,2BAA2B,GAAG,CAAC,CAAC,KAAG,CAAC;AAAA,CAC/D;AAED,SAAS,gBAAgB,CAAC,IAOzB,EAAoB;IACpB,OAAO;QACN,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,OAAO,EAAE,sBAAsB,CAAC,IAAI,CAAC,OAAO,CAAC;QAC7C,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;QACvC,SAAS,EAAE,IAAI,CAAC,SAAS;KACzB,CAAC;AAAA,CACF;AAED,MAAM,UAAU,wBAAwB,CAAC,IAOxC,EAAoB;IACpB,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,YAAY,EAAE,cAAc,EAAE,QAAQ,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAEnF,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;QACvB,OAAO,gBAAgB,CAAC;YACvB,IAAI,EAAE,OAAO;YACb,UAAU,EAAE,m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CAAC;IAC9D,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAEvF,OAAO,IAAI,CAAC;AAAA,CACZ;AAED,MAAM,UAAU,+BAA+B,CAAC,QAA0B,EAAoB;IAC7F,OAAO;QACN,IAAI,EAAE,QAAQ,CAAC,IAAI;QACnB,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB;QAC3C,SAAS,EAAE,QAAQ,CAAC,SAAS;KAC7B,CAAC;AAAA,CACF","sourcesContent":["import type { LearningDecision } from \"../autonomy/contracts.ts\";\n\nexport type DurableChangeLayer =\n\t| \"memory\"\n\t| \"skill\"\n\t| \"prompt\"\n\t| \"extension\"\n\t| \"tool\"\n\t| \"script\"\n\t| \"settings\"\n\t| \"source\";\n\nexport interface DurableChangeProposal {\n\tid: string;\n\tlayer: DurableChangeLayer;\n\tsummary: string;\n\tevidenceIds?: readonly string[];\n\trollbackPlan?: string;\n}\n\nexport interface LearningGateSettings {\n\tenabled: boolean;\n\tautoApplyEnabled: boolean;\n\tconfidenceThreshold: number;\n\tminObservations: number;\n\tallowedAutoApplyLayers: readonly DurableChangeLayer[];\n\trequireRollbackPlan?: boolean;\n\trequireEvidence?: boolean;\n}\n\nconst MAX_DECISION_SUMMARY_LENGTH = 240;\n\nfunction boundedDecisionSummary(summary: string): string {\n\tif (summary.length <= MAX_DECISION_SUMMARY_LENGTH) return summary;\n\treturn `${summary.slice(0, MAX_DECISION_SUMMARY_LENGTH - 1)}…`;\n}\n\nfunction learningDecision(args: {\n\tkind: LearningDecision[\"kind\"];\n\treasonCode: string;\n\tconfidence: number;\n\tsummary: string;\n\trequiresApproval: boolean;\n\tcreatedAt?: string;\n}): LearningDecision {\n\treturn {\n\t\tkind: args.kind,\n\t\treasonCode: args.reasonCode,\n\t\tconfidence: args.confidence,\n\t\tsummary: boundedDecisionSummary(args.summary),\n\t\trequiresApproval: args.requiresApproval,\n\t\tcreatedAt: args.createdAt,\n\t};\n}\n\nexport function evaluateLearningDecision(args: {\n\tproposal: DurableChangeProposal;\n\tconfidence: number;\n\tobservations: number;\n\tcontradictions: number;\n\tsettings: LearningGateSettings;\n\tnow?: string;\n}): LearningDecision {\n\tconst { proposal, confidence, observations, contradictions, settings, now } = args;\n\n\tif (!settings.enabled) {\n\t\treturn learningDecision({\n\t\t\tkind: \"no-op\",\n\t\t\treasonCode: \"learning_disabled\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: false,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (contradictions > 0) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"contradictions_present\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (confidence < settings.confidenceThreshold) {\n\t\tconst hasEvidence = !!(proposal.evidenceIds && proposal.evidenceIds.length > 0);\n\t\treturn learningDecision({\n\t\t\tkind: hasEvidence ? \"proposal\" : \"no-op\",\n\t\t\treasonCode: \"below_confidence_threshold\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: hasEvidence,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (observations < settings.minObservations) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"insufficient_observations\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (settings.requireEvidence) {\n\t\tconst hasEvidence = !!(proposal.evidenceIds && proposal.evidenceIds.length > 0);\n\t\tif (!hasEvidence) {\n\t\t\treturn learningDecision({\n\t\t\t\tkind: \"proposal\",\n\t\t\t\treasonCode: \"missing_evidence\",\n\t\t\t\tconfidence,\n\t\t\t\tsummary: proposal.summary,\n\t\t\t\trequiresApproval: true,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (settings.requireRollbackPlan) {\n\t\tconst hasRollback = proposal.rollbackPlan !== undefined && proposal.rollbackPlan.trim().length > 0;\n\t\tif (!hasRollback) {\n\t\t\treturn learningDecision({\n\t\t\t\tkind: \"proposal\",\n\t\t\t\treasonCode: \"missing_rollback_plan\",\n\t\t\t\tconfidence,\n\t\t\t\tsummary: proposal.summary,\n\t\t\t\trequiresApproval: true,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (!settings.autoApplyEnabled) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"auto_apply_disabled\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tconst isAllowed = settings.allowedAutoApplyLayers.includes(proposal.layer);\n\tif (!isAllowed) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"layer_not_allowed_for_auto_apply\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\treturn learningDecision({\n\t\tkind: \"apply\",\n\t\treasonCode: \"eligible_auto_apply\",\n\t\tconfidence,\n\t\tsummary: proposal.summary,\n\t\trequiresApproval: false,\n\t\tcreatedAt: now,\n\t});\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function isLearningDecision(value: unknown): value is LearningDecision {\n\tif (!isPlainRecord(value)) return false;\n\n\tif (typeof value.kind !== \"string\" || ![\"no-op\", \"proposal\", \"apply\"].includes(value.kind)) {\n\t\treturn false;\n\t}\n\n\tif (typeof value.reasonCode !== \"string\") return false;\n\tif (typeof value.confidence !== \"number\" || !Number.isFinite(value.confidence)) return false;\n\tif (typeof value.summary !== \"string\") return false;\n\tif (typeof value.requiresApproval !== \"boolean\") return false;\n\tif (value.createdAt !== undefined && typeof value.createdAt !== \"string\") return false;\n\n\treturn true;\n}\n\nexport function cloneLearningDecisionForStorage(decision: LearningDecision): LearningDecision {\n\treturn {\n\t\tkind: decision.kind,\n\t\treasonCode: decision.reasonCode,\n\t\tconfidence: decision.confidence,\n\t\tsummary: decision.summary,\n\t\trequiresApproval: decision.requiresApproval,\n\t\tcreatedAt: decision.createdAt,\n\t};\n}\n"]}
1
+ {"version":3,"file":"learning-gate.js","sourceRoot":"","sources":["../../../src/core/learning/learning-gate.ts"],"names":[],"mappings":"AAiCA,MAAM,2BAA2B,GAAG,GAAG,CAAC;AAExC,SAAS,sBAAsB,CAAC,OAAe,EAAU;IACxD,IAAI,OAAO,CAAC,MAAM,IAAI,2BAA2B;QAAE,OAAO,OAAO,CAAC;IAClE,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,2BAA2B,GAAG,CAAC,CAAC,KAAG,CAAC;AAAA,CAC/D;AAED,SAAS,gBAAgB,CAAC,IAOzB,EAAoB;IACpB,OAAO;QACN,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,OAAO,EAAE,sBAAsB,CAAC,IAAI,CAAC,OAAO,CAAC;QAC7C,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;QACvC,SAAS,EAAE,IAAI,CAAC,SAAS;KACzB,CAAC;AAAA,CACF;AAED,MAAM,UAAU,wBAAwB,CAAC,IAOxC,EAAoB;IACpB,MAAM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Q,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7F,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACpD,IAAI,OAAO,KAAK,CAAC,gBAAgB,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IAC9D,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAEvF,OAAO,IAAI,CAAC;AAAA,CACZ;AAED,MAAM,UAAU,+BAA+B,CAAC,QAA0B,EAAoB;IAC7F,OAAO;QACN,IAAI,EAAE,QAAQ,CAAC,IAAI;QACnB,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB;QAC3C,SAAS,EAAE,QAAQ,CAAC,SAAS;KAC7B,CAAC;AAAA,CACF","sourcesContent":["import type { LearningDecision } from \"../autonomy/contracts.ts\";\n\nexport type DurableChangeLayer =\n\t| \"memory\"\n\t| \"skill\"\n\t| \"prompt\"\n\t| \"extension\"\n\t| \"tool\"\n\t| \"script\"\n\t| \"settings\"\n\t| \"source\";\n\nexport interface DurableChangeProposal {\n\tid: string;\n\tlayer: DurableChangeLayer;\n\tsummary: string;\n\tevidenceIds?: readonly string[];\n\trollbackPlan?: string;\n}\n\nexport interface LearningGateSettings {\n\tenabled: boolean;\n\tautoApplyEnabled: boolean;\n\tconfidenceThreshold: number;\n\tminObservations: number;\n\tallowedAutoApplyLayers: readonly DurableChangeLayer[];\n\trequireRollbackPlan?: boolean;\n\trequireEvidence?: boolean;\n\t/** default: false — a memory_replace/memory_remove (supersedes/deletes an existing fact) stays an\n\t * approval-gated proposal even when otherwise eligible, unless explicitly opted in. */\n\tautoApplySupersessions?: boolean;\n}\n\nconst MAX_DECISION_SUMMARY_LENGTH = 240;\n\nfunction boundedDecisionSummary(summary: string): string {\n\tif (summary.length <= MAX_DECISION_SUMMARY_LENGTH) return summary;\n\treturn `${summary.slice(0, MAX_DECISION_SUMMARY_LENGTH - 1)}…`;\n}\n\nfunction learningDecision(args: {\n\tkind: LearningDecision[\"kind\"];\n\treasonCode: string;\n\tconfidence: number;\n\tsummary: string;\n\trequiresApproval: boolean;\n\tcreatedAt?: string;\n}): LearningDecision {\n\treturn {\n\t\tkind: args.kind,\n\t\treasonCode: args.reasonCode,\n\t\tconfidence: args.confidence,\n\t\tsummary: boundedDecisionSummary(args.summary),\n\t\trequiresApproval: args.requiresApproval,\n\t\tcreatedAt: args.createdAt,\n\t};\n}\n\nexport function evaluateLearningDecision(args: {\n\tproposal: DurableChangeProposal;\n\tconfidence: number;\n\tobservations: number;\n\tcontradictions: number;\n\tsettings: LearningGateSettings;\n\tnow?: string;\n}): LearningDecision {\n\tconst { proposal, confidence, observations, contradictions, settings, now } = args;\n\n\tif (!settings.enabled) {\n\t\treturn learningDecision({\n\t\t\tkind: \"no-op\",\n\t\t\treasonCode: \"learning_disabled\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: false,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\t// A replace/remove supersedes or deletes an existing fact — the reflection engine's\n\t// confront-before-write conflict signal — so by default it routes through approval rather than\n\t// silently overwriting prior memory. With `autoApplySupersessions` opted in, that signal no longer\n\t// short-circuits the decision outright: it FALLS THROUGH to the standard eligibility chain below,\n\t// so a supersession auto-applies only when everything else (threshold/observations/evidence/\n\t// rollback/autoApplyEnabled/layer) also passes.\n\tif (contradictions > 0 && !settings.autoApplySupersessions) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"contradictions_present\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (confidence < settings.confidenceThreshold) {\n\t\t// Below-threshold confidence degrades to an approval-gated proposal, never a silent no-op:\n\t\t// learning stays fail-closed (it can only auto-apply above the threshold) while remaining\n\t\t// VISIBLE and audited. A silent no-op here disabled learning entirely under stock settings\n\t\t// (reflectionSourceConfidence < confidenceThreshold, reflection writes carrying no evidenceIds).\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"below_confidence_threshold\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (observations < settings.minObservations) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"insufficient_observations\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tif (settings.requireEvidence) {\n\t\tconst hasEvidence = !!(proposal.evidenceIds && proposal.evidenceIds.length > 0);\n\t\tif (!hasEvidence) {\n\t\t\treturn learningDecision({\n\t\t\t\tkind: \"proposal\",\n\t\t\t\treasonCode: \"missing_evidence\",\n\t\t\t\tconfidence,\n\t\t\t\tsummary: proposal.summary,\n\t\t\t\trequiresApproval: true,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (settings.requireRollbackPlan) {\n\t\tconst hasRollback = proposal.rollbackPlan !== undefined && proposal.rollbackPlan.trim().length > 0;\n\t\tif (!hasRollback) {\n\t\t\treturn learningDecision({\n\t\t\t\tkind: \"proposal\",\n\t\t\t\treasonCode: \"missing_rollback_plan\",\n\t\t\t\tconfidence,\n\t\t\t\tsummary: proposal.summary,\n\t\t\t\trequiresApproval: true,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (!settings.autoApplyEnabled) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"auto_apply_disabled\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\tconst isAllowed = settings.allowedAutoApplyLayers.includes(proposal.layer);\n\tif (!isAllowed) {\n\t\treturn learningDecision({\n\t\t\tkind: \"proposal\",\n\t\t\treasonCode: \"layer_not_allowed_for_auto_apply\",\n\t\t\tconfidence,\n\t\t\tsummary: proposal.summary,\n\t\t\trequiresApproval: true,\n\t\t\tcreatedAt: now,\n\t\t});\n\t}\n\n\treturn learningDecision({\n\t\tkind: \"apply\",\n\t\treasonCode: \"eligible_auto_apply\",\n\t\tconfidence,\n\t\tsummary: proposal.summary,\n\t\trequiresApproval: false,\n\t\tcreatedAt: now,\n\t});\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function isLearningDecision(value: unknown): value is LearningDecision {\n\tif (!isPlainRecord(value)) return false;\n\n\tif (typeof value.kind !== \"string\" || ![\"no-op\", \"proposal\", \"apply\"].includes(value.kind)) {\n\t\treturn false;\n\t}\n\n\tif (typeof value.reasonCode !== \"string\") return false;\n\tif (typeof value.confidence !== \"number\" || !Number.isFinite(value.confidence)) return false;\n\tif (typeof value.summary !== \"string\") return false;\n\tif (typeof value.requiresApproval !== \"boolean\") return false;\n\tif (value.createdAt !== undefined && typeof value.createdAt !== \"string\") return false;\n\n\treturn true;\n}\n\nexport function cloneLearningDecisionForStorage(decision: LearningDecision): LearningDecision {\n\treturn {\n\t\tkind: decision.kind,\n\t\treasonCode: decision.reasonCode,\n\t\tconfidence: decision.confidence,\n\t\tsummary: decision.summary,\n\t\trequiresApproval: decision.requiresApproval,\n\t\tcreatedAt: decision.createdAt,\n\t};\n}\n"]}
@@ -5,6 +5,8 @@ export interface LocalRegistrationResult {
5
5
  /** When the file cannot be safely rewritten: the entry the user should add by hand. */
6
6
  manualSnippet?: string;
7
7
  }
8
+ /** Provider name pi registers pulled local models under (see registerLocalModel below). */
9
+ export declare const OLLAMA_PROVIDER = "ollama";
8
10
  export declare function registerLocalModel(args: {
9
11
  agentDir: string;
10
12
  ref: string;
@@ -1 +1 @@
1
- {"version":3,"file":"local-registration.d.ts","sourceRoot":"","sources":["../../../src/core/models/local-registration.ts"],"names":[],"mappings":"AAsCA,MAAM,WAAW,uBAAuB;IACvC,EAAE,EAAE,OAAO,CAAC;IACZ,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,uFAAuF;IACvF,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AA4BD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB,GAAG,uBAAuB,CAoC1B;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,uBAAuB,CAgBrG","sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Persistent registration for pulled local models: merges an \"ollama\" provider entry into the\n * user's `<agentDir>/models.json` — the exact file ModelRegistry loads at startup — so a pulled\n * model resolves as `ollama/<ref>` immediately AND across sessions (usable as session model,\n * lane model, judge, or curator).\n *\n * Non-destructive contract: the file is parsed with STRICT JSON first; a file that only parses\n * with comments/relaxed syntax is the user's hand-authored config and is never rewritten — the\n * caller gets `manualSnippet` to show instead.\n */\n\ninterface ModelsJsonModel {\n\tid: string;\n\tname?: string;\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n\treasoning?: boolean;\n\tinput?: string[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n}\n\ninterface ModelsJson {\n\tproviders: Record<\n\t\tstring,\n\t\t{\n\t\t\tbaseUrl?: string;\n\t\t\tapi?: string;\n\t\t\tapiKey?: string;\n\t\t\tmodels?: ModelsJsonModel[];\n\t\t\t[key: string]: unknown;\n\t\t}\n\t>;\n\t[key: string]: unknown;\n}\n\nexport interface LocalRegistrationResult {\n\tok: boolean;\n\tmodelsJsonPath: string;\n\treason?: string;\n\t/** When the file cannot be safely rewritten: the entry the user should add by hand. */\n\tmanualSnippet?: string;\n}\n\nconst OLLAMA_PROVIDER = \"ollama\";\n\nfunction localModelEntry(ref: string, contextWindow: number): ModelsJsonModel {\n\treturn {\n\t\tid: ref,\n\t\tname: ref,\n\t\tcontextWindow,\n\t\tmaxTokens: 2048,\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t};\n}\n\nfunction loadStrict(path: string): { json?: ModelsJson; reason?: string } {\n\tif (!existsSync(path)) return { json: { providers: {} } };\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as ModelsJson;\n\t\tif (!parsed || typeof parsed !== \"object\") return { reason: \"models.json is not a JSON object\" };\n\t\tparsed.providers = parsed.providers ?? {};\n\t\treturn { json: parsed };\n\t} catch {\n\t\treturn { reason: \"models.json uses comments/relaxed JSON — pi will not rewrite a hand-authored file\" };\n\t}\n}\n\nexport function registerLocalModel(args: {\n\tagentDir: string;\n\tref: string;\n\tbaseUrl: string;\n\tcontextWindow?: number;\n}): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst contextWindow = args.contextWindow ?? 8192;\n\tconst entry = localModelEntry(args.ref, contextWindow);\n\tconst providerBase = {\n\t\tbaseUrl: `${args.baseUrl.replace(/\\/$/, \"\")}/v1`,\n\t\tapi: \"openai-completions\",\n\t\tapiKey: \"ollama\",\n\t};\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmodelsJsonPath,\n\t\t\treason,\n\t\t\tmanualSnippet: JSON.stringify(\n\t\t\t\t{ providers: { [OLLAMA_PROVIDER]: { ...providerBase, models: [entry] } } },\n\t\t\t\tnull,\n\t\t\t\t\"\\t\",\n\t\t\t),\n\t\t};\n\t}\n\tjson.providers[OLLAMA_PROVIDER] ??= { ...providerBase, models: [] };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tprovider.baseUrl ??= providerBase.baseUrl;\n\tprovider.api ??= providerBase.api;\n\tprovider.apiKey ??= providerBase.apiKey;\n\tprovider.models ??= [];\n\tconst existing = provider.models.findIndex((model) => model.id === args.ref);\n\tif (existing >= 0) {\n\t\tprovider.models[existing] = { ...provider.models[existing], ...entry };\n\t} else {\n\t\tprovider.models.push(entry);\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function unregisterLocalModel(args: { agentDir: string; ref: string }): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) return { ok: false, modelsJsonPath, reason };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tif (!provider?.models) return { ok: true, modelsJsonPath };\n\tconst before = provider.models.length;\n\tprovider.models = provider.models.filter((model) => model.id !== args.ref);\n\tif (provider.models.length === before) return { ok: true, modelsJsonPath };\n\t// Drop the whole provider entry when its last pi-registered model goes (leave user fields alone\n\t// if they added any models themselves — only an all-pi-managed empty list is removed).\n\tif (provider.models.length === 0) {\n\t\tdelete json.providers[OLLAMA_PROVIDER];\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n"]}
1
+ {"version":3,"file":"local-registration.d.ts","sourceRoot":"","sources":["../../../src/core/models/local-registration.ts"],"names":[],"mappings":"AAsCA,MAAM,WAAW,uBAAuB;IACvC,EAAE,EAAE,OAAO,CAAC;IACZ,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,uFAAuF;IACvF,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,2FAA2F;AAC3F,eAAO,MAAM,eAAe,WAAW,CAAC;AA0BxC,wBAAgB,kBAAkB,CAAC,IAAI,EAAE;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB,GAAG,uBAAuB,CAoC1B;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,uBAAuB,CAgBrG","sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Persistent registration for pulled local models: merges an \"ollama\" provider entry into the\n * user's `<agentDir>/models.json` — the exact file ModelRegistry loads at startup — so a pulled\n * model resolves as `ollama/<ref>` immediately AND across sessions (usable as session model,\n * lane model, judge, or curator).\n *\n * Non-destructive contract: the file is parsed with STRICT JSON first; a file that only parses\n * with comments/relaxed syntax is the user's hand-authored config and is never rewritten — the\n * caller gets `manualSnippet` to show instead.\n */\n\ninterface ModelsJsonModel {\n\tid: string;\n\tname?: string;\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n\treasoning?: boolean;\n\tinput?: string[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n}\n\ninterface ModelsJson {\n\tproviders: Record<\n\t\tstring,\n\t\t{\n\t\t\tbaseUrl?: string;\n\t\t\tapi?: string;\n\t\t\tapiKey?: string;\n\t\t\tmodels?: ModelsJsonModel[];\n\t\t\t[key: string]: unknown;\n\t\t}\n\t>;\n\t[key: string]: unknown;\n}\n\nexport interface LocalRegistrationResult {\n\tok: boolean;\n\tmodelsJsonPath: string;\n\treason?: string;\n\t/** When the file cannot be safely rewritten: the entry the user should add by hand. */\n\tmanualSnippet?: string;\n}\n\n/** Provider name pi registers pulled local models under (see registerLocalModel below). */\nexport const OLLAMA_PROVIDER = \"ollama\";\n\nfunction localModelEntry(ref: string, contextWindow: number): ModelsJsonModel {\n\treturn {\n\t\tid: ref,\n\t\tname: ref,\n\t\tcontextWindow,\n\t\tmaxTokens: 2048,\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t};\n}\n\nfunction loadStrict(path: string): { json?: ModelsJson; reason?: string } {\n\tif (!existsSync(path)) return { json: { providers: {} } };\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as ModelsJson;\n\t\tif (!parsed || typeof parsed !== \"object\") return { reason: \"models.json is not a JSON object\" };\n\t\tparsed.providers = parsed.providers ?? {};\n\t\treturn { json: parsed };\n\t} catch {\n\t\treturn { reason: \"models.json uses comments/relaxed JSON — pi will not rewrite a hand-authored file\" };\n\t}\n}\n\nexport function registerLocalModel(args: {\n\tagentDir: string;\n\tref: string;\n\tbaseUrl: string;\n\tcontextWindow?: number;\n}): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst contextWindow = args.contextWindow ?? 8192;\n\tconst entry = localModelEntry(args.ref, contextWindow);\n\tconst providerBase = {\n\t\tbaseUrl: `${args.baseUrl.replace(/\\/$/, \"\")}/v1`,\n\t\tapi: \"openai-completions\",\n\t\tapiKey: \"ollama\",\n\t};\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmodelsJsonPath,\n\t\t\treason,\n\t\t\tmanualSnippet: JSON.stringify(\n\t\t\t\t{ providers: { [OLLAMA_PROVIDER]: { ...providerBase, models: [entry] } } },\n\t\t\t\tnull,\n\t\t\t\t\"\\t\",\n\t\t\t),\n\t\t};\n\t}\n\tjson.providers[OLLAMA_PROVIDER] ??= { ...providerBase, models: [] };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tprovider.baseUrl ??= providerBase.baseUrl;\n\tprovider.api ??= providerBase.api;\n\tprovider.apiKey ??= providerBase.apiKey;\n\tprovider.models ??= [];\n\tconst existing = provider.models.findIndex((model) => model.id === args.ref);\n\tif (existing >= 0) {\n\t\tprovider.models[existing] = { ...provider.models[existing], ...entry };\n\t} else {\n\t\tprovider.models.push(entry);\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function unregisterLocalModel(args: { agentDir: string; ref: string }): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) return { ok: false, modelsJsonPath, reason };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tif (!provider?.models) return { ok: true, modelsJsonPath };\n\tconst before = provider.models.length;\n\tprovider.models = provider.models.filter((model) => model.id !== args.ref);\n\tif (provider.models.length === before) return { ok: true, modelsJsonPath };\n\t// Drop the whole provider entry when its last pi-registered model goes (leave user fields alone\n\t// if they added any models themselves — only an all-pi-managed empty list is removed).\n\tif (provider.models.length === 0) {\n\t\tdelete json.providers[OLLAMA_PROVIDER];\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- const OLLAMA_PROVIDER = "ollama";
3
+ /** Provider name pi registers pulled local models under (see registerLocalModel below). */
4
+ export const OLLAMA_PROVIDER = "ollama";
4
5
  function localModelEntry(ref, contextWindow) {
5
6
  return {
6
7
  id: ref,
@@ -1 +1 @@
1
- {"version":3,"file":"local-registration.js","sourceRoot":"","sources":["../../../src/core/models/local-registration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AA6CjC,MAAM,eAAe,GAAG,QAAQ,CAAC;AAEjC,SAAS,eAAe,CAAC,GAAW,EAAE,aAAqB,EAAmB;IAC7E,OAAO;QACN,EAAE,EAAE,GAAG;QACP,IAAI,EAAE,GAAG;QACT,aAAa;QACb,SAAS,EAAE,IAAI;QACf,SAAS,EAAE,KAAK;QAChB,KAAK,EAAE,CAAC,MAAM,CAAC;QACf,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE;KAC1D,CAAC;AAAA,CACF;AAED,SAAS,UAAU,CAAC,IAAY,EAA0C;IACzE,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,CAAC;IAC1D,IAAI,CAAC;QACJ,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAe,CAAC;QACrE,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ;YAAE,OAAO,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC;QACjG,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,IAAI,EAAE,CAAC;QAC1C,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IACzB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,EAAE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,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,CAAC;IAC3E,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,KAAK,MAAM;QAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;IAC3E,gGAAgG;IAChG,yFAAuF;IACvF,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClC,OAAO,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACxC,CAAC;IACD,aAAa,CAAC,cAAc,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAChF,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAAA,CACpC","sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Persistent registration for pulled local models: merges an \"ollama\" provider entry into the\n * user's `<agentDir>/models.json` — the exact file ModelRegistry loads at startup — so a pulled\n * model resolves as `ollama/<ref>` immediately AND across sessions (usable as session model,\n * lane model, judge, or curator).\n *\n * Non-destructive contract: the file is parsed with STRICT JSON first; a file that only parses\n * with comments/relaxed syntax is the user's hand-authored config and is never rewritten — the\n * caller gets `manualSnippet` to show instead.\n */\n\ninterface ModelsJsonModel {\n\tid: string;\n\tname?: string;\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n\treasoning?: boolean;\n\tinput?: string[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n}\n\ninterface ModelsJson {\n\tproviders: Record<\n\t\tstring,\n\t\t{\n\t\t\tbaseUrl?: string;\n\t\t\tapi?: string;\n\t\t\tapiKey?: string;\n\t\t\tmodels?: ModelsJsonModel[];\n\t\t\t[key: string]: unknown;\n\t\t}\n\t>;\n\t[key: string]: unknown;\n}\n\nexport interface LocalRegistrationResult {\n\tok: boolean;\n\tmodelsJsonPath: string;\n\treason?: string;\n\t/** When the file cannot be safely rewritten: the entry the user should add by hand. */\n\tmanualSnippet?: string;\n}\n\nconst OLLAMA_PROVIDER = \"ollama\";\n\nfunction localModelEntry(ref: string, contextWindow: number): ModelsJsonModel {\n\treturn {\n\t\tid: ref,\n\t\tname: ref,\n\t\tcontextWindow,\n\t\tmaxTokens: 2048,\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t};\n}\n\nfunction loadStrict(path: string): { json?: ModelsJson; reason?: string } {\n\tif (!existsSync(path)) return { json: { providers: {} } };\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as ModelsJson;\n\t\tif (!parsed || typeof parsed !== \"object\") return { reason: \"models.json is not a JSON object\" };\n\t\tparsed.providers = parsed.providers ?? {};\n\t\treturn { json: parsed };\n\t} catch {\n\t\treturn { reason: \"models.json uses comments/relaxed JSON — pi will not rewrite a hand-authored file\" };\n\t}\n}\n\nexport function registerLocalModel(args: {\n\tagentDir: string;\n\tref: string;\n\tbaseUrl: string;\n\tcontextWindow?: number;\n}): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst contextWindow = args.contextWindow ?? 8192;\n\tconst entry = localModelEntry(args.ref, contextWindow);\n\tconst providerBase = {\n\t\tbaseUrl: `${args.baseUrl.replace(/\\/$/, \"\")}/v1`,\n\t\tapi: \"openai-completions\",\n\t\tapiKey: \"ollama\",\n\t};\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmodelsJsonPath,\n\t\t\treason,\n\t\t\tmanualSnippet: JSON.stringify(\n\t\t\t\t{ providers: { [OLLAMA_PROVIDER]: { ...providerBase, models: [entry] } } },\n\t\t\t\tnull,\n\t\t\t\t\"\\t\",\n\t\t\t),\n\t\t};\n\t}\n\tjson.providers[OLLAMA_PROVIDER] ??= { ...providerBase, models: [] };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tprovider.baseUrl ??= providerBase.baseUrl;\n\tprovider.api ??= providerBase.api;\n\tprovider.apiKey ??= providerBase.apiKey;\n\tprovider.models ??= [];\n\tconst existing = provider.models.findIndex((model) => model.id === args.ref);\n\tif (existing >= 0) {\n\t\tprovider.models[existing] = { ...provider.models[existing], ...entry };\n\t} else {\n\t\tprovider.models.push(entry);\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function unregisterLocalModel(args: { agentDir: string; ref: string }): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) return { ok: false, modelsJsonPath, reason };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tif (!provider?.models) return { ok: true, modelsJsonPath };\n\tconst before = provider.models.length;\n\tprovider.models = provider.models.filter((model) => model.id !== args.ref);\n\tif (provider.models.length === before) return { ok: true, modelsJsonPath };\n\t// Drop the whole provider entry when its last pi-registered model goes (leave user fields alone\n\t// if they added any models themselves — only an all-pi-managed empty list is removed).\n\tif (provider.models.length === 0) {\n\t\tdelete json.providers[OLLAMA_PROVIDER];\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n"]}
1
+ {"version":3,"file":"local-registration.js","sourceRoot":"","sources":["../../../src/core/models/local-registration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AA6CjC,2FAA2F;AAC3F,MAAM,CAAC,MAAM,eAAe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C,SAAS,CAAC,eAAe,CAAC,CAAC;IACxC,CAAC;IACD,aAAa,CAAC,cAAc,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAChF,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAAA,CACpC","sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Persistent registration for pulled local models: merges an \"ollama\" provider entry into the\n * user's `<agentDir>/models.json` — the exact file ModelRegistry loads at startup — so a pulled\n * model resolves as `ollama/<ref>` immediately AND across sessions (usable as session model,\n * lane model, judge, or curator).\n *\n * Non-destructive contract: the file is parsed with STRICT JSON first; a file that only parses\n * with comments/relaxed syntax is the user's hand-authored config and is never rewritten — the\n * caller gets `manualSnippet` to show instead.\n */\n\ninterface ModelsJsonModel {\n\tid: string;\n\tname?: string;\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n\treasoning?: boolean;\n\tinput?: string[];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n}\n\ninterface ModelsJson {\n\tproviders: Record<\n\t\tstring,\n\t\t{\n\t\t\tbaseUrl?: string;\n\t\t\tapi?: string;\n\t\t\tapiKey?: string;\n\t\t\tmodels?: ModelsJsonModel[];\n\t\t\t[key: string]: unknown;\n\t\t}\n\t>;\n\t[key: string]: unknown;\n}\n\nexport interface LocalRegistrationResult {\n\tok: boolean;\n\tmodelsJsonPath: string;\n\treason?: string;\n\t/** When the file cannot be safely rewritten: the entry the user should add by hand. */\n\tmanualSnippet?: string;\n}\n\n/** Provider name pi registers pulled local models under (see registerLocalModel below). */\nexport const OLLAMA_PROVIDER = \"ollama\";\n\nfunction localModelEntry(ref: string, contextWindow: number): ModelsJsonModel {\n\treturn {\n\t\tid: ref,\n\t\tname: ref,\n\t\tcontextWindow,\n\t\tmaxTokens: 2048,\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t};\n}\n\nfunction loadStrict(path: string): { json?: ModelsJson; reason?: string } {\n\tif (!existsSync(path)) return { json: { providers: {} } };\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as ModelsJson;\n\t\tif (!parsed || typeof parsed !== \"object\") return { reason: \"models.json is not a JSON object\" };\n\t\tparsed.providers = parsed.providers ?? {};\n\t\treturn { json: parsed };\n\t} catch {\n\t\treturn { reason: \"models.json uses comments/relaxed JSON — pi will not rewrite a hand-authored file\" };\n\t}\n}\n\nexport function registerLocalModel(args: {\n\tagentDir: string;\n\tref: string;\n\tbaseUrl: string;\n\tcontextWindow?: number;\n}): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst contextWindow = args.contextWindow ?? 8192;\n\tconst entry = localModelEntry(args.ref, contextWindow);\n\tconst providerBase = {\n\t\tbaseUrl: `${args.baseUrl.replace(/\\/$/, \"\")}/v1`,\n\t\tapi: \"openai-completions\",\n\t\tapiKey: \"ollama\",\n\t};\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmodelsJsonPath,\n\t\t\treason,\n\t\t\tmanualSnippet: JSON.stringify(\n\t\t\t\t{ providers: { [OLLAMA_PROVIDER]: { ...providerBase, models: [entry] } } },\n\t\t\t\tnull,\n\t\t\t\t\"\\t\",\n\t\t\t),\n\t\t};\n\t}\n\tjson.providers[OLLAMA_PROVIDER] ??= { ...providerBase, models: [] };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tprovider.baseUrl ??= providerBase.baseUrl;\n\tprovider.api ??= providerBase.api;\n\tprovider.apiKey ??= providerBase.apiKey;\n\tprovider.models ??= [];\n\tconst existing = provider.models.findIndex((model) => model.id === args.ref);\n\tif (existing >= 0) {\n\t\tprovider.models[existing] = { ...provider.models[existing], ...entry };\n\t} else {\n\t\tprovider.models.push(entry);\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n\nexport function unregisterLocalModel(args: { agentDir: string; ref: string }): LocalRegistrationResult {\n\tconst modelsJsonPath = join(args.agentDir, \"models.json\");\n\tconst { json, reason } = loadStrict(modelsJsonPath);\n\tif (!json) return { ok: false, modelsJsonPath, reason };\n\tconst provider = json.providers[OLLAMA_PROVIDER];\n\tif (!provider?.models) return { ok: true, modelsJsonPath };\n\tconst before = provider.models.length;\n\tprovider.models = provider.models.filter((model) => model.id !== args.ref);\n\tif (provider.models.length === before) return { ok: true, modelsJsonPath };\n\t// Drop the whole provider entry when its last pi-registered model goes (leave user fields alone\n\t// if they added any models themselves — only an all-pi-managed empty list is removed).\n\tif (provider.models.length === 0) {\n\t\tdelete json.providers[OLLAMA_PROVIDER];\n\t}\n\twriteFileSync(modelsJsonPath, `${JSON.stringify(json, null, \"\\t\")}\\n`, \"utf-8\");\n\treturn { ok: true, modelsJsonPath };\n}\n"]}
@@ -25,6 +25,22 @@ export interface InstalledLocalModel {
25
25
  name: string;
26
26
  sizeBytes: number;
27
27
  }
28
+ /** Pinned ollama release for the managed installer below. Bump here when needed — one constant. */
29
+ export declare const OLLAMA_PINNED_VERSION = "0.31.1";
30
+ export type OllamaAssetKind = "tar-zst" | "tar-gz" | "zip";
31
+ export interface OllamaReleaseAsset {
32
+ name: string;
33
+ kind: OllamaAssetKind;
34
+ }
35
+ /**
36
+ * Maps a platform/arch pair (node's `os.platform()`/`os.arch()`) to the exact ollama release asset
37
+ * name for {@link OLLAMA_PINNED_VERSION} — verified against the real ollama/ollama GitHub release
38
+ * and its own install.sh, not guessed: darwin ships a CLI `.tgz` (the `.app`/`.dmg`/`Ollama-*.zip`
39
+ * assets are the separate GUI-app installer, not what we want), linux ships `.tar.zst` per arch,
40
+ * windows ships `.zip` per arch. Pure and exported so it's independently testable and reusable
41
+ * (e.g. by a future doctor-driven managed install) without touching OllamaRuntime.
42
+ */
43
+ export declare function resolveOllamaAsset(plat: string, architecture: string): OllamaReleaseAsset | undefined;
28
44
  export interface LocalRuntimeDeps {
29
45
  fetchFn?: typeof fetch;
30
46
  spawnFn?: (command: string, args: string[], options: {
@@ -34,6 +50,22 @@ export interface LocalRuntimeDeps {
34
50
  envPath?: string;
35
51
  homeDir?: string;
36
52
  sleepFn?: (ms: number) => Promise<void>;
53
+ /** os.platform()/os.arch() equivalents — injectable so asset resolution is testable per platform. */
54
+ platform?: () => string;
55
+ arch?: () => string;
56
+ /** Node's built-in zstd decompress transform, when THIS runtime's node:zlib has it — undefined
57
+ * forces the system-zstd fallback. Injectable so tests can force either path deterministically
58
+ * instead of depending on whatever Node happens to be running the test. */
59
+ createZstdDecompress?: () => NodeJS.ReadWriteStream;
60
+ /** Whether a named command exists on PATH (e.g. system `zstd`), for the extraction fallback. */
61
+ hasCommand?: (command: string) => boolean;
62
+ /** Runs the extraction step for a downloaded archive. Injectable so installManaged's
63
+ * download->extract->verify orchestration is testable without a real tar/zstd/unzip pipeline;
64
+ * defaults to the real spawn-based extractor. */
65
+ extractArchive?: (input: NodeJS.ReadableStream, destDir: string, kind: OllamaAssetKind) => Promise<{
66
+ ok: boolean;
67
+ error?: string;
68
+ }>;
37
69
  }
38
70
  export declare class OllamaRuntime {
39
71
  private readonly _agentDir;
@@ -44,6 +76,11 @@ export declare class OllamaRuntime {
44
76
  private readonly _envPath;
45
77
  private readonly _homeDir;
46
78
  private readonly _sleep;
79
+ private readonly _platform;
80
+ private readonly _arch;
81
+ private readonly _createZstdDecompress;
82
+ private readonly _hasCommand;
83
+ private readonly _extractArchiveOverride;
47
84
  private _child;
48
85
  constructor(args: {
49
86
  agentDir: string;
@@ -55,16 +92,53 @@ export declare class OllamaRuntime {
55
92
  private _findBinary;
56
93
  private _serverUp;
57
94
  detect(): Promise<LocalRuntimeStatus>;
58
- /** GUIDE MODE: exact manual steps, printed, never executed (no `curl | sh`, no sudo). */
95
+ /**
96
+ * Manual-steps fallback text — shown when the managed install below wasn't offered (headless),
97
+ * was declined, or itself failed. #31 reversed the stance for ollama specifically: pi CAN install
98
+ * it for you now (consent-gated, a controlled download into pi's own runtimes dir, never
99
+ * `curl | sh`) — these steps are the alternative for when that path isn't taken.
100
+ */
59
101
  installGuide(): string[];
102
+ /** Which decompressor to use for a `.tar.zst` asset — native (this Node's own zlib) is always
103
+ * preferred when available, even if a system `zstd` ALSO exists, since it needs no external
104
+ * dependency at all. Verified per-runtime by feature detection (see the constructor), not by
105
+ * guessing from a Node version number. */
106
+ private _chooseZstdStrategy;
107
+ /**
108
+ * Managed install (#31): a consent-gated, controlled download of the pinned ollama release into
109
+ * pi's OWN runtimes dir (`<agentDir>/runtimes/ollama/`) — never `curl | sh`, never a second
110
+ * server instance, and distinct from {@link start}'s owned MODEL storage (this is the binary
111
+ * itself). Callers (the router's consent flow, and later a doctor-driven install) own the
112
+ * consent/UI; this method only does the mechanical download+extract+verify and reports the
113
+ * outcome honestly. `onProgress` is best-effort UI feedback, not a completion signal.
114
+ */
115
+ installManaged(onProgress?: (status: string) => void): Promise<{
116
+ ok: boolean;
117
+ error?: string;
118
+ }>;
119
+ private _extractArchive;
120
+ private _extractTar;
121
+ private _extractZip;
122
+ private _spawnAndPoll;
60
123
  /**
61
124
  * Start a pi-managed serve with OWNED storage and the hardened env verified on this class of
62
- * hardware. No-op (reported) when a server already responds — pi never double-serves.
125
+ * hardware. No-op (reported) when a server already responds — pi never double-serves. Used by
126
+ * `/models add` et al, where isolated per-model-pull storage is the point.
63
127
  */
64
128
  start(): Promise<{
65
129
  started: boolean;
66
130
  reason: string;
67
131
  }>;
132
+ /**
133
+ * Start a serve that REUSES the user's own existing models directory (no `OLLAMA_MODELS`
134
+ * override — falls through to Ollama's own default, `~/.ollama`), for callers that must see the
135
+ * user's already-pulled models rather than pi's isolated/owned storage. Same idempotency and
136
+ * hardened perf env as {@link start}; the only difference is which storage the server sees.
137
+ */
138
+ startReuseExisting(): Promise<{
139
+ started: boolean;
140
+ reason: string;
141
+ }>;
68
142
  /** Resource hygiene only: stops the pi-managed serve process; never deletes anything. */
69
143
  stop(): {
70
144
  stopped: boolean;