@apralabs/apra-fleet 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +145 -7
- package/dist/agents/backlog-groomer.md +17 -1
- package/dist/agents/ci-watcher.md +13 -1
- package/dist/agents/deployer.md +15 -3
- package/dist/agents/doer.md +35 -1
- package/dist/agents/harvester.md +22 -3
- package/dist/agents/integ-test-runner.md +18 -2
- package/dist/agents/kb-reconciler.md +216 -0
- package/dist/agents/plan-reviewer.md +14 -1
- package/dist/agents/planner.md +88 -5
- package/dist/agents/regression-test-runner.md +19 -1
- package/dist/agents/reviewer.md +104 -3
- package/dist/agents/schemas/doer-output.json +63 -3
- package/dist/agents/schemas/harvester-output.json +59 -2
- package/dist/agents/schemas/integ-test-runner-output.json +2 -2
- package/dist/agents/schemas/kb-reconciler-output.json +87 -0
- package/dist/agents/schemas/planner-output.json +65 -0
- package/dist/agents/schemas/reviewer-output.json +105 -8
- package/dist/cli/install.d.ts +1 -0
- package/dist/cli/install.d.ts.map +1 -1
- package/dist/cli/install.js +136 -5
- package/dist/cli/install.js.map +1 -1
- package/dist/cli/join.js +1 -1
- package/dist/cli/join.js.map +1 -1
- package/dist/cli/kb-commit.d.ts +12 -0
- package/dist/cli/kb-commit.d.ts.map +1 -0
- package/dist/cli/kb-commit.js +53 -0
- package/dist/cli/kb-commit.js.map +1 -0
- package/dist/cli/kb-directives.d.ts +17 -0
- package/dist/cli/kb-directives.d.ts.map +1 -0
- package/dist/cli/kb-directives.js +146 -0
- package/dist/cli/kb-directives.js.map +1 -0
- package/dist/cli/kb-import.d.ts +13 -0
- package/dist/cli/kb-import.d.ts.map +1 -0
- package/dist/cli/kb-import.js +56 -0
- package/dist/cli/kb-import.js.map +1 -0
- package/dist/cli/uninstall.d.ts.map +1 -1
- package/dist/cli/uninstall.js +11 -0
- package/dist/cli/uninstall.js.map +1 -1
- package/dist/cli/watch.d.ts +53 -4
- package/dist/cli/watch.d.ts.map +1 -1
- package/dist/cli/watch.js +118 -17
- package/dist/cli/watch.js.map +1 -1
- package/dist/commands/kb-server.d.ts +8 -0
- package/dist/commands/kb-server.d.ts.map +1 -0
- package/dist/commands/kb-server.js +221 -0
- package/dist/commands/kb-server.js.map +1 -0
- package/dist/index.js +77 -2
- package/dist/index.js.map +1 -1
- package/dist/os/linux.d.ts +1 -0
- package/dist/os/linux.d.ts.map +1 -1
- package/dist/os/linux.js +18 -1
- package/dist/os/linux.js.map +1 -1
- package/dist/os/os-commands.d.ts +5 -0
- package/dist/os/os-commands.d.ts.map +1 -1
- package/dist/os/windows.d.ts +35 -0
- package/dist/os/windows.d.ts.map +1 -1
- package/dist/os/windows.js +67 -31
- package/dist/os/windows.js.map +1 -1
- package/dist/providers/agy.d.ts +12 -1
- package/dist/providers/agy.d.ts.map +1 -1
- package/dist/providers/agy.js +134 -9
- package/dist/providers/agy.js.map +1 -1
- package/dist/providers/claude.d.ts +11 -1
- package/dist/providers/claude.d.ts.map +1 -1
- package/dist/providers/claude.js +47 -19
- package/dist/providers/claude.js.map +1 -1
- package/dist/providers/codex.d.ts +11 -1
- package/dist/providers/codex.d.ts.map +1 -1
- package/dist/providers/codex.js +29 -6
- package/dist/providers/codex.js.map +1 -1
- package/dist/providers/copilot.d.ts +11 -1
- package/dist/providers/copilot.d.ts.map +1 -1
- package/dist/providers/copilot.js +26 -6
- package/dist/providers/copilot.js.map +1 -1
- package/dist/providers/email/headers.d.ts +15 -0
- package/dist/providers/email/headers.d.ts.map +1 -0
- package/dist/providers/email/headers.js +42 -0
- package/dist/providers/email/headers.js.map +1 -0
- package/dist/providers/email/index.d.ts +18 -0
- package/dist/providers/email/index.d.ts.map +1 -0
- package/dist/providers/email/index.js +60 -0
- package/dist/providers/email/index.js.map +1 -0
- package/dist/providers/email/provider.d.ts +49 -0
- package/dist/providers/email/provider.d.ts.map +1 -0
- package/dist/providers/email/provider.js +2 -0
- package/dist/providers/email/provider.js.map +1 -0
- package/dist/providers/email/sendgrid.d.ts +12 -0
- package/dist/providers/email/sendgrid.d.ts.map +1 -0
- package/dist/providers/email/sendgrid.js +67 -0
- package/dist/providers/email/sendgrid.js.map +1 -0
- package/dist/providers/email/smtp.d.ts +65 -0
- package/dist/providers/email/smtp.d.ts.map +1 -0
- package/dist/providers/email/smtp.js +373 -0
- package/dist/providers/email/smtp.js.map +1 -0
- package/dist/providers/gemini.d.ts +11 -1
- package/dist/providers/gemini.d.ts.map +1 -1
- package/dist/providers/gemini.js +38 -4
- package/dist/providers/gemini.js.map +1 -1
- package/dist/providers/none.d.ts +11 -1
- package/dist/providers/none.d.ts.map +1 -1
- package/dist/providers/none.js +21 -0
- package/dist/providers/none.js.map +1 -1
- package/dist/providers/opencode.d.ts +11 -1
- package/dist/providers/opencode.d.ts.map +1 -1
- package/dist/providers/opencode.js +55 -4
- package/dist/providers/opencode.js.map +1 -1
- package/dist/providers/provider.d.ts +77 -0
- package/dist/providers/provider.d.ts.map +1 -1
- package/dist/providers/provider.js +44 -0
- package/dist/providers/provider.js.map +1 -1
- package/dist/services/agent-provisioner.d.ts.map +1 -1
- package/dist/services/agent-provisioner.js +3 -6
- package/dist/services/agent-provisioner.js.map +1 -1
- package/dist/services/cloud/lifecycle.d.ts.map +1 -1
- package/dist/services/cloud/lifecycle.js +3 -0
- package/dist/services/cloud/lifecycle.js.map +1 -1
- package/dist/services/cloud/task-wrapper.d.ts +18 -0
- package/dist/services/cloud/task-wrapper.d.ts.map +1 -1
- package/dist/services/cloud/task-wrapper.js +157 -0
- package/dist/services/cloud/task-wrapper.js.map +1 -1
- package/dist/services/github-app.d.ts.map +1 -1
- package/dist/services/github-app.js +11 -2
- package/dist/services/github-app.js.map +1 -1
- package/dist/services/knowledge/audn.d.ts +37 -0
- package/dist/services/knowledge/audn.d.ts.map +1 -0
- package/dist/services/knowledge/audn.js +219 -0
- package/dist/services/knowledge/audn.js.map +1 -0
- package/dist/services/knowledge/file-hash.d.ts +11 -0
- package/dist/services/knowledge/file-hash.d.ts.map +1 -0
- package/dist/services/knowledge/file-hash.js +123 -0
- package/dist/services/knowledge/file-hash.js.map +1 -0
- package/dist/services/knowledge/http-provider.d.ts +46 -0
- package/dist/services/knowledge/http-provider.d.ts.map +1 -0
- package/dist/services/knowledge/http-provider.js +254 -0
- package/dist/services/knowledge/http-provider.js.map +1 -0
- package/dist/services/knowledge/kb-providers.d.ts +15 -0
- package/dist/services/knowledge/kb-providers.d.ts.map +1 -0
- package/dist/services/knowledge/kb-providers.js +92 -0
- package/dist/services/knowledge/kb-providers.js.map +1 -0
- package/dist/services/knowledge/kb-scope-input.d.ts +5 -0
- package/dist/services/knowledge/kb-scope-input.d.ts.map +1 -0
- package/dist/services/knowledge/kb-scope-input.js +11 -0
- package/dist/services/knowledge/kb-scope-input.js.map +1 -0
- package/dist/services/knowledge/kb-service.d.ts +3 -0
- package/dist/services/knowledge/kb-service.d.ts.map +1 -0
- package/dist/services/knowledge/kb-service.js +2 -0
- package/dist/services/knowledge/kb-service.js.map +1 -0
- package/dist/services/knowledge/path-validation.d.ts +2 -0
- package/dist/services/knowledge/path-validation.d.ts.map +1 -0
- package/dist/services/knowledge/path-validation.js +13 -0
- package/dist/services/knowledge/path-validation.js.map +1 -0
- package/dist/services/knowledge/pre-init.d.ts +14 -0
- package/dist/services/knowledge/pre-init.d.ts.map +1 -0
- package/dist/services/knowledge/pre-init.js +147 -0
- package/dist/services/knowledge/pre-init.js.map +1 -0
- package/dist/services/knowledge/project-slug.d.ts +2 -0
- package/dist/services/knowledge/project-slug.d.ts.map +1 -0
- package/dist/services/knowledge/project-slug.js +49 -0
- package/dist/services/knowledge/project-slug.js.map +1 -0
- package/dist/services/knowledge/sqlite-provider.d.ts +147 -0
- package/dist/services/knowledge/sqlite-provider.d.ts.map +1 -0
- package/dist/services/knowledge/sqlite-provider.js +1646 -0
- package/dist/services/knowledge/sqlite-provider.js.map +1 -0
- package/dist/services/knowledge/types.d.ts +163 -0
- package/dist/services/knowledge/types.d.ts.map +1 -0
- package/dist/services/knowledge/types.js +9 -0
- package/dist/services/knowledge/types.js.map +1 -0
- package/dist/services/member-home.d.ts +89 -0
- package/dist/services/member-home.d.ts.map +1 -0
- package/dist/services/member-home.js +256 -0
- package/dist/services/member-home.js.map +1 -0
- package/dist/services/member-remote-url.d.ts +34 -0
- package/dist/services/member-remote-url.d.ts.map +1 -0
- package/dist/services/member-remote-url.js +39 -0
- package/dist/services/member-remote-url.js.map +1 -0
- package/dist/services/orphan-recovery.d.ts +5 -2
- package/dist/services/orphan-recovery.d.ts.map +1 -1
- package/dist/services/orphan-recovery.js +19 -8
- package/dist/services/orphan-recovery.js.map +1 -1
- package/dist/services/preflight-check.d.ts +56 -0
- package/dist/services/preflight-check.d.ts.map +1 -0
- package/dist/services/preflight-check.js +277 -0
- package/dist/services/preflight-check.js.map +1 -0
- package/dist/services/stall/log-path-resolver.d.ts +11 -8
- package/dist/services/stall/log-path-resolver.d.ts.map +1 -1
- package/dist/services/stall/log-path-resolver.js +17 -40
- package/dist/services/stall/log-path-resolver.js.map +1 -1
- package/dist/services/stall/stall-detector.d.ts +32 -0
- package/dist/services/stall/stall-detector.d.ts.map +1 -1
- package/dist/services/stall/stall-detector.js +149 -6
- package/dist/services/stall/stall-detector.js.map +1 -1
- package/dist/services/stall/stall-poller.d.ts +34 -0
- package/dist/services/stall/stall-poller.d.ts.map +1 -1
- package/dist/services/stall/stall-poller.js +134 -2
- package/dist/services/stall/stall-poller.js.map +1 -1
- package/dist/services/strategy.d.ts.map +1 -1
- package/dist/services/strategy.js +2 -2
- package/dist/services/strategy.js.map +1 -1
- package/dist/services/tool-registry.d.ts.map +1 -1
- package/dist/services/tool-registry.js +87 -1
- package/dist/services/tool-registry.js.map +1 -1
- package/dist/services/vcs/github.d.ts.map +1 -1
- package/dist/services/vcs/github.js +32 -1
- package/dist/services/vcs/github.js.map +1 -1
- package/dist/services/version-check.d.ts +22 -0
- package/dist/services/version-check.d.ts.map +1 -0
- package/dist/services/version-check.js +103 -0
- package/dist/services/version-check.js.map +1 -0
- package/dist/skills/fleet-sprint-cli/SKILL.md +13 -2
- package/dist/skills/pm/beads.md +6 -0
- package/dist/skills/pm/fleet-addendum.md +6 -0
- package/dist/skills/pm/index.md +56 -0
- package/dist/skills/pm/kb-reconcile.md +132 -0
- package/dist/skills/pm/kb-review.md +109 -0
- package/dist/tools/check-status.d.ts +47 -0
- package/dist/tools/check-status.d.ts.map +1 -1
- package/dist/tools/check-status.js +242 -0
- package/dist/tools/check-status.js.map +1 -1
- package/dist/tools/child-id-allocator.d.ts +2 -2
- package/dist/tools/code-intelligence-codebase-memory.d.ts +11 -0
- package/dist/tools/code-intelligence-codebase-memory.d.ts.map +1 -0
- package/dist/tools/code-intelligence-codebase-memory.js +270 -0
- package/dist/tools/code-intelligence-codebase-memory.js.map +1 -0
- package/dist/tools/code-intelligence-freshness.d.ts +2 -0
- package/dist/tools/code-intelligence-freshness.d.ts.map +1 -0
- package/dist/tools/code-intelligence-freshness.js +26 -0
- package/dist/tools/code-intelligence-freshness.js.map +1 -0
- package/dist/tools/code-intelligence-gitnexus.d.ts +14 -0
- package/dist/tools/code-intelligence-gitnexus.d.ts.map +1 -0
- package/dist/tools/code-intelligence-gitnexus.js +475 -0
- package/dist/tools/code-intelligence-gitnexus.js.map +1 -0
- package/dist/tools/code-intelligence-kb-enrich.d.ts +2 -0
- package/dist/tools/code-intelligence-kb-enrich.d.ts.map +1 -0
- package/dist/tools/code-intelligence-kb-enrich.js +65 -0
- package/dist/tools/code-intelligence-kb-enrich.js.map +1 -0
- package/dist/tools/code-intelligence-reindex.d.ts +7 -0
- package/dist/tools/code-intelligence-reindex.d.ts.map +1 -0
- package/dist/tools/code-intelligence-reindex.js +106 -0
- package/dist/tools/code-intelligence-reindex.js.map +1 -0
- package/dist/tools/code-intelligence-telemetry.d.ts +5 -0
- package/dist/tools/code-intelligence-telemetry.d.ts.map +1 -0
- package/dist/tools/code-intelligence-telemetry.js +52 -0
- package/dist/tools/code-intelligence-telemetry.js.map +1 -0
- package/dist/tools/code-intelligence-tests.d.ts +2 -0
- package/dist/tools/code-intelligence-tests.d.ts.map +1 -0
- package/dist/tools/code-intelligence-tests.js +24 -0
- package/dist/tools/code-intelligence-tests.js.map +1 -0
- package/dist/tools/code-intelligence.d.ts +114 -0
- package/dist/tools/code-intelligence.d.ts.map +1 -0
- package/dist/tools/code-intelligence.js +124 -0
- package/dist/tools/code-intelligence.js.map +1 -0
- package/dist/tools/compose-permissions.d.ts +26 -0
- package/dist/tools/compose-permissions.d.ts.map +1 -1
- package/dist/tools/compose-permissions.js +244 -33
- package/dist/tools/compose-permissions.js.map +1 -1
- package/dist/tools/execute-command.d.ts +2 -0
- package/dist/tools/execute-command.d.ts.map +1 -1
- package/dist/tools/execute-command.js +86 -16
- package/dist/tools/execute-command.js.map +1 -1
- package/dist/tools/execute-prompt.d.ts +13 -1
- package/dist/tools/execute-prompt.d.ts.map +1 -1
- package/dist/tools/execute-prompt.js +257 -45
- package/dist/tools/execute-prompt.js.map +1 -1
- package/dist/tools/kb-capture.d.ts +53 -0
- package/dist/tools/kb-capture.d.ts.map +1 -0
- package/dist/tools/kb-capture.js +130 -0
- package/dist/tools/kb-capture.js.map +1 -0
- package/dist/tools/kb-context.d.ts +17 -0
- package/dist/tools/kb-context.d.ts.map +1 -0
- package/dist/tools/kb-context.js +29 -0
- package/dist/tools/kb-context.js.map +1 -0
- package/dist/tools/kb-export.d.ts +19 -0
- package/dist/tools/kb-export.d.ts.map +1 -0
- package/dist/tools/kb-export.js +344 -0
- package/dist/tools/kb-export.js.map +1 -0
- package/dist/tools/kb-feedback.d.ts +23 -0
- package/dist/tools/kb-feedback.d.ts.map +1 -0
- package/dist/tools/kb-feedback.js +43 -0
- package/dist/tools/kb-feedback.js.map +1 -0
- package/dist/tools/kb-freshness-sweep.d.ts +14 -0
- package/dist/tools/kb-freshness-sweep.d.ts.map +1 -0
- package/dist/tools/kb-freshness-sweep.js +29 -0
- package/dist/tools/kb-freshness-sweep.js.map +1 -0
- package/dist/tools/kb-harvest.d.ts +20 -0
- package/dist/tools/kb-harvest.d.ts.map +1 -0
- package/dist/tools/kb-harvest.js +143 -0
- package/dist/tools/kb-harvest.js.map +1 -0
- package/dist/tools/kb-import.d.ts +44 -0
- package/dist/tools/kb-import.d.ts.map +1 -0
- package/dist/tools/kb-import.js +239 -0
- package/dist/tools/kb-import.js.map +1 -0
- package/dist/tools/kb-invalidate.d.ts +19 -0
- package/dist/tools/kb-invalidate.d.ts.map +1 -0
- package/dist/tools/kb-invalidate.js +34 -0
- package/dist/tools/kb-invalidate.js.map +1 -0
- package/dist/tools/kb-list.d.ts +32 -0
- package/dist/tools/kb-list.d.ts.map +1 -0
- package/dist/tools/kb-list.js +43 -0
- package/dist/tools/kb-list.js.map +1 -0
- package/dist/tools/kb-promote.d.ts +20 -0
- package/dist/tools/kb-promote.d.ts.map +1 -0
- package/dist/tools/kb-promote.js +20 -0
- package/dist/tools/kb-promote.js.map +1 -0
- package/dist/tools/kb-query.d.ts +35 -0
- package/dist/tools/kb-query.d.ts.map +1 -0
- package/dist/tools/kb-query.js +111 -0
- package/dist/tools/kb-query.js.map +1 -0
- package/dist/tools/kb-reconcile-prefilter.d.ts +14 -0
- package/dist/tools/kb-reconcile-prefilter.d.ts.map +1 -0
- package/dist/tools/kb-reconcile-prefilter.js +26 -0
- package/dist/tools/kb-reconcile-prefilter.js.map +1 -0
- package/dist/tools/kb-resolve-contradiction.d.ts +23 -0
- package/dist/tools/kb-resolve-contradiction.d.ts.map +1 -0
- package/dist/tools/kb-resolve-contradiction.js +37 -0
- package/dist/tools/kb-resolve-contradiction.js.map +1 -0
- package/dist/tools/kb-session-prime.d.ts +26 -0
- package/dist/tools/kb-session-prime.d.ts.map +1 -0
- package/dist/tools/kb-session-prime.js +392 -0
- package/dist/tools/kb-session-prime.js.map +1 -0
- package/dist/tools/kb-setup.d.ts +20 -0
- package/dist/tools/kb-setup.d.ts.map +1 -0
- package/dist/tools/kb-setup.js +49 -0
- package/dist/tools/kb-setup.js.map +1 -0
- package/dist/tools/kb-stats.d.ts +20 -0
- package/dist/tools/kb-stats.d.ts.map +1 -0
- package/dist/tools/kb-stats.js +115 -0
- package/dist/tools/kb-stats.js.map +1 -0
- package/dist/tools/member-detail.d.ts.map +1 -1
- package/dist/tools/member-detail.js +8 -0
- package/dist/tools/member-detail.js.map +1 -1
- package/dist/tools/monitor-task.d.ts.map +1 -1
- package/dist/tools/monitor-task.js +21 -3
- package/dist/tools/monitor-task.js.map +1 -1
- package/dist/tools/provision-auth.d.ts.map +1 -1
- package/dist/tools/provision-auth.js +10 -3
- package/dist/tools/provision-auth.js.map +1 -1
- package/dist/tools/register-member.d.ts +3 -0
- package/dist/tools/register-member.d.ts.map +1 -1
- package/dist/tools/register-member.js +30 -1
- package/dist/tools/register-member.js.map +1 -1
- package/dist/tools/remove-member.d.ts.map +1 -1
- package/dist/tools/remove-member.js +17 -3
- package/dist/tools/remove-member.js.map +1 -1
- package/dist/tools/report-status.d.ts.map +1 -1
- package/dist/tools/report-status.js +2 -1
- package/dist/tools/report-status.js.map +1 -1
- package/dist/tools/send-email.d.ts +69 -0
- package/dist/tools/send-email.d.ts.map +1 -0
- package/dist/tools/send-email.js +177 -0
- package/dist/tools/send-email.js.map +1 -0
- package/dist/tools/setup-ssh-key.d.ts.map +1 -1
- package/dist/tools/setup-ssh-key.js +2 -0
- package/dist/tools/setup-ssh-key.js.map +1 -1
- package/dist/tools/update-member.d.ts +3 -0
- package/dist/tools/update-member.d.ts.map +1 -1
- package/dist/tools/update-member.js +25 -1
- package/dist/tools/update-member.js.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/prompt-errors.js +1 -1
- package/dist/utils/prompt-errors.js.map +1 -1
- package/dist/utils/session-caller.d.ts +28 -0
- package/dist/utils/session-caller.d.ts.map +1 -0
- package/dist/utils/session-caller.js +24 -0
- package/dist/utils/session-caller.js.map +1 -0
- package/dist/utils/work-folder-validation.d.ts +39 -0
- package/dist/utils/work-folder-validation.d.ts.map +1 -0
- package/dist/utils/work-folder-validation.js +60 -0
- package/dist/utils/work-folder-validation.js.map +1 -0
- package/dist/workflows/auto-sprint.js +546 -6
- package/package.json +7 -4
- package/packages/apra-fleet-client/src/client/api.mjs +118 -4
- package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +17 -1
- package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +13 -1
- package/packages/apra-fleet-se/apra-pm/agents/deployer.md +15 -3
- package/packages/apra-fleet-se/apra-pm/agents/doer.md +35 -1
- package/packages/apra-fleet-se/apra-pm/agents/harvester.md +22 -3
- package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +18 -2
- package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +216 -0
- package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +14 -1
- package/packages/apra-fleet-se/apra-pm/agents/planner.md +88 -5
- package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +19 -1
- package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +104 -3
- package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +63 -3
- package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-output.json +59 -2
- package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-output.json +2 -2
- package/packages/apra-fleet-se/apra-pm/agents/schemas/kb-reconciler-output.json +87 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/planner-output.json +65 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +105 -8
- package/packages/apra-fleet-se/apra-pm/skills/pm/beads.md +6 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +6 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +56 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/kb-reconcile.md +132 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/kb-review.md +109 -0
- package/packages/apra-fleet-se/bin/cli.mjs +7 -0
- package/packages/apra-fleet-se/bin/serve.mjs +14 -2
- package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +31 -5
- package/packages/apra-fleet-se/fleet-sprint/docs/README.md +1 -1
- package/packages/apra-fleet-se/fleet-sprint/docs/coach-role-design.md +23 -151
- package/packages/apra-fleet-se/fleet-sprint/docs/dolt-manual-recovery-verified.md +256 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +1482 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +908 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/shared-orchestrator-reservation-design.md +399 -0
- package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +972 -0
- package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +167 -101
- package/packages/apra-fleet-se/fleet-sprint/errors.mjs +50 -6
- package/packages/apra-fleet-se/fleet-sprint/runner.js +1416 -116
- package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +13 -2
- package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +350 -0
- package/packages/apra-fleet-se/fleet-sprint/sprint-progress.mjs +101 -0
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +30 -17
- package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +62 -2
- package/packages/apra-fleet-se/package.json +1 -0
- package/packages/apra-fleet-workflow/src/viewer/index.mjs +127 -13
- package/packages/apra-fleet-workflow/src/viewer/run-title.mjs +60 -0
- package/packages/apra-fleet-workflow/src/workflow/index.mjs +8 -4
- package/skills/fleet/knowledge-agent.md +66 -0
- package/skills/fleet/permissions.md +28 -4
- package/skills/fleet/profiles/base-dev.json +10 -1
- package/skills/fleet/profiles/base-reviewer.json +8 -1
- package/skills/fleet/profiles/tag-kb-reconciler.json +20 -0
- package/version.json +1 -1
- package/packages/apra-fleet-se/fleet-sprint/docs/dolt-tier2-runbook.md +0 -127
- package/packages/apra-fleet-se/fleet-sprint/dolt-recovery-path-b.mjs +0 -339
- package/packages/apra-fleet-se/fleet-sprint/dolt-recovery-tier2.mjs +0 -360
- package/packages/apra-fleet-se/fleet-sprint/dolt-recovery.mjs +0 -363
|
@@ -0,0 +1,1646 @@
|
|
|
1
|
+
// node:sqlite, not better-sqlite3: the fleet server ships as a Node SEA, whose
|
|
2
|
+
// require() resolves builtins only. better-sqlite3 reaches its native addon via
|
|
3
|
+
// require('bindings')('better_sqlite3.node') -- a RUNTIME path require the SEA
|
|
4
|
+
// routes to the builtin loader, producing "No such built-in module: <build-host
|
|
5
|
+
// path>/dist/build/better_sqlite3.node". build-sea.mjs's loader {'.node':
|
|
6
|
+
// 'empty'} hides this at build time, so the failure only ever surfaced at
|
|
7
|
+
// runtime, on every kb_* call, non-fatally (every call site catches), which is
|
|
8
|
+
// how a total KB outage stayed invisible. node:sqlite is a builtin, so it is
|
|
9
|
+
// SEA-safe by construction. FTS5 is compiled in (kb_query depends on it).
|
|
10
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import { randomUUID } from 'node:crypto';
|
|
14
|
+
import { FLEET_DIR } from '../../paths.js';
|
|
15
|
+
import { resolveProjectSlug } from './project-slug.js';
|
|
16
|
+
import { makeFtsQuery, makeAudnDecision, orJoinFtsTerms, } from './audn.js';
|
|
17
|
+
import { computeFileHashBatch } from './file-hash.js';
|
|
18
|
+
import { KbCaptureRejected } from './types.js';
|
|
19
|
+
const CONTENT_CAP = 4000;
|
|
20
|
+
const TRUNCATION_SUFFIX = '...[truncated]';
|
|
21
|
+
function truncateContent(content) {
|
|
22
|
+
if (content.length <= CONTENT_CAP)
|
|
23
|
+
return content;
|
|
24
|
+
return content.slice(0, CONTENT_CAP) + TRUNCATION_SUFFIX;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Minimum length of a kb_promote reason. Matches the length floor kb_harvest
|
|
28
|
+
* already applies to an extracted learning -- short enough that a real one-line
|
|
29
|
+
* citation passes, long enough that "ok" / "lgtm" / "verified" does not.
|
|
30
|
+
*/
|
|
31
|
+
const MIN_PROMOTE_REASON_LENGTH = 20;
|
|
32
|
+
function isNonTrivialPromoteReason(reason) {
|
|
33
|
+
return (reason ?? '').trim().length >= MIN_PROMOTE_REASON_LENGTH;
|
|
34
|
+
}
|
|
35
|
+
class NotImplementedError extends Error {
|
|
36
|
+
constructor(method) {
|
|
37
|
+
super(`SqliteProvider.${method}() not yet implemented`);
|
|
38
|
+
this.name = 'NotImplementedError';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export class SqliteProvider {
|
|
42
|
+
db = null;
|
|
43
|
+
dbPath;
|
|
44
|
+
projectSlug;
|
|
45
|
+
/**
|
|
46
|
+
* Root of the repo this provider's KB is about. capture() resolves relative
|
|
47
|
+
* source_files against it, so the basis check is anchored to the repo the
|
|
48
|
+
* entry describes rather than to the fleet server's process.cwd() -- the
|
|
49
|
+
* repo-blindness failure class of apra-fleet-tm7. Undefined for the single
|
|
50
|
+
* shared global KB, which spans every repo and has no one root.
|
|
51
|
+
*/
|
|
52
|
+
repoPath;
|
|
53
|
+
constructor(dbPath, repoPath) {
|
|
54
|
+
this.repoPath = repoPath;
|
|
55
|
+
if (dbPath !== undefined) {
|
|
56
|
+
this.dbPath = dbPath;
|
|
57
|
+
this.projectSlug = path.basename(dbPath, '.sqlite') || 'custom';
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
const slug = resolveProjectSlug();
|
|
61
|
+
this.projectSlug = slug;
|
|
62
|
+
const dir = path.join(FLEET_DIR, 'knowledge', slug);
|
|
63
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
64
|
+
this.dbPath = path.join(dir, 'kb.sqlite');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async init() {
|
|
68
|
+
if (this.db !== null)
|
|
69
|
+
return;
|
|
70
|
+
const dir = path.dirname(this.dbPath);
|
|
71
|
+
if (!fs.existsSync(dir)) {
|
|
72
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
73
|
+
}
|
|
74
|
+
this.db = new DatabaseSync(this.dbPath);
|
|
75
|
+
// node:sqlite has no pragma() helper -- same statements, issued via exec().
|
|
76
|
+
this.db.exec('PRAGMA journal_mode=WAL');
|
|
77
|
+
this.db.exec('PRAGMA busy_timeout=5000');
|
|
78
|
+
this.db.exec('PRAGMA synchronous=NORMAL');
|
|
79
|
+
this.db.exec('PRAGMA cache_size=-20000');
|
|
80
|
+
this.db.exec(`
|
|
81
|
+
CREATE TABLE IF NOT EXISTS entries (
|
|
82
|
+
id TEXT PRIMARY KEY,
|
|
83
|
+
type TEXT NOT NULL,
|
|
84
|
+
title TEXT NOT NULL,
|
|
85
|
+
summary TEXT NOT NULL,
|
|
86
|
+
content TEXT NOT NULL,
|
|
87
|
+
source_files TEXT NOT NULL DEFAULT '[]',
|
|
88
|
+
symbols TEXT NOT NULL DEFAULT '[]',
|
|
89
|
+
module TEXT,
|
|
90
|
+
tags TEXT NOT NULL DEFAULT '[]',
|
|
91
|
+
content_hash TEXT NOT NULL DEFAULT '',
|
|
92
|
+
content_hash_type TEXT NOT NULL DEFAULT 'sha256',
|
|
93
|
+
stale INTEGER NOT NULL DEFAULT 0,
|
|
94
|
+
flagged_for_review INTEGER NOT NULL DEFAULT 0,
|
|
95
|
+
contradiction_of TEXT,
|
|
96
|
+
author TEXT NOT NULL DEFAULT '',
|
|
97
|
+
source TEXT NOT NULL DEFAULT 'doer',
|
|
98
|
+
confidence TEXT NOT NULL DEFAULT 'INFERRED',
|
|
99
|
+
scope TEXT NOT NULL DEFAULT 'project',
|
|
100
|
+
created_at TEXT NOT NULL,
|
|
101
|
+
superseded_at TEXT,
|
|
102
|
+
promoted_at TEXT,
|
|
103
|
+
use_count INTEGER NOT NULL DEFAULT 0,
|
|
104
|
+
last_accessed TEXT
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(type);
|
|
108
|
+
CREATE INDEX IF NOT EXISTS idx_entries_confidence ON entries(confidence);
|
|
109
|
+
CREATE INDEX IF NOT EXISTS idx_entries_created_at ON entries(created_at);
|
|
110
|
+
CREATE INDEX IF NOT EXISTS idx_entries_superseded_at ON entries(superseded_at);
|
|
111
|
+
CREATE INDEX IF NOT EXISTS idx_entries_use_count ON entries(use_count);
|
|
112
|
+
|
|
113
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS entries_fts USING fts5(
|
|
114
|
+
title,
|
|
115
|
+
summary,
|
|
116
|
+
content,
|
|
117
|
+
tags,
|
|
118
|
+
content='entries',
|
|
119
|
+
content_rowid='rowid'
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
CREATE TRIGGER IF NOT EXISTS entries_ai AFTER INSERT ON entries BEGIN
|
|
123
|
+
INSERT INTO entries_fts(rowid, title, summary, content, tags)
|
|
124
|
+
VALUES (new.rowid, new.title, new.summary, new.content, new.tags);
|
|
125
|
+
END;
|
|
126
|
+
|
|
127
|
+
CREATE TRIGGER IF NOT EXISTS entries_ad AFTER DELETE ON entries BEGIN
|
|
128
|
+
INSERT INTO entries_fts(entries_fts, rowid, title, summary, content, tags)
|
|
129
|
+
VALUES ('delete', old.rowid, old.title, old.summary, old.content, old.tags);
|
|
130
|
+
END;
|
|
131
|
+
|
|
132
|
+
CREATE TRIGGER IF NOT EXISTS entries_au AFTER UPDATE ON entries BEGIN
|
|
133
|
+
INSERT INTO entries_fts(entries_fts, rowid, title, summary, content, tags)
|
|
134
|
+
VALUES ('delete', old.rowid, old.title, old.summary, old.content, old.tags);
|
|
135
|
+
INSERT INTO entries_fts(rowid, title, summary, content, tags)
|
|
136
|
+
VALUES (new.rowid, new.title, new.summary, new.content, new.tags);
|
|
137
|
+
END;
|
|
138
|
+
|
|
139
|
+
CREATE TABLE IF NOT EXISTS links (
|
|
140
|
+
from_id TEXT NOT NULL,
|
|
141
|
+
to_id TEXT NOT NULL,
|
|
142
|
+
link_type TEXT NOT NULL,
|
|
143
|
+
PRIMARY KEY (from_id, to_id, link_type)
|
|
144
|
+
);
|
|
145
|
+
`);
|
|
146
|
+
// Migration: add scope column to existing DBs
|
|
147
|
+
try {
|
|
148
|
+
this.db.exec("ALTER TABLE entries ADD COLUMN scope TEXT NOT NULL DEFAULT 'project'");
|
|
149
|
+
}
|
|
150
|
+
catch { }
|
|
151
|
+
// T2.2 (F3 PART A, revised D3): additive column storing a JSON map of
|
|
152
|
+
// source_file -> content hash captured AT CAPTURE TIME, for ALL entry
|
|
153
|
+
// types (not just context-cache). No migration -- existing rows default
|
|
154
|
+
// to '{}' (no basis) and are treated fresh/unknown, never falsely stale
|
|
155
|
+
// (D1/D3 no-mass-migration). This is the freshness basis checkFreshness
|
|
156
|
+
// compares against at prime() time.
|
|
157
|
+
try {
|
|
158
|
+
this.db.exec("ALTER TABLE entries ADD COLUMN source_file_hashes TEXT NOT NULL DEFAULT '{}'");
|
|
159
|
+
}
|
|
160
|
+
catch { }
|
|
161
|
+
}
|
|
162
|
+
getDb() {
|
|
163
|
+
if (!this.db)
|
|
164
|
+
throw new Error('SqliteProvider not initialized. Call init() first.');
|
|
165
|
+
return this.db;
|
|
166
|
+
}
|
|
167
|
+
rowToEntry(row) {
|
|
168
|
+
return {
|
|
169
|
+
id: row.id,
|
|
170
|
+
type: row.type,
|
|
171
|
+
title: row.title,
|
|
172
|
+
summary: row.summary,
|
|
173
|
+
content: row.content,
|
|
174
|
+
source_files: JSON.parse(row.source_files || '[]'),
|
|
175
|
+
symbols: JSON.parse(row.symbols || '[]'),
|
|
176
|
+
module: row.module,
|
|
177
|
+
tags: JSON.parse(row.tags || '[]'),
|
|
178
|
+
content_hash: row.content_hash,
|
|
179
|
+
content_hash_type: row.content_hash_type,
|
|
180
|
+
stale: row.stale === 1,
|
|
181
|
+
flagged_for_review: row.flagged_for_review === 1,
|
|
182
|
+
contradiction_of: row.contradiction_of,
|
|
183
|
+
author: row.author,
|
|
184
|
+
source: row.source,
|
|
185
|
+
confidence: row.confidence,
|
|
186
|
+
scope: row.scope ?? 'project',
|
|
187
|
+
created_at: row.created_at,
|
|
188
|
+
superseded_at: row.superseded_at,
|
|
189
|
+
promoted_at: row.promoted_at,
|
|
190
|
+
use_count: row.use_count,
|
|
191
|
+
last_accessed: row.last_accessed,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
insertEntry(db, id, input, content, now, sourceFileHashes = {}) {
|
|
195
|
+
db.prepare(`
|
|
196
|
+
INSERT INTO entries (
|
|
197
|
+
id, type, title, summary, content,
|
|
198
|
+
source_files, symbols, module, tags,
|
|
199
|
+
content_hash, content_hash_type, stale,
|
|
200
|
+
flagged_for_review, contradiction_of,
|
|
201
|
+
author, source, confidence, scope, created_at,
|
|
202
|
+
source_file_hashes,
|
|
203
|
+
superseded_at, promoted_at, use_count
|
|
204
|
+
) VALUES (
|
|
205
|
+
?, ?, ?, ?, ?,
|
|
206
|
+
?, ?, ?, ?,
|
|
207
|
+
?, ?, ?,
|
|
208
|
+
?, ?,
|
|
209
|
+
?, ?, ?, ?, ?,
|
|
210
|
+
?,
|
|
211
|
+
NULL, NULL, 0
|
|
212
|
+
)
|
|
213
|
+
`).run(id, input.type, input.title, input.summary, content, JSON.stringify(input.source_files ?? []), JSON.stringify(input.symbols ?? []), input.module ?? null, JSON.stringify(input.tags ?? []), input.content_hash ?? '', input.content_hash_type ?? 'sha256', 0, input.flagged_for_review ? 1 : 0, input.contradiction_of ?? null, input.author ?? '', input.source, input.confidence, input.scope ?? 'project', now, JSON.stringify(sourceFileHashes));
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Resolve a source_files entry for existence checking. Absolute paths pass
|
|
217
|
+
* through; relative paths anchor at this provider's repo. Mirrors the
|
|
218
|
+
* resolution computeFileHashBatch does with an explicit { cwd } root.
|
|
219
|
+
*/
|
|
220
|
+
resolveBasisFile(p) {
|
|
221
|
+
return path.isAbsolute(p) || this.repoPath === undefined ? p : path.join(this.repoPath, p);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Basis files that are CHECKABLE and absent. A relative path with no repo root
|
|
225
|
+
* (the shared global KB) is not checkable and is therefore not reported --
|
|
226
|
+
* capture() and promote() must apply exactly the same rule, or an entry that
|
|
227
|
+
* was legitimately capturable would be permanently un-promotable.
|
|
228
|
+
*/
|
|
229
|
+
unresolvableBasisFiles(files) {
|
|
230
|
+
return files.filter((f) => {
|
|
231
|
+
if (this.repoPath === undefined && !path.isAbsolute(f))
|
|
232
|
+
return false;
|
|
233
|
+
return !fs.existsSync(this.resolveBasisFile(f));
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* apra-fleet-b4g.4: TRUE when this provider carries a repo anchor that does
|
|
238
|
+
* not exist on this host -- the remote-member case, where repo_remote_url
|
|
239
|
+
* routes the call to the REAL shared project KB while repo_path names a
|
|
240
|
+
* Windows/remote work folder the fleet server cannot see.
|
|
241
|
+
*
|
|
242
|
+
* Such an anchor can verify NOTHING about this host's tree, so the freshness
|
|
243
|
+
* verdicts that depend on it (checkFreshness, freshnessSweep) are suppressed
|
|
244
|
+
* entirely rather than re-hashed against a tree that does not exist: every
|
|
245
|
+
* relative basis path would fail to resolve, basisFullyMatches would return
|
|
246
|
+
* false, and up to 10 healthy entries per prime call would be UPDATEd to
|
|
247
|
+
* stale=1 in the shared DB.
|
|
248
|
+
*
|
|
249
|
+
* Suppression is deliberately all-or-nothing rather than per-file (entries
|
|
250
|
+
* whose basis happens to be fully absolute are skipped too): a missing anchor
|
|
251
|
+
* means this host cannot speak to the tree the entry describes at all, and a
|
|
252
|
+
* half-rule that stales some entries and not others is harder to reason about
|
|
253
|
+
* than "no anchor, no verdict". The anchor is NOT replaced by process.cwd() --
|
|
254
|
+
* that is the apra-fleet-b4g.2 corruption mode.
|
|
255
|
+
*
|
|
256
|
+
* Note the write side needs no equivalent guard: capture() already fails
|
|
257
|
+
* closed here, because assertCheckableBasis rejects any cited source file
|
|
258
|
+
* that cannot be resolved under repoPath.
|
|
259
|
+
*/
|
|
260
|
+
anchorIsMissing(anchor = this.repoPath) {
|
|
261
|
+
return anchor !== undefined && !fs.existsSync(anchor);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The Phase 1 fail-closed gate. See the call site in capture() for rationale.
|
|
265
|
+
* Throws KbCaptureRejected so batch writers can isolate and count a rejected
|
|
266
|
+
* entry while unexpected failures still propagate.
|
|
267
|
+
*/
|
|
268
|
+
assertCheckableBasis(input) {
|
|
269
|
+
const files = input.source_files ?? [];
|
|
270
|
+
if (files.length === 0) {
|
|
271
|
+
if (input.type === 'user-directive')
|
|
272
|
+
return;
|
|
273
|
+
throw new KbCaptureRejected('no_source_files', 'kb capture rejected: an entry must cite at least one source file. '
|
|
274
|
+
+ 'An entry with no basis can never be staled by the freshness sweep, '
|
|
275
|
+
+ 'so nothing can ever falsify it. Entry: ' + input.title);
|
|
276
|
+
}
|
|
277
|
+
const missing = this.unresolvableBasisFiles(files);
|
|
278
|
+
if (missing.length > 0) {
|
|
279
|
+
throw new KbCaptureRejected('missing_source_files', 'kb capture rejected: source file(s) do not exist'
|
|
280
|
+
+ (this.repoPath ? ' in ' + this.repoPath : '')
|
|
281
|
+
+ ': ' + missing.join(', ') + '. Entry: ' + input.title);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
// T2.2 (F3 PART A): resolve a per-file hash basis for the given source_files
|
|
285
|
+
// at capture time, for ALL types. Files that do not resolve are simply
|
|
286
|
+
// absent from the returned map (not an error). Bounded to the caller's own
|
|
287
|
+
// source_files list. Non-fatal: any hashing error yields an empty basis
|
|
288
|
+
// rather than failing the capture.
|
|
289
|
+
async computeSourceFileHashes(files) {
|
|
290
|
+
if (files.length === 0)
|
|
291
|
+
return {};
|
|
292
|
+
try {
|
|
293
|
+
// Anchor relative basis paths at this provider's repo, the same root the
|
|
294
|
+
// capture gate checked them against and the one freshnessSweep(root) uses.
|
|
295
|
+
const hashes = await computeFileHashBatch(files, this.repoPath !== undefined ? { cwd: this.repoPath } : undefined);
|
|
296
|
+
const map = {};
|
|
297
|
+
for (const file of Object.keys(hashes)) {
|
|
298
|
+
const result = hashes[file];
|
|
299
|
+
if (result)
|
|
300
|
+
map[file] = result.hash;
|
|
301
|
+
}
|
|
302
|
+
return map;
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
return {};
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
// T1.3 (F2/D2 HARDENED): the ANCHORED feedback-downvote marker. feedback()
|
|
309
|
+
// writes exactly '\n\n[feedback ' + new Date().toISOString() + '] ...'
|
|
310
|
+
// (see feedback()). The predicate below excludes any entry carrying this
|
|
311
|
+
// marker from revival, so a feedback-downvoted entry stays retired even if
|
|
312
|
+
// some later flow clears its flagged_for_review bit (the T3.1 winner path
|
|
313
|
+
// clears flags; the marker is the durable downvote record). We anchor to the
|
|
314
|
+
// two-newline prefix PLUS the ISO date shape ('[feedback ' + YYYY-MM-DDT)
|
|
315
|
+
// rather than a bare '[feedback ' substring: an entry whose content merely
|
|
316
|
+
// QUOTES the feedback-note format (e.g. a learning ABOUT the kb_feedback
|
|
317
|
+
// mechanism -- such entries exist in this very KB) must NOT be permanently
|
|
318
|
+
// excluded from revival once freshness-staled. Chosen pattern stated here and
|
|
319
|
+
// used verbatim by the shared predicate.
|
|
320
|
+
static FEEDBACK_MARKER_RE = /\n\n\[feedback \d{4}-\d{2}-\d{2}T/;
|
|
321
|
+
// T1.3 (F2/D2 HARDENED) -- THE UN-STALE PREDICATE (binding, verbatim):
|
|
322
|
+
//
|
|
323
|
+
// stale = 1
|
|
324
|
+
// AND superseded_at IS NULL
|
|
325
|
+
// AND flagged_for_review = 0
|
|
326
|
+
// AND content_hash != 'invalidated'
|
|
327
|
+
// AND content NOT LIKE the ANCHORED feedback marker (FEEDBACK_MARKER_RE:
|
|
328
|
+
// /\n\n\[feedback \d{4}-\d{2}-\d{2}T/ -- the newline+ISO-timestamp
|
|
329
|
+
// form feedback() actually writes, NOT a bare substring)
|
|
330
|
+
// AND the re-hash of the FULL stored basis matches current files
|
|
331
|
+
//
|
|
332
|
+
// That is precisely the freshness-staled population. stale=1 is set by FOUR
|
|
333
|
+
// actors -- freshness mismatch (prime/sweep), supersede (AUDN update, carries
|
|
334
|
+
// superseded_at), feedback downvote (carries flagged_for_review=1 AND the
|
|
335
|
+
// marker), and invalidate() (sets content_hash='invalidated', leaves
|
|
336
|
+
// flagged=0, superseded NULL, basis untouched) -- and ONLY the first may
|
|
337
|
+
// revive. This method evaluates the four NON-hash reason conjuncts; the
|
|
338
|
+
// caller owns the stale=1 gate and the full-basis re-hash (it batches the
|
|
339
|
+
// hashing). Shared by checkFreshness(), freshnessSweep(), and (T3.1)
|
|
340
|
+
// resolveContradiction() -- ONE implementation, never copied.
|
|
341
|
+
freshnessRevivable(e) {
|
|
342
|
+
if (e.superseded_at)
|
|
343
|
+
return false; // supersede actor
|
|
344
|
+
if (e.flagged_for_review)
|
|
345
|
+
return false; // feedback flag standing
|
|
346
|
+
if (e.content_hash === 'invalidated')
|
|
347
|
+
return false; // invalidate actor
|
|
348
|
+
if (SqliteProvider.FEEDBACK_MARKER_RE.test(e.content ?? ''))
|
|
349
|
+
return false; // durable downvote
|
|
350
|
+
return true;
|
|
351
|
+
}
|
|
352
|
+
// T1.3 (F2/D2): the FULL-basis re-hash conjunct. Returns true only when the
|
|
353
|
+
// stored basis is non-empty AND every basis file resolves to a current hash
|
|
354
|
+
// equal to the stored one. An empty basis never matches (never revive on an
|
|
355
|
+
// empty/malformed basis); a partial match (some file changed/missing) is NOT
|
|
356
|
+
// a full match, so a multi-file entry with only one file matching is not
|
|
357
|
+
// revived. Complement (not a full match) is exactly "basis mismatch" used for
|
|
358
|
+
// the stale=1 direction.
|
|
359
|
+
basisFullyMatches(basis, currentHashes) {
|
|
360
|
+
const files = Object.keys(basis);
|
|
361
|
+
if (files.length === 0)
|
|
362
|
+
return false;
|
|
363
|
+
for (const file of files) {
|
|
364
|
+
const current = currentHashes[file];
|
|
365
|
+
if (!current || current.hash !== basis[file])
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
return true;
|
|
369
|
+
}
|
|
370
|
+
// Parse a stored source_file_hashes JSON map; returns null for empty or
|
|
371
|
+
// malformed bases (never falsely stale, never falsely revive).
|
|
372
|
+
parseBasis(raw) {
|
|
373
|
+
try {
|
|
374
|
+
const parsed = JSON.parse(raw || '{}');
|
|
375
|
+
if (parsed && typeof parsed === 'object' && Object.keys(parsed).length > 0)
|
|
376
|
+
return parsed;
|
|
377
|
+
return null;
|
|
378
|
+
}
|
|
379
|
+
catch {
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
// T1.3 (F2/D2 HARDENED): freshness check bounded to the primed set, now
|
|
384
|
+
// BIDIRECTIONAL. Keyed off source_files with a per-file hash basis persisted
|
|
385
|
+
// at capture time (source_file_hashes) -- NOT content_hash, which is only ever
|
|
386
|
+
// set for context-cache entries that prime() already excludes from
|
|
387
|
+
// top_entries. Entries with no source_files, or an empty/unparseable stored
|
|
388
|
+
// basis, are left untouched (never falsely stale). For entries that DO have a
|
|
389
|
+
// basis, re-hash the union of basis files ONCE (bounded to the primed set,
|
|
390
|
+
// never the whole KB): a basis MISMATCH marks stale=1 and drops the entry from
|
|
391
|
+
// the returned list; a FULL basis match on an entry that is stale AND passes
|
|
392
|
+
// the shared un-stale predicate clears stale=0.
|
|
393
|
+
//
|
|
394
|
+
// CAVEAT (also on freshnessSweep): prime()'s candidate set EXCLUDES stale
|
|
395
|
+
// entries by definition (query filters stale=0), so in practice the un-stale
|
|
396
|
+
// direction here is a no-op -- prime alone CANNOT revive a staled entry.
|
|
397
|
+
// Branch-switch revival requires freshnessSweep() (invoked by kb_import in
|
|
398
|
+
// T2.1 and /pm kb-reconcile in T3.2), NOT just a prime. kb_stats stays
|
|
399
|
+
// read-only (D2). The un-stale branch is implemented here for consistency and
|
|
400
|
+
// to share the exact predicate, but the real revival surface is the sweep.
|
|
401
|
+
async checkFreshness(db, entries) {
|
|
402
|
+
// apra-fleet-b4g.4: an anchor that does not exist on this host yields no
|
|
403
|
+
// freshness verdict at all -- see anchorIsMissing(). Returning the entries
|
|
404
|
+
// untouched keeps prime read-only for remote members instead of staling
|
|
405
|
+
// healthy entries in the shared project KB.
|
|
406
|
+
if (this.anchorIsMissing())
|
|
407
|
+
return entries;
|
|
408
|
+
const candidates = entries.filter(e => e.source_files.length > 0);
|
|
409
|
+
if (candidates.length === 0)
|
|
410
|
+
return entries;
|
|
411
|
+
const candidateIds = candidates.map(e => e.id);
|
|
412
|
+
const rows = db.prepare(`SELECT id, source_file_hashes FROM entries WHERE id IN (${candidateIds.map(() => '?').join(',')})`).all(...candidateIds);
|
|
413
|
+
const basisById = new Map();
|
|
414
|
+
for (const row of rows) {
|
|
415
|
+
const basis = this.parseBasis(row.source_file_hashes);
|
|
416
|
+
if (basis)
|
|
417
|
+
basisById.set(row.id, basis);
|
|
418
|
+
}
|
|
419
|
+
if (basisById.size === 0)
|
|
420
|
+
return entries;
|
|
421
|
+
const entryById = new Map(entries.map(e => [e.id, e]));
|
|
422
|
+
const fileSet = new Set();
|
|
423
|
+
for (const basis of basisById.values()) {
|
|
424
|
+
for (const file of Object.keys(basis))
|
|
425
|
+
fileSet.add(file);
|
|
426
|
+
}
|
|
427
|
+
// Anchor at the provider's own repo, the SAME root computeSourceFileHashes
|
|
428
|
+
// stored the basis against at capture time. Without this the two disagree
|
|
429
|
+
// whenever the process cwd is not the repo -- which is the normal case in
|
|
430
|
+
// the long-lived fleet server -- so every relative basis path would re-hash
|
|
431
|
+
// to a different value and prime would stale healthy entries on sight.
|
|
432
|
+
const currentHashes = await computeFileHashBatch([...fileSet], this.repoPath !== undefined ? { cwd: this.repoPath } : undefined);
|
|
433
|
+
const staleIds = [];
|
|
434
|
+
const unstaleIds = [];
|
|
435
|
+
for (const [id, basis] of basisById) {
|
|
436
|
+
const entry = entryById.get(id);
|
|
437
|
+
const matches = this.basisFullyMatches(basis, currentHashes);
|
|
438
|
+
if (!matches) {
|
|
439
|
+
staleIds.push(id);
|
|
440
|
+
}
|
|
441
|
+
else if (entry && entry.stale && this.freshnessRevivable(entry)) {
|
|
442
|
+
unstaleIds.push(id);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (staleIds.length > 0) {
|
|
446
|
+
db.prepare(`UPDATE entries SET stale = 1 WHERE id IN (${staleIds.map(() => '?').join(',')})`).run(...staleIds);
|
|
447
|
+
}
|
|
448
|
+
if (unstaleIds.length > 0) {
|
|
449
|
+
db.prepare(`UPDATE entries SET stale = 0 WHERE id IN (${unstaleIds.map(() => '?').join(',')})`).run(...unstaleIds);
|
|
450
|
+
}
|
|
451
|
+
const staleSet = new Set(staleIds);
|
|
452
|
+
return entries.filter(e => !staleSet.has(e.id));
|
|
453
|
+
}
|
|
454
|
+
// T1.3 (F2/D2 HARDENED) resolution R2: a bounded, full-KB bidirectional
|
|
455
|
+
// freshness sweep -- the revival surface that prime() cannot be (its candidate
|
|
456
|
+
// set excludes stale entries). Runs the SAME shared predicate in BOTH
|
|
457
|
+
// directions over ALL entries with a non-empty basis: a basis mismatch marks a
|
|
458
|
+
// currently-fresh entry stale=1; a full basis match revives a stale entry that
|
|
459
|
+
// passes freshnessRevivable() (superseded, feedback-downvoted, and invalidated
|
|
460
|
+
// entries stay retired). Bounded: ONE computeFileHashBatch over the union of
|
|
461
|
+
// all basis files (the KB is <1000 entries -- fine for an explicit command;
|
|
462
|
+
// NOT wired into prime). Exposed as MCP tool kb_freshness_sweep and invoked by
|
|
463
|
+
// kb_import (T2.1) and /pm kb-reconcile (T3.2).
|
|
464
|
+
//
|
|
465
|
+
// Return semantics: `checked` counts entries with a non-empty, parseable basis
|
|
466
|
+
// that were evaluated against the hash batch (entries with no/empty/malformed
|
|
467
|
+
// basis are neither staled nor revived nor counted). `staled` counts fresh
|
|
468
|
+
// entries newly marked stale on a mismatch; `unstaled` counts stale entries
|
|
469
|
+
// revived on a full match.
|
|
470
|
+
//
|
|
471
|
+
// T3.1 (D4 fold-in, Phase 2 review MEDIUM yashr-d8b): optional `root` anchors
|
|
472
|
+
// basis re-hashing at an explicit repo path (e.g. kb_import's --repo) WITHOUT
|
|
473
|
+
// a global process.chdir. Previously kb-import.ts's sweepAnchored() wrapped
|
|
474
|
+
// this call in process.chdir(repoAnchor)/process.chdir(prevCwd) across the
|
|
475
|
+
// await -- a global, process-wide mutation for the duration of the hashing
|
|
476
|
+
// that any other concurrent async work in the same process would also
|
|
477
|
+
// observe. Threading the anchor straight into computeFileHashBatch's { cwd }
|
|
478
|
+
// option removes that global side effect entirely; behavior is identical
|
|
479
|
+
// (relative basis paths still resolve against the intended repo root,
|
|
480
|
+
// absolute basis paths are unaffected either way). Omitting root preserves
|
|
481
|
+
// exact prior behavior (implicit process.cwd() resolution).
|
|
482
|
+
//
|
|
483
|
+
// apra-fleet-b4g.4 (acceptance criterion 5): when `root` is omitted the sweep
|
|
484
|
+
// now falls back to THIS PROVIDER'S anchor, not process.cwd(). kb_freshness_sweep
|
|
485
|
+
// (src/tools/kb-freshness-sweep.ts) called this with no root, so it re-hashed
|
|
486
|
+
// relative basis paths against the fleet server's own working directory while
|
|
487
|
+
// checkFreshness re-hashed the very same basis against repoPath -- two actors
|
|
488
|
+
// writing opposite stale verdicts for one entry. The provider anchor is the
|
|
489
|
+
// root the basis was stored against (computeSourceFileHashes), so it is the
|
|
490
|
+
// only correct default; an explicit root (kb_import's --repo) still wins, and
|
|
491
|
+
// a provider with no anchor at all (the shared global KB) keeps the previous
|
|
492
|
+
// implicit-cwd behaviour. A resolved anchor that does not exist on this host
|
|
493
|
+
// yields no verdict at all -- see anchorIsMissing().
|
|
494
|
+
async freshnessSweep(root) {
|
|
495
|
+
const anchor = root ?? this.repoPath;
|
|
496
|
+
if (this.anchorIsMissing(anchor))
|
|
497
|
+
return { checked: 0, staled: 0, unstaled: 0 };
|
|
498
|
+
const db = this.getDb();
|
|
499
|
+
const rows = db.prepare(`SELECT id, stale, superseded_at, flagged_for_review, content_hash, content, source_file_hashes
|
|
500
|
+
FROM entries`).all();
|
|
501
|
+
const basisById = new Map();
|
|
502
|
+
const rowById = new Map();
|
|
503
|
+
for (const row of rows) {
|
|
504
|
+
const basis = this.parseBasis(row.source_file_hashes);
|
|
505
|
+
if (basis) {
|
|
506
|
+
basisById.set(row.id, basis);
|
|
507
|
+
rowById.set(row.id, row);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
if (basisById.size === 0)
|
|
511
|
+
return { checked: 0, staled: 0, unstaled: 0 };
|
|
512
|
+
const fileSet = new Set();
|
|
513
|
+
for (const basis of basisById.values()) {
|
|
514
|
+
for (const file of Object.keys(basis))
|
|
515
|
+
fileSet.add(file);
|
|
516
|
+
}
|
|
517
|
+
const currentHashes = await computeFileHashBatch([...fileSet], anchor ? { cwd: anchor } : undefined);
|
|
518
|
+
const staleIds = [];
|
|
519
|
+
const unstaleIds = [];
|
|
520
|
+
let checked = 0;
|
|
521
|
+
for (const [id, basis] of basisById) {
|
|
522
|
+
checked++;
|
|
523
|
+
const row = rowById.get(id);
|
|
524
|
+
const matches = this.basisFullyMatches(basis, currentHashes);
|
|
525
|
+
const isStale = row.stale === 1;
|
|
526
|
+
if (!matches) {
|
|
527
|
+
if (!isStale)
|
|
528
|
+
staleIds.push(id); // freshness mismatch actor
|
|
529
|
+
}
|
|
530
|
+
else if (isStale && this.freshnessRevivable({
|
|
531
|
+
superseded_at: row.superseded_at,
|
|
532
|
+
flagged_for_review: row.flagged_for_review === 1,
|
|
533
|
+
content_hash: row.content_hash,
|
|
534
|
+
content: row.content,
|
|
535
|
+
})) {
|
|
536
|
+
unstaleIds.push(id);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
if (staleIds.length > 0) {
|
|
540
|
+
db.prepare(`UPDATE entries SET stale = 1 WHERE id IN (${staleIds.map(() => '?').join(',')})`).run(...staleIds);
|
|
541
|
+
}
|
|
542
|
+
if (unstaleIds.length > 0) {
|
|
543
|
+
db.prepare(`UPDATE entries SET stale = 0 WHERE id IN (${unstaleIds.map(() => '?').join(',')})`).run(...unstaleIds);
|
|
544
|
+
}
|
|
545
|
+
return { checked, staled: staleIds.length, unstaled: unstaleIds.length };
|
|
546
|
+
}
|
|
547
|
+
findAudnCandidates(db, input) {
|
|
548
|
+
const ftsQuery = makeFtsQuery(input.title);
|
|
549
|
+
if (!ftsQuery)
|
|
550
|
+
return [];
|
|
551
|
+
try {
|
|
552
|
+
// D2 HALF B (candidate-discovery fix): candidates are discovered by symbol/
|
|
553
|
+
// title overlap across ALL entry types -- the same-type restriction was
|
|
554
|
+
// removed so cross-type contradictions (e.g. a 'knowledge' entry
|
|
555
|
+
// contradicting a 'learning' entry on shared symbols) are discoverable.
|
|
556
|
+
// makeAudnDecision re-imposes candidate.type === input.type for the
|
|
557
|
+
// dedup/update decisions; only the contradiction path stays cross-type.
|
|
558
|
+
const rows = db.prepare(`
|
|
559
|
+
SELECT e.* FROM entries e
|
|
560
|
+
JOIN entries_fts ON entries_fts.rowid = e.rowid
|
|
561
|
+
WHERE entries_fts MATCH ?
|
|
562
|
+
AND e.superseded_at IS NULL
|
|
563
|
+
ORDER BY rank
|
|
564
|
+
LIMIT 10
|
|
565
|
+
`).all(ftsQuery);
|
|
566
|
+
return rows.map(r => this.rowToEntry(r));
|
|
567
|
+
}
|
|
568
|
+
catch {
|
|
569
|
+
return [];
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
evaluateAudn(db, input, candidates, newContent, now, sourceFileHashes) {
|
|
573
|
+
const decision = makeAudnDecision(input, candidates, newContent);
|
|
574
|
+
if (!decision)
|
|
575
|
+
return null;
|
|
576
|
+
if (decision.decision === 'none') {
|
|
577
|
+
return { id: decision.matchedId, audn_decision: 'none' };
|
|
578
|
+
}
|
|
579
|
+
if (decision.decision === 'flagged') {
|
|
580
|
+
db.prepare('UPDATE entries SET flagged_for_review = 1 WHERE id = ?').run(decision.matchedId);
|
|
581
|
+
const newId = randomUUID();
|
|
582
|
+
this.insertEntry(db, newId, { ...input, ...decision.newEntryOverrides }, newContent, now, sourceFileHashes);
|
|
583
|
+
this.wireLinks(db, newId, input);
|
|
584
|
+
return { id: newId, audn_decision: 'flagged' };
|
|
585
|
+
}
|
|
586
|
+
if (decision.decision === 'update') {
|
|
587
|
+
const newId = randomUUID();
|
|
588
|
+
if (input.supersedes === decision.matchedId) {
|
|
589
|
+
// EXPLICIT: the caller named what it replaces and AUDN independently
|
|
590
|
+
// matched it. Retire it exactly as before -- superseded_at + stale = 1.
|
|
591
|
+
// D2 (F2a): both flags are required so the old row is excluded from
|
|
592
|
+
// query()/prime() by default (query filters stale = 0 independently of
|
|
593
|
+
// superseded_at). content_hash is left intact.
|
|
594
|
+
// flagged_for_review is deliberately NOT cleared here; that is
|
|
595
|
+
// resolveContradiction's behavior, and kb-review.md depends on the
|
|
596
|
+
// difference (a kept entry stays listed under flagged_only).
|
|
597
|
+
db.prepare('UPDATE entries SET superseded_at = ?, stale = 1 WHERE id = ?')
|
|
598
|
+
.run(now, decision.matchedId);
|
|
599
|
+
this.insertEntry(db, newId, input, newContent, now, sourceFileHashes);
|
|
600
|
+
this.wireLinks(db, newId, input);
|
|
601
|
+
return { id: newId, audn_decision: 'update' };
|
|
602
|
+
}
|
|
603
|
+
// IMPLICIT: same type, overlapping symbol and file, different content.
|
|
604
|
+
// That is a topicality signal, not consent to destroy -- two DISTINCT
|
|
605
|
+
// facts about one symbol used to eat each other. Link and keep both;
|
|
606
|
+
// curation retires what it means to retire, explicitly.
|
|
607
|
+
this.insertEntry(db, newId, input, newContent, now, sourceFileHashes);
|
|
608
|
+
this.wireLinks(db, newId, input);
|
|
609
|
+
db.prepare('INSERT OR IGNORE INTO links (from_id, to_id, link_type) VALUES (?, ?, ?)').run(newId, decision.matchedId, 'refines');
|
|
610
|
+
return { id: newId, audn_decision: 'update' };
|
|
611
|
+
}
|
|
612
|
+
return null;
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* LEGACY-ONLY as of 2026-08-03 (decided with KB-TRUST PHASE 1). The predicate
|
|
616
|
+
* below matches only rows whose source_files is empty -- "concept entries" --
|
|
617
|
+
* and capture() now refuses to create such a row at all. Every entry captured
|
|
618
|
+
* from here on carries a basis, so this can only ever match rows predating the
|
|
619
|
+
* Phase 1 gate. Staleness for basis-carrying entries is freshnessSweep()'s job
|
|
620
|
+
* instead; note the two mechanisms differ (a stale flag, not a confidence
|
|
621
|
+
* downgrade), so the INFERRED -> UNVERIFIED ladder simply stops firing for new
|
|
622
|
+
* knowledge. Tracked as apra-fleet-4wz.7. Kept as-is deliberately: legacy rows
|
|
623
|
+
* still exist in live KBs and must still decay.
|
|
624
|
+
*/
|
|
625
|
+
decayConceptEntries(db, days) {
|
|
626
|
+
const cutoff = new Date(Date.now() - days * 86400 * 1000).toISOString();
|
|
627
|
+
// F1 (D1): only an ACTIVE directive (type='user-directive' AND
|
|
628
|
+
// confidence='CONFIRMED') is exempt from decay. A pending/rejected directive
|
|
629
|
+
// proposal is UNVERIFIED, so it is already below the INFERRED decay target
|
|
630
|
+
// and decay is not observable on it (L2). The rekeyed guard
|
|
631
|
+
// `NOT (type='user-directive' AND confidence='CONFIRMED')` keeps the
|
|
632
|
+
// invariant precise: a hypothetical INFERRED user-directive row would decay
|
|
633
|
+
// like any concept, while an ACTIVE directive never does.
|
|
634
|
+
db.prepare(`
|
|
635
|
+
UPDATE entries
|
|
636
|
+
SET confidence = 'UNVERIFIED'
|
|
637
|
+
WHERE confidence = 'INFERRED'
|
|
638
|
+
AND NOT (type = 'user-directive' AND confidence = 'CONFIRMED')
|
|
639
|
+
AND superseded_at IS NULL
|
|
640
|
+
AND (source_files = '[]' OR source_files IS NULL OR source_files = '')
|
|
641
|
+
AND (last_accessed IS NULL OR last_accessed < ?)
|
|
642
|
+
AND (promoted_at IS NULL OR promoted_at < ?)
|
|
643
|
+
`).run(cutoff, cutoff);
|
|
644
|
+
}
|
|
645
|
+
wireLinks(db, newId, input) {
|
|
646
|
+
const symbols = input.symbols ?? [];
|
|
647
|
+
const files = input.source_files ?? [];
|
|
648
|
+
if (symbols.length === 0 && files.length === 0)
|
|
649
|
+
return;
|
|
650
|
+
const existingRows = db.prepare('SELECT id, symbols, source_files FROM entries WHERE id != ? AND superseded_at IS NULL').all(newId);
|
|
651
|
+
const linkStmt = db.prepare('INSERT OR IGNORE INTO links (from_id, to_id, link_type) VALUES (?, ?, ?)');
|
|
652
|
+
for (const row of existingRows) {
|
|
653
|
+
const existingSymbols = JSON.parse(row.symbols || '[]');
|
|
654
|
+
const existingFiles = JSON.parse(row.source_files || '[]');
|
|
655
|
+
if (symbols.length > 0 && symbols.some(s => existingSymbols.includes(s))) {
|
|
656
|
+
linkStmt.run(newId, row.id, 'shares_symbol');
|
|
657
|
+
}
|
|
658
|
+
if (files.length > 0 && files.some(f => existingFiles.includes(f))) {
|
|
659
|
+
linkStmt.run(newId, row.id, 'shares_file');
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
async capture(input, opts) {
|
|
664
|
+
const db = this.getDb();
|
|
665
|
+
const now = new Date().toISOString();
|
|
666
|
+
// F1 (D1, closes yashr-9ha): capture() is the single choke point every
|
|
667
|
+
// MCP-reachable route flows through (the kb_capture handler AND the HTTP
|
|
668
|
+
// /api/kb/capture route on the KB server). Enforcing the directive
|
|
669
|
+
// proposal-transformation HERE -- not only in the kb_capture handler --
|
|
670
|
+
// means no capture route can mint an active directive. A user-directive
|
|
671
|
+
// captured over MCP is forced to a PENDING PROPOSAL: confidence downgraded
|
|
672
|
+
// to UNVERIFIED, flagged_for_review set, a 'directive:pending' tag added,
|
|
673
|
+
// and scope forced to 'project' (M1: a global proposal would be unreachable
|
|
674
|
+
// by the project CLI that approves it). Activation is CLI-only via the
|
|
675
|
+
// dedicated approveDirective/addDirective methods, which bypass capture().
|
|
676
|
+
if (input.type === 'user-directive') {
|
|
677
|
+
const existingTags = input.tags ?? [];
|
|
678
|
+
const tags = existingTags.includes('directive:pending')
|
|
679
|
+
? existingTags
|
|
680
|
+
: [...existingTags, 'directive:pending'];
|
|
681
|
+
input = {
|
|
682
|
+
...input,
|
|
683
|
+
confidence: 'UNVERIFIED',
|
|
684
|
+
flagged_for_review: true,
|
|
685
|
+
scope: 'project',
|
|
686
|
+
tags,
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
// KB-TRUST PHASE 1 (decided 2026-08-03): capture FAILS CLOSED on an
|
|
690
|
+
// uncheckable basis, and this is the ENFORCEMENT copy for the same reason
|
|
691
|
+
// the confidence clamp below is here -- three of the four capture call
|
|
692
|
+
// sites (kb_harvest, kb_import, the HTTP /api/kb/capture route) never touch
|
|
693
|
+
// the kb_capture handler, so a tool-layer check would be bypassed by most
|
|
694
|
+
// of the traffic.
|
|
695
|
+
//
|
|
696
|
+
// Rationale: freshnessSweep() builds its work set ONLY from entries with a
|
|
697
|
+
// parsed source_file_hashes basis, so an entry citing no files is never
|
|
698
|
+
// checked and can never be staled -- permanently CONFIRMED-able and
|
|
699
|
+
// structurally unfalsifiable. An entry citing files that do not exist is
|
|
700
|
+
// checkable and already wrong.
|
|
701
|
+
//
|
|
702
|
+
// NO exemption for source='harvest' or for importMode. Import is exempt
|
|
703
|
+
// from the confidence clamp only; an unfalsifiable entry must not enter
|
|
704
|
+
// through any path, including a legacy bible.
|
|
705
|
+
//
|
|
706
|
+
// user-directive IS exempt from the empty-basis half: a standing human
|
|
707
|
+
// instruction ("never force-push to main") is not a claim about code and
|
|
708
|
+
// cites no files by nature. It is still quarantined to an UNVERIFIED
|
|
709
|
+
// pending proposal by the directive gate above and can only be activated
|
|
710
|
+
// CLI-side, so it never reaches the bible on its own. A directive that DOES
|
|
711
|
+
// cite files is still held to those files existing.
|
|
712
|
+
this.assertCheckableBasis(input);
|
|
713
|
+
// T1.2 (F3, R3, KB 9462ab04): general confidence clamp -- the ENFORCEMENT
|
|
714
|
+
// copy. The kb_capture tool handler (kb-capture.ts) also clamps and returns
|
|
715
|
+
// a confidence_clamped UX flag to MCP callers, but the HTTP /api/kb/capture
|
|
716
|
+
// route calls provider.capture(JSON.parse(body)) directly
|
|
717
|
+
// (kb-server.ts:133-141), bypassing that handler and previously able to mint
|
|
718
|
+
// CONFIRMED for non-directive types. This block is the single enforcement
|
|
719
|
+
// choke point every route flows through: for NON-directive types an incoming
|
|
720
|
+
// CONFIRMED is downgraded to INFERRED with a bracketed content note that
|
|
721
|
+
// mirrors the handler's wording. CONFIRMED is minted ONLY by promote() and
|
|
722
|
+
// approveDirective/addDirective, all of which bypass capture() -- they are
|
|
723
|
+
// not exemptions here, they simply never reach this code.
|
|
724
|
+
//
|
|
725
|
+
// Ordering: the directive gate above has already forced user-directive
|
|
726
|
+
// entries to UNVERIFIED proposals, so this clamp never fires for them; the
|
|
727
|
+
// explicit type check keeps that intent legible. Keep this block AFTER the
|
|
728
|
+
// directive gate.
|
|
729
|
+
//
|
|
730
|
+
// T2.1 (F4, D3, MEDIUM-4) PROVENANCE NORMALIZATION -- runs BEFORE the clamp,
|
|
731
|
+
// AFTER the directive gate. insertEntry() persists input.source verbatim, so
|
|
732
|
+
// the two PRIVILEGED provenance values -- 'import' (the kb_import trusted
|
|
733
|
+
// channel) and 'promotion' (stamped only by promote(), which never calls
|
|
734
|
+
// capture()) -- must never be settable by a deserialized route body. When the
|
|
735
|
+
// internal import mode is NOT engaged, a caller-supplied source of 'import'
|
|
736
|
+
// or 'promotion' is OVERWRITTEN with 'unknown' (we mark provenance we cannot
|
|
737
|
+
// vouch for, rather than lying with 'session'). Under import mode the tool's
|
|
738
|
+
// own source='import' is legitimate and survives. Without this, an HTTP
|
|
739
|
+
// caller could stamp forged trusted-channel provenance (clamped, but
|
|
740
|
+
// mislabeled -- audits keyed on source='import' would trust forged rows).
|
|
741
|
+
if (!opts?.importMode && (input.source === 'import' || input.source === 'promotion')) {
|
|
742
|
+
input = { ...input, source: 'unknown' };
|
|
743
|
+
}
|
|
744
|
+
// T2.1 (F4, D3): import is the SOLE capture()-level exemption to this clamp.
|
|
745
|
+
// The internal import-mode flag is a SECOND parameter of capture() (opts),
|
|
746
|
+
// NEVER a field of the deserialized input (the HTTP route passes exactly one
|
|
747
|
+
// argument and the MCP handler builds input from zod fields, so a second
|
|
748
|
+
// parameter is structurally unreachable from any deserialized route -- R4).
|
|
749
|
+
// When import mode is engaged, a NON-directive entry keeps its bible
|
|
750
|
+
// confidence: the bible is a git-reviewed, human-merged artifact (the trusted
|
|
751
|
+
// channel) and re-clamping would demote the whole team's CONFIRMED knowledge
|
|
752
|
+
// on every import. The directive gate above still ran first, so a bible
|
|
753
|
+
// cannot smuggle an active directive even under import mode.
|
|
754
|
+
// String concatenation (not a template literal) per the ASCII pre-commit
|
|
755
|
+
// hook's backtick-escape false-positive.
|
|
756
|
+
if (!opts?.importMode && input.type !== 'user-directive' && input.confidence === 'CONFIRMED') {
|
|
757
|
+
input = {
|
|
758
|
+
...input,
|
|
759
|
+
confidence: 'INFERRED',
|
|
760
|
+
content: input.content + '\n\n[confidence clamped: CONFIRMED requires kb_promote]',
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
const content = truncateContent(input.content);
|
|
764
|
+
// T2.2 (F3 PART A): capture() is the single choke point every caller
|
|
765
|
+
// (kb_capture, kb_harvest, future paths) goes through, so every entry
|
|
766
|
+
// gets a hash basis here regardless of type.
|
|
767
|
+
const sourceFileHashes = await this.computeSourceFileHashes(input.source_files ?? []);
|
|
768
|
+
const candidates = this.findAudnCandidates(db, input);
|
|
769
|
+
if (candidates.length > 0) {
|
|
770
|
+
const result = this.evaluateAudn(db, input, candidates, content, now, sourceFileHashes);
|
|
771
|
+
if (result)
|
|
772
|
+
return result;
|
|
773
|
+
}
|
|
774
|
+
// T2.1 (F4, D3, LOW-2): on the pure 'add' path, kb_import preserves the
|
|
775
|
+
// bible entry's id (opts.preferredId) so a re-import dedupes EXACTLY via the
|
|
776
|
+
// id-skip gate (kb_import checks hasEntry() before ever calling capture, so
|
|
777
|
+
// the id is guaranteed free here). AUDN's update/flagged branches above
|
|
778
|
+
// always mint a fresh randomUUID -- an id collision with different content is
|
|
779
|
+
// resolved by AUDN under a new id, never by overwriting the preserved id.
|
|
780
|
+
const id = opts?.preferredId ?? randomUUID();
|
|
781
|
+
this.insertEntry(db, id, input, content, now, sourceFileHashes);
|
|
782
|
+
this.wireLinks(db, id, input);
|
|
783
|
+
return { id, audn_decision: 'add' };
|
|
784
|
+
}
|
|
785
|
+
// T2.1 (F4, D3, LOW-2): existence check for kb_import's per-entry id-skip --
|
|
786
|
+
// the FIRST gate, run BEFORE capture()/AUDN. Idempotency cannot rely on AUDN
|
|
787
|
+
// alone: AUDN dedupe needs symbol AND file overlap (symbolsOverlap/filesOverlap
|
|
788
|
+
// return false on empty arrays), so a symbol-less or file-less bible entry
|
|
789
|
+
// would re-add on every import if AUDN were the only guard. Checks ALL rows
|
|
790
|
+
// (superseded/stale included) so a previously-absorbed entry never re-adds, and
|
|
791
|
+
// -- unlike query({ids}) -- bumps no use_count/last_accessed telemetry.
|
|
792
|
+
hasEntry(id) {
|
|
793
|
+
const row = this.getDb().prepare('SELECT 1 FROM entries WHERE id = ?').get(id);
|
|
794
|
+
return row !== undefined;
|
|
795
|
+
}
|
|
796
|
+
// KB audit 2026-08-11: the write half of "delivery is retrieval".
|
|
797
|
+
//
|
|
798
|
+
// query() bumps use_count/last_accessed for everything it returns, but an
|
|
799
|
+
// entry delivered to an agent from the canonical-bible cold-seed never goes
|
|
800
|
+
// through query() -- it is parsed out of a JSON file. Since the sprint engine
|
|
801
|
+
// primes without hints, the bible is the ONLY thing it delivers, so every
|
|
802
|
+
// delivery was invisible to the retrieval telemetry and hit_rate read 0 while
|
|
803
|
+
// entries were genuinely being handed out.
|
|
804
|
+
//
|
|
805
|
+
// Existence-tolerant BY DESIGN, not by accident: a bible is exported from one
|
|
806
|
+
// machine and read on another, so an id with no local row is the normal case,
|
|
807
|
+
// not an error. Returns how many rows were actually bumped -- the caller can
|
|
808
|
+
// tell "delivered from our own KB" from "delivered from someone else's".
|
|
809
|
+
async touch(ids) {
|
|
810
|
+
if (ids.length === 0)
|
|
811
|
+
return 0;
|
|
812
|
+
const db = this.getDb();
|
|
813
|
+
const placeholders = ids.map(() => '?').join(',');
|
|
814
|
+
const res = db.prepare(`
|
|
815
|
+
UPDATE entries SET use_count = use_count + 1, last_accessed = ?
|
|
816
|
+
WHERE id IN (${placeholders})
|
|
817
|
+
`).run(new Date().toISOString(), ...ids);
|
|
818
|
+
// node:sqlite types changes as number|bigint (bigint only past 2^53 rows).
|
|
819
|
+
return Number(res.changes);
|
|
820
|
+
}
|
|
821
|
+
async query(opts) {
|
|
822
|
+
const db = this.getDb();
|
|
823
|
+
const conditions = [];
|
|
824
|
+
const params = [];
|
|
825
|
+
// Direct ID lookup bypasses FTS and filters
|
|
826
|
+
if (opts.ids?.length) {
|
|
827
|
+
const placeholders = opts.ids.map(() => '?').join(',');
|
|
828
|
+
const rows = db.prepare(`SELECT * FROM entries WHERE id IN (${placeholders})`).all(...opts.ids);
|
|
829
|
+
const results = rows.map(r => this.rowToEntry(r));
|
|
830
|
+
if (results.length > 0) {
|
|
831
|
+
db.prepare(`
|
|
832
|
+
UPDATE entries SET use_count = use_count + 1, last_accessed = ?
|
|
833
|
+
WHERE id IN (${results.map(() => '?').join(',')})
|
|
834
|
+
`).run(new Date().toISOString(), ...results.map(r => r.id));
|
|
835
|
+
}
|
|
836
|
+
return { results, total: results.length, l1_only: false };
|
|
837
|
+
}
|
|
838
|
+
if (!opts.include_superseded) {
|
|
839
|
+
conditions.push('e.superseded_at IS NULL');
|
|
840
|
+
}
|
|
841
|
+
if (!opts.include_stale) {
|
|
842
|
+
conditions.push('e.stale = 0');
|
|
843
|
+
}
|
|
844
|
+
if (opts.type) {
|
|
845
|
+
conditions.push('e.type = ?');
|
|
846
|
+
params.push(opts.type);
|
|
847
|
+
}
|
|
848
|
+
if (opts.tag) {
|
|
849
|
+
// T-tag-filter: exact-match WHERE clause via json_each, same pattern as
|
|
850
|
+
// list()'s symbol filter above. This is NOT an FTS term -- it is ANDed
|
|
851
|
+
// into `conditions`, which both the FTS-query branch (ftsWhere) and the
|
|
852
|
+
// plain-listing branch (where) already consume below, so it composes
|
|
853
|
+
// with `query` and other filters without touching the FTS/OR-join logic.
|
|
854
|
+
conditions.push('EXISTS (SELECT 1 FROM json_each(e.tags) WHERE value = ?)');
|
|
855
|
+
params.push(opts.tag);
|
|
856
|
+
}
|
|
857
|
+
if (opts.flagged_only) {
|
|
858
|
+
conditions.push('(e.flagged_for_review = 1 OR e.contradiction_of IS NOT NULL)');
|
|
859
|
+
}
|
|
860
|
+
else {
|
|
861
|
+
// H2 (F1, D1, closes yashr-9ha): default retrieval NEVER surfaces a
|
|
862
|
+
// pending or rejected directive PROPOSAL (type='user-directive' with
|
|
863
|
+
// confidence != 'CONFIRMED'). Only an ACTIVE (CONFIRMED) directive
|
|
864
|
+
// surfaces. This is the surgical exclusion the pending representation
|
|
865
|
+
// alone does not provide (flagged UNVERIFIED rows otherwise match FTS).
|
|
866
|
+
// The flagged_only audit path is exempt (above) -- that is where a human
|
|
867
|
+
// finds pending proposals; kb_list uses a separate method and is likewise
|
|
868
|
+
// unaffected. prime() delegates here, so it inherits the exclusion.
|
|
869
|
+
conditions.push("NOT (e.type = 'user-directive' AND e.confidence != 'CONFIRMED')");
|
|
870
|
+
}
|
|
871
|
+
const where = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';
|
|
872
|
+
const limit = opts.limit ?? 20;
|
|
873
|
+
let rows;
|
|
874
|
+
if (opts.query || opts.fts_terms?.length) {
|
|
875
|
+
// ONE sanitization point. Free text is tokenized then OR-joined; internal
|
|
876
|
+
// callers pass discrete terms via fts_terms. Raw MATCH threw on '.', '-',
|
|
877
|
+
// '(', ')', '/' and implicit-AND'd multi-term queries to zero rows.
|
|
878
|
+
const ftsQuery = opts.fts_terms?.length
|
|
879
|
+
? orJoinFtsTerms(opts.fts_terms)
|
|
880
|
+
: orJoinFtsTerms(opts.query.match(/[A-Za-z0-9_]+/g) ?? []);
|
|
881
|
+
if (!ftsQuery)
|
|
882
|
+
return { results: [], total: 0, l1_only: !!opts.l1_only };
|
|
883
|
+
const ftsWhere = conditions.length > 0 ? 'AND ' + conditions.join(' AND ') : '';
|
|
884
|
+
rows = db.prepare(`
|
|
885
|
+
SELECT e.* FROM entries e
|
|
886
|
+
JOIN entries_fts ON entries_fts.rowid = e.rowid
|
|
887
|
+
WHERE entries_fts MATCH ?
|
|
888
|
+
${ftsWhere}
|
|
889
|
+
ORDER BY rank
|
|
890
|
+
LIMIT ?
|
|
891
|
+
`).all(ftsQuery, ...params, limit);
|
|
892
|
+
}
|
|
893
|
+
else {
|
|
894
|
+
rows = db.prepare(`
|
|
895
|
+
SELECT e.* FROM entries e
|
|
896
|
+
${where}
|
|
897
|
+
ORDER BY e.created_at DESC
|
|
898
|
+
LIMIT ?
|
|
899
|
+
`).all(...params, limit);
|
|
900
|
+
}
|
|
901
|
+
const results = rows.map(r => {
|
|
902
|
+
const entry = this.rowToEntry(r);
|
|
903
|
+
if (opts.l1_only) {
|
|
904
|
+
return { ...entry, content: '' };
|
|
905
|
+
}
|
|
906
|
+
return entry;
|
|
907
|
+
});
|
|
908
|
+
if (results.length > 0) {
|
|
909
|
+
db.prepare(`
|
|
910
|
+
UPDATE entries SET use_count = use_count + 1, last_accessed = ?
|
|
911
|
+
WHERE id IN (${results.map(() => '?').join(',')})
|
|
912
|
+
`).run(new Date().toISOString(), ...results.map(r => r.id));
|
|
913
|
+
}
|
|
914
|
+
return { results, total: results.length, l1_only: opts.l1_only ?? false };
|
|
915
|
+
}
|
|
916
|
+
async context(files) {
|
|
917
|
+
const db = this.getDb();
|
|
918
|
+
const results = [];
|
|
919
|
+
const fileEntries = new Map();
|
|
920
|
+
for (const file of files) {
|
|
921
|
+
const rows = db.prepare(`
|
|
922
|
+
SELECT * FROM entries
|
|
923
|
+
WHERE type = 'context-cache'
|
|
924
|
+
AND superseded_at IS NULL
|
|
925
|
+
AND EXISTS (SELECT 1 FROM json_each(source_files) WHERE value = ?)
|
|
926
|
+
ORDER BY created_at DESC
|
|
927
|
+
LIMIT 1
|
|
928
|
+
`).all(file);
|
|
929
|
+
if (rows.length > 0) {
|
|
930
|
+
fileEntries.set(file, this.rowToEntry(rows[0]));
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
const hashes = await computeFileHashBatch(files);
|
|
934
|
+
for (const file of files) {
|
|
935
|
+
const entry = fileEntries.get(file);
|
|
936
|
+
if (!entry) {
|
|
937
|
+
results.push({ file, status: 'missing' });
|
|
938
|
+
continue;
|
|
939
|
+
}
|
|
940
|
+
if (entry.content_hash === 'invalidated') {
|
|
941
|
+
results.push({ file, status: 'stale', reason: 'invalidated', entry_id: entry.id });
|
|
942
|
+
continue;
|
|
943
|
+
}
|
|
944
|
+
const hashResult = hashes[file];
|
|
945
|
+
if (!hashResult) {
|
|
946
|
+
results.push({ file, status: 'stale', reason: 'file_missing', entry_id: entry.id });
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
if (hashResult.hash === entry.content_hash) {
|
|
950
|
+
results.push({
|
|
951
|
+
file,
|
|
952
|
+
status: 'fresh',
|
|
953
|
+
summary: entry.summary,
|
|
954
|
+
content_hash: entry.content_hash,
|
|
955
|
+
entry_id: entry.id,
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
else {
|
|
959
|
+
results.push({ file, status: 'stale', reason: 'hash_mismatch', entry_id: entry.id });
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
return results;
|
|
963
|
+
}
|
|
964
|
+
async invalidate(files) {
|
|
965
|
+
const db = this.getDb();
|
|
966
|
+
let invalidated = 0;
|
|
967
|
+
for (const file of files) {
|
|
968
|
+
const rows = db.prepare(`
|
|
969
|
+
SELECT id FROM entries
|
|
970
|
+
WHERE type = 'context-cache'
|
|
971
|
+
AND superseded_at IS NULL
|
|
972
|
+
AND EXISTS (
|
|
973
|
+
SELECT 1 FROM json_each(source_files) WHERE value = ?
|
|
974
|
+
)
|
|
975
|
+
`).all(file);
|
|
976
|
+
if (rows.length > 0) {
|
|
977
|
+
const ids = rows.map(r => r.id);
|
|
978
|
+
db.prepare(`
|
|
979
|
+
UPDATE entries
|
|
980
|
+
SET content_hash = 'invalidated', stale = 1
|
|
981
|
+
WHERE id IN (${ids.map(() => '?').join(',')})
|
|
982
|
+
`).run(...ids);
|
|
983
|
+
invalidated += ids.length;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
return { invalidated };
|
|
987
|
+
}
|
|
988
|
+
async getLinked(id) {
|
|
989
|
+
const db = this.getDb();
|
|
990
|
+
const rows = db.prepare(`
|
|
991
|
+
SELECT DISTINCT e.* FROM entries e
|
|
992
|
+
JOIN links l ON (l.from_id = ? AND l.to_id = e.id)
|
|
993
|
+
OR (l.to_id = ? AND l.from_id = e.id)
|
|
994
|
+
WHERE e.superseded_at IS NULL
|
|
995
|
+
`).all(id, id);
|
|
996
|
+
return rows.map(r => this.rowToEntry(r));
|
|
997
|
+
}
|
|
998
|
+
// KB audit 2026-08-11: the first read of the KB's own graph.
|
|
999
|
+
//
|
|
1000
|
+
// The KB writes 554 edges across three live stores and traverses none of them
|
|
1001
|
+
// -- retrieval is pure FTS. This reads the two edge kinds FTS cannot stand in
|
|
1002
|
+
// for. shares_file/shares_symbol (520 of the 554) are topicality, which an FTS
|
|
1003
|
+
// match over the same fields already finds; `refines` and `contradiction_of`
|
|
1004
|
+
// are the KB's JUDGEMENT about its own contents ("there is a newer framing of
|
|
1005
|
+
// this", "something disputes this") and exist nowhere else.
|
|
1006
|
+
//
|
|
1007
|
+
// Both are traversed in BOTH directions on purpose. Given an entry, the useful
|
|
1008
|
+
// question is not "what did this supersede" but "is there anything I should
|
|
1009
|
+
// know about this claim" -- and a challenger captured a day later points AT
|
|
1010
|
+
// the entry a doer is holding, not away from it. This is precisely the warehouse
|
|
1011
|
+
// chain-A shape, where the incorrect entry outranks its two corrections on
|
|
1012
|
+
// confidence tier and the edge is the only thing that says so.
|
|
1013
|
+
//
|
|
1014
|
+
// Superseded rows are excluded (they are already retired) and the input ids are
|
|
1015
|
+
// never echoed back. `limit` caps the total, since this rides into a prompt.
|
|
1016
|
+
async relatedClaims(ids, limit = 5) {
|
|
1017
|
+
if (ids.length === 0)
|
|
1018
|
+
return [];
|
|
1019
|
+
const db = this.getDb();
|
|
1020
|
+
const ph = ids.map(() => '?').join(',');
|
|
1021
|
+
const rows = db.prepare(`
|
|
1022
|
+
SELECT DISTINCT e.* FROM entries e
|
|
1023
|
+
WHERE e.superseded_at IS NULL
|
|
1024
|
+
AND e.id NOT IN (${ph})
|
|
1025
|
+
AND (
|
|
1026
|
+
EXISTS (
|
|
1027
|
+
SELECT 1 FROM links l
|
|
1028
|
+
WHERE l.link_type = 'refines'
|
|
1029
|
+
AND ((l.from_id = e.id AND l.to_id IN (${ph}))
|
|
1030
|
+
OR (l.to_id = e.id AND l.from_id IN (${ph})))
|
|
1031
|
+
)
|
|
1032
|
+
OR e.contradiction_of IN (${ph})
|
|
1033
|
+
OR e.id IN (SELECT contradiction_of FROM entries WHERE id IN (${ph}) AND contradiction_of IS NOT NULL)
|
|
1034
|
+
)
|
|
1035
|
+
LIMIT ?
|
|
1036
|
+
`).all(...ids, ...ids, ...ids, ...ids, ...ids, limit);
|
|
1037
|
+
return rows.map(r => this.rowToEntry(r));
|
|
1038
|
+
}
|
|
1039
|
+
async prime(opts) {
|
|
1040
|
+
this.decayConceptEntries(this.getDb(), opts.decay_after_days ?? 30);
|
|
1041
|
+
const fileResults = opts.session_files?.length
|
|
1042
|
+
? await this.context(opts.session_files)
|
|
1043
|
+
: [];
|
|
1044
|
+
const stale_files = fileResults
|
|
1045
|
+
.filter(r => r.status === 'stale' || r.status === 'missing')
|
|
1046
|
+
.map(r => r.file);
|
|
1047
|
+
const fresh_summaries = fileResults.filter(r => r.status === 'fresh');
|
|
1048
|
+
const session_warm = opts.session_files?.length
|
|
1049
|
+
? stale_files.length === 0
|
|
1050
|
+
: true;
|
|
1051
|
+
const searchTerms = [];
|
|
1052
|
+
if (opts.hint_symbols?.length)
|
|
1053
|
+
searchTerms.push(...opts.hint_symbols);
|
|
1054
|
+
if (opts.hint_modules?.length)
|
|
1055
|
+
searchTerms.push(...opts.hint_modules);
|
|
1056
|
+
let top_entries = [];
|
|
1057
|
+
if (searchTerms.length > 0) {
|
|
1058
|
+
try {
|
|
1059
|
+
// D4 (T2.1): OR-join across hint terms via the shared helper -- each
|
|
1060
|
+
// term is still ftsSafeTerm-quoted (tokens WITHIN one term stay
|
|
1061
|
+
// AND-joined), but terms are OR-joined so an entry matching ANY hint
|
|
1062
|
+
// symbol/module surfaces instead of requiring ALL of them.
|
|
1063
|
+
const l1 = await this.query({
|
|
1064
|
+
fts_terms: searchTerms,
|
|
1065
|
+
l1_only: true,
|
|
1066
|
+
limit: 10,
|
|
1067
|
+
include_stale: false,
|
|
1068
|
+
});
|
|
1069
|
+
top_entries = l1.results
|
|
1070
|
+
.filter(e => e.type !== 'context-cache')
|
|
1071
|
+
.map(e => ({ ...e, content: '' }));
|
|
1072
|
+
}
|
|
1073
|
+
catch {
|
|
1074
|
+
// FTS match may fail on unusual tokens
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
// T2.2 (F3 PART B): bounded, non-fatal freshness check keyed off
|
|
1078
|
+
// source_files -- see checkFreshness. Any error (hash batch throws, DB
|
|
1079
|
+
// error) degrades to leaving top_entries exactly as built above.
|
|
1080
|
+
try {
|
|
1081
|
+
top_entries = await this.checkFreshness(this.getDb(), top_entries);
|
|
1082
|
+
}
|
|
1083
|
+
catch {
|
|
1084
|
+
// graceful degradation: prime() returns today's output on any error
|
|
1085
|
+
}
|
|
1086
|
+
const recommended_code_calls = [];
|
|
1087
|
+
if (opts.hint_symbols?.length) {
|
|
1088
|
+
for (const symbol of opts.hint_symbols) {
|
|
1089
|
+
recommended_code_calls.push({ tool: 'code_context', args: { name: symbol } });
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
if (opts.session_files?.length) {
|
|
1093
|
+
for (const file of opts.session_files) {
|
|
1094
|
+
recommended_code_calls.push({ tool: 'code_impact', args: { target: file, direction: 'upstream' } });
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
let token_estimate = 0;
|
|
1098
|
+
for (const entry of top_entries) {
|
|
1099
|
+
token_estimate += Math.ceil((entry.summary?.length || 0) / 4);
|
|
1100
|
+
}
|
|
1101
|
+
for (const result of fresh_summaries) {
|
|
1102
|
+
token_estimate += Math.ceil((result.summary?.length || 0) / 4);
|
|
1103
|
+
}
|
|
1104
|
+
return {
|
|
1105
|
+
session_warm,
|
|
1106
|
+
stale_files,
|
|
1107
|
+
top_entries,
|
|
1108
|
+
fresh_summaries,
|
|
1109
|
+
recommended_code_calls,
|
|
1110
|
+
token_estimate,
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
// T3.3 (F8a, D8): dedicated read-only listing for kb_list. CHOICE (stated
|
|
1114
|
+
// per PLAN.md): a separate provider method rather than a query() option --
|
|
1115
|
+
// query() bumps use_count/last_accessed unconditionally (its "retrieval
|
|
1116
|
+
// means relevance" telemetry contract, exercised by retrieval paths like
|
|
1117
|
+
// kb_query/prime), and kb_list's purpose is pure audit/inspection ("is the
|
|
1118
|
+
// CONFIRMED set what we think it is") which should not perturb that
|
|
1119
|
+
// telemetry. A dedicated method keeps the two contracts textually distinct
|
|
1120
|
+
// instead of an easy-to-miss opt-out flag threaded through query(). Always
|
|
1121
|
+
// excludes superseded and stale entries (no override -- this is an
|
|
1122
|
+
// audit-the-live-set tool, not a full-history query).
|
|
1123
|
+
async list(opts) {
|
|
1124
|
+
const db = this.getDb();
|
|
1125
|
+
const conditions = ['e.superseded_at IS NULL', 'e.stale = 0'];
|
|
1126
|
+
const params = [];
|
|
1127
|
+
if (opts.confidence) {
|
|
1128
|
+
conditions.push('e.confidence = ?');
|
|
1129
|
+
params.push(opts.confidence);
|
|
1130
|
+
}
|
|
1131
|
+
if (opts.type) {
|
|
1132
|
+
conditions.push('e.type = ?');
|
|
1133
|
+
params.push(opts.type);
|
|
1134
|
+
}
|
|
1135
|
+
if (opts.module) {
|
|
1136
|
+
conditions.push('e.module = ?');
|
|
1137
|
+
params.push(opts.module);
|
|
1138
|
+
}
|
|
1139
|
+
if (opts.symbol) {
|
|
1140
|
+
conditions.push('EXISTS (SELECT 1 FROM json_each(e.symbols) WHERE value = ?)');
|
|
1141
|
+
params.push(opts.symbol);
|
|
1142
|
+
}
|
|
1143
|
+
if (opts.tag) {
|
|
1144
|
+
conditions.push('EXISTS (SELECT 1 FROM json_each(e.tags) WHERE value = ?)');
|
|
1145
|
+
params.push(opts.tag);
|
|
1146
|
+
}
|
|
1147
|
+
const where = 'WHERE ' + conditions.join(' AND ');
|
|
1148
|
+
const limitClause = opts.limit !== undefined ? 'LIMIT ?' : '';
|
|
1149
|
+
if (opts.limit !== undefined)
|
|
1150
|
+
params.push(opts.limit);
|
|
1151
|
+
const rows = db.prepare(`
|
|
1152
|
+
SELECT e.* FROM entries e
|
|
1153
|
+
${where}
|
|
1154
|
+
ORDER BY e.id ASC
|
|
1155
|
+
${limitClause}
|
|
1156
|
+
`).all(...params);
|
|
1157
|
+
return rows.map(r => this.rowToEntry(r));
|
|
1158
|
+
}
|
|
1159
|
+
async promote(id, reason) {
|
|
1160
|
+
const db = this.getDb();
|
|
1161
|
+
const row = db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
|
|
1162
|
+
if (!row)
|
|
1163
|
+
throw new Error(`Entry not found: ${id}`);
|
|
1164
|
+
const entry = this.rowToEntry(row);
|
|
1165
|
+
if (entry.superseded_at)
|
|
1166
|
+
throw new Error(`Cannot promote superseded entry: ${id}`);
|
|
1167
|
+
// H1 (F1, D1, closes yashr-9ha): promote() REFUSES any user-directive entry.
|
|
1168
|
+
// The promote ladder (UNVERIFIED -> INFERRED -> CONFIRMED) would otherwise
|
|
1169
|
+
// let two agent-callable kb_promote calls walk a pending directive proposal
|
|
1170
|
+
// up to type='user-directive' + confidence='CONFIRMED' -- exactly the ACTIVE
|
|
1171
|
+
// predicate -- re-opening the forge-a-directive attack through the side door.
|
|
1172
|
+
// Directive activation is human-terminal ONLY, via the dedicated
|
|
1173
|
+
// approveDirective() method (which does NOT delegate here). Refuse ENTIRELY
|
|
1174
|
+
// so the pending/active state stays binary.
|
|
1175
|
+
if (entry.type === 'user-directive') {
|
|
1176
|
+
throw new Error('Cannot promote a user-directive via kb_promote (F1/D1): directive activation is human-terminal only. Run `apra-fleet kb approve-directive ' + id + '` (or `reject-directive ' + id + '` to discard).');
|
|
1177
|
+
}
|
|
1178
|
+
// KB-TRUST PHASE 1 (decided 2026-08-03): promotion is the ONLY path that
|
|
1179
|
+
// mints CONFIRMED, so it carries two extra gates.
|
|
1180
|
+
//
|
|
1181
|
+
// (1) A promotion without a recorded evidence string is refused. The
|
|
1182
|
+
// promote note is the only durable record of WHY an entry was trusted; a
|
|
1183
|
+
// blank or throwaway reason makes a CONFIRMED entry as unauditable as the
|
|
1184
|
+
// 97-entry bible this work exists to replace.
|
|
1185
|
+
if (!isNonTrivialPromoteReason(reason)) {
|
|
1186
|
+
throw new Error('kb_promote requires a reason recording the evidence for this promotion '
|
|
1187
|
+
+ '(at least ' + MIN_PROMOTE_REASON_LENGTH + ' characters stating what you checked). Entry: ' + id);
|
|
1188
|
+
}
|
|
1189
|
+
// (2) An entry whose basis no longer resolves cannot be verified against
|
|
1190
|
+
// the tree, so it cannot earn CONFIRMED. Zero source_files is included:
|
|
1191
|
+
// capture now refuses those, but rows predating this rule still exist and
|
|
1192
|
+
// are exactly the structurally unfalsifiable entries.
|
|
1193
|
+
const unresolved = this.unresolvableBasisFiles(entry.source_files);
|
|
1194
|
+
if (entry.source_files.length === 0 || unresolved.length > 0) {
|
|
1195
|
+
throw new Error('Cannot promote an entry whose basis does not resolve: '
|
|
1196
|
+
+ (entry.source_files.length === 0
|
|
1197
|
+
? 'it cites no source files'
|
|
1198
|
+
: 'missing ' + unresolved.join(', '))
|
|
1199
|
+
+ '. Entry: ' + id);
|
|
1200
|
+
}
|
|
1201
|
+
const confidence_before = entry.confidence;
|
|
1202
|
+
let confidence_after;
|
|
1203
|
+
if (confidence_before === 'UNVERIFIED') {
|
|
1204
|
+
confidence_after = 'INFERRED';
|
|
1205
|
+
}
|
|
1206
|
+
else if (confidence_before === 'INFERRED') {
|
|
1207
|
+
confidence_after = 'CONFIRMED';
|
|
1208
|
+
}
|
|
1209
|
+
else {
|
|
1210
|
+
return { id, confidence_before, confidence_after: confidence_before };
|
|
1211
|
+
}
|
|
1212
|
+
const now = new Date().toISOString();
|
|
1213
|
+
// String concatenation (not a template literal) per the ASCII pre-commit
|
|
1214
|
+
// hook gotcha: backtick-n escapes inside JS template literals false-
|
|
1215
|
+
// positive on the hook's non-ASCII scan.
|
|
1216
|
+
const promotionNote = reason
|
|
1217
|
+
? '\n[Promoted: ' + reason + ' -- ' + (entry.author || 'unknown') + ']'
|
|
1218
|
+
: '\n[Promoted -- ' + (entry.author || 'unknown') + ']';
|
|
1219
|
+
const newContent = entry.content + promotionNote;
|
|
1220
|
+
// D5 (T2.3): kb_promote is a tool-layer provenance event -- stamp
|
|
1221
|
+
// source='promotion' on the promoted row. This is a deliberate D5
|
|
1222
|
+
// choice: the row's provenance reflects the promotion mechanism rather
|
|
1223
|
+
// than preserving the original capture source.
|
|
1224
|
+
db.prepare('UPDATE entries SET confidence = ?, promoted_at = ?, content = ?, source = ? WHERE id = ?')
|
|
1225
|
+
.run(confidence_after, now, newContent, 'promotion', id);
|
|
1226
|
+
return { id, confidence_before, confidence_after };
|
|
1227
|
+
}
|
|
1228
|
+
// T3.1 (F8, D7): kb_feedback downvote path -- marks an entry stale=1 +
|
|
1229
|
+
// flagged_for_review=1 and appends an ASCII feedback note. NEVER deletes,
|
|
1230
|
+
// NEVER touches confidence: a downvoted CONFIRMED entry stays
|
|
1231
|
+
// CONFIRMED-but-stale-flagged; the human resolves it in kb-review.
|
|
1232
|
+
// EXCEPTION (D7, verbatim): an ACTIVE user-directive (type='user-directive'
|
|
1233
|
+
// AND confidence='CONFIRMED') outranks agent experience -- feedback flags it
|
|
1234
|
+
// for review but must NOT stale it (the human decides in kb-review). This is
|
|
1235
|
+
// keyed off ACTIVE directives only (type + CONFIRMED, same rekey as the T1.1
|
|
1236
|
+
// supersede/decay guards) -- a pending directive proposal (confidence !=
|
|
1237
|
+
// 'CONFIRMED') is not yet "active" and stales normally like any other entry.
|
|
1238
|
+
async feedback(id, reason, author) {
|
|
1239
|
+
const db = this.getDb();
|
|
1240
|
+
const row = db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
|
|
1241
|
+
if (!row)
|
|
1242
|
+
throw new Error('Entry not found: ' + id);
|
|
1243
|
+
const entry = this.rowToEntry(row);
|
|
1244
|
+
const now = new Date().toISOString();
|
|
1245
|
+
// String concatenation (not a template literal) per the ASCII pre-commit
|
|
1246
|
+
// hook gotcha: backtick-n/t/r escapes inside template literals
|
|
1247
|
+
// false-positive on the hook's non-ASCII scan (same convention as
|
|
1248
|
+
// promote()'s promotionNote above and kb-export.ts).
|
|
1249
|
+
const note = '\n\n[feedback ' + now + '] ' + author + ': ' + reason;
|
|
1250
|
+
const newContent = truncateContent(entry.content + note);
|
|
1251
|
+
const isActiveDirective = entry.type === 'user-directive' && entry.confidence === 'CONFIRMED';
|
|
1252
|
+
if (isActiveDirective) {
|
|
1253
|
+
db.prepare('UPDATE entries SET flagged_for_review = 1, content = ? WHERE id = ?')
|
|
1254
|
+
.run(newContent, id);
|
|
1255
|
+
}
|
|
1256
|
+
else {
|
|
1257
|
+
db.prepare('UPDATE entries SET stale = 1, flagged_for_review = 1, content = ? WHERE id = ?')
|
|
1258
|
+
.run(newContent, id);
|
|
1259
|
+
}
|
|
1260
|
+
const updated = db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
|
|
1261
|
+
return this.rowToEntry(updated);
|
|
1262
|
+
}
|
|
1263
|
+
// T3.1 (F5 step 3, D4 HARDENED): flaggedPairs() -- flagged entries joined to
|
|
1264
|
+
// their contradiction_of counterpart. LIVENESS CONTRACT (binding, MEDIUM-3):
|
|
1265
|
+
// pair membership requires ONLY superseded_at IS NULL on BOTH sides -- STALE
|
|
1266
|
+
// MEMBERS MUST BE INCLUDED. Do NOT reuse the codebase's default "live"
|
|
1267
|
+
// filter (superseded_at IS NULL AND stale = 0, as in list()/stats()/
|
|
1268
|
+
// query()): the imported side of a pair is TYPICALLY stale after the
|
|
1269
|
+
// post-import freshnessSweep, and the default filter would make this method
|
|
1270
|
+
// return nothing and the prefilter silently no-op.
|
|
1271
|
+
//
|
|
1272
|
+
// PAIR ASYMMETRY (verified, KB a2781b82 + feedback.md): AUDN's contradiction
|
|
1273
|
+
// branch inserts the NEW entry (the "challenger") with contradiction_of
|
|
1274
|
+
// pointing at the OLD entry (the "original") and flagged_for_review lands on
|
|
1275
|
+
// the OLD side ONLY (the new entry's flagged_for_review is explicitly false
|
|
1276
|
+
// in newEntryOverrides). A genuine pair is therefore identified by
|
|
1277
|
+
// challenger.contradiction_of = original.id -- NOT by flagged_for_review
|
|
1278
|
+
// alone: a lone entry downvoted via feedback() also carries
|
|
1279
|
+
// flagged_for_review = 1 but has no contradiction_of counterpart and must
|
|
1280
|
+
// NEVER be returned here.
|
|
1281
|
+
//
|
|
1282
|
+
// Pairs involving an ACTIVE user-directive (type = 'user-directive' AND
|
|
1283
|
+
// confidence = 'CONFIRMED') on EITHER side are excluded entirely -- an
|
|
1284
|
+
// active directive can be the target of AUDN's contradiction path (the
|
|
1285
|
+
// contradiction check runs before the AUDN active-directive supersede guard,
|
|
1286
|
+
// see audn.ts), but directives outrank mechanics: the flag stays for a human
|
|
1287
|
+
// via /pm kb-review, never the mechanical prefilter or the reconciler agent.
|
|
1288
|
+
async flaggedPairs() {
|
|
1289
|
+
const db = this.getDb();
|
|
1290
|
+
const idRows = db.prepare(`
|
|
1291
|
+
SELECT o.id as original_id, c.id as challenger_id
|
|
1292
|
+
FROM entries c
|
|
1293
|
+
JOIN entries o ON o.id = c.contradiction_of
|
|
1294
|
+
WHERE c.contradiction_of IS NOT NULL
|
|
1295
|
+
AND o.superseded_at IS NULL
|
|
1296
|
+
AND c.superseded_at IS NULL
|
|
1297
|
+
AND NOT (o.type = 'user-directive' AND o.confidence = 'CONFIRMED')
|
|
1298
|
+
AND NOT (c.type = 'user-directive' AND c.confidence = 'CONFIRMED')
|
|
1299
|
+
`).all();
|
|
1300
|
+
const pairs = [];
|
|
1301
|
+
for (const row of idRows) {
|
|
1302
|
+
const originalRow = db.prepare('SELECT * FROM entries WHERE id = ?').get(row.original_id);
|
|
1303
|
+
const challengerRow = db.prepare('SELECT * FROM entries WHERE id = ?').get(row.challenger_id);
|
|
1304
|
+
if (!originalRow || !challengerRow)
|
|
1305
|
+
continue; // defensive; join guarantees both exist
|
|
1306
|
+
pairs.push({ original: this.rowToEntry(originalRow), challenger: this.rowToEntry(challengerRow) });
|
|
1307
|
+
}
|
|
1308
|
+
return pairs;
|
|
1309
|
+
}
|
|
1310
|
+
// T3.1 (F5 step 3, D4 HARDENED HIGH-1/R7): the SINGLE write path for ALL
|
|
1311
|
+
// reconcile resolutions -- both kb_reconcile_prefilter's mechanical wins and
|
|
1312
|
+
// the T3.2 reconciler agent's code-decided wins. Deliberately NOT composed
|
|
1313
|
+
// from promote() + feedback(): promote()'s one-step ladder cannot lift
|
|
1314
|
+
// AUDN's UNVERIFIED contradiction-born entries directly to CONFIRMED, and
|
|
1315
|
+
// neither promote() nor feedback() clears flagged_for_review or
|
|
1316
|
+
// contradiction_of (KB a2781b82) -- this method is the only place both
|
|
1317
|
+
// outcomes are produced together, atomically, for a pair.
|
|
1318
|
+
//
|
|
1319
|
+
// LINKAGE REFUSAL (re-review MEDIUM-1, binding): before writing ANYTHING,
|
|
1320
|
+
// verify the two ids form a GENUINE contradiction pair --
|
|
1321
|
+
// loser.contradiction_of === winner.id OR winner.contradiction_of ===
|
|
1322
|
+
// loser.id (the AUDN pair asymmetry means the pointer sits on either side
|
|
1323
|
+
// depending on which side happens to win) -- AND both rows exist AND
|
|
1324
|
+
// neither is already superseded AND neither side is an ACTIVE
|
|
1325
|
+
// user-directive. Refuse (throw) otherwise: NOTHING is written. Without this
|
|
1326
|
+
// check any caller could mint CONFIRMED from any tier in ONE call and
|
|
1327
|
+
// permanently retire an arbitrary unrelated entry.
|
|
1328
|
+
//
|
|
1329
|
+
// WINNER path -- explicit order (re-review MEDIUM-2, THE ORDER MATTERS):
|
|
1330
|
+
// (1) confidence = 'CONFIRMED' regardless of starting tier (the merged
|
|
1331
|
+
// code IS the verdict; reconcile is verdict-equivalent), with the
|
|
1332
|
+
// evidence note appended to content.
|
|
1333
|
+
// (2) clear the winner's flag fields FIRST: flagged_for_review = 0 AND
|
|
1334
|
+
// contradiction_of = NULL, unconditionally on the winner row -- the
|
|
1335
|
+
// pair asymmetry means exactly one of the two was actually set, so
|
|
1336
|
+
// clearing both is harmless on whichever side the winner is.
|
|
1337
|
+
// (3) THEN, and only then, evaluate the shared D2 freshnessRevivable
|
|
1338
|
+
// predicate (+ the full-basis re-hash conjunct) against the
|
|
1339
|
+
// POST-flag-clear row, and clear stale ONLY if it holds. Evaluating
|
|
1340
|
+
// the predicate BEFORE step (2) would self-defeat for a flagged
|
|
1341
|
+
// OLD-side winner (the predicate requires flagged_for_review = 0) --
|
|
1342
|
+
// it would end CONFIRMED but stale = 1 and silently vanish from the
|
|
1343
|
+
// kb_export bible. The durable exclusions (the anchored "[feedback "
|
|
1344
|
+
// marker, content_hash = 'invalidated') are UNAFFECTED by the
|
|
1345
|
+
// flag-clear, so a downvoted or invalidated winner still stays
|
|
1346
|
+
// retired: it wins the CONTRADICTION, not its reputation.
|
|
1347
|
+
//
|
|
1348
|
+
// LOSER: superseded_at = now + stale = 1 + flagged_for_review cleared
|
|
1349
|
+
// (retired with an audit trail -- the existing loser invariant). NEVER
|
|
1350
|
+
// deletes anything, on either side.
|
|
1351
|
+
async resolveContradiction(winnerId, loserId, evidence) {
|
|
1352
|
+
const db = this.getDb();
|
|
1353
|
+
const winnerRow = db.prepare('SELECT * FROM entries WHERE id = ?').get(winnerId);
|
|
1354
|
+
const loserRow = db.prepare('SELECT * FROM entries WHERE id = ?').get(loserId);
|
|
1355
|
+
if (!winnerRow || !loserRow) {
|
|
1356
|
+
throw new Error('resolveContradiction: refused -- one or both entries do not exist (winner=' + winnerId + ', loser=' + loserId + ')');
|
|
1357
|
+
}
|
|
1358
|
+
const winner = this.rowToEntry(winnerRow);
|
|
1359
|
+
const loser = this.rowToEntry(loserRow);
|
|
1360
|
+
if (winner.superseded_at || loser.superseded_at) {
|
|
1361
|
+
throw new Error('resolveContradiction: refused -- one or both entries are already superseded (winner=' + winnerId + ', loser=' + loserId + ')');
|
|
1362
|
+
}
|
|
1363
|
+
const linked = loser.contradiction_of === winner.id || winner.contradiction_of === loser.id;
|
|
1364
|
+
if (!linked) {
|
|
1365
|
+
throw new Error('resolveContradiction: refused -- ids do not form a genuine contradiction pair (winner=' + winnerId + ', loser=' + loserId + ')');
|
|
1366
|
+
}
|
|
1367
|
+
const isActiveDirective = (e) => e.type === 'user-directive' && e.confidence === 'CONFIRMED';
|
|
1368
|
+
if (isActiveDirective(winner) || isActiveDirective(loser)) {
|
|
1369
|
+
throw new Error('resolveContradiction: refused -- pair involves an active user-directive; directives are never auto-resolved (winner=' + winnerId + ', loser=' + loserId + ')');
|
|
1370
|
+
}
|
|
1371
|
+
const now = new Date().toISOString();
|
|
1372
|
+
// String concatenation (not a template literal) per the ASCII pre-commit
|
|
1373
|
+
// hook gotcha: backtick-n/t/r escapes inside template literals
|
|
1374
|
+
// false-positive on the hook's non-ASCII scan.
|
|
1375
|
+
const evidenceNote = '\n\n[reconciled ' + now + '] winner over ' + loserId + ': ' + evidence;
|
|
1376
|
+
const newContent = truncateContent(winner.content + evidenceNote);
|
|
1377
|
+
// (1) confidence + evidence note, (2) flag-clear FIRST (both fields,
|
|
1378
|
+
// unconditionally -- harmless on whichever side actually held a value).
|
|
1379
|
+
db.prepare("UPDATE entries SET confidence = 'CONFIRMED', content = ?, flagged_for_review = 0, contradiction_of = NULL WHERE id = ?").run(newContent, winnerId);
|
|
1380
|
+
// (3) THEN evaluate the shared D2 predicate on the POST-flag-clear row.
|
|
1381
|
+
const refreshedRow = db.prepare('SELECT * FROM entries WHERE id = ?').get(winnerId);
|
|
1382
|
+
const refreshedWinner = this.rowToEntry(refreshedRow);
|
|
1383
|
+
if (refreshedWinner.stale) {
|
|
1384
|
+
const revivable = this.freshnessRevivable({
|
|
1385
|
+
superseded_at: refreshedWinner.superseded_at ?? null,
|
|
1386
|
+
flagged_for_review: refreshedWinner.flagged_for_review,
|
|
1387
|
+
content_hash: refreshedWinner.content_hash,
|
|
1388
|
+
content: refreshedWinner.content,
|
|
1389
|
+
});
|
|
1390
|
+
if (revivable) {
|
|
1391
|
+
const basis = this.parseBasis(refreshedRow.source_file_hashes ?? null);
|
|
1392
|
+
if (basis) {
|
|
1393
|
+
const currentHashes = await computeFileHashBatch(Object.keys(basis));
|
|
1394
|
+
if (this.basisFullyMatches(basis, currentHashes)) {
|
|
1395
|
+
db.prepare('UPDATE entries SET stale = 0 WHERE id = ?').run(winnerId);
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
// LOSER: audit trail, never deletes. contradiction_of is intentionally
|
|
1401
|
+
// left as-is on the loser (harmless, and preserves which pair this row
|
|
1402
|
+
// was once part of for later inspection); only flagged_for_review is
|
|
1403
|
+
// cleared per the stated invariant.
|
|
1404
|
+
db.prepare('UPDATE entries SET superseded_at = ?, stale = 1, flagged_for_review = 0 WHERE id = ?').run(now, loserId);
|
|
1405
|
+
return { winnerId, loserId };
|
|
1406
|
+
}
|
|
1407
|
+
// T3.1 (F5 step 3, D4 HARDENED, resolution R1): kb_reconcile_prefilter's
|
|
1408
|
+
// provider backing. For each pair from flaggedPairs(), re-hash BOTH sides'
|
|
1409
|
+
// FULL bases against the CURRENT worktree (one computeFileHashBatch over the
|
|
1410
|
+
// union of every basis file across every pair -- same batching discipline as
|
|
1411
|
+
// freshnessSweep): exactly one side fully matches -> that side WINS
|
|
1412
|
+
// mechanically via resolveContradiction with the verbatim evidence string
|
|
1413
|
+
// "hash-basis match on merged worktree". Both match, both mismatch, or
|
|
1414
|
+
// EITHER side has an empty/missing basis -> left untouched for the T3.2
|
|
1415
|
+
// reconciler agent. Directive pairs are already excluded by flaggedPairs()
|
|
1416
|
+
// itself (MEDIUM-3 liveness contract); the explicit re-check here is
|
|
1417
|
+
// belt-and-suspenders defense in depth and feeds the skipped_directive
|
|
1418
|
+
// count honestly rather than assuming the upstream filter can never regress.
|
|
1419
|
+
async reconcilePrefilter() {
|
|
1420
|
+
const pairs = await this.flaggedPairs();
|
|
1421
|
+
const resolved = [];
|
|
1422
|
+
const left_for_agent = [];
|
|
1423
|
+
let skipped_directive = 0;
|
|
1424
|
+
if (pairs.length === 0) {
|
|
1425
|
+
return { pairs: 0, resolved, left_for_agent, skipped_directive };
|
|
1426
|
+
}
|
|
1427
|
+
const isActiveDirective = (e) => e.type === 'user-directive' && e.confidence === 'CONFIRMED';
|
|
1428
|
+
const liveTouchable = pairs.filter(pair => {
|
|
1429
|
+
if (isActiveDirective(pair.original) || isActiveDirective(pair.challenger)) {
|
|
1430
|
+
skipped_directive++;
|
|
1431
|
+
return false;
|
|
1432
|
+
}
|
|
1433
|
+
return true;
|
|
1434
|
+
});
|
|
1435
|
+
const db = this.getDb();
|
|
1436
|
+
const allIds = liveTouchable.flatMap(p => [p.original.id, p.challenger.id]);
|
|
1437
|
+
const basisById = new Map();
|
|
1438
|
+
if (allIds.length > 0) {
|
|
1439
|
+
const basisRows = db.prepare(`SELECT id, source_file_hashes FROM entries WHERE id IN (${allIds.map(() => '?').join(',')})`).all(...allIds);
|
|
1440
|
+
for (const row of basisRows)
|
|
1441
|
+
basisById.set(row.id, this.parseBasis(row.source_file_hashes));
|
|
1442
|
+
}
|
|
1443
|
+
const fileSet = new Set();
|
|
1444
|
+
for (const basis of basisById.values()) {
|
|
1445
|
+
if (basis)
|
|
1446
|
+
for (const file of Object.keys(basis))
|
|
1447
|
+
fileSet.add(file);
|
|
1448
|
+
}
|
|
1449
|
+
const currentHashes = await computeFileHashBatch([...fileSet]);
|
|
1450
|
+
for (const pair of liveTouchable) {
|
|
1451
|
+
const originalBasis = basisById.get(pair.original.id) ?? null;
|
|
1452
|
+
const challengerBasis = basisById.get(pair.challenger.id) ?? null;
|
|
1453
|
+
const originalMatches = originalBasis ? this.basisFullyMatches(originalBasis, currentHashes) : false;
|
|
1454
|
+
const challengerMatches = challengerBasis ? this.basisFullyMatches(challengerBasis, currentHashes) : false;
|
|
1455
|
+
if (originalMatches && !challengerMatches) {
|
|
1456
|
+
await this.resolveContradiction(pair.original.id, pair.challenger.id, 'hash-basis match on merged worktree');
|
|
1457
|
+
resolved.push({ winnerId: pair.original.id, loserId: pair.challenger.id });
|
|
1458
|
+
}
|
|
1459
|
+
else if (challengerMatches && !originalMatches) {
|
|
1460
|
+
await this.resolveContradiction(pair.challenger.id, pair.original.id, 'hash-basis match on merged worktree');
|
|
1461
|
+
resolved.push({ winnerId: pair.challenger.id, loserId: pair.original.id });
|
|
1462
|
+
}
|
|
1463
|
+
else {
|
|
1464
|
+
left_for_agent.push({ originalId: pair.original.id, challengerId: pair.challenger.id });
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
return { pairs: pairs.length, resolved, left_for_agent, skipped_directive };
|
|
1468
|
+
}
|
|
1469
|
+
// --- F1 (D1) directive activation primitives ---
|
|
1470
|
+
// These are the human-terminal trust surface for user-directives. They are
|
|
1471
|
+
// called ONLY by the `apra-fleet kb ...` CLI commands (src/cli/kb-directives.ts)
|
|
1472
|
+
// and are NEVER exposed over MCP: MCP has no user-vs-agent identity, so the
|
|
1473
|
+
// only unforgeable channel is a command the human runs in their own terminal.
|
|
1474
|
+
// approveDirective is DEDICATED (it does NOT delegate to promote(), which
|
|
1475
|
+
// refuses user-directive entries outright per H1).
|
|
1476
|
+
// Audit read (no use_count bump): all non-rejected directives -- pending
|
|
1477
|
+
// proposals (UNVERIFIED + 'directive:pending') and active directives
|
|
1478
|
+
// (CONFIRMED). Rejected directives are superseded and excluded.
|
|
1479
|
+
async listDirectives() {
|
|
1480
|
+
const db = this.getDb();
|
|
1481
|
+
const rows = db.prepare(`
|
|
1482
|
+
SELECT * FROM entries
|
|
1483
|
+
WHERE type = 'user-directive' AND superseded_at IS NULL
|
|
1484
|
+
ORDER BY created_at DESC
|
|
1485
|
+
`).all();
|
|
1486
|
+
return rows.map(r => this.rowToEntry(r));
|
|
1487
|
+
}
|
|
1488
|
+
// Human approval: a pending proposal becomes an ACTIVE directive. Sets
|
|
1489
|
+
// confidence='CONFIRMED', author='user' (the human at the terminal is the
|
|
1490
|
+
// authority), clears flagged_for_review, drops the 'directive:pending' tag,
|
|
1491
|
+
// and stamps promoted_at=now (activation is the promotion-equivalent event,
|
|
1492
|
+
// keeping kb_export's updated_at and F5's promote_ratio coherent). From here
|
|
1493
|
+
// all directive semantics apply (never decayed, top-tier retrieval, only a
|
|
1494
|
+
// human supersede via reject).
|
|
1495
|
+
async approveDirective(id) {
|
|
1496
|
+
const db = this.getDb();
|
|
1497
|
+
const row = db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
|
|
1498
|
+
if (!row)
|
|
1499
|
+
throw new Error('Directive not found: ' + id);
|
|
1500
|
+
const entry = this.rowToEntry(row);
|
|
1501
|
+
if (entry.type !== 'user-directive')
|
|
1502
|
+
throw new Error('Not a user-directive: ' + id);
|
|
1503
|
+
if (entry.superseded_at)
|
|
1504
|
+
throw new Error('Cannot approve a rejected directive: ' + id);
|
|
1505
|
+
if (entry.confidence === 'CONFIRMED')
|
|
1506
|
+
throw new Error('Directive already active: ' + id);
|
|
1507
|
+
const now = new Date().toISOString();
|
|
1508
|
+
const tags = entry.tags.filter(t => t !== 'directive:pending');
|
|
1509
|
+
db.prepare("UPDATE entries SET confidence = 'CONFIRMED', author = 'user', flagged_for_review = 0, tags = ?, promoted_at = ? WHERE id = ?").run(JSON.stringify(tags), now, id);
|
|
1510
|
+
const updated = db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
|
|
1511
|
+
return this.rowToEntry(updated);
|
|
1512
|
+
}
|
|
1513
|
+
// Human rejection: works on a pending proposal OR an active directive (the
|
|
1514
|
+
// approve-new + reject-old supersede flow, resolution 2). Marks superseded_at
|
|
1515
|
+
// and stale so it drops from retrieval, but NEVER deletes and KEEPS the
|
|
1516
|
+
// 'directive:pending' tag as an audit trail.
|
|
1517
|
+
async rejectDirective(id) {
|
|
1518
|
+
const db = this.getDb();
|
|
1519
|
+
const row = db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
|
|
1520
|
+
if (!row)
|
|
1521
|
+
throw new Error('Directive not found: ' + id);
|
|
1522
|
+
const entry = this.rowToEntry(row);
|
|
1523
|
+
if (entry.type !== 'user-directive')
|
|
1524
|
+
throw new Error('Not a user-directive: ' + id);
|
|
1525
|
+
if (entry.superseded_at)
|
|
1526
|
+
throw new Error('Directive already rejected: ' + id);
|
|
1527
|
+
const now = new Date().toISOString();
|
|
1528
|
+
db.prepare('UPDATE entries SET superseded_at = ?, stale = 1 WHERE id = ?').run(now, id);
|
|
1529
|
+
const updated = db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
|
|
1530
|
+
return this.rowToEntry(updated);
|
|
1531
|
+
}
|
|
1532
|
+
// Direct human add: creates an ALREADY-ACTIVE directive (the human terminal is
|
|
1533
|
+
// the trust root, D1). Bypasses capture() -- which would force the proposal
|
|
1534
|
+
// representation -- and inserts directly at confidence='CONFIRMED',
|
|
1535
|
+
// author='user', source='user-directive', promoted_at=now.
|
|
1536
|
+
async addDirective(text, symbols) {
|
|
1537
|
+
const db = this.getDb();
|
|
1538
|
+
const now = new Date().toISOString();
|
|
1539
|
+
const id = randomUUID();
|
|
1540
|
+
const title = text.length > 80 ? text.slice(0, 77) + '...' : text;
|
|
1541
|
+
const summary = text.length > 200 ? text.slice(0, 197) + '...' : text;
|
|
1542
|
+
const input = {
|
|
1543
|
+
type: 'user-directive',
|
|
1544
|
+
title,
|
|
1545
|
+
summary,
|
|
1546
|
+
content: text,
|
|
1547
|
+
source_files: [],
|
|
1548
|
+
symbols: symbols ?? [],
|
|
1549
|
+
module: undefined,
|
|
1550
|
+
tags: [],
|
|
1551
|
+
content_hash: '',
|
|
1552
|
+
content_hash_type: 'sha256',
|
|
1553
|
+
flagged_for_review: false,
|
|
1554
|
+
contradiction_of: undefined,
|
|
1555
|
+
author: 'user',
|
|
1556
|
+
source: 'user-directive',
|
|
1557
|
+
confidence: 'CONFIRMED',
|
|
1558
|
+
scope: 'project',
|
|
1559
|
+
};
|
|
1560
|
+
this.insertEntry(db, id, input, truncateContent(text), now);
|
|
1561
|
+
db.prepare('UPDATE entries SET promoted_at = ? WHERE id = ?').run(now, id);
|
|
1562
|
+
this.wireLinks(db, id, input);
|
|
1563
|
+
const row = db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
|
|
1564
|
+
return this.rowToEntry(row);
|
|
1565
|
+
}
|
|
1566
|
+
async sync(opts) {
|
|
1567
|
+
return { synced: false, reason: 'local-only provider' };
|
|
1568
|
+
}
|
|
1569
|
+
// T2.1 (F5, D4): dedicated no-bump aggregation read, following the kb_list
|
|
1570
|
+
// pattern -- every query below is a plain SELECT/COUNT/GROUP BY, never an
|
|
1571
|
+
// UPDATE, so use_count/last_accessed telemetry is untouched (inspecting the
|
|
1572
|
+
// KB's health is not "retrieval" for that purpose, same rationale as list()).
|
|
1573
|
+
//
|
|
1574
|
+
// "Live" (used for retrieval.hit_rate's denominator and coverage, per
|
|
1575
|
+
// resolution 6 and D4) means superseded_at IS NULL AND stale = 0 --
|
|
1576
|
+
// identical to list()'s and query()'s default filter. totals/stale/
|
|
1577
|
+
// flagged/superseded below are deliberately UNFILTERED (whole-table counts)
|
|
1578
|
+
// so they show full volume; only retrieval.hit_rate and coverage are
|
|
1579
|
+
// liveness-scoped.
|
|
1580
|
+
async stats(opts) {
|
|
1581
|
+
const db = this.getDb();
|
|
1582
|
+
const byConfidenceRows = db.prepare('SELECT confidence, COUNT(*) as c FROM entries GROUP BY confidence').all();
|
|
1583
|
+
const by_confidence = { CONFIRMED: 0, INFERRED: 0, UNVERIFIED: 0 };
|
|
1584
|
+
let total = 0;
|
|
1585
|
+
for (const row of byConfidenceRows) {
|
|
1586
|
+
by_confidence[row.confidence] = row.c;
|
|
1587
|
+
total += row.c;
|
|
1588
|
+
}
|
|
1589
|
+
const byTypeRows = db.prepare('SELECT type, COUNT(*) as c FROM entries GROUP BY type').all();
|
|
1590
|
+
const by_type = {
|
|
1591
|
+
'context-cache': 0,
|
|
1592
|
+
'learning': 0,
|
|
1593
|
+
'knowledge': 0,
|
|
1594
|
+
'runbook': 0,
|
|
1595
|
+
'user-directive': 0,
|
|
1596
|
+
};
|
|
1597
|
+
for (const row of byTypeRows) {
|
|
1598
|
+
by_type[row.type] = row.c;
|
|
1599
|
+
}
|
|
1600
|
+
const staleRow = db.prepare('SELECT COUNT(*) as c FROM entries WHERE stale = 1').get();
|
|
1601
|
+
const flaggedRow = db.prepare('SELECT COUNT(*) as c FROM entries WHERE flagged_for_review = 1').get();
|
|
1602
|
+
const supersededRow = db.prepare('SELECT COUNT(*) as c FROM entries WHERE superseded_at IS NOT NULL').get();
|
|
1603
|
+
const liveRow = db.prepare('SELECT COUNT(*) as c FROM entries WHERE superseded_at IS NULL AND stale = 0').get();
|
|
1604
|
+
const totalLive = liveRow.c;
|
|
1605
|
+
const retrievedRow = db.prepare('SELECT COUNT(*) as c FROM entries WHERE use_count > 0 AND superseded_at IS NULL AND stale = 0').get();
|
|
1606
|
+
const totalUsesRow = db.prepare('SELECT COALESCE(SUM(use_count), 0) as s FROM entries').get();
|
|
1607
|
+
const hit_rate = totalLive > 0 ? retrievedRow.c / totalLive : null;
|
|
1608
|
+
const confirmedRow = db.prepare("SELECT COUNT(*) as c FROM entries WHERE confidence = 'CONFIRMED'").get();
|
|
1609
|
+
const promotedRow = db.prepare('SELECT COUNT(*) as c FROM entries WHERE promoted_at IS NOT NULL').get();
|
|
1610
|
+
const promote_ratio = confirmedRow.c > 0 ? promotedRow.c / confirmedRow.c : null;
|
|
1611
|
+
const result = {
|
|
1612
|
+
totals: { by_confidence, by_type, total },
|
|
1613
|
+
stale: staleRow.c,
|
|
1614
|
+
flagged: flaggedRow.c,
|
|
1615
|
+
superseded: supersededRow.c,
|
|
1616
|
+
retrieval: { entries_retrieved: retrievedRow.c, total_uses: totalUsesRow.s, hit_rate },
|
|
1617
|
+
promote_ratio,
|
|
1618
|
+
};
|
|
1619
|
+
if (opts?.symbols?.length) {
|
|
1620
|
+
const symbolStmt = db.prepare(`
|
|
1621
|
+
SELECT COUNT(*) as c FROM entries
|
|
1622
|
+
WHERE confidence = 'CONFIRMED' AND superseded_at IS NULL AND stale = 0
|
|
1623
|
+
AND EXISTS (SELECT 1 FROM json_each(symbols) WHERE value = ?)
|
|
1624
|
+
`);
|
|
1625
|
+
const symbols = {};
|
|
1626
|
+
let trueCount = 0;
|
|
1627
|
+
for (const symbol of opts.symbols) {
|
|
1628
|
+
const row = symbolStmt.get(symbol);
|
|
1629
|
+
const covered = row.c > 0;
|
|
1630
|
+
symbols[symbol] = covered;
|
|
1631
|
+
if (covered)
|
|
1632
|
+
trueCount++;
|
|
1633
|
+
}
|
|
1634
|
+
result.coverage = {
|
|
1635
|
+
fraction: opts.symbols.length > 0 ? trueCount / opts.symbols.length : 0,
|
|
1636
|
+
symbols,
|
|
1637
|
+
};
|
|
1638
|
+
}
|
|
1639
|
+
return result;
|
|
1640
|
+
}
|
|
1641
|
+
close() {
|
|
1642
|
+
this.db?.close();
|
|
1643
|
+
this.db = null;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
//# sourceMappingURL=sqlite-provider.js.map
|