From 28a64750ba6cd65624c0485fb6091a0b8be566b9 Mon Sep 17 00:00:00 2001 From: selftune-bot Date: Wed, 21 Oct 2026 09:58:07 +0300 Subject: [PATCH 1/2] chore: export from selftune-cloud-app Verified canonical optimization candidate, generated journal parity repair, and rendered backup privacy coverage. --- .changeset/local-skill-revision-history.md | 5 + .changeset/responsive-local-library.md | 5 + .changeset/skill-package-inspection.md | 5 + .github/release-notes.json | 253 + ARCHITECTURE.md | 16 + README.md | 5 + apps/cli/package.json | 6 +- apps/cli/src/commands/uninstall/errors.ts | 2 +- .../src/effect-cli/argument-compatibility.ts | 22 + apps/cli/src/effect-cli/commands/badge.ts | 10 +- .../cli/src/effect-cli/commands/contribute.ts | 18 +- .../src/effect-cli/commands/contributions.ts | 28 +- apps/cli/src/effect-cli/commands/create.ts | 6 +- .../effect-cli/commands/create/evaluation.ts | 16 +- .../src/effect-cli/commands/create/publish.ts | 20 +- .../effect-cli/commands/create/scaffolding.ts | 44 +- .../commands/creator-contributions.ts | 44 +- apps/cli/src/effect-cli/commands/daemon.ts | 38 +- apps/cli/src/effect-cli/commands/dashboard.ts | 20 +- apps/cli/src/effect-cli/commands/eval.ts | 97 +- apps/cli/src/effect-cli/commands/export.ts | 8 +- apps/cli/src/effect-cli/commands/library.ts | 4 +- .../src/effect-cli/commands/plugin-eval.ts | 50 + apps/cli/src/effect-cli/commands/project.ts | 34 +- apps/cli/src/effect-cli/commands/publish.ts | 10 +- apps/cli/src/effect-cli/commands/recover.ts | 28 +- apps/cli/src/effect-cli/commands/registry.ts | 17 +- apps/cli/src/effect-cli/commands/service.ts | 30 +- apps/cli/src/effect-cli/commands/sets.ts | 10 +- .../effect-cli/commands/skills-activation.ts | 23 +- .../src/effect-cli/commands/skills-search.ts | 8 +- apps/cli/src/effect-cli/commands/skills.ts | 68 +- apps/cli/src/effect-cli/commands/sync.ts | 22 +- apps/cli/src/effect-cli/commands/uninstall.ts | 20 +- apps/cli/src/effect-cli/commands/verify.ts | 22 +- apps/cli/src/effect-cli/commands/watch.ts | 20 +- apps/cli/src/effect-cli/commands/workflows.ts | 14 +- apps/cli/src/effect-cli/program.ts | 9 +- apps/desktop/package.json | 4 +- apps/desktop/scripts/build-sidecar.ts | 20 +- apps/desktop/scripts/sidecar-entry.test.ts | 39 + apps/desktop/scripts/sidecar-entry.ts | 8 + apps/desktop/scripts/smoke-packaged.ts | 2 +- apps/desktop/scripts/smoke-sidecar.ts | 11 +- apps/desktop/src/main/background-service.ts | 2 +- apps/desktop/src/main/desktop-runtime.test.ts | 103 + apps/desktop/src/main/desktop-runtime.ts | 44 +- .../src/main/managed-connection-lifecycle.ts | 2 +- apps/desktop/src/main/runtime-install.ts | 2 +- apps/local-dashboard/package.json | 2 +- apps/local-dashboard/src/App.tsx | 4 + apps/local-dashboard/src/api.ts | 66 +- .../src/components/SkillEvaluations.tsx | 34 + .../src/components/SkillHistory.test.tsx | 57 + .../src/components/SkillHistory.tsx | 186 + .../components/SkillPackageInspector.test.tsx | 45 + .../src/components/SkillPackageInspector.tsx | 94 + .../settings/BillingSettingsPanel.test.tsx | 25 +- .../settings/BillingSettingsPanel.tsx | 331 +- .../src/dashboard-host-sharing.test.tsx | 2 +- .../src/dashboard-host.test.ts | 17 + apps/local-dashboard/src/dashboard-host.ts | 50 +- apps/local-dashboard/src/dashboard-http.ts | 2 + apps/local-dashboard/src/hooks/useLibrary.ts | 19 +- apps/local-dashboard/src/hooks/useSettings.ts | 4 + apps/local-dashboard/src/lib/reactivity.ts | 2 +- .../src/library-index-api.test.ts | 51 + .../src/library-index.test.tsx | 103 + .../src/local-library-index-model.ts | 97 + .../src/local-library-model.ts | 39 +- .../src/local-library-transfer-actions.ts | 9 +- .../src/pages/LocalSkillReport.test.tsx | 136 + .../src/pages/Settings.test.tsx | 49 +- apps/local-dashboard/src/pages/Settings.tsx | 57 +- .../src/pages/SkillReport.test.tsx | 99 +- .../local-dashboard/src/pages/SkillReport.tsx | 677 +-- .../src/use-local-library-inventory.ts | 111 + apps/local/package.json | 4 +- apps/local/src/cloud-account-link.ts | 7 +- apps/local/src/cloud-billing.ts | 55 +- apps/local/src/cloud-team-collaboration.ts | 2 +- apps/local/src/correction-study-service.ts | 2 +- apps/local/src/daemon.ts | 2 +- apps/local/src/dashboard-events.ts | 24 +- apps/local/src/dashboard-operation-errors.ts | 2 +- apps/local/src/dashboard-operations.ts | 19 +- apps/local/src/dashboard-server.ts | 74 +- .../local/src/historical-skill-improve-cli.ts | 59 +- .../historical-skill-improvement-service.ts | 2 +- .../src/historical-skill-replay-executor.ts | 176 +- apps/local/src/historical-task-candidate.ts | 54 +- apps/local/src/hosted-state.ts | 21 +- apps/local/src/installed-skill-discovery.ts | 51 + apps/local/src/interactive-report-worker.ts | 107 + apps/local/src/operation-cache.ts | 24 +- apps/local/src/private-library-sync.ts | 85 + .../src/proactive-correction-e2-service.ts | 4 +- apps/local/src/remote-library-operations.ts | 16 + apps/local/src/report-caches.ts | 15 +- apps/local/src/report-compute.ts | 96 +- apps/local/src/report-contract.ts | 35 +- apps/local/src/report-version.ts | 6 +- apps/local/src/report-worker-command.ts | 2 + apps/local/src/report-worker.ts | 42 +- apps/local/src/routes/core.ts | 22 + apps/local/src/routes/evaluations.ts | 45 + apps/local/src/routes/library-transfer.ts | 78 +- apps/local/src/routes/overview.ts | 23 +- apps/local/src/service-contract.ts | 2 +- apps/local/src/service/launchd/backend.ts | 4 +- .../windows/installation/controller.ts | 2 +- .../service/windows/installation/io-error.ts | 4 +- .../installation/legacy-cleanup-controller.ts | 2 +- .../src/service/windows/installation/store.ts | 2 +- .../src/service/windows/lock-compatibility.ts | 6 +- .../src/service/windows/mutation-lock.ts | 2 +- apps/local/src/skill-package-inspector.ts | 159 + apps/local/src/skill-revision-service.ts | 188 + apps/local/src/trace-candidate-contract.ts | 2 +- apps/local/tests/cloud-billing.test.ts | 22 +- apps/local/tests/dashboard-events.test.ts | 48 + .../local/tests/dashboard-shell-cache.test.ts | 32 + apps/local/tests/evaluations.test.ts | 54 + apps/local/tests/fixtures/report-worker.ts | 17 +- .../historical-skill-improve-cli.test.ts | 39 + .../historical-skill-replay-executor.test.ts | 14 +- .../tests/historical-task-candidate.test.ts | 1 + apps/local/tests/hosted-state.test.ts | 26 + apps/local/tests/overview-worker.test.ts | 137 + apps/local/tests/report-contract.test.ts | 27 + apps/local/tests/report-lifecycle.test.ts | 61 + .../tests/report-process-boundary.test.ts | 8 +- .../tests/skill-package-inspector.test.ts | 74 + .../tests/skill-revision-history.test.ts | 233 + .../tests/source-task-reconstruction.test.ts | 322 + apps/selfhost/package.json | 2 +- apps/selfhost/src/config.ts | 2 +- apps/selfhost/src/remote-dashboard.ts | 2 +- apps/selfhost/src/repository.ts | 2 +- apps/use-once-helper/package.json | 2 +- bun.lock | 213 +- docs/design-docs/evolution-pipeline.md | 11 + e2e/src/services.ts | 4 +- package.json | 13 +- packages/config/package.json | 8 +- packages/config/src/load.ts | 11 +- packages/control-plane/package.json | 14 +- packages/control-plane/scripts/test.mjs | 13 + .../src/domain/adjacent-instructions.ts | 2 +- packages/control-plane/src/domain/errors.ts | 2 +- .../src/domain/evaluation-report.ts | 39 + .../src/domain/package-bundle.ts | 4 +- .../src/domain/plugin-capability-bundle.ts | 2 +- .../src/domain/portable-plugin-export.ts | 2 +- .../src/domain/portable-skill-set.ts | 4 +- .../control-plane/src/domain/remote-errors.ts | 8 +- .../src/domain/skill-set-dependencies.ts | 2 +- .../src/domain/skill-set-pack.ts | 2 +- .../src/domain/skill-set-source-composer.ts | 2 +- .../control-plane/src/domain/synthesis.ts | 4 +- .../control-plane/src/library-index.test.ts | 102 + packages/control-plane/src/library-index.ts | 144 + .../src/library-transport.test.ts | 85 + .../control-plane/src/library-transport.ts | 73 + .../control-plane/src/science/evaluation.ts | 27 +- .../tests/evaluation-science.test.ts | 27 +- packages/control-plane/vitest.config.ts | 12 + packages/dashboard-core/package.json | 1 + .../src/chrome/DashboardSidebar.test.tsx | 2 + .../src/chrome/DashboardSidebar.tsx | 2 +- ...ServerProfileSwitcher.interaction.test.tsx | 7 + .../src/chrome/ServerProfileSwitcher.test.ts | 24 +- .../src/chrome/ServerProfileSwitcher.tsx | 9 +- packages/dashboard-core/src/chrome/types.ts | 1 + .../src/gates/CloudFeatureGateDialog.tsx | 6 +- packages/dashboard-core/src/host/adapter.ts | 8 +- packages/dashboard-core/src/models/library.ts | 3 + .../src/screens/settings/PricingCards.tsx | 74 + .../src/screens/settings/index.ts | 1 + .../skill-report/EvaluationCaseInspector.tsx | 108 + .../screens/skill-report/LocalSkillReport.tsx | 331 + .../skill-report/SkillEvaluations.test.tsx | 107 + .../screens/skill-report/SkillEvaluations.tsx | 252 + .../SkillReportRecentActivity.tsx | 115 + .../src/screens/skill-report/index.ts | 3 + .../src/screens/skills/ContextSavings.tsx | 61 +- .../skills/InstalledSkillHistory.test.tsx | 42 + .../screens/skills/InstalledSkillHistory.tsx | 35 + .../screens/skills/InstalledSkillPackage.tsx | 34 + .../src/screens/skills/LibraryPagination.tsx | 37 + .../screens/skills/OnDemandSkillsPanel.tsx | 3 + .../skills/OnDemandSkillsReview.test.tsx | 33 + .../screens/skills/OnDemandSkillsReview.tsx | 129 +- .../src/screens/skills/SkillsLibraryRows.ts | 96 + .../SkillsLibraryScreen.interaction.test.tsx | 29 + .../screens/skills/SkillsLibraryScreen.tsx | 177 +- .../src/screens/skills/table-interaction.ts | 6 + packages/harnesses/claude-code/package.json | 2 +- .../harnesses/claude-code/src/descriptor.ts | 13 +- .../harnesses/claude-code/src/presentation.ts | 12 + .../harnesses/claude-code/src/source-sync.ts | 4 +- packages/harnesses/cline/src/descriptor.ts | 16 +- packages/harnesses/cline/src/presentation.ts | 18 + packages/harnesses/codex/package.json | 2 +- .../codex/src/adapters/codex/install.ts | 6 +- packages/harnesses/codex/src/descriptor.ts | 14 +- .../codex/src/ingestors/codex-rollout.ts | 56 +- .../codex/src/ingestors/rollout-contract.ts | 2 + .../src/ingestors/rollout-line-scanner.ts | 24 + .../src/ingestors/skill-read-evidence.ts | 67 + packages/harnesses/codex/src/presentation.ts | 13 + packages/harnesses/codex/src/source-sync.ts | 78 +- packages/harnesses/core/package.json | 2 +- packages/harnesses/core/src/source-adapter.ts | 2 +- packages/harnesses/openclaw/src/descriptor.ts | 17 +- .../harnesses/openclaw/src/presentation.ts | 18 + packages/harnesses/opencode/package.json | 2 +- packages/harnesses/opencode/src/descriptor.ts | 13 +- .../harnesses/opencode/src/presentation.ts | 12 + .../harnesses/opencode/src/source-sync.ts | 1 + packages/harnesses/pi/package.json | 2 +- packages/harnesses/pi/src/descriptor.ts | 14 +- packages/harnesses/pi/src/presentation.ts | 13 + packages/harnesses/pi/src/source-sync.ts | 12 +- .../harnesses/registry/src/presentation.ts | 15 + packages/library/package.json | 2 +- packages/library/src/hash.ts | 13 + packages/library/src/remote/effect-sync.ts | 2 +- packages/library/src/remote/sync.ts | 40 +- packages/library/src/skills-sh-catalog.ts | 8 +- .../library/src/skills-sh-materializer.ts | 12 +- packages/local-store/package.json | 2 +- .../src/analytical-import-checkpoints.ts | 2 +- .../src/correction-signal-study-drafts.ts | 4 +- .../local-store/src/correction-studies.ts | 4 +- packages/local-store/src/drizzle-schema.ts | 46 +- .../src/drizzle/0019_narrow_magma.sql | 11 + .../src/drizzle/0020_numerous_apocalypse.sql | 2 + .../src/drizzle/meta/0019_snapshot.json | 5353 ++++++++++++++++ .../src/drizzle/meta/0020_snapshot.json | 5364 +++++++++++++++++ .../src/drizzle/meta/_journal.json | 14 + .../src/embedded-migrations.gen.ts | 6 +- .../src/evaluation-submission-drafts.ts | 2 +- packages/local-store/src/index.ts | 1 + .../local-store/src/skill-revision-schema.ts | 17 + packages/local-store/src/skill-revisions.ts | 57 + packages/observability/package.json | 5 +- packages/observability/src/duckdb-node-api.ts | 137 +- packages/observability/src/duckdb-store.ts | 382 +- .../observability/src/durable-summary-sql.ts | 104 + packages/observability/src/evidence-cohort.ts | 2 +- .../observability/src/historical-backfill.ts | 19 +- .../observability/src/local-trace-importer.ts | 14 +- packages/observability/src/otlp.ts | 2 +- packages/observability/src/source-identity.ts | 22 + .../src/source-reconstruction.ts | 108 + .../observability/src/storage-capacity.ts | 67 + packages/orchestration/package.json | 6 +- .../orchestration/src/canonical-export.ts | 2 +- .../orchestration/src/historical-backfill.ts | 2 +- packages/orchestration/src/improve.ts | 74 +- .../orchestration/src/orchestrate/signals.ts | 2 +- .../src/reconstruct-source-task.ts | 54 + .../src/sync/local-trace-importer.ts | 32 +- packages/orchestration/src/sync/services.ts | 2 +- packages/orchestration/src/watch/services.ts | 2 +- packages/runtime/billing-plans.ts | 39 + .../runtime/command-surface/improvement.ts | 23 +- packages/runtime/contribute/sanitize.ts | 6 +- packages/runtime/credential-store.ts | 2 +- .../dashboard-contract/action-events.ts | 5 +- .../dashboard-contract/local-management.ts | 3 +- .../dashboard-contract/report-schemas.ts | 2 +- packages/runtime/eval/baseline.ts | 7 +- packages/runtime/eval/cli-contract.ts | 11 + packages/runtime/eval/history.ts | 63 + packages/runtime/eval/output-quality.ts | 34 +- packages/runtime/eval/plugin.ts | 101 + packages/runtime/eval/programs.ts | 54 + packages/runtime/eval/report.ts | 190 + packages/runtime/eval/score-gate.ts | 13 + packages/runtime/evolution/audit.ts | 2 +- packages/runtime/evolution/evidence.ts | 2 +- .../runtime/evolution/validate-host-replay.ts | 2 + .../evolution/validate-host-replay/runner.ts | 20 +- packages/runtime/grading/grade-session.ts | 59 +- packages/runtime/grading/pre-gates.ts | 98 +- packages/runtime/installer/materializer.ts | 2 +- packages/runtime/installer/types.ts | 2 +- packages/runtime/localdb/queries/dashboard.ts | 145 +- packages/runtime/localdb/queries/skills.ts | 152 + packages/runtime/localdb/queries/trust.ts | 39 +- packages/runtime/package.json | 2 +- packages/runtime/registry/client.ts | 18 +- packages/runtime/registry/path-policy.ts | 4 +- packages/runtime/registry/program-types.ts | 2 +- packages/runtime/registry/registry-state.ts | 2 +- packages/runtime/remote-library/restore.ts | 4 +- packages/runtime/skill-package-inspector.ts | 14 + packages/runtime/skill-revision-history.ts | 236 + .../runtime/skill-sets/catalog-resolution.ts | 6 +- packages/runtime/team-contribution.ts | 4 +- packages/runtime/team-revalidation.ts | 2 +- packages/runtime/testing-readiness.ts | 80 +- .../evidence-completeness.ts | 208 + packages/runtime/types/grading.ts | 3 + packages/runtime/utils/frontmatter.ts | 2 +- packages/runtime/utils/jsonl.ts | 27 +- packages/runtime/utils/log-contracts.ts | 14 +- .../runtime/utils/preserving-schema.test.ts | 18 + packages/runtime/utils/preserving-schema.ts | 52 + packages/runtime/utils/skill-discovery.ts | 49 + .../skill-intelligence/src/blind-benchmark.ts | 2 +- .../skill-intelligence/src/paired-replay.ts | 2 +- packages/source-management/package.json | 2 +- packages/source-management/src/contracts.ts | 2 +- packages/source-management/src/sync.ts | 2 +- .../ui/src/components/SkillPackageViewer.tsx | 202 + packages/ui/src/components/index.ts | 1 + packages/ui/src/primitives/alert.tsx | 68 + packages/ui/src/primitives/index.ts | 1 + scripts/benchmark-dashboard-http.ts | 77 + scripts/benchmark-dashboard.ts | 38 + scripts/benchmark-library-transport.ts | 30 + scripts/benchmark-local-reads.ts | 70 + scripts/inspect-analytical-storage.ts | 18 + scripts/inspect-evidence-artifacts.ts | 24 + scripts/pack-package.ts | 11 +- scripts/prepare-effect.sh | 6 +- scripts/qualify-analytical-copy.ts | 263 + scripts/sanitize-packed-package.test.ts | 4 +- scripts/smoke-packed-package.ts | 11 +- skill/SKILL.md | 2 +- skill/references/cli-quick-reference.md | 2 +- skill/references/grading-methodology.md | 19 +- skill/workflows/Evolve.md | 11 +- skill/workflows/Grade.md | 5 +- skill/workflows/Improve.md | 16 +- skill/workflows/Ingest.md | 10 + tests/cli/eval-effect-cli.test.ts | 22 + tests/dashboard/dashboard-server.test.ts | 16 + tests/dashboard/sync-destination.test.ts | 11 - tests/eval/evidence-completeness.test.ts | 269 + tests/eval/output-quality.test.ts | 43 + tests/eval/plugin.test.ts | 46 + tests/eval/report.test.ts | 48 + tests/eval/score-gate.test.ts | 14 + tests/evolution/validate-host-replay.test.ts | 52 + tests/grading/grade-session-flow.test.ts | 91 +- tests/grading/grader-output-boundary.test.ts | 8 + tests/grading/pre-gates.test.ts | 254 +- tests/improve.test.ts | 103 + .../codex-source-sync-analytics.test.ts | 46 +- .../ingestors/codex-version-evidence.test.ts | 90 + tests/library/remote-library-sync.test.ts | 83 + tests/library/synthesis.test.ts | 4 + tests/localdb/drizzle-migrations.test.ts | 26 +- tests/localdb/read-queries.test.ts | 28 + tests/localdb/trust-query-contracts.test.ts | 47 + tests/observability/compact-fixture.ts | 74 + tests/observability/duckdb-migration.test.ts | 44 +- tests/observability/duckdb-node-api.test.ts | 55 +- tests/observability/duckdb-store.test.ts | 4 +- tests/observability/durable-summary.test.ts | 118 + tests/observability/qualified-copy.test.ts | 88 + .../rollup-revision-isolation.test.ts | 117 + tests/observability/source-lifecycle.test.ts | 190 + .../source-reconstruction.test.ts | 49 + tests/observability/storage-capacity.test.ts | 40 + .../observability/storage-inspection.test.ts | 79 + .../local-trace-importer.test.ts | 38 + tests/runtime/service-launchd-backend.test.ts | 4 +- tests/sandbox/docker/output-contracts.ts | 15 +- ...telligence-catalog-duckdb-failsoft.test.ts | 1 + tests/testing-readiness-evidence.test.ts | 36 + tests/testing-readiness.test.ts | 33 +- tests/trust-floor/publish-deps.test.ts | 18 +- tests/utils/frontmatter.test.ts | 7 + tests/utils/jsonl.test.ts | 46 +- tests/utils/skill-discovery.test.ts | 35 +- 380 files changed, 23941 insertions(+), 2503 deletions(-) create mode 100644 .changeset/local-skill-revision-history.md create mode 100644 .changeset/responsive-local-library.md create mode 100644 .changeset/skill-package-inspection.md create mode 100644 apps/cli/src/effect-cli/commands/plugin-eval.ts create mode 100644 apps/desktop/scripts/sidecar-entry.test.ts create mode 100644 apps/desktop/scripts/sidecar-entry.ts create mode 100644 apps/local-dashboard/src/components/SkillEvaluations.tsx create mode 100644 apps/local-dashboard/src/components/SkillHistory.test.tsx create mode 100644 apps/local-dashboard/src/components/SkillHistory.tsx create mode 100644 apps/local-dashboard/src/components/SkillPackageInspector.test.tsx create mode 100644 apps/local-dashboard/src/components/SkillPackageInspector.tsx create mode 100644 apps/local-dashboard/src/library-index-api.test.ts create mode 100644 apps/local-dashboard/src/library-index.test.tsx create mode 100644 apps/local-dashboard/src/local-library-index-model.ts create mode 100644 apps/local-dashboard/src/pages/LocalSkillReport.test.tsx create mode 100644 apps/local-dashboard/src/use-local-library-inventory.ts create mode 100644 apps/local/src/installed-skill-discovery.ts create mode 100644 apps/local/src/interactive-report-worker.ts create mode 100644 apps/local/src/private-library-sync.ts create mode 100644 apps/local/src/report-worker-command.ts create mode 100644 apps/local/src/routes/evaluations.ts create mode 100644 apps/local/src/skill-package-inspector.ts create mode 100644 apps/local/src/skill-revision-service.ts create mode 100644 apps/local/tests/dashboard-shell-cache.test.ts create mode 100644 apps/local/tests/evaluations.test.ts create mode 100644 apps/local/tests/historical-skill-improve-cli.test.ts create mode 100644 apps/local/tests/overview-worker.test.ts create mode 100644 apps/local/tests/report-lifecycle.test.ts create mode 100644 apps/local/tests/skill-package-inspector.test.ts create mode 100644 apps/local/tests/skill-revision-history.test.ts create mode 100644 apps/local/tests/source-task-reconstruction.test.ts create mode 100644 packages/control-plane/scripts/test.mjs create mode 100644 packages/control-plane/src/domain/evaluation-report.ts create mode 100644 packages/control-plane/src/library-index.test.ts create mode 100644 packages/control-plane/src/library-index.ts create mode 100644 packages/control-plane/src/library-transport.test.ts create mode 100644 packages/control-plane/src/library-transport.ts create mode 100644 packages/dashboard-core/src/screens/settings/PricingCards.tsx create mode 100644 packages/dashboard-core/src/screens/skill-report/EvaluationCaseInspector.tsx create mode 100644 packages/dashboard-core/src/screens/skill-report/LocalSkillReport.tsx create mode 100644 packages/dashboard-core/src/screens/skill-report/SkillEvaluations.test.tsx create mode 100644 packages/dashboard-core/src/screens/skill-report/SkillEvaluations.tsx create mode 100644 packages/dashboard-core/src/screens/skill-report/SkillReportRecentActivity.tsx create mode 100644 packages/dashboard-core/src/screens/skills/InstalledSkillHistory.test.tsx create mode 100644 packages/dashboard-core/src/screens/skills/InstalledSkillHistory.tsx create mode 100644 packages/dashboard-core/src/screens/skills/InstalledSkillPackage.tsx create mode 100644 packages/dashboard-core/src/screens/skills/LibraryPagination.tsx create mode 100644 packages/dashboard-core/src/screens/skills/SkillsLibraryRows.ts create mode 100644 packages/dashboard-core/src/screens/skills/table-interaction.ts create mode 100644 packages/harnesses/claude-code/src/presentation.ts create mode 100644 packages/harnesses/cline/src/presentation.ts create mode 100644 packages/harnesses/codex/src/ingestors/skill-read-evidence.ts create mode 100644 packages/harnesses/codex/src/presentation.ts create mode 100644 packages/harnesses/openclaw/src/presentation.ts create mode 100644 packages/harnesses/opencode/src/presentation.ts create mode 100644 packages/harnesses/pi/src/presentation.ts create mode 100644 packages/harnesses/registry/src/presentation.ts create mode 100644 packages/local-store/src/drizzle/0019_narrow_magma.sql create mode 100644 packages/local-store/src/drizzle/0020_numerous_apocalypse.sql create mode 100644 packages/local-store/src/drizzle/meta/0019_snapshot.json create mode 100644 packages/local-store/src/drizzle/meta/0020_snapshot.json create mode 100644 packages/local-store/src/skill-revision-schema.ts create mode 100644 packages/local-store/src/skill-revisions.ts create mode 100644 packages/observability/src/durable-summary-sql.ts create mode 100644 packages/observability/src/source-identity.ts create mode 100644 packages/observability/src/source-reconstruction.ts create mode 100644 packages/observability/src/storage-capacity.ts create mode 100644 packages/orchestration/src/reconstruct-source-task.ts create mode 100644 packages/runtime/billing-plans.ts create mode 100644 packages/runtime/eval/history.ts create mode 100644 packages/runtime/eval/plugin.ts create mode 100644 packages/runtime/eval/report.ts create mode 100644 packages/runtime/eval/score-gate.ts create mode 100644 packages/runtime/localdb/queries/skills.ts create mode 100644 packages/runtime/skill-package-inspector.ts create mode 100644 packages/runtime/skill-revision-history.ts create mode 100644 packages/runtime/testing-readiness/evidence-completeness.ts create mode 100644 packages/runtime/utils/preserving-schema.test.ts create mode 100644 packages/runtime/utils/preserving-schema.ts create mode 100644 packages/ui/src/components/SkillPackageViewer.tsx create mode 100644 packages/ui/src/primitives/alert.tsx create mode 100644 scripts/benchmark-dashboard-http.ts create mode 100644 scripts/benchmark-dashboard.ts create mode 100644 scripts/benchmark-library-transport.ts create mode 100644 scripts/benchmark-local-reads.ts create mode 100644 scripts/inspect-analytical-storage.ts create mode 100644 scripts/inspect-evidence-artifacts.ts create mode 100644 scripts/qualify-analytical-copy.ts create mode 100644 tests/eval/evidence-completeness.test.ts create mode 100644 tests/eval/plugin.test.ts create mode 100644 tests/eval/report.test.ts create mode 100644 tests/eval/score-gate.test.ts create mode 100644 tests/ingestors/codex-version-evidence.test.ts create mode 100644 tests/observability/compact-fixture.ts create mode 100644 tests/observability/durable-summary.test.ts create mode 100644 tests/observability/qualified-copy.test.ts create mode 100644 tests/observability/rollup-revision-isolation.test.ts create mode 100644 tests/observability/source-lifecycle.test.ts create mode 100644 tests/observability/source-reconstruction.test.ts create mode 100644 tests/observability/storage-capacity.test.ts create mode 100644 tests/observability/storage-inspection.test.ts create mode 100644 tests/testing-readiness-evidence.test.ts diff --git a/.changeset/local-skill-revision-history.md b/.changeset/local-skill-revision-history.md new file mode 100644 index 00000000..d19daac7 --- /dev/null +++ b/.changeset/local-skill-revision-history.md @@ -0,0 +1,5 @@ +--- +"@selftune/desktop": patch +--- + +Automatically capture numbered local revisions of installed skill packages while the runtime is running. Add file comparisons and guarded restore to Library details, preserving prior contents without publishing team releases or rewriting skill version fields. diff --git a/.changeset/responsive-local-library.md b/.changeset/responsive-local-library.md new file mode 100644 index 00000000..803617af --- /dev/null +++ b/.changeset/responsive-local-library.md @@ -0,0 +1,5 @@ +--- +"@selftune/desktop": patch +--- + +Reduce library browsing payloads, load complete skill details on demand, and keep cold dashboard, statistics, and reports off the service event loop. Share accepted observation facts until SQLite changes, narrow readiness reads, load only the selected installation's history, and detect rewritten or replaced session files without parsing unchanged transcripts. Desktop reuses one compiled executable for isolated report workers. diff --git a/.changeset/skill-package-inspection.md b/.changeset/skill-package-inspection.md new file mode 100644 index 00000000..1fb54eda --- /dev/null +++ b/.changeset/skill-package-inspection.md @@ -0,0 +1,5 @@ +--- +"@selftune/desktop": patch +--- + +Browse installed skill package files in a searchable tree, preview Markdown, and inspect source without uploading or executing files. Simplify the Billing header while retaining payment and activation notices. diff --git a/.github/release-notes.json b/.github/release-notes.json index 6c3bedaf..f54202e7 100644 --- a/.github/release-notes.json +++ b/.github/release-notes.json @@ -3,6 +3,259 @@ "generatedFrom": "sites/docs/changelog.mdx", "docsUrl": "https://docs.selftune.dev/changelog", "entries": [ + { + "label": "2026-10-20", + "description": "macOS desktop loading", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-30", + "description": "Analytical storage safety", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-29", + "description": "Evidence-bound grading", + "tags": ["CLI", "Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-20", + "description": "Codex historical skill evidence", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-17", + "description": "Effect runtime upgrade", + "tags": ["CLI", "Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-12", + "description": "Native plugin evaluations", + "tags": ["CLI"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-11", + "description": "Desktop recovery reconnect", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-10", + "description": "Private backup inspection", + "tags": ["Cloud"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-10", + "description": "Private skill backup storage", + "tags": ["Cloud"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-10", + "description": "Cloud workspace foundations", + "tags": ["Cloud"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-09", + "description": "Cloud library loading hotfix", + "tags": ["Cloud"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-09", + "description": "Local-first skill reports", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-09", + "description": "Open Team from the Cloud menu", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-09", + "description": "Reports for unused on-demand skills", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-08", + "description": "Automatic local skill revision history", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-08", + "description": "Inspect installed skill packages", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-08", + "description": "Browse Desktop pricing before connecting", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-08", + "description": "Internal workspace access", + "tags": ["Cloud"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-08", + "description": "Explain Skill Set publishing access", + "tags": ["Cloud", "Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-08", + "description": "Avoid unnecessary Desktop recovery reloads", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-08", + "description": "One familiar workspace in Desktop and Cloud", + "tags": ["Cloud"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-08", + "description": "Connect Desktop before upgrading", + "tags": ["Cloud", "Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, + { + "label": "2026-09-07", + "description": "Preserve Desktop approval through Cloud sign-in", + "tags": ["Cloud", "Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, { "label": "2026-09-07", "description": "Validate redacted contributions and preserve diagnostic errors", diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index d58d0c64..5641a9c9 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -47,6 +47,11 @@ audit entries, and packages the user deliberately shares. - Project scoping uses managed filesystem links so an agent sees the right skills only where they are needed. - SQLite is operational product state; DuckDB is bounded local analytics. +- DuckDB retains compact per-batch discovery facts and metric contributions separately + from detail. Codex reconstruction recipes record hashes and parser inputs, not + transcript copies; historical candidate preparation can resolve bounded missing + tasks from exact originals. Recipe pins retain provenance, while saved evaluation + artifacts remain authoritative for their evidence bytes. Automatic eviction is disabled. - JSONL exists for compatibility and recovery, not as a second source of truth. - Apps compose capabilities; packages never import app implementations. - Destructive library operations require preview, explicit approval, and a @@ -68,3 +73,14 @@ Managed billing, public signup, unrelated-customer SaaS isolation, abuse operations, and fleet administration are not part of the portable seam. Skill contents and operational history remain local unless the user explicitly shares a package or consents to a bounded contributor signal. + +### Local skill revision history + +`packages/local-store/src/skill-revisions.ts` owns numbered immutable snapshots in +`skill_local_revisions`, separate from published Skill Set revisions. The runtime +`skill-revision-history.ts` adapter captures bounded regular-file packages, +compares revisions, and restores with a current-content precondition. The local +host's `skill-revision-service.ts` owns polling and authenticated HTTP access; +its lifecycle ends with the dashboard server. History remains local and is not a +hosted-state field. Library history UI is supplied through the optional Skills +module History component so Cloud does not expose local filesystem operations. diff --git a/README.md b/README.md index 6fe14483..21834235 100644 --- a/README.md +++ b/README.md @@ -408,6 +408,11 @@ Wrapper-only messages and structurally complete agent handoff or approval-review envelopes do not become user queries or skill triggers; any real user text after a leading wrapper is retained and processed normally. +Eligible Codex source imports retain hash-verified reconstruction recipes for +bounded historical-task recovery. Recovery requires the captured skill revision; +unknown revisions remain unknown. Original files are never modified, and +automatic analytical-detail eviction remains disabled. + Requires [Bun](https://bun.sh) or Node.js 18+. No extra API keys. --- diff --git a/apps/cli/package.json b/apps/cli/package.json index ce1cefd1..1c1a4662 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -14,8 +14,8 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@effect/platform-bun": "4.0.0-beta.66", - "@effect/platform-node-shared": "4.0.0-beta.66", + "@effect/platform-bun": "4.0.0-rc.115", + "@effect/platform-node-shared": "4.0.0-rc.115", "@selftune/control-plane": "workspace:*", "@selftune/harness-claude-code": "workspace:*", "@selftune/harness-cline": "workspace:*", @@ -27,7 +27,7 @@ "@selftune/local-store": "workspace:*", "@selftune/orchestration": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/apps/cli/src/commands/uninstall/errors.ts b/apps/cli/src/commands/uninstall/errors.ts index 154191b9..e8613b22 100644 --- a/apps/cli/src/commands/uninstall/errors.ts +++ b/apps/cli/src/commands/uninstall/errors.ts @@ -1,6 +1,6 @@ import * as Schema from "effect/Schema"; -export class UninstallCleanupFailure extends Schema.TaggedErrorClass()( +export class UninstallCleanupFailure extends Schema.TaggedError()( "UninstallCleanupFailure", { operation: Schema.Literals(["remove-agents", "remove-hooks"]), diff --git a/apps/cli/src/effect-cli/argument-compatibility.ts b/apps/cli/src/effect-cli/argument-compatibility.ts index 76de1711..cbfd3d77 100644 --- a/apps/cli/src/effect-cli/argument-compatibility.ts +++ b/apps/cli/src/effect-cli/argument-compatibility.ts @@ -272,6 +272,27 @@ interface EvalLeafSpec { } const EVAL_LEAF_SPECS: ReadonlyMap = new Map([ + ["report", { booleans: new Set(["--json"]), values: new Set(["--input", "--threshold"]) }], + [ + "plugin", + { + booleans: new Set(["--trust-plugin", "--json"]), + values: new Set([ + "--target", + "--runs", + "--threshold", + "--concurrency", + "--max-cost-usd", + "--model", + "--judge-model", + "--case", + "--eval-dir", + "--output-dir", + "--report", + "--ablation", + ]), + }, + ], [ "generate", { @@ -311,6 +332,7 @@ const EVAL_LEAF_SPECS: ReadonlyMap = new Map([ { booleans: new Set(["--json"]), values: new Set([ + "--threshold", "--skill-path", "--evals", "--workspace", diff --git a/apps/cli/src/effect-cli/commands/badge.ts b/apps/cli/src/effect-cli/commands/badge.ts index ce865dc9..d0df79a3 100644 --- a/apps/cli/src/effect-cli/commands/badge.ts +++ b/apps/cli/src/effect-cli/commands/badge.ts @@ -59,14 +59,14 @@ export function makeBadgeCommand(action: BadgeAction = runBadgeAction) { return Command.make( "badge", { - _noOperands: Argument.none.pipe(Argument.optional, Argument.withMetavar("")), - internalHelp: Flag.boolean(BADGE_INTERNAL_HELP_FLAG), - skill: Flag.string("skill").pipe(Flag.withDescription("Skill name (required)")), - format: Flag.choice("format", ["svg", "markdown", "url"]).pipe( + _noOperands: Argument.Never.pipe(Argument.optional, Argument.withMetavar("")), + internalHelp: Flag.Boolean(BADGE_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), + skill: Flag.String("skill").pipe(Flag.withDescription("Skill name (required)")), + format: Flag.Literals("format", ["svg", "markdown", "url"]).pipe( Flag.withDescription("Output format: svg, markdown, or url"), Flag.withDefault("svg"), ), - output: Flag.string("output").pipe( + output: Flag.String("output").pipe( Flag.withDescription("Write to a file instead of stdout"), Flag.optional, ), diff --git a/apps/cli/src/effect-cli/commands/contribute.ts b/apps/cli/src/effect-cli/commands/contribute.ts index f7010f52..e5800fd3 100644 --- a/apps/cli/src/effect-cli/commands/contribute.ts +++ b/apps/cli/src/effect-cli/commands/contribute.ts @@ -101,15 +101,15 @@ export function makeContributeCommand(action: ContributeAction = runContributeAc return Command.make( "contribute", { - internalHelp: Flag.boolean(CONTRIBUTE_INTERNAL_HELP_FLAG), - skill: Flag.string("skill").pipe(Flag.optional), - output: Flag.string("output").pipe(Flag.optional), - preview: Flag.boolean("preview"), - sanitize: Flag.string("sanitize").pipe(Flag.optional), - since: Flag.string("since").pipe(Flag.optional), - submit: Flag.boolean("submit"), - endpoint: Flag.string("endpoint").pipe(Flag.optional), - github: Flag.boolean("github"), + internalHelp: Flag.Boolean(CONTRIBUTE_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), + skill: Flag.String("skill").pipe(Flag.optional), + output: Flag.String("output").pipe(Flag.optional), + preview: Flag.Boolean("preview").pipe(Flag.withDefault(false)), + sanitize: Flag.String("sanitize").pipe(Flag.optional), + since: Flag.String("since").pipe(Flag.optional), + submit: Flag.Boolean("submit").pipe(Flag.withDefault(false)), + endpoint: Flag.String("endpoint").pipe(Flag.optional), + github: Flag.Boolean("github").pipe(Flag.withDefault(false)), }, (input) => { if (input.internalHelp) return Console.log(CONTRIBUTE_HELP); diff --git a/apps/cli/src/effect-cli/commands/contributions.ts b/apps/cli/src/effect-cli/commands/contributions.ts index ac728947..05b7aeed 100644 --- a/apps/cli/src/effect-cli/commands/contributions.ts +++ b/apps/cli/src/effect-cli/commands/contributions.ts @@ -218,33 +218,35 @@ export function makeContributionsCommand( const status = Command.make("status", {}, () => actions.status()); const preview = Command.make( "preview", - { skill: Argument.string("skill").pipe(Argument.optional) }, + { skill: Argument.String("skill").pipe(Argument.optional) }, ({ skill }) => actions.preview(decodeArgument(skill)), ); const approve = Command.make( "approve", - { skill: Argument.string("skill").pipe(Argument.optional) }, + { skill: Argument.String("skill").pipe(Argument.optional) }, ({ skill }) => actions.approve(decodeArgument(skill)), ); const revoke = Command.make( "revoke", - { skill: Argument.string("skill").pipe(Argument.optional) }, + { skill: Argument.String("skill").pipe(Argument.optional) }, ({ skill }) => actions.revoke(decodeArgument(skill)), ); const setDefault = Command.make( "default", - { value: Argument.string("value").pipe(Argument.optional) }, + { value: Argument.String("value").pipe(Argument.optional) }, ({ value }) => actions.setDefault(decodeFlag(value)), ); const upload = Command.make( "upload", { - internalHelp: Flag.boolean(CONTRIBUTIONS_INTERNAL_UPLOAD_HELP_FLAG), - dryRun: Flag.boolean("dry-run"), - retryFailed: Flag.boolean("retry-failed"), - limit: Flag.string("limit").pipe(Flag.optional), - endpoint: Flag.string("endpoint").pipe(Flag.optional), - apiKey: Flag.string("api-key").pipe(Flag.optional), + internalHelp: Flag.Boolean(CONTRIBUTIONS_INTERNAL_UPLOAD_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)), + retryFailed: Flag.Boolean("retry-failed").pipe(Flag.withDefault(false)), + limit: Flag.String("limit").pipe(Flag.optional), + endpoint: Flag.String("endpoint").pipe(Flag.optional), + apiKey: Flag.String("api-key").pipe(Flag.optional), }, (input) => { if (input.internalHelp) return Console.log(CONTRIBUTIONS_UPLOAD_HELP); @@ -262,7 +264,11 @@ export function makeContributionsCommand( return Command.make( "contributions", - { internalHelp: Flag.boolean(CONTRIBUTIONS_INTERNAL_PARENT_HELP_FLAG) }, + { + internalHelp: Flag.Boolean(CONTRIBUTIONS_INTERNAL_PARENT_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + }, ({ internalHelp }) => (internalHelp ? Console.log(CONTRIBUTIONS_HELP) : Effect.void), ).pipe( Command.withSubcommands([status, preview, approve, revoke, setDefault, upload, reset]), diff --git a/apps/cli/src/effect-cli/commands/create.ts b/apps/cli/src/effect-cli/commands/create.ts index 9d76c66a..d584e2c3 100644 --- a/apps/cli/src/effect-cli/commands/create.ts +++ b/apps/cli/src/effect-cli/commands/create.ts @@ -34,7 +34,11 @@ export function makeCreateCommand(actions: CreateCommandActions = liveCreateComm return Command.make( "create", - { internalParentHelp: Flag.boolean(CREATE_INTERNAL_PARENT_HELP_FLAG) }, + { + internalParentHelp: Flag.Boolean(CREATE_INTERNAL_PARENT_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + }, () => Console.log(CREATE_HELP), ).pipe( Command.withSubcommands([ diff --git a/apps/cli/src/effect-cli/commands/create/evaluation.ts b/apps/cli/src/effect-cli/commands/create/evaluation.ts index 51cc2dc4..f319f518 100644 --- a/apps/cli/src/effect-cli/commands/create/evaluation.ts +++ b/apps/cli/src/effect-cli/commands/create/evaluation.ts @@ -12,19 +12,21 @@ import { import type { CreateCommandActions } from "./contracts.js"; const optionalString = (name: string, description: string) => - Flag.string(name).pipe(Flag.withDescription(description), Flag.optional); + Flag.String(name).pipe(Flag.withDescription(description), Flag.optional); function makeEvaluationFlags() { return { - internalHelp: Flag.boolean(CREATE_INTERNAL_HELP_FLAG), + internalHelp: Flag.Boolean(CREATE_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), skillPath: optionalString("skill-path", "Path to a skill directory or SKILL.md"), - mode: Flag.string("mode").pipe( + mode: Flag.String("mode").pipe( Flag.withDescription("Evaluation scope: routing or package"), Flag.withDefault("routing"), ), agent: optionalString("agent", "Runtime agent to use"), evalSetPath: optionalString("eval-set", "Override the canonical eval-set path"), - json: Flag.boolean("json").pipe(Flag.withDescription("Emit the evaluation result as JSON")), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Emit the evaluation result as JSON")), }; } @@ -56,11 +58,13 @@ export function makeCreateEvaluationCommands(actions: CreateCommandActions) { const report = Command.make( "report", { - internalHelp: Flag.boolean(CREATE_INTERNAL_HELP_FLAG), + internalHelp: Flag.Boolean(CREATE_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), skillPath: optionalString("skill-path", "Path to a skill directory or SKILL.md"), agent: optionalString("agent", "Runtime agent to use"), evalSetPath: optionalString("eval-set", "Override the canonical eval-set path"), - json: Flag.boolean("json").pipe(Flag.withDescription("Emit the evaluation result as JSON")), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Emit the evaluation result as JSON")), }, (input) => { if (input.internalHelp) diff --git a/apps/cli/src/effect-cli/commands/create/publish.ts b/apps/cli/src/effect-cli/commands/create/publish.ts index e31cd57b..63fd7e27 100644 --- a/apps/cli/src/effect-cli/commands/create/publish.ts +++ b/apps/cli/src/effect-cli/commands/create/publish.ts @@ -15,15 +15,17 @@ export function makeCreatePublishCommand(actions: CreateCommandActions) { return Command.make( "publish", { - internalHelp: Flag.boolean(CREATE_INTERNAL_HELP_FLAG), - skillPath: Flag.string("skill-path").pipe(Flag.optional), - watch: Flag.boolean("watch").pipe( - Flag.withDescription("Start watch immediately after publish succeeds"), - ), - ignoreWatchAlerts: Flag.boolean("ignore-watch-alerts").pipe( - Flag.withDescription("Bypass the publish-time watch gate"), - ), - json: Flag.boolean("json").pipe(Flag.withDescription("Emit the publish result as JSON")), + internalHelp: Flag.Boolean(CREATE_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), + skillPath: Flag.String("skill-path").pipe(Flag.optional), + watch: Flag.Boolean("watch") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Start watch immediately after publish succeeds")), + ignoreWatchAlerts: Flag.Boolean("ignore-watch-alerts") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Bypass the publish-time watch gate")), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Emit the publish result as JSON")), }, (input) => { if (input.internalHelp) diff --git a/apps/cli/src/effect-cli/commands/create/scaffolding.ts b/apps/cli/src/effect-cli/commands/create/scaffolding.ts index a5b54bed..a7251776 100644 --- a/apps/cli/src/effect-cli/commands/create/scaffolding.ts +++ b/apps/cli/src/effect-cli/commands/create/scaffolding.ts @@ -12,23 +12,25 @@ import { import type { CreateCommandActions } from "./contracts.js"; const optionalString = (name: string, description: string) => - Flag.string(name).pipe(Flag.withDescription(description), Flag.optional); + Flag.String(name).pipe(Flag.withDescription(description), Flag.optional); export function makeCreateScaffoldingCommands(actions: CreateCommandActions) { const init = Command.make( "init", { - internalHelp: Flag.boolean(CREATE_INTERNAL_HELP_FLAG), + internalHelp: Flag.Boolean(CREATE_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), name: optionalString("name", "Display name for the new skill package (required)"), description: optionalString( "description", "Short routing description for the draft skill (required)", ), outputDir: optionalString("output-dir", "Parent directory for the new package"), - force: Flag.boolean("force").pipe( - Flag.withDescription("Overwrite scaffold files when the package already exists"), - ), - json: Flag.boolean("json").pipe(Flag.withDescription("Emit the package summary as JSON")), + force: Flag.Boolean("force") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Overwrite scaffold files when the package already exists")), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Emit the package summary as JSON")), }, (input) => { if (input.internalHelp) @@ -46,9 +48,11 @@ export function makeCreateScaffoldingCommands(actions: CreateCommandActions) { const status = Command.make( "status", { - internalHelp: Flag.boolean(CREATE_INTERNAL_HELP_FLAG), + internalHelp: Flag.Boolean(CREATE_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), skillPath: optionalString("skill-path", "Path to a skill directory or SKILL.md"), - json: Flag.boolean("json").pipe(Flag.withDescription("Emit the readiness state as JSON")), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Emit the readiness state as JSON")), }, (input) => { if (input.internalHelp) @@ -63,7 +67,7 @@ export function makeCreateScaffoldingCommands(actions: CreateCommandActions) { const scaffold = Command.make( "scaffold", { - internalHelp: Flag.boolean(CREATE_INTERNAL_HELP_FLAG), + internalHelp: Flag.Boolean(CREATE_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), fromWorkflow: optionalString( "from-workflow", "Workflow ID or 1-based index from selftune workflows (required)", @@ -71,13 +75,15 @@ export function makeCreateScaffoldingCommands(actions: CreateCommandActions) { outputDir: optionalString("output-dir", "Parent directory for the new package"), skillName: optionalString("skill-name", "Override the generated skill name"), description: optionalString("description", "Override the routing description"), - write: Flag.boolean("write").pipe( - Flag.withDescription("Persist the package instead of previewing it"), - ), - force: Flag.boolean("force").pipe( - Flag.withDescription("Overwrite scaffold files when the package already exists"), - ), - json: Flag.boolean("json").pipe(Flag.withDescription("Emit the package summary as JSON")), + write: Flag.Boolean("write") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Persist the package instead of previewing it")), + force: Flag.Boolean("force") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Overwrite scaffold files when the package already exists")), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Emit the package summary as JSON")), minOccurrences: optionalString( "min-occurrences", "Minimum workflow frequency used for selection", @@ -104,9 +110,11 @@ export function makeCreateScaffoldingCommands(actions: CreateCommandActions) { const check = Command.make( "check", { - internalHelp: Flag.boolean(CREATE_INTERNAL_HELP_FLAG), + internalHelp: Flag.Boolean(CREATE_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), skillPath: optionalString("skill-path", "Path to a skill directory or SKILL.md"), - json: Flag.boolean("json").pipe(Flag.withDescription("Emit the readiness report as JSON")), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Emit the readiness report as JSON")), }, (input) => { if (input.internalHelp) diff --git a/apps/cli/src/effect-cli/commands/creator-contributions.ts b/apps/cli/src/effect-cli/commands/creator-contributions.ts index a2792849..234540fe 100644 --- a/apps/cli/src/effect-cli/commands/creator-contributions.ts +++ b/apps/cli/src/effect-cli/commands/creator-contributions.ts @@ -150,8 +150,10 @@ export function makeCreatorContributionsCommand( const status = Command.make( "status", { - internalHelp: Flag.boolean(CREATOR_CONTRIBUTIONS_INTERNAL_STATUS_HELP_FLAG), - skill: Flag.string("skill").pipe(Flag.optional), + internalHelp: Flag.Boolean(CREATOR_CONTRIBUTIONS_INTERNAL_STATUS_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + skill: Flag.String("skill").pipe(Flag.optional), }, (input) => input.internalHelp @@ -161,17 +163,19 @@ export function makeCreatorContributionsCommand( const enable = Command.make( "enable", { - internalHelp: Flag.boolean(CREATOR_CONTRIBUTIONS_INTERNAL_ENABLE_HELP_FLAG), - skill: Flag.string("skill").pipe(Flag.optional), - all: Flag.boolean("all"), - prefix: Flag.string("prefix").pipe(Flag.optional), - skillPath: Flag.string("skill-path").pipe(Flag.optional), - creatorId: Flag.string("creator-id").pipe(Flag.optional), - signals: Flag.string("signals").pipe(Flag.optional), - message: Flag.string("message").pipe(Flag.optional), - privacyUrl: Flag.string("privacy-url").pipe(Flag.optional), - feedbackEndpoint: Flag.string("feedback-endpoint").pipe(Flag.optional), - noHelper: Flag.boolean("no-helper"), + internalHelp: Flag.Boolean(CREATOR_CONTRIBUTIONS_INTERNAL_ENABLE_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + skill: Flag.String("skill").pipe(Flag.optional), + all: Flag.Boolean("all").pipe(Flag.withDefault(false)), + prefix: Flag.String("prefix").pipe(Flag.optional), + skillPath: Flag.String("skill-path").pipe(Flag.optional), + creatorId: Flag.String("creator-id").pipe(Flag.optional), + signals: Flag.String("signals").pipe(Flag.optional), + message: Flag.String("message").pipe(Flag.optional), + privacyUrl: Flag.String("privacy-url").pipe(Flag.optional), + feedbackEndpoint: Flag.String("feedback-endpoint").pipe(Flag.optional), + noHelper: Flag.Boolean("no-helper").pipe(Flag.withDefault(false)), }, (input) => input.internalHelp @@ -192,9 +196,11 @@ export function makeCreatorContributionsCommand( const disable = Command.make( "disable", { - internalHelp: Flag.boolean(CREATOR_CONTRIBUTIONS_INTERNAL_DISABLE_HELP_FLAG), - skill: Flag.string("skill").pipe(Flag.optional), - skillPath: Flag.string("skill-path").pipe(Flag.optional), + internalHelp: Flag.Boolean(CREATOR_CONTRIBUTIONS_INTERNAL_DISABLE_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + skill: Flag.String("skill").pipe(Flag.optional), + skillPath: Flag.String("skill-path").pipe(Flag.optional), }, (input) => input.internalHelp @@ -204,7 +210,11 @@ export function makeCreatorContributionsCommand( return Command.make( "creator-contributions", - { internalHelp: Flag.boolean(CREATOR_CONTRIBUTIONS_INTERNAL_PARENT_HELP_FLAG) }, + { + internalHelp: Flag.Boolean(CREATOR_CONTRIBUTIONS_INTERNAL_PARENT_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + }, ({ internalHelp }) => (internalHelp ? Console.log(CREATOR_CONTRIBUTIONS_HELP) : Effect.void), ).pipe( Command.withSubcommands([status, enable, disable]), diff --git a/apps/cli/src/effect-cli/commands/daemon.ts b/apps/cli/src/effect-cli/commands/daemon.ts index 190a408b..8fa99eb7 100644 --- a/apps/cli/src/effect-cli/commands/daemon.ts +++ b/apps/cli/src/effect-cli/commands/daemon.ts @@ -119,36 +119,36 @@ export const liveDaemonCommandActions: DaemonCommandActions = { runDaemonRotateTokenActionWithDependencies(input, LIVE_DAEMON_DEPENDENCIES), }; -const noOperands = () => Argument.none.pipe(Argument.optional, Argument.withMetavar("")); +const noOperands = () => Argument.Never.pipe(Argument.optional, Argument.withMetavar("")); export function makeDaemonCommand(actions: DaemonCommandActions = liveDaemonCommandActions) { const run = Command.make( "run", { _noOperands: noOperands(), - port: Flag.integer("port").pipe( + port: Flag.Int("port").pipe( Flag.filter( (port) => port >= 0 && port <= 65_535, (port) => `Invalid daemon port: ${port}`, ), Flag.withDefault(DEFAULT_DAEMON_PORT), ), - hostname: Flag.string("hostname").pipe(Flag.withDefault("127.0.0.1")), - configDir: Flag.string("config-dir").pipe(Flag.optional), - spaDir: Flag.string("spa-dir").pipe(Flag.optional), - owner: Flag.choice("owner", ["desktop", "cli"]).pipe(Flag.optional), - runtimeMode: Flag.choice("runtime-mode", ["standalone", "dev-server", "test"]).pipe( + hostname: Flag.String("hostname").pipe(Flag.withDefault("127.0.0.1")), + configDir: Flag.String("config-dir").pipe(Flag.optional), + spaDir: Flag.String("spa-dir").pipe(Flag.optional), + owner: Flag.Literals("owner", ["desktop", "cli"]).pipe(Flag.optional), + runtimeMode: Flag.Literals("runtime-mode", ["standalone", "dev-server", "test"]).pipe( Flag.optional, ), - serviceInstallationNonce: Flag.string("service-installation-nonce").pipe( + serviceInstallationNonce: Flag.String("service-installation-nonce").pipe( Flag.filter(isServiceInstallationNonce, () => "Expected 32-128 base64url characters"), Flag.optional, ), - foreground: Flag.boolean("foreground").pipe( - Flag.withDescription("Compatibility no-op; daemon run is always foreground"), - ), - supervised: Flag.boolean("supervised"), - readySentinel: Flag.boolean("ready-sentinel"), + foreground: Flag.Boolean("foreground") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Compatibility no-op; daemon run is always foreground")), + supervised: Flag.Boolean("supervised").pipe(Flag.withDefault(false)), + readySentinel: Flag.Boolean("ready-sentinel").pipe(Flag.withDefault(false)), }, (input) => { const serviceInstallationNonce = Option.getOrUndefined(input.serviceInstallationNonce); @@ -180,8 +180,8 @@ export function makeDaemonCommand(actions: DaemonCommandActions = liveDaemonComm "status", { _noOperands: noOperands(), - configDir: Flag.string("config-dir").pipe(Flag.optional), - json: Flag.boolean("json"), + configDir: Flag.String("config-dir").pipe(Flag.optional), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, (input) => actions.status({ @@ -194,15 +194,15 @@ export function makeDaemonCommand(actions: DaemonCommandActions = liveDaemonComm "stop", { _noOperands: noOperands(), - configDir: Flag.string("config-dir").pipe(Flag.optional), - expectedPid: Flag.integer("expected-pid").pipe( + configDir: Flag.String("config-dir").pipe(Flag.optional), + expectedPid: Flag.Int("expected-pid").pipe( Flag.filter( (pid) => Number.isSafeInteger(pid) && pid > 1, (pid) => `Invalid expected daemon pid: ${pid}`, ), Flag.optional, ), - expectedInstanceId: Flag.string("expected-instance-id").pipe(Flag.optional), + expectedInstanceId: Flag.String("expected-instance-id").pipe(Flag.optional), }, (input) => { const expectedPid = Option.getOrUndefined(input.expectedPid); @@ -237,7 +237,7 @@ export function makeDaemonCommand(actions: DaemonCommandActions = liveDaemonComm "rotate-token", { _noOperands: noOperands(), - configDir: Flag.string("config-dir").pipe(Flag.optional), + configDir: Flag.String("config-dir").pipe(Flag.optional), }, (input) => actions.rotateToken({ configDir: Option.getOrUndefined(input.configDir) }), ).pipe(Command.withDescription("Rotate local daemon authentication")); diff --git a/apps/cli/src/effect-cli/commands/dashboard.ts b/apps/cli/src/effect-cli/commands/dashboard.ts index c4346091..780f6c82 100644 --- a/apps/cli/src/effect-cli/commands/dashboard.ts +++ b/apps/cli/src/effect-cli/commands/dashboard.ts @@ -67,8 +67,8 @@ export function makeDashboardCommand(action: DashboardAction = runDashboardActio return Command.make( "dashboard", { - _noOperands: Argument.none.pipe(Argument.optional, Argument.withMetavar("")), - port: Flag.integer("port").pipe( + _noOperands: Argument.Never.pipe(Argument.optional, Argument.withMetavar("")), + port: Flag.Int("port").pipe( Flag.withDescription(`Listening port (default: ${DEFAULT_DASHBOARD_PORT})`), Flag.filter( (port) => port >= 1 && port <= 65_535, @@ -76,13 +76,15 @@ export function makeDashboardCommand(action: DashboardAction = runDashboardActio ), Flag.withDefault(DEFAULT_DASHBOARD_PORT), ), - restart: Flag.boolean("restart").pipe( - Flag.withDescription("Restart an existing dashboard on the target port"), - ), - noOpen: Flag.boolean("no-open").pipe(Flag.withDescription("Start without opening a browser")), - serve: Flag.boolean("serve").pipe( - Flag.withDescription("Deprecated alias for the default behavior"), - ), + restart: Flag.Boolean("restart") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Restart an existing dashboard on the target port")), + noOpen: Flag.Boolean("no-open") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Start without opening a browser")), + serve: Flag.Boolean("serve") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Deprecated alias for the default behavior")), }, (input) => action({ diff --git a/apps/cli/src/effect-cli/commands/eval.ts b/apps/cli/src/effect-cli/commands/eval.ts index c46cc787..cfb66b3c 100644 --- a/apps/cli/src/effect-cli/commands/eval.ts +++ b/apps/cli/src/effect-cli/commands/eval.ts @@ -1,4 +1,5 @@ import * as Effect from "effect/Effect"; +import { makePluginEvalCommand } from "./plugin-eval.js"; import * as Option from "effect/Option"; import * as Command from "effect/unstable/cli/Command"; import * as Flag from "effect/unstable/cli/Flag"; @@ -58,60 +59,62 @@ export const runEvalAction: EvalAction = (request) => runEvalActionWithDependencies(request, LIVE_EVAL_DEPENDENCIES); const optionalString = (name: string, description: string) => - Flag.string(name).pipe(Flag.withDescription(description), Flag.optional); + Flag.String(name).pipe(Flag.withDescription(description), Flag.optional); export function makeEvalCommand(action: EvalAction = runEvalAction) { const generate = Command.make( "generate", { skill: optionalString("skill", "Skill name (required unless --list-skills)"), - output: Flag.string("output").pipe( + output: Flag.String("output").pipe( Flag.withAlias("out"), Flag.withDescription("Output file path (default: _trigger_eval.json)"), Flag.optional, ), agent: optionalString("agent", "Agent CLI for synthetic or blended generation"), - max: Flag.string("max").pipe( + max: Flag.String("max").pipe( Flag.withDescription("Maximum eval entries per side"), Flag.withDefault("50"), ), - seed: Flag.string("seed").pipe( + seed: Flag.String("seed").pipe( Flag.withDescription("Deterministic shuffle seed"), Flag.withDefault("42"), ), - listSkills: Flag.boolean("list-skills").pipe( - Flag.withDescription("List skills with trusted-vs-raw readiness counts"), - ), - stats: Flag.boolean("stats").pipe( - Flag.withDescription("Show aggregate telemetry stats for the skill"), - ), - noNegatives: Flag.boolean("no-negatives").pipe( - Flag.withDescription("Exclude negative examples from output"), - ), - noTaxonomy: Flag.boolean("no-taxonomy").pipe( - Flag.withDescription("Skip invocation_type classification"), - ), - skillLog: Flag.string("skill-log").pipe( + listSkills: Flag.Boolean("list-skills") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("List skills with trusted-vs-raw readiness counts")), + stats: Flag.Boolean("stats") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Show aggregate telemetry stats for the skill")), + noNegatives: Flag.Boolean("no-negatives") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Exclude negative examples from output")), + noTaxonomy: Flag.Boolean("no-taxonomy") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Skip invocation_type classification")), + skillLog: Flag.String("skill-log").pipe( Flag.withDescription("Skill usage JSONL override"), Flag.withDefault(SKILL_LOG), ), - queryLog: Flag.string("query-log").pipe( + queryLog: Flag.String("query-log").pipe( Flag.withDescription("Query log JSONL override"), Flag.withDefault(QUERY_LOG), ), - telemetryLog: Flag.string("telemetry-log").pipe( + telemetryLog: Flag.String("telemetry-log").pipe( Flag.withDescription("Session telemetry JSONL override"), Flag.withDefault(TELEMETRY_LOG), ), - synthetic: Flag.boolean("synthetic").pipe( - Flag.withDescription("Generate from SKILL.md instead of logs"), - ), - autoSynthetic: Flag.boolean("auto-synthetic").pipe( - Flag.withDescription("Fall back to cold-start generation when trusted logs are sparse"), - ), - blend: Flag.boolean("blend").pipe( - Flag.withDescription("Blend log-derived and synthetic eval entries"), - ), + synthetic: Flag.Boolean("synthetic") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Generate from SKILL.md instead of logs")), + autoSynthetic: Flag.Boolean("auto-synthetic") + .pipe(Flag.withDefault(false)) + .pipe( + Flag.withDescription("Fall back to cold-start generation when trusted logs are sparse"), + ), + blend: Flag.Boolean("blend") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Blend log-derived and synthetic eval entries")), skillPath: optionalString("skill-path", "Path to SKILL.md for synthetic generation"), model: optionalString("model", "Model override for synthetic generation"), }, @@ -157,12 +160,12 @@ export function makeEvalCommand(action: EvalAction = runEvalAction) { { skill: optionalString("skill", "Skill name (required)"), tests: optionalString("tests", "Unit-test JSON path"), - runAgent: Flag.boolean("run-agent").pipe( - Flag.withDescription("Run tests through an agent instead of static dry-run checks"), - ), - generate: Flag.boolean("generate").pipe( - Flag.withDescription("Generate tests from skill content using an agent"), - ), + runAgent: Flag.Boolean("run-agent") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Run tests through an agent instead of static dry-run checks")), + generate: Flag.Boolean("generate") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Generate tests from skill content using an agent")), skillPath: optionalString("skill-path", "Skill file used for test generation"), evalSet: optionalString("eval-set", "Eval set used as failure context"), model: optionalString("model", "Model override for agent calls"), @@ -185,6 +188,7 @@ export function makeEvalCommand(action: EvalAction = runEvalAction) { const run = Command.make( "run", { + threshold: optionalString("threshold", "Fail CI when any case scores below this value (0–1)"), skillPath: optionalString("skill-path", "Skill directory or SKILL.md path (required)"), evals: optionalString("evals", "Override evals/evals.json"), workspace: optionalString("workspace", "Override the sibling evaluation workspace"), @@ -195,12 +199,15 @@ export function makeEvalCommand(action: EvalAction = runEvalAction) { feedback: optionalString("feedback", "Human feedback JSON to copy into the iteration"), agent: optionalString("agent", "Agent CLI for isolated runs and grading"), model: optionalString("model", "Model override"), - json: Flag.boolean("json").pipe(Flag.withDescription("Print benchmark result as JSON")), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Print benchmark result as JSON")), }, (input) => action({ action: "run", input: { + threshold: Option.getOrUndefined(input.threshold), skillPath: Option.getOrUndefined(input.skillPath), evals: Option.getOrUndefined(input.evals), workspace: Option.getOrUndefined(input.workspace), @@ -219,7 +226,7 @@ export function makeEvalCommand(action: EvalAction = runEvalAction) { dir: optionalString("dir", "SkillsBench corpus directory (required)"), skill: optionalString("skill", "Target skill name (required)"), output: optionalString("output", "Output eval-set JSON path"), - matchStrategy: Flag.choice("match-strategy", ["exact", "fuzzy"]).pipe( + matchStrategy: Flag.Literals("match-strategy", ["exact", "fuzzy"]).pipe( Flag.withDescription("Task matching strategy"), Flag.withDefault("exact"), ), @@ -289,6 +296,22 @@ export function makeEvalCommand(action: EvalAction = runEvalAction) { return Command.make("eval").pipe( Command.withSubcommands([ + Command.make( + "report", + { + input: Flag.String("input").pipe( + Flag.withDescription("Native aggregate-result.json or SelfTune benchmark.json"), + ), + threshold: Flag.String("threshold").pipe(Flag.withDefault("1")), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), + }, + (input) => action({ action: "report", input }), + ).pipe( + Command.withDescription( + "Read either evaluation format and apply a per-case CI gate without model calls", + ), + ), + makePluginEvalCommand(action), generate, unitTest, run, @@ -299,7 +322,7 @@ export function makeEvalCommand(action: EvalAction = runEvalAction) { Command.withDescription( `Evaluation and testing tools -Actions: generate, unit-test, run, import, composability, family-overlap +Actions: generate, unit-test, run, plugin, report, import, composability, family-overlap Recommended creator loop: 1. selftune eval generate --skill diff --git a/apps/cli/src/effect-cli/commands/export.ts b/apps/cli/src/effect-cli/commands/export.ts index 98e591ff..1cf1f268 100644 --- a/apps/cli/src/effect-cli/commands/export.ts +++ b/apps/cli/src/effect-cli/commands/export.ts @@ -71,19 +71,19 @@ export function makeExportCommand(action: ExportAction = runExportAction) { return Command.make( "export", { - internalHelp: Flag.boolean(EXPORT_INTERNAL_HELP_FLAG), - tables: Argument.choice("table", EXPORT_TABLE_NAMES).pipe( + internalHelp: Flag.Boolean(EXPORT_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), + tables: Argument.Literals("table", EXPORT_TABLE_NAMES).pipe( Argument.withDescription( `SQLite table snapshot to export (${EXPORT_TABLE_NAMES.join(", ")})`, ), Argument.variadic(), ), - outputDirs: Flag.string("output").pipe( + outputDirs: Flag.String("output").pipe( Flag.withAlias("o"), Flag.withDescription("Output directory (default: current directory)"), Flag.atMost(Number.MAX_SAFE_INTEGER), ), - sinceValues: Flag.string("since").pipe( + sinceValues: Flag.String("since").pipe( Flag.withDescription("Only export records after this ISO 8601 date"), Flag.atMost(Number.MAX_SAFE_INTEGER), ), diff --git a/apps/cli/src/effect-cli/commands/library.ts b/apps/cli/src/effect-cli/commands/library.ts index 95c4e899..316f8a68 100644 --- a/apps/cli/src/effect-cli/commands/library.ts +++ b/apps/cli/src/effect-cli/commands/library.ts @@ -94,7 +94,7 @@ function decode(value: Option.Option): string | undefined { return decodeLibraryInternalValue(Option.getOrUndefined(value)); } -const optionalString = (name: string) => Flag.string(name).pipe(Flag.optional); +const optionalString = (name: string) => Flag.String(name).pipe(Flag.optional); export function makeLibraryCommand(action: LibraryAction = makeLiveLibraryAction()) { const list = Command.make("list", {}, () => action({ operation: "list" })); @@ -171,7 +171,7 @@ export function makeLibraryCommand(action: LibraryAction = makeLiveLibraryAction return Command.make( "library", - { internalHelp: Flag.boolean(LIBRARY_INTERNAL_PARENT_HELP_FLAG) }, + { internalHelp: Flag.Boolean(LIBRARY_INTERNAL_PARENT_HELP_FLAG).pipe(Flag.withDefault(false)) }, ({ internalHelp }) => (internalHelp ? Console.log(LIBRARY_HELP) : Effect.void), ).pipe( Command.withSubcommands([ diff --git a/apps/cli/src/effect-cli/commands/plugin-eval.ts b/apps/cli/src/effect-cli/commands/plugin-eval.ts new file mode 100644 index 00000000..d13b7a1e --- /dev/null +++ b/apps/cli/src/effect-cli/commands/plugin-eval.ts @@ -0,0 +1,50 @@ +import * as Option from "effect/Option"; +import * as Command from "effect/unstable/cli/Command"; +import * as Flag from "effect/unstable/cli/Flag"; +import type { EvalAction } from "./eval.js"; + +const optional = (name: string) => Flag.String(name).pipe(Flag.optional); + +export function makePluginEvalCommand(action: EvalAction) { + return Command.make( + "plugin", + { + target: Flag.String("target").pipe(Flag.withDefault(".")), + runs: Flag.String("runs").pipe(Flag.withDefault("3")), + threshold: Flag.String("threshold").pipe(Flag.withDefault("1")), + concurrency: Flag.String("concurrency").pipe(Flag.withDefault("1")), + maxCostUsd: optional("max-cost-usd"), + model: optional("model"), + judgeModel: optional("judge-model"), + case: optional("case"), + evalDir: optional("eval-dir"), + outputDir: optional("output-dir"), + report: optional("report"), + ablation: Flag.Literals("ablation", ["none", "with-without"]).pipe( + Flag.withDefault("with-without"), + ), + trustPlugin: Flag.Boolean("trust-plugin") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Explicitly trust the plugin and suite; never implied")), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), + }, + (input) => + action({ + action: "plugin", + input: { + ...input, + maxCostUsd: Option.getOrUndefined(input.maxCostUsd), + model: Option.getOrUndefined(input.model), + judgeModel: Option.getOrUndefined(input.judgeModel), + case: Option.getOrUndefined(input.case), + evalDir: Option.getOrUndefined(input.evalDir), + outputDir: Option.getOrUndefined(input.outputDir), + report: Option.getOrUndefined(input.report), + }, + }), + ).pipe( + Command.withDescription( + "Run Claude-native plugin evals; keep reports local and preserve native CI exit codes", + ), + ); +} diff --git a/apps/cli/src/effect-cli/commands/project.ts b/apps/cli/src/effect-cli/commands/project.ts index 9d8dfd4c..b0954813 100644 --- a/apps/cli/src/effect-cli/commands/project.ts +++ b/apps/cli/src/effect-cli/commands/project.ts @@ -79,9 +79,9 @@ function decode(value: Option.Option): string | undefined { } export function makeProjectCommand(action: ProjectAction = makeLiveProjectAction()) { - const project = Flag.string("project").pipe(Flag.optional); - const sets = Flag.string("set").pipe(Flag.atLeast(0)); - const json = Flag.boolean("json"); + const project = Flag.String("project").pipe(Flag.optional); + const sets = Flag.String("set").pipe(Flag.atLeast(0)); + const json = Flag.Boolean("json").pipe(Flag.withDefault(false)); const makeInput = (input: { project: Option.Option; sets: ReadonlyArray }) => { const projectRoot = decode(input.project); if (!projectRoot?.trim()) { @@ -95,18 +95,22 @@ export function makeProjectCommand(action: ProjectAction = makeLiveProjectAction const configure = Command.make("configure", { project, sets, json }, (input) => action("configure", makeInput(input), input.json), ); - const init = Command.make("init", { project, sets, json, yes: Flag.boolean("yes") }, (input) => { - if (!input.yes) { - return Effect.fail( - new CLIError( - "Project initialization requires --yes because it creates a new React project and installs Skill Sets.", - "MISSING_FLAG", - "Review the selected Skill Sets, then rerun with --yes.", - ), - ); - } - return action("init", makeInput(input), input.json); - }); + const init = Command.make( + "init", + { project, sets, json, yes: Flag.Boolean("yes").pipe(Flag.withDefault(false)) }, + (input) => { + if (!input.yes) { + return Effect.fail( + new CLIError( + "Project initialization requires --yes because it creates a new React project and installs Skill Sets.", + "MISSING_FLAG", + "Review the selected Skill Sets, then rerun with --yes.", + ), + ); + } + return action("init", makeInput(input), input.json); + }, + ); return Command.make("project", {}, () => Console.log(PROJECT_HELP)).pipe( Command.withSubcommands([plan, configure, init]), Command.withDescription("Plan and configure project Skill Sets"), diff --git a/apps/cli/src/effect-cli/commands/publish.ts b/apps/cli/src/effect-cli/commands/publish.ts index 3c811ec5..3bc326ba 100644 --- a/apps/cli/src/effect-cli/commands/publish.ts +++ b/apps/cli/src/effect-cli/commands/publish.ts @@ -104,11 +104,11 @@ export function makePublishCommand(action: PublishAction = runPublishAction) { return Command.make( "publish", { - internalHelp: Flag.boolean(PUBLISH_INTERNAL_HELP_FLAG), - internalWatch: Flag.boolean(PUBLISH_INTERNAL_WATCH_FLAG), - skillPath: Flag.string("skill-path").pipe(Flag.optional), - ignoreWatchAlerts: Flag.boolean("ignore-watch-alerts"), - json: Flag.boolean("json"), + internalHelp: Flag.Boolean(PUBLISH_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), + internalWatch: Flag.Boolean(PUBLISH_INTERNAL_WATCH_FLAG).pipe(Flag.withDefault(false)), + skillPath: Flag.String("skill-path").pipe(Flag.optional), + ignoreWatchAlerts: Flag.Boolean("ignore-watch-alerts").pipe(Flag.withDefault(false)), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, (input) => { if (input.internalHelp) return Console.log(PUBLISH_HELP); diff --git a/apps/cli/src/effect-cli/commands/recover.ts b/apps/cli/src/effect-cli/commands/recover.ts index 0d6b4455..59f36a92 100644 --- a/apps/cli/src/effect-cli/commands/recover.ts +++ b/apps/cli/src/effect-cli/commands/recover.ts @@ -76,33 +76,37 @@ export function makeRecoverCommand(action: RecoverAction = runRecoverAction) { return Command.make( "recover", { - internalHelp: Flag.boolean(RECOVER_INTERNAL_HELP_FLAG), - full: Flag.boolean("full").pipe(Flag.withDescription("Rebuild SQLite tables from scratch")), - force: Flag.boolean("force").pipe( - Flag.withDescription("Skip the preflight guard for SQLite-only rows"), - ), - since: Flag.string("since").pipe( + internalHelp: Flag.Boolean(RECOVER_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), + full: Flag.Boolean("full") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Rebuild SQLite tables from scratch")), + force: Flag.Boolean("force") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Skip the preflight guard for SQLite-only rows")), + since: Flag.String("since").pipe( Flag.withDescription("Incrementally materialize records on or after this date"), Flag.optional, ), - json: Flag.boolean("json").pipe(Flag.withDescription("Output a JSON summary")), - canonicalLog: Flag.string("canonical-log").pipe( + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Output a JSON summary")), + canonicalLog: Flag.String("canonical-log").pipe( Flag.withDescription("Canonical JSONL path"), Flag.withDefault(CANONICAL_LOG), ), - telemetryLog: Flag.string("telemetry-log").pipe( + telemetryLog: Flag.String("telemetry-log").pipe( Flag.withDescription("Session telemetry JSONL path"), Flag.withDefault(TELEMETRY_LOG), ), - evolutionAuditLog: Flag.string("evolution-audit-log").pipe( + evolutionAuditLog: Flag.String("evolution-audit-log").pipe( Flag.withDescription("Evolution audit JSONL path"), Flag.withDefault(EVOLUTION_AUDIT_LOG), ), - evolutionEvidenceLog: Flag.string("evolution-evidence-log").pipe( + evolutionEvidenceLog: Flag.String("evolution-evidence-log").pipe( Flag.withDescription("Evolution evidence JSONL path"), Flag.withDefault(EVOLUTION_EVIDENCE_LOG), ), - orchestrateRunLog: Flag.string("orchestrate-run-log").pipe( + orchestrateRunLog: Flag.String("orchestrate-run-log").pipe( Flag.withDescription("Orchestrate runs JSONL path"), Flag.withDefault(ORCHESTRATE_RUN_LOG), ), diff --git a/apps/cli/src/effect-cli/commands/registry.ts b/apps/cli/src/effect-cli/commands/registry.ts index a6f2322e..bf66e66a 100644 --- a/apps/cli/src/effect-cli/commands/registry.ts +++ b/apps/cli/src/effect-cli/commands/registry.ts @@ -119,7 +119,7 @@ export function makeLiveRegistryAction( return (input) => runRegistryActionWithDependencies(input, dependencies); } -const optionalString = (name: string) => Flag.string(name).pipe(Flag.optional); +const optionalString = (name: string) => Flag.String(name).pipe(Flag.optional); function decode(value: Option.Option): string | undefined { return decodeRegistryInternalValue(Option.getOrUndefined(value)); @@ -144,7 +144,10 @@ export function makeRegistryCommand(action: RegistryAction = makeLiveRegistryAct const install = Command.make( "install", - { target: optionalString("target"), global: Flag.boolean("global") }, + { + target: optionalString("target"), + global: Flag.Boolean("global").pipe(Flag.withDefault(false)), + }, (input) => action({ operation: "install", target: decode(input.target), global: input.global }), ).pipe(Command.withDescription("Install a skill from the registry or GitHub")); @@ -164,8 +167,10 @@ export function makeRegistryCommand(action: RegistryAction = makeLiveRegistryAct }), ).pipe(Command.withDescription("Submit local skill changes to the workspace creator")); - const sync = Command.make("sync", { automaticOnly: Flag.boolean("automatic-only") }, (input) => - action({ operation: "sync", automaticOnly: input.automaticOnly }), + const sync = Command.make( + "sync", + { automaticOnly: Flag.Boolean("automatic-only").pipe(Flag.withDefault(false)) }, + (input) => action({ operation: "sync", automaticOnly: input.automaticOnly }), ).pipe(Command.withDescription("Pull the latest versions of installed skills")); const status = Command.make("status", {}, () => action({ operation: "status" })).pipe( Command.withDescription("Show installed skills and version drift"), @@ -194,7 +199,9 @@ export function makeRegistryCommand(action: RegistryAction = makeLiveRegistryAct return Command.make( "registry", - { internalHelp: Flag.boolean(REGISTRY_INTERNAL_PARENT_HELP_FLAG) }, + { + internalHelp: Flag.Boolean(REGISTRY_INTERNAL_PARENT_HELP_FLAG).pipe(Flag.withDefault(false)), + }, () => Console.log(REGISTRY_HELP), ).pipe( Command.withSubcommands([push, suggest, install, sync, status, rollback, history, list]), diff --git a/apps/cli/src/effect-cli/commands/service.ts b/apps/cli/src/effect-cli/commands/service.ts index f2753aad..ea7e56c8 100644 --- a/apps/cli/src/effect-cli/commands/service.ts +++ b/apps/cli/src/effect-cli/commands/service.ts @@ -161,29 +161,31 @@ export const liveServiceCommandActions: ServiceCommandActions = { function makeServiceFlags() { return { - _noOperands: Argument.none.pipe(Argument.optional, Argument.withMetavar("")), - port: Flag.integer("port").pipe( + _noOperands: Argument.Never.pipe(Argument.optional, Argument.withMetavar("")), + port: Flag.Int("port").pipe( Flag.filter( (port) => port >= 1 && port <= 65_535, (port) => `Invalid service port: ${port}`, ), Flag.withDefault(DEFAULT_SERVICE_PORT), ), - configDir: Flag.string("config-dir").pipe(Flag.optional), - owner: Flag.choice("owner", ["desktop", "cli"]).pipe(Flag.optional), - boot: Flag.boolean("boot").pipe( - Flag.withDescription("Windows only: start before login (requires elevation)"), - ), - json: Flag.boolean("json").pipe(Flag.withDescription("Emit a machine-readable response")), - executable: Flag.string("executable").pipe( + configDir: Flag.String("config-dir").pipe(Flag.optional), + owner: Flag.Literals("owner", ["desktop", "cli"]).pipe(Flag.optional), + boot: Flag.Boolean("boot") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Windows only: start before login (requires elevation)")), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Emit a machine-readable response")), + executable: Flag.String("executable").pipe( Flag.withDescription("SelfTune executable registered with the OS supervisor"), Flag.optional, ), - resourceDir: Flag.string("resource-dir").pipe( + resourceDir: Flag.String("resource-dir").pipe( Flag.withDescription("Packaged SelfTune resource directory"), Flag.optional, ), - serviceVersion: Flag.string("service-version").pipe( + serviceVersion: Flag.String("service-version").pipe( Flag.withDescription("Version recorded for the supervised SelfTune runtime"), Flag.optional, ), @@ -192,8 +194,10 @@ function makeServiceFlags() { function makeMaintenanceFlags() { return { - _noOperands: Argument.none.pipe(Argument.optional, Argument.withMetavar("")), - json: Flag.boolean("json").pipe(Flag.withDescription("Emit a machine-readable response")), + _noOperands: Argument.Never.pipe(Argument.optional, Argument.withMetavar("")), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Emit a machine-readable response")), }; } diff --git a/apps/cli/src/effect-cli/commands/sets.ts b/apps/cli/src/effect-cli/commands/sets.ts index e43bf7d1..233a0be3 100644 --- a/apps/cli/src/effect-cli/commands/sets.ts +++ b/apps/cli/src/effect-cli/commands/sets.ts @@ -122,10 +122,10 @@ function helpOrRun( return internalHelp ? Console.log(SKILL_SETS_HELP) : action(input, json); } -const helpFlag = () => Flag.boolean(SETS_INTERNAL_HELP_FLAG); -const jsonFlag = () => Flag.boolean("json"); -const optionalString = (name: string) => Flag.string(name).pipe(Flag.optional); -const repeatedString = (name: string) => Flag.string(name).pipe(Flag.atLeast(0)); +const helpFlag = () => Flag.Boolean(SETS_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)); +const jsonFlag = () => Flag.Boolean("json").pipe(Flag.withDefault(false)); +const optionalString = (name: string) => Flag.String(name).pipe(Flag.optional); +const repeatedString = (name: string) => Flag.String(name).pipe(Flag.atLeast(0)); export function makeSkillSetsCommand(action: SkillSetsAction = makeLiveSkillSetsAction()) { const list = Command.make("list", { internalHelp: helpFlag(), json: jsonFlag() }, (input) => @@ -344,7 +344,7 @@ export function makeSkillSetsCommand(action: SkillSetsAction = makeLiveSkillSets return Command.make( "sets", - { internalHelp: Flag.boolean(SETS_INTERNAL_PARENT_HELP_FLAG) }, + { internalHelp: Flag.Boolean(SETS_INTERNAL_PARENT_HELP_FLAG).pipe(Flag.withDefault(false)) }, ({ internalHelp }) => (internalHelp ? Console.log(SKILL_SETS_HELP) : Effect.void), ).pipe( Command.withSubcommands([ diff --git a/apps/cli/src/effect-cli/commands/skills-activation.ts b/apps/cli/src/effect-cli/commands/skills-activation.ts index 23a58c0c..0a9fc096 100644 --- a/apps/cli/src/effect-cli/commands/skills-activation.ts +++ b/apps/cli/src/effect-cli/commands/skills-activation.ts @@ -33,11 +33,14 @@ const execute = Effect.fn("selftune.skills.activation")(function* (run: () => }); export function makeSkillsActivationCommands() { - const project = Flag.string("project").pipe(Flag.withDefault(".")); - const json = Flag.boolean("json"); - const task = Flag.string("task"); - const approval = { yes: Flag.boolean("yes"), dryRun: Flag.boolean("dry-run") }; - const lookup = { searchDirs: Flag.string("search-dir").pipe(Flag.atLeast(0)) }; + const project = Flag.String("project").pipe(Flag.withDefault(".")); + const json = Flag.Boolean("json").pipe(Flag.withDefault(false)); + const task = Flag.String("task"); + const approval = { + yes: Flag.Boolean("yes").pipe(Flag.withDefault(false)), + dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)), + }; + const lookup = { searchDirs: Flag.String("search-dir").pipe(Flag.atLeast(0)) }; const activate = Command.make( "activate", { @@ -46,9 +49,9 @@ export function makeSkillsActivationCommands() { json, ...approval, ...lookup, - ids: Flag.string("id").pipe(Flag.atLeast(0)), - set: Flag.string("set").pipe(Flag.optional), - harness: Flag.choice("harness", ["codex", "claude_code", "opencode", "openclaw", "pi"]), + ids: Flag.String("id").pipe(Flag.atLeast(0)), + set: Flag.String("set").pipe(Flag.optional), + harness: Flag.Literals("harness", ["codex", "claude_code", "opencode", "openclaw", "pi"]), }, (input) => execute(() => { @@ -93,7 +96,7 @@ export function makeSkillsActivationCommands() { json, ...approval, task: task.pipe(Flag.optional), - receipt: Flag.string("receipt").pipe(Flag.optional), + receipt: Flag.String("receipt").pipe(Flag.optional), }, (input) => execute(() => { @@ -112,7 +115,7 @@ export function makeSkillsActivationCommands() { "Remove only this task's temporary project paths; previews unless --yes.", ), ); - const load = Command.make("load", { id: Flag.string("id"), json, ...lookup }, (input) => + const load = Command.make("load", { id: Flag.String("id"), json, ...lookup }, (input) => execute(() => loadSkill(input.id, { searchDirs: input.searchDirs.length ? input.searchDirs : undefined }), ), diff --git a/apps/cli/src/effect-cli/commands/skills-search.ts b/apps/cli/src/effect-cli/commands/skills-search.ts index a214f150..2b0a9e0d 100644 --- a/apps/cli/src/effect-cli/commands/skills-search.ts +++ b/apps/cli/src/effect-cli/commands/skills-search.ts @@ -9,10 +9,10 @@ export function makeSkillsSearchCommand() { return Command.make( "search", { - query: Argument.string("query"), - limit: Flag.integer("limit").pipe(Flag.withDefault(5)), - searchDirs: Flag.string("search-dir").pipe(Flag.atLeast(0)), - json: Flag.boolean("json"), + query: Argument.String("query"), + limit: Flag.Int("limit").pipe(Flag.withDefault(5)), + searchDirs: Flag.String("search-dir").pipe(Flag.atLeast(0)), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, Effect.fn(function* ({ query, limit, searchDirs, json }) { const result = yield* searchLocalSkillsEffect({ diff --git a/apps/cli/src/effect-cli/commands/skills.ts b/apps/cli/src/effect-cli/commands/skills.ts index 6a66ffa7..e34dea9d 100644 --- a/apps/cli/src/effect-cli/commands/skills.ts +++ b/apps/cli/src/effect-cli/commands/skills.ts @@ -232,11 +232,11 @@ export function makeSkillsCommand(actions: SkillsCommandActions = makeLiveSkills const audit = Command.make( "audit", { - internalHelp: Flag.boolean(SKILLS_INTERNAL_AUDIT_HELP_FLAG), - minSessions: Flag.string("min-sessions").pipe(Flag.optional), - inactiveDays: Flag.string("inactive-days").pipe(Flag.optional), - searchDirs: Flag.string("search-dir").pipe(Flag.atLeast(0)), - json: Flag.boolean("json"), + internalHelp: Flag.Boolean(SKILLS_INTERNAL_AUDIT_HELP_FLAG).pipe(Flag.withDefault(false)), + minSessions: Flag.String("min-sessions").pipe(Flag.optional), + inactiveDays: Flag.String("inactive-days").pipe(Flag.optional), + searchDirs: Flag.String("search-dir").pipe(Flag.atLeast(0)), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, (input) => input.internalHelp @@ -253,20 +253,24 @@ export function makeSkillsCommand(actions: SkillsCommandActions = makeLiveSkills const quarantined = Command.make( "quarantined", { - internalHelp: Flag.boolean(SKILLS_INTERNAL_QUARANTINED_HELP_FLAG), - json: Flag.boolean("json"), + internalHelp: Flag.Boolean(SKILLS_INTERNAL_QUARANTINED_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, (input) => (input.internalHelp ? Console.log(SKILLS_HELP) : actions.quarantined(input.json)), ); const quarantine = Command.make( "quarantine", { - internalHelp: Flag.boolean(SKILLS_INTERNAL_QUARANTINE_HELP_FLAG), - skill: Flag.string("skill").pipe(Flag.optional), - skillPath: Flag.string("skill-path").pipe(Flag.optional), - yes: Flag.boolean("yes"), - dryRun: Flag.boolean("dry-run"), - json: Flag.boolean("json"), + internalHelp: Flag.Boolean(SKILLS_INTERNAL_QUARANTINE_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + skill: Flag.String("skill").pipe(Flag.optional), + skillPath: Flag.String("skill-path").pipe(Flag.optional), + yes: Flag.Boolean("yes").pipe(Flag.withDefault(false)), + dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, (input) => input.internalHelp @@ -284,10 +288,10 @@ export function makeSkillsCommand(actions: SkillsCommandActions = makeLiveSkills const restore = Command.make( "restore", { - internalHelp: Flag.boolean(SKILLS_INTERNAL_RESTORE_HELP_FLAG), - quarantineId: Flag.string("id").pipe(Flag.optional), - dryRun: Flag.boolean("dry-run"), - json: Flag.boolean("json"), + internalHelp: Flag.Boolean(SKILLS_INTERNAL_RESTORE_HELP_FLAG).pipe(Flag.withDefault(false)), + quarantineId: Flag.String("id").pipe(Flag.optional), + dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, (input) => input.internalHelp @@ -297,13 +301,15 @@ export function makeSkillsCommand(actions: SkillsCommandActions = makeLiveSkills const consolidate = Command.make( "consolidate", { - internalHelp: Flag.boolean(SKILLS_INTERNAL_CONSOLIDATE_HELP_FLAG), - skill: Flag.string("skill").pipe(Flag.optional), - allSafe: Flag.boolean("all-safe"), - searchDirs: Flag.string("search-dir").pipe(Flag.atLeast(0)), - yes: Flag.boolean("yes"), - dryRun: Flag.boolean("dry-run"), - json: Flag.boolean("json"), + internalHelp: Flag.Boolean(SKILLS_INTERNAL_CONSOLIDATE_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + skill: Flag.String("skill").pipe(Flag.optional), + allSafe: Flag.Boolean("all-safe").pipe(Flag.withDefault(false)), + searchDirs: Flag.String("search-dir").pipe(Flag.atLeast(0)), + yes: Flag.Boolean("yes").pipe(Flag.withDefault(false)), + dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, (input) => input.internalHelp @@ -322,11 +328,13 @@ export function makeSkillsCommand(actions: SkillsCommandActions = makeLiveSkills const consolidationRollback = Command.make( "consolidation-rollback", { - internalHelp: Flag.boolean(SKILLS_INTERNAL_CONSOLIDATION_ROLLBACK_HELP_FLAG), - decisionId: Flag.string("id").pipe(Flag.optional), - yes: Flag.boolean("yes"), - dryRun: Flag.boolean("dry-run"), - json: Flag.boolean("json"), + internalHelp: Flag.Boolean(SKILLS_INTERNAL_CONSOLIDATION_ROLLBACK_HELP_FLAG).pipe( + Flag.withDefault(false), + ), + decisionId: Flag.String("id").pipe(Flag.optional), + yes: Flag.Boolean("yes").pipe(Flag.withDefault(false)), + dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, (input) => input.internalHelp @@ -343,7 +351,7 @@ export function makeSkillsCommand(actions: SkillsCommandActions = makeLiveSkills return Command.make( "skills", - { internalHelp: Flag.boolean(SKILLS_INTERNAL_PARENT_HELP_FLAG) }, + { internalHelp: Flag.Boolean(SKILLS_INTERNAL_PARENT_HELP_FLAG).pipe(Flag.withDefault(false)) }, ({ internalHelp }) => (internalHelp ? Console.log(SKILLS_HELP) : Effect.void), ).pipe( Command.withSubcommands([ diff --git a/apps/cli/src/effect-cli/commands/sync.ts b/apps/cli/src/effect-cli/commands/sync.ts index 59fc268b..2ecdb7bb 100644 --- a/apps/cli/src/effect-cli/commands/sync.ts +++ b/apps/cli/src/effect-cli/commands/sync.ts @@ -123,7 +123,7 @@ export function makeLiveSyncAction( runSyncActionWithDependencies(input, jsonRequested, dependencies); } -const optionalString = (name: string) => Flag.string(name).pipe(Flag.optional); +const optionalString = (name: string) => Flag.String(name).pipe(Flag.optional); function decode(value: Option.Option): string | undefined { return decodeSyncInternalValue(Option.getOrUndefined(value)); @@ -150,16 +150,16 @@ export function makeSyncCommand(action: SyncAction = makeLiveSyncAction()) { repairedSkillLogPath: optionalString("repaired-skill-log"), repairedSessionsPath: optionalString("repaired-sessions-marker"), since: optionalString("since"), - dryRun: Flag.boolean("dry-run"), - force: Flag.boolean("force"), - skipClaude: Flag.boolean("no-claude"), - skipCodex: Flag.boolean("no-codex"), - skipOpenCode: Flag.boolean("no-opencode"), - skipOpenClaw: Flag.boolean("no-openclaw"), - skipPi: Flag.boolean("no-pi"), - skipRepair: Flag.boolean("no-repair"), - json: Flag.boolean("json"), - internalHelp: Flag.boolean(SYNC_INTERNAL_HELP_FLAG), + dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)), + force: Flag.Boolean("force").pipe(Flag.withDefault(false)), + skipClaude: Flag.Boolean("no-claude").pipe(Flag.withDefault(false)), + skipCodex: Flag.Boolean("no-codex").pipe(Flag.withDefault(false)), + skipOpenCode: Flag.Boolean("no-opencode").pipe(Flag.withDefault(false)), + skipOpenClaw: Flag.Boolean("no-openclaw").pipe(Flag.withDefault(false)), + skipPi: Flag.Boolean("no-pi").pipe(Flag.withDefault(false)), + skipRepair: Flag.Boolean("no-repair").pipe(Flag.withDefault(false)), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), + internalHelp: Flag.Boolean(SYNC_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), }, (input) => input.internalHelp diff --git a/apps/cli/src/effect-cli/commands/uninstall.ts b/apps/cli/src/effect-cli/commands/uninstall.ts index bd50355f..1cf6b488 100644 --- a/apps/cli/src/effect-cli/commands/uninstall.ts +++ b/apps/cli/src/effect-cli/commands/uninstall.ts @@ -82,16 +82,16 @@ export function makeUninstallCommand(action: UninstallAction = runLiveUninstall) return Command.make( "uninstall", { - internalHelp: Flag.boolean(UNINSTALL_INTERNAL_HELP_FLAG), - dryRun: Flag.boolean("dry-run").pipe( - Flag.withDescription("Preview what would be removed without deleting anything"), - ), - keepLogs: Flag.boolean("keep-logs").pipe( - Flag.withDescription("Preserve legacy JSONL telemetry logs"), - ), - npmUninstall: Flag.boolean("npm-uninstall").pipe( - Flag.withDescription("Also run 'npm uninstall -g selftune'"), - ), + internalHelp: Flag.Boolean(UNINSTALL_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), + dryRun: Flag.Boolean("dry-run") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Preview what would be removed without deleting anything")), + keepLogs: Flag.Boolean("keep-logs") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Preserve legacy JSONL telemetry logs")), + npmUninstall: Flag.Boolean("npm-uninstall") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Also run 'npm uninstall -g selftune'")), }, (input) => { if (input.internalHelp) return Console.log(UNINSTALL_HELP); diff --git a/apps/cli/src/effect-cli/commands/verify.ts b/apps/cli/src/effect-cli/commands/verify.ts index f584ee7b..623d45f5 100644 --- a/apps/cli/src/effect-cli/commands/verify.ts +++ b/apps/cli/src/effect-cli/commands/verify.ts @@ -104,25 +104,27 @@ export function makeVerifyCommand(action: VerifyAction = runVerifyAction) { return Command.make( "verify", { - internalHelp: Flag.boolean(VERIFY_INTERNAL_HELP_FLAG), - skillPath: Flag.string("skill-path").pipe( + internalHelp: Flag.Boolean(VERIFY_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), + skillPath: Flag.String("skill-path").pipe( Flag.withDescription("Path to a skill directory or SKILL.md file (required)"), Flag.optional, ), - agent: Flag.string("agent").pipe( + agent: Flag.String("agent").pipe( Flag.withDescription("Runtime agent to use for package evaluation once readiness passes"), Flag.optional, ), - evalSet: Flag.string("eval-set").pipe( + evalSet: Flag.String("eval-set").pipe( Flag.withDescription("Override the eval-set path instead of using the canonical one"), Flag.optional, ), - noAutoFix: Flag.boolean("no-auto-fix").pipe( - Flag.withDescription("Skip automatic evidence generation when readiness checks fail"), - ), - json: Flag.boolean("json").pipe( - Flag.withDescription("Emit readiness plus report data as JSON"), - ), + noAutoFix: Flag.Boolean("no-auto-fix") + .pipe(Flag.withDefault(false)) + .pipe( + Flag.withDescription("Skip automatic evidence generation when readiness checks fail"), + ), + json: Flag.Boolean("json") + .pipe(Flag.withDefault(false)) + .pipe(Flag.withDescription("Emit readiness plus report data as JSON")), }, (input) => { if (input.internalHelp) return Console.log(VERIFY_HELP); diff --git a/apps/cli/src/effect-cli/commands/watch.ts b/apps/cli/src/effect-cli/commands/watch.ts index 60ed7049..866576db 100644 --- a/apps/cli/src/effect-cli/commands/watch.ts +++ b/apps/cli/src/effect-cli/commands/watch.ts @@ -121,16 +121,16 @@ export function makeWatchCommand(action: WatchAction = makeLiveWatchAction()) { return Command.make( "watch", { - skillName: Flag.string("skill").pipe(Flag.optional), - skillPath: Flag.string("skill-path").pipe(Flag.optional), - windowSessions: Flag.integer("window").pipe(Flag.optional), - regressionThreshold: Flag.float("threshold").pipe(Flag.optional), - gradeRegressionThreshold: Flag.float("grade-threshold").pipe(Flag.optional), - autoRollback: Flag.boolean("auto-rollback"), - disableGradeWatch: Flag.boolean("no-grade-watch"), - syncFirst: Flag.boolean("sync-first"), - syncForce: Flag.boolean("sync-force"), - internalHelp: Flag.boolean(WATCH_INTERNAL_HELP_FLAG), + skillName: Flag.String("skill").pipe(Flag.optional), + skillPath: Flag.String("skill-path").pipe(Flag.optional), + windowSessions: Flag.Int("window").pipe(Flag.optional), + regressionThreshold: Flag.Finite("threshold").pipe(Flag.optional), + gradeRegressionThreshold: Flag.Finite("grade-threshold").pipe(Flag.optional), + autoRollback: Flag.Boolean("auto-rollback").pipe(Flag.withDefault(false)), + disableGradeWatch: Flag.Boolean("no-grade-watch").pipe(Flag.withDefault(false)), + syncFirst: Flag.Boolean("sync-first").pipe(Flag.withDefault(false)), + syncForce: Flag.Boolean("sync-force").pipe(Flag.withDefault(false)), + internalHelp: Flag.Boolean(WATCH_INTERNAL_HELP_FLAG).pipe(Flag.withDefault(false)), }, (input) => input.internalHelp diff --git a/apps/cli/src/effect-cli/commands/workflows.ts b/apps/cli/src/effect-cli/commands/workflows.ts index 4132afe4..144c2e33 100644 --- a/apps/cli/src/effect-cli/commands/workflows.ts +++ b/apps/cli/src/effect-cli/commands/workflows.ts @@ -122,7 +122,7 @@ function decodeNumber(value: Option.Option): number | undefined { return decoded === undefined ? undefined : Number(decoded); } -const optionalString = (name: string) => Flag.string(name).pipe(Flag.optional); +const optionalString = (name: string) => Flag.String(name).pipe(Flag.optional); export function makeWorkflowsCommand(action: WorkflowsAction = makeLiveWorkflowsAction()) { const discover = Command.make( @@ -131,7 +131,7 @@ export function makeWorkflowsCommand(action: WorkflowsAction = makeLiveWorkflows minOccurrences: optionalString("min-occurrences"), window: optionalString("window"), skill: optionalString("skill"), - json: Flag.boolean("json"), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, (input) => action( @@ -176,9 +176,9 @@ export function makeWorkflowsCommand(action: WorkflowsAction = makeLiveWorkflows outputDir: optionalString("output-dir"), skillName: optionalString("skill-name"), description: optionalString("description"), - write: Flag.boolean("write"), - force: Flag.boolean("force"), - json: Flag.boolean("json"), + write: Flag.Boolean("write").pipe(Flag.withDefault(false)), + force: Flag.Boolean("force").pipe(Flag.withDefault(false)), + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), }, (input) => action( @@ -200,7 +200,9 @@ export function makeWorkflowsCommand(action: WorkflowsAction = makeLiveWorkflows return Command.make( "workflows", - { internalHelp: Flag.boolean(WORKFLOWS_INTERNAL_PARENT_HELP_FLAG) }, + { + internalHelp: Flag.Boolean(WORKFLOWS_INTERNAL_PARENT_HELP_FLAG).pipe(Flag.withDefault(false)), + }, ({ internalHelp }) => (internalHelp ? Console.log(WORKFLOWS_HELP) : Effect.void), ).pipe( Command.withSubcommands([discover, save, scaffold]), diff --git a/apps/cli/src/effect-cli/program.ts b/apps/cli/src/effect-cli/program.ts index 75dd7335..b54ea7c0 100644 --- a/apps/cli/src/effect-cli/program.ts +++ b/apps/cli/src/effect-cli/program.ts @@ -43,7 +43,11 @@ export const makeEffectCliProgram = Effect.fn("selftune.cli.program")(function* args: ReadonlyArray, ) { const preparedArgs = yield* prepareEffectCliArguments(args); - yield* runLiveCommand(preparedArgs); + yield* runLiveCommand(preparedArgs).pipe( + Effect.catchTag("ShowHelp", (error) => + error.errors.length === 0 ? Effect.void : Effect.fail(error), + ), + ); }); export interface EffectCliTestProgramOptions { @@ -350,6 +354,9 @@ export function makeEffectCliTestProgram( return Effect.gen(function* () { const preparedArgs = yield* prepareEffectCliArguments(args); yield* runTestCommand(preparedArgs).pipe( + Effect.catchTag("ShowHelp", (error) => + error.errors.length === 0 ? Effect.void : Effect.fail(error), + ), Effect.provide(FetchHttpClient.layer), Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ); diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 65c04b8f..b84f1405 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@selftune/desktop", - "version": "0.4.12", + "version": "0.5.1", "private": true, "description": "Native desktop control plane for SelfTune skill observability and improvement", "homepage": "https://selftune.dev", @@ -33,7 +33,7 @@ "@selftune/config": "workspace:*", "@sentry/electron": "^7.8.0", "@zip.js/zip.js": "^2.8.17", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", "electron-log": "^5.4.3", "electron-updater": "^6.6.2" }, diff --git a/apps/desktop/scripts/build-sidecar.ts b/apps/desktop/scripts/build-sidecar.ts index ebb43bf6..4f2febc9 100644 --- a/apps/desktop/scripts/build-sidecar.ts +++ b/apps/desktop/scripts/build-sidecar.ts @@ -156,9 +156,6 @@ const target = compileTarget(process.env.BUN_TARGET); const windowsTarget = target?.startsWith("bun-windows-") ?? process.platform === "win32"; const executable = windowsTarget ? "selftune.exe" : "selftune"; const executablePath = join(resourceRoot, executable); -const reportWorkerExecutable = windowsTarget - ? "selftune-report-worker.exe" - : "selftune-report-worker"; const prebuiltExecutable = process.env.SELFTUNE_PREBUILT_SIDECAR?.trim(); if (prebuiltExecutable) { @@ -175,7 +172,7 @@ if (prebuiltExecutable) { const compile: Bun.CompileBuildOptions = { outfile: executablePath }; if (target) compile.target = target; const result = await Bun.build({ - entrypoints: [join(selfTuneRoot, "apps/cli/src/main.ts")], + entrypoints: [join(desktopRoot, "scripts/sidecar-entry.ts")], define: { SELFTUNE_DESKTOP_SIDECAR_BUILD: "true" }, minify: true, compile, @@ -186,23 +183,8 @@ if (prebuiltExecutable) { } } -const reportWorkerCompile: Bun.CompileBuildOptions = { - outfile: join(resourceRoot, reportWorkerExecutable), -}; -if (target) reportWorkerCompile.target = target; -const reportWorkerResult = await Bun.build({ - entrypoints: [join(selfTuneRoot, "apps/local/src/report-worker.ts")], - minify: true, - compile: reportWorkerCompile, -}); - -if (!reportWorkerResult.success) { - throw new Error(reportWorkerResult.logs.map((entry) => entry.message).join("\n")); -} - if (!windowsTarget) { await chmod(executablePath, 0o755); - await chmod(join(resourceRoot, reportWorkerExecutable), 0o755); } await stageDuckDbNativeBindings(target); await cp(join(selfTuneRoot, "apps/local-dashboard/dist"), join(resourceRoot, "dashboard"), { diff --git a/apps/desktop/scripts/sidecar-entry.test.ts b/apps/desktop/scripts/sidecar-entry.test.ts new file mode 100644 index 00000000..1f52e570 --- /dev/null +++ b/apps/desktop/scripts/sidecar-entry.test.ts @@ -0,0 +1,39 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as Schema from "effect/Schema"; + +test("Desktop entry dispatches reports without loading the public CLI workflow", () => { + const root = mkdtempSync(join(tmpdir(), "selftune-shared-executable-")); + const output = join(root, "report.json"); + try { + const child = Bun.spawnSync( + [ + process.execPath, + join(import.meta.dir, "sidecar-entry.ts"), + "__selftune_report_worker", + "portfolio-audit", + JSON.stringify({ + configRoot: root, + searchDirs: [], + storagePaths: { + configRoot: root, + localDatabasePath: join(root, "selftune.db"), + localAnalyticsPath: join(root, "observability.duckdb"), + }, + }), + output, + ], + { stdout: "pipe", stderr: "pipe" }, + ); + expect(child.exitCode, new TextDecoder().decode(child.stderr)).toBe(0); + const report = Schema.decodeUnknownSync( + Schema.fromJsonString(Schema.Struct({ installed_count: Schema.Number })), + )(readFileSync(output, "utf8")); + expect(report.installed_count).toBe(0); + expect(new TextDecoder().decode(child.stdout)).toBe(""); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/desktop/scripts/sidecar-entry.ts b/apps/desktop/scripts/sidecar-entry.ts new file mode 100644 index 00000000..780be0c2 --- /dev/null +++ b/apps/desktop/scripts/sidecar-entry.ts @@ -0,0 +1,8 @@ +import { INTERNAL_REPORT_WORKER_COMMAND } from "../../local/src/report-worker-command.js"; + +if (process.argv[2] === INTERNAL_REPORT_WORKER_COMMAND) { + process.argv.splice(2, 1); + await import("../../local/src/report-worker.js"); +} else { + await import("../../cli/src/main.js"); +} diff --git a/apps/desktop/scripts/smoke-packaged.ts b/apps/desktop/scripts/smoke-packaged.ts index b29c10ad..8b002b9a 100644 --- a/apps/desktop/scripts/smoke-packaged.ts +++ b/apps/desktop/scripts/smoke-packaged.ts @@ -14,7 +14,7 @@ import * as Schema from "effect/Schema"; import { readServerManifest } from "@selftune/local/local-runtime"; import { PENDING_WINDOW_IPC_TEST_DOCUMENT } from "../src/desktop-test-contract"; -class PackagedSmokeFailure extends Schema.TaggedErrorClass()( +class PackagedSmokeFailure extends Schema.TaggedError()( "PackagedSmokeFailure", { operation: Schema.String, diff --git a/apps/desktop/scripts/smoke-sidecar.ts b/apps/desktop/scripts/smoke-sidecar.ts index 464ea8fc..aac24b09 100644 --- a/apps/desktop/scripts/smoke-sidecar.ts +++ b/apps/desktop/scripts/smoke-sidecar.ts @@ -17,13 +17,10 @@ import { import { INTERNAL_PACKAGE_BUNDLE_SMOKE_COMMAND } from "@selftune/runtime/remote-library/package-bundle-collector-command"; import { createLineBuffer, parseReadyPort } from "../src/main/sidecar-protocol"; -class SidecarSmokeFailure extends Schema.TaggedErrorClass()( - "SidecarSmokeFailure", - { - operation: Schema.String, - message: Schema.String, - }, -) {} +class SidecarSmokeFailure extends Schema.TaggedError()("SidecarSmokeFailure", { + operation: Schema.String, + message: Schema.String, +}) {} const LocalAuthRecord = Schema.Struct({ version: Schema.Literal(1), diff --git a/apps/desktop/src/main/background-service.ts b/apps/desktop/src/main/background-service.ts index 316da914..06b6fc44 100644 --- a/apps/desktop/src/main/background-service.ts +++ b/apps/desktop/src/main/background-service.ts @@ -24,7 +24,7 @@ export interface BackgroundServiceOptions { type BackgroundServiceAction = "install" | "restart" | "start" | "status" | "stop" | "uninstall"; -export class BackgroundServiceFailure extends Schema.TaggedErrorClass()( +export class BackgroundServiceFailure extends Schema.TaggedError()( "BackgroundServiceFailure", { operation: Schema.String, diff --git a/apps/desktop/src/main/desktop-runtime.test.ts b/apps/desktop/src/main/desktop-runtime.test.ts index 6912dd00..d897af42 100644 --- a/apps/desktop/src/main/desktop-runtime.test.ts +++ b/apps/desktop/src/main/desktop-runtime.test.ts @@ -99,6 +99,109 @@ async function loadService( } describe("scoped desktop runtime", () => { + it("leaves the recovery screen when the supervised service becomes healthy later", async () => { + const events: string[] = []; + const failed = Promise.withResolvers(); + const observedRecovery = Promise.withResolvers(); + let healthy = false; + let statusReads = 0; + let starts = 0; + const active = connection("1", "os-service"); + const baseCallbacks = callbacks(events); + const runtime = ManagedRuntime.make( + makeDesktopRuntimeLayer( + dependencies({ + canManageBackgroundService: true, + monitorIntervalMs: 2, + monitorFailureThreshold: 1, + fetch: async () => new Response(null, { status: healthy ? 200 : 503 }), + attachSupervisedSidecar: async () => active, + getBackgroundStatus: () => + ++statusReads === 1 + ? Effect.succeed({ + detail: [], + pid: active.pid, + platform: "darwin", + registered: true, + running: true, + supported: true, + }) + : Effect.fail(new Error("Service status timed out")), + startSidecar: async () => { + starts += 1; + return active; + }, + }), + { + ...baseCallbacks, + onRecoveryFailed: async (cause) => { + await baseCallbacks.onRecoveryFailed(cause); + failed.resolve(); + }, + onConnectionActivated: async (value) => { + await baseCallbacks.onConnectionActivated(value); + if (healthy) observedRecovery.resolve(); + }, + }, + ), + ); + try { + const service = await loadService(runtime); + await runtime.runPromise(service.boot); + await failed.promise; + healthy = true; + const recovered = await Promise.race([ + observedRecovery.promise.then(() => true), + Bun.sleep(150).then(() => false), + ]); + expect(recovered).toBe(true); + expect(events.filter((event) => event.startsWith("rebind:"))).toEqual([ + "rebind:1", + "rebind:1", + ]); + expect(starts).toBe(0); + } finally { + await runtime.dispose(); + } + }); + it.each([true, false])( + "rechecks health before replacing the runtime (restored: %s)", + async (restored) => { + const events: string[] = []; + const checkedAgain = Promise.withResolvers(); + let probes = 0; + let starts = 0; + const runtime = ManagedRuntime.make( + makeDesktopRuntimeLayer( + dependencies({ + monitorFailureThreshold: 1, + monitorIntervalMs: 2, + fetch: async () => { + probes += 1; + if (probes === 1 || (!restored && starts === 1)) + return new Response(null, { status: 503 }); + checkedAgain.resolve(); + return new Response(null, { status: 200 }); + }, + startSidecar: async () => connection(String(++starts)), + }), + callbacks(events), + ), + ); + try { + const service = await loadService(runtime); + await runtime.runPromise(service.boot); + await checkedAgain.promise; + await runtime.runPromise(service.connection); + expect(starts).toBe(restored ? 1 : 2); + expect(events.filter((event) => event.startsWith("rebind:"))).toEqual( + restored ? ["rebind:1"] : ["rebind:1", "rebind:2"], + ); + } finally { + await runtime.dispose(); + } + }, + ); it("boots one desktop child and stops only that owned child on disposal", async () => { const events: string[] = []; const stopped: string[] = []; diff --git a/apps/desktop/src/main/desktop-runtime.ts b/apps/desktop/src/main/desktop-runtime.ts index ddf1540b..f31d05db 100644 --- a/apps/desktop/src/main/desktop-runtime.ts +++ b/apps/desktop/src/main/desktop-runtime.ts @@ -40,6 +40,7 @@ export interface DesktopRuntimeCallbacks { type DesktopRuntimeLogDetails = | DesktopRuntimeError | ResetStateResult + | { readonly recoveryReason: string } | { readonly cleanupFailure: DesktopRuntimeError; readonly rebindFailure: DesktopRuntimeError } | { readonly attempt: number; @@ -78,7 +79,7 @@ export interface DesktopRuntimeDependencies { readonly writeBackgroundPreference: (enabled: boolean) => void; } -export class DesktopRuntimeError extends Schema.TaggedErrorClass()( +export class DesktopRuntimeError extends Schema.TaggedError()( "DesktopRuntimeError", { operation: Schema.String, @@ -336,6 +337,10 @@ export function makeDesktopRuntimeLayer( }); if (!claimed) return; + yield* log("warn", "SelfTune local runtime recovery requested", { + recoveryReason: cause instanceof Error ? cause.message : String(cause), + }); + const recovery = yield* Effect.result(runMutation(recoverManagedConnection(generation))); if (Result.isSuccess(recovery)) return; @@ -580,6 +585,15 @@ export function makeDesktopRuntimeLayer( return; } const activeConnection = snapshot.connection; + if (yield* probeConnection(activeConnection)) { + yield* Ref.update(state, (current) => ({ + ...current, + misses: 0, + recoveringGeneration: null, + })); + yield* log("info", "SelfTune local runtime health restored; keeping current window"); + return; + } if (isCliOwnedStandalone(activeConnection)) { const reattached = yield* attempt( "reattach to CLI-owned runtime", @@ -957,6 +971,34 @@ export function makeDesktopRuntimeLayer( const generation = snapshot.generation; const connection = snapshot.connection; const healthy = yield* probeConnection(connection); + if (healthy && snapshot.recoveringGeneration === generation) { + yield* runMutation( + Effect.gen(function* () { + const current = yield* Ref.get(state); + if ( + current.quitting || + current.generation !== generation || + current.recoveringGeneration !== generation + ) + return; + const attached = + connection.supervision === "os-service" + ? yield* attempt( + "reattach recovered background service", + dependencies.attachSupervisedSidecar, + ) + : connection; + if (!attached) return; + yield* activateConnection(attached); + yield* log("info", "SelfTune reconnected after delayed local service recovery"); + }), + ).pipe( + Effect.catch((failure) => + log("warn", "SelfTune could not reconnect the recovered local service", failure), + ), + ); + return; + } const shouldRecover = yield* Ref.modify(state, (current) => { if ( current.quitting || diff --git a/apps/desktop/src/main/managed-connection-lifecycle.ts b/apps/desktop/src/main/managed-connection-lifecycle.ts index 5c613e9b..6fdfe049 100644 --- a/apps/desktop/src/main/managed-connection-lifecycle.ts +++ b/apps/desktop/src/main/managed-connection-lifecycle.ts @@ -21,7 +21,7 @@ export interface ManagedConnectionReplacementResult { readonly connection: Connection; } -export class ManagedConnectionTransitionFailure extends Schema.TaggedErrorClass()( +export class ManagedConnectionTransitionFailure extends Schema.TaggedError()( "ManagedConnectionTransitionFailure", { attempt: Schema.Number, diff --git a/apps/desktop/src/main/runtime-install.ts b/apps/desktop/src/main/runtime-install.ts index 4291ee31..57e61e41 100644 --- a/apps/desktop/src/main/runtime-install.ts +++ b/apps/desktop/src/main/runtime-install.ts @@ -13,7 +13,7 @@ import { verifyRuntimeDirectory, } from "./runtime-integrity"; -export class RuntimeInstallFailure extends Schema.TaggedErrorClass()( +export class RuntimeInstallFailure extends Schema.TaggedError()( "RuntimeInstallFailure", { message: Schema.String }, ) {} diff --git a/apps/local-dashboard/package.json b/apps/local-dashboard/package.json index ec8f48b1..92e90959 100644 --- a/apps/local-dashboard/package.json +++ b/apps/local-dashboard/package.json @@ -28,7 +28,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", "lucide-react": "^0.577.0", "next-themes": "^0.4.6", "react": "^19.1.0", diff --git a/apps/local-dashboard/src/App.tsx b/apps/local-dashboard/src/App.tsx index 04c56327..7c83bf43 100644 --- a/apps/local-dashboard/src/App.tsx +++ b/apps/local-dashboard/src/App.tsx @@ -53,6 +53,7 @@ import { getLocalAppCoreNavigation, isLocalAppCoreRouteActive, LOCAL_APP_CORE_ROUTE_MANIFEST, + LOCAL_APP_CORE_ROUTES, LOCAL_APP_CORE_ROUTE_REGISTRY, matchLocalAppCoreShellRoute, } from "@/shared-app-routes"; @@ -220,6 +221,8 @@ function DashboardShell({ runtime }: { runtime: ServerRuntimeProfile }) { toast.success("selftune Cloud connected", { description: `Cloud inventory updated: ${firstBackup.uploaded} reported, ${firstBackup.unchanged} unchanged.`, }); + } else if (firstBackup.status === "not_configured") { + toast.info("SelfTune Cloud connected", { description: firstBackup.message }); } else { toast.warning("selftune Cloud connected", { description: `The first inventory update did not finish: ${firstBackup.message}`, @@ -227,6 +230,7 @@ function DashboardShell({ runtime }: { runtime: ServerRuntimeProfile }) { } }, manage: () => navigate("/settings?section=remote-library"), + openWorkspace: () => navigate(LOCAL_APP_CORE_ROUTES.collaboration.path), openDashboard: async () => { const url = "https://cloud.selftune.dev"; if (window.selftuneDesktop) { diff --git a/apps/local-dashboard/src/api.ts b/apps/local-dashboard/src/api.ts index 613a8342..f68c0a81 100644 --- a/apps/local-dashboard/src/api.ts +++ b/apps/local-dashboard/src/api.ts @@ -1,6 +1,12 @@ import { decodeResponse, portfolioRequest, responseError, schemaRequest } from "./dashboard-http"; export { DashboardApiError } from "./dashboard-http"; import { Schema } from "effect"; +import { LibrarySnapshot as LibrarySnapshotSchema } from "@selftune/control-plane/domain/library"; +import { LibraryIndexPage } from "@selftune/control-plane/library-index"; +import { + CompactLibrarySnapshot, + expandLibrarySnapshot, +} from "@selftune/control-plane/library-transport"; import { HealthResponse } from "@selftune/runtime/dashboard-contract/health"; import { ApplyOnboardingResponse, @@ -181,10 +187,62 @@ export function finalizeCloudBillingCheckout( ); } -export async function fetchLibrary(): Promise { - const res = await fetch(`${BASE}/api/v2/library`); - if (!res.ok) throw new Error(`API error: ${res.status} ${res.statusText}`); - return res.json(); +export async function fetchLibrary(selection?: { + skillId: string; + snapshot?: string; +}): Promise { + const params = new URLSearchParams({ format: "compact" }); + if (selection) { + params.set("skill_id", selection.skillId); + if (selection.snapshot) params.set("snapshot", selection.snapshot); + } + const snapshot = await schemaRequest( + `${BASE}/api/v2/library?${params}`, + Schema.Union([CompactLibrarySnapshot, LibrarySnapshotSchema]), + ); + return "format" in snapshot ? expandLibrarySnapshot(snapshot) : snapshot; +} + +export async function fetchLibraryIndex( + search: string, + signal?: AbortSignal, +): Promise { + const params = new URLSearchParams({ view: "index", limit: "50", search }); + const first = await schemaRequest( + `${BASE}/api/v2/library?${params}`, + LibraryIndexPage, + undefined, + signal, + ); + const skills = [...first.skills]; + let offset = first.nextOffset; + while (offset !== null) { + params.set("offset", String(offset)); + params.set("snapshot", first.generatedAt); + // oxlint-disable-next-line no-await-in-loop -- Pages are generation-checked and bounded; do not fan out the full graph. + const page = await schemaRequest( + `${BASE}/api/v2/library?${params}`, + LibraryIndexPage, + undefined, + signal, + ); + if ( + page.generatedAt !== first.generatedAt || + page.total !== first.total || + (page.nextOffset !== null && page.nextOffset <= offset) + ) { + throw new Error("The library changed while loading. Refresh and try again."); + } + skills.push(...page.skills); + offset = page.nextOffset; + } + if ( + skills.length !== first.total || + new Set(skills.map((skill) => skill.skillId)).size !== skills.length + ) { + throw new Error("The library index is incomplete. Refresh and try again."); + } + return { ...first, skills, nextOffset: null }; } export function backupLibrarySkill(skillId: string): Promise<{ diff --git a/apps/local-dashboard/src/components/SkillEvaluations.tsx b/apps/local-dashboard/src/components/SkillEvaluations.tsx new file mode 100644 index 00000000..f00a9658 --- /dev/null +++ b/apps/local-dashboard/src/components/SkillEvaluations.tsx @@ -0,0 +1,34 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { EvaluationHistory } from "@selftune/control-plane/domain/evaluation-report"; +import { SkillEvaluations as EvaluationView } from "@selftune/dashboard-core/screens/skill-report"; +import { schemaRequest } from "../dashboard-http"; +import { useSettings } from "../hooks/useSettings"; + +export function SkillEvaluations({ skillName }: { skillName: string }) { + const client = useQueryClient(); + const key = ["evaluation-history", skillName]; + const path = `/api/v2/evaluations?skill=${encodeURIComponent(skillName)}`; + const query = useQuery({ + queryKey: key, + queryFn: () => schemaRequest(path, EvaluationHistory), + staleTime: 5000, + refetchInterval: 30000, + }); + const settings = useSettings(); + const upload = useMutation({ + mutationFn: async (file: File) => { + if (file.size > 2 * 1024 * 1024) throw new Error("Report exceeds 2 MiB"); + return schemaRequest(path, EvaluationHistory, await file.text()); + }, + onSuccess: (history) => client.setQueryData(key, history), + }); + return ( + upload.mutate(file)} + /> + ); +} diff --git a/apps/local-dashboard/src/components/SkillHistory.test.tsx b/apps/local-dashboard/src/components/SkillHistory.test.tsx new file mode 100644 index 00000000..3e7731d3 --- /dev/null +++ b/apps/local-dashboard/src/components/SkillHistory.test.tsx @@ -0,0 +1,57 @@ +// @vitest-environment jsdom +import { afterEach, expect, it, vi } from "vitest"; +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { SkillHistory } from "./SkillHistory"; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +it("shows comparisons and requires confirmation before restoring with the reviewed hash", async () => { + const revision = (number: number) => ({ + package_path: "/skills/brand", + revision: number, + content_hash: `hash-${number}`, + captured_at: "2026-09-08T08:00:00Z", + reason: "observed", + restored_from: null, + }); + const fetcher = vi.fn(async (input: string, init?: RequestInit) => { + if (init?.method === "POST") return Response.json(revision(3)); + if (input.includes("revision=")) + return Response.json({ + files: [ + { + path: "SKILL.md", + change: "added", + before: null, + after: "Approved brand voice", + beforeMode: null, + afterMode: 420, + }, + ], + }); + return Response.json({ revisions: [revision(2), revision(1)] }); + }); + vi.stubGlobal("fetch", fetcher); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render( + + + , + ); + fireEvent.click(await screen.findByRole("button", { name: /Revision 1 ·/ })); + expect(await screen.findByText("Approved brand voice")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Restore revision 1" })); + expect(fetcher.mock.calls.filter(([, init]) => init?.method === "POST")).toHaveLength(0); + fireEvent.click(screen.getByRole("button", { name: "Confirm restore" })); + await waitFor(() => + expect(fetcher.mock.calls.filter(([, init]) => init?.method === "POST")).toHaveLength(1), + ); + expect(fetcher.mock.calls.find(([, init]) => init?.method === "POST")?.[1]?.body).toBe( + JSON.stringify({ path: "/skills/brand", revision: 1, expectedHash: "hash-2" }), + ); + client.clear(); +}); diff --git a/apps/local-dashboard/src/components/SkillHistory.tsx b/apps/local-dashboard/src/components/SkillHistory.tsx new file mode 100644 index 00000000..552fe2fc --- /dev/null +++ b/apps/local-dashboard/src/components/SkillHistory.tsx @@ -0,0 +1,186 @@ +import { useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Schema } from "effect"; +import { + Button, + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@selftune/ui/primitives"; +import { schemaRequest } from "../dashboard-http"; +import { useSSEConnected } from "../lib/reactivity"; + +const Revision = Schema.Struct({ + package_path: Schema.String, + revision: Schema.Number, + content_hash: Schema.String, + captured_at: Schema.String, + reason: Schema.String, + restored_from: Schema.NullOr(Schema.Number), +}); +const History = Schema.Struct({ revisions: Schema.Array(Revision) }); +const Diff = Schema.Struct({ + files: Schema.Array( + Schema.Struct({ + path: Schema.String, + change: Schema.String, + before: Schema.NullOr(Schema.String), + after: Schema.NullOr(Schema.String), + beforeMode: Schema.NullOr(Schema.Number), + afterMode: Schema.NullOr(Schema.Number), + }), + ), +}); + +export function SkillHistory({ skillPath }: { skillPath: string }) { + const client = useQueryClient(); + const sseConnected = useSSEConnected(); + const [selected, setSelected] = useState(null); + const [confirmRestore, setConfirmRestore] = useState(false); + const [restoreHash, setRestoreHash] = useState(null); + const [before, setBefore] = useState(null); + const endpoint = `/api/v2/skill-history?path=${encodeURIComponent(skillPath)}`; + const history = useQuery({ + queryKey: ["skill-history", skillPath, before], + queryFn: ({ signal }) => + schemaRequest(`${endpoint}${before ? `&before=${before}` : ""}`, History, undefined, signal), + staleTime: 10_000, + refetchInterval: sseConnected ? false : 5_000, + }); + const diff = useQuery({ + queryKey: ["skill-history-diff", skillPath, selected], + enabled: selected !== null, + queryFn: () => schemaRequest(`${endpoint}&revision=${selected}`, Diff), + }); + const latest = history.data?.revisions[0]; + const restore = useMutation({ + mutationFn: () => { + if (!latest || !selected || before || !restoreHash) + throw new Error("Return to latest history before restoring."); + return schemaRequest( + "/api/v2/skill-history", + Revision, + JSON.stringify({ + path: latest.package_path, + revision: selected, + expectedHash: restoreHash, + }), + ); + }, + onSuccess: () => { + setSelected(null); + setConfirmRestore(false); + void client.invalidateQueries({ queryKey: ["skill-history"] }); + void client.invalidateQueries({ queryKey: ["library"] }); + }, + }); + return ( + + + Local revision history + + Automatic snapshots while SelfTune is running. Revision numbers are local; team releases + stay explicit. + + + + {history.isPending &&

Loading history…

} + {history.error &&

{history.error.message}

} + {history.data?.revisions.length === 0 &&

No revisions recorded yet.

} +
+ {history.data?.revisions.map((entry) => ( + + ))} +
+
+ {before && ( + + )} + {history.data?.revisions.length === 50 && ( + + )} +
+ {diff.isFetching && selected !== null &&

Loading changes…

} + {diff.error &&

{diff.error.message}

} + {selected !== null && + diff.data?.files.map((file) => ( +
+ + {file.path} · {file.change} + +
+ {[ + { label: "Before", value: file.before }, + { label: "After", value: file.after }, + ].map((side) => ( +
+

{side.label}

+
+                      {side.value ?? "File absent or binary"}
+                    
+
+ ))} +
+
+ ))} + {selected !== null && latest && selected !== latest.revision && !before && ( +
+ {confirmRestore ? ( + <> +

+ Restore revision {selected}? Current files will be preserved in history. This + replaces the installed skill folder. +

+ + + + ) : ( + + )} +
+ )} + {restore.error &&

{restore.error.message}

} +
+
+ ); +} diff --git a/apps/local-dashboard/src/components/SkillPackageInspector.test.tsx b/apps/local-dashboard/src/components/SkillPackageInspector.test.tsx new file mode 100644 index 00000000..2b753936 --- /dev/null +++ b/apps/local-dashboard/src/components/SkillPackageInspector.test.tsx @@ -0,0 +1,45 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { SkillPackageViewer } from "@selftune/ui/components"; + +afterEach(cleanup); +describe("package Markdown inspection", () => { + it("renders Markdown by default, exposes source, and opens package-relative links", () => { + const onSelect = vi.fn(); + const content = + "---\nname: example\n---\n# Package guide\n\nRead [reference](references/guide.md)."; + render( + , + ); + expect(screen.getByRole("heading", { name: "Package guide" })).not.toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "reference" })); + expect(onSelect).toHaveBeenCalledWith("references/guide.md"); + fireEvent.click(screen.getByRole("button", { name: "Source" })); + expect(screen.queryByRole("heading", { name: "Package guide" })).toBeNull(); + expect(screen.getByLabelText("File content").querySelector("diffs-container")).not.toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Preview" })); + expect(screen.getByRole("heading", { name: "Package guide" })).not.toBeNull(); + }); + it("does not execute HTML or load remote images", () => { + const { container } = render( + alert(1)\n\n![tracker](https://example.com/pixel.png)\n\n[bad](javascript:alert(1))" + } + onSelect={vi.fn()} + />, + ); + expect(container.querySelector("script")).toBeNull(); + expect(container.querySelector("img")).toBeNull(); + expect(container.querySelector('[href^="javascript:"]')).toBeNull(); + expect(screen.getByText(/not loaded in preview/)).not.toBeNull(); + }); +}); diff --git a/apps/local-dashboard/src/components/SkillPackageInspector.tsx b/apps/local-dashboard/src/components/SkillPackageInspector.tsx new file mode 100644 index 00000000..3a3b112a --- /dev/null +++ b/apps/local-dashboard/src/components/SkillPackageInspector.tsx @@ -0,0 +1,94 @@ +import { useMemo, useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { SkillPackageViewer } from "@selftune/ui/components"; +import { + Button, + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@selftune/ui/primitives"; +import { SkillPackageIndex, SkillPackageFile } from "@selftune/runtime/skill-package-inspector"; +import { schemaRequest } from "../dashboard-http"; +import { useTheme } from "@selftune/dashboard-core/chrome"; + +export function SkillPackageInspector({ skillPath }: { readonly skillPath: string }) { + const { resolvedTheme } = useTheme(); + const [selected, setSelected] = useState(null); + const endpoint = `/api/v2/skill-package?skillPath=${encodeURIComponent(skillPath)}`; + const index = useQuery({ + queryKey: ["skill-package", skillPath], + queryFn: () => schemaRequest(endpoint, SkillPackageIndex), + }); + const paths = useMemo(() => index.data?.files.map((file) => file.path) ?? [], [index.data]); + const path = + selected && paths.includes(selected) + ? selected + : paths.includes("SKILL.md") + ? "SKILL.md" + : (paths[0] ?? null); + const file = useQuery({ + queryKey: ["skill-package-file", skillPath, path], + enabled: path !== null, + queryFn: () => + schemaRequest(`${endpoint}&file=${encodeURIComponent(path ?? "")}`, SkillPackageFile), + }); + const reason = file.data?.reason; + const message = + file.error?.message ?? + (reason === "too_large" + ? "This file exceeds the 256 KiB preview limit." + : reason === "binary" + ? "Binary file. Text preview is not available." + : reason === "symlink" + ? "Symbolic link. The inspector does not follow links inside a package." + : undefined); + return ( + + +
+ Package contents + +
+ + Browse the installed files. Read-only; nothing is uploaded or executed. Git data and + node_modules are excluded. + +
+ + {index.isPending ? ( +

Loading package files…

+ ) : index.error ? ( +

{index.error.message}

+ ) : paths.length === 0 ? ( +

No files found in this package.

+ ) : ( + + )} + {index.data?.limited ? ( +

+ Showing a bounded listing of up to 2,000 entries and 20 directory levels. +

+ ) : null} +
+
+ ); +} diff --git a/apps/local-dashboard/src/components/settings/BillingSettingsPanel.test.tsx b/apps/local-dashboard/src/components/settings/BillingSettingsPanel.test.tsx index f2df5d4c..4e3a3ffd 100644 --- a/apps/local-dashboard/src/components/settings/BillingSettingsPanel.test.tsx +++ b/apps/local-dashboard/src/components/settings/BillingSettingsPanel.test.tsx @@ -65,6 +65,25 @@ afterEach(() => { }); describe("BillingSettingsPanel", () => { + it("shows prices before linking and carries the selected plan to Cloud sign-in", async () => { + const openExternal = vi.fn(); + renderPanel({ cloudConfigured: false, openExternal }); + expect(screen.getByLabelText("$19/month")).not.toBeNull(); + expect(screen.getByLabelText("$49/month")).not.toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Choose Team" })); + await waitFor(() => + expect(openExternal).toHaveBeenCalledWith("https://cloud.selftune.dev/?billing=team&seats=3"), + ); + }); + + it("does not offer a Stripe portal for internal Team access", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue( + Response.json(status({ plan: "team", subscriptionStatus: "active" })), + ); + renderPanel(); + await screen.findByText("Current plan: Team"); + expect(screen.queryByRole("button", { name: "Manage subscription" })).toBeNull(); + }); it("offers Connect Cloud while Desktop is not linked", () => { const fetch = vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Unexpected request")); const onConnect = vi.fn(); @@ -92,7 +111,7 @@ describe("BillingSettingsPanel", () => { }); renderPanel({ openExternal }); await screen.findByText("Current plan: Community"); - expect(screen.getByText("$12/month")).not.toBeNull(); + expect(screen.getByLabelText("$12/month")).not.toBeNull(); fireEvent.change(screen.getByLabelText("Team seats"), { target: { value: "7" } }); const [pro, team] = screen.getAllByRole("button", { name: "Choose plan" }); if (!pro || !team) throw new Error("Expected Pro and Team choices"); @@ -115,12 +134,12 @@ describe("BillingSettingsPanel", () => { ) .mockImplementation(async () => Response.json(status())); renderPanel(); - expect((await screen.findByRole("alert")).textContent).toBe("Cloud offline"); + expect((await screen.findByRole("alert")).textContent).toContain("Cloud offline"); expect(screen.queryByRole("button", { name: "Connect Cloud" })).toBeNull(); fireEvent.click(screen.getByRole("button", { name: /retry/i })); await screen.findByText("Current plan: Community"); expect(fetch).toHaveBeenCalledTimes(2); - expect(screen.queryByRole("alert")).toBeNull(); + expect(screen.queryByText("Cloud offline")).toBeNull(); }); it("opens the portal for an existing subscription instead of creating checkout", async () => { diff --git a/apps/local-dashboard/src/components/settings/BillingSettingsPanel.tsx b/apps/local-dashboard/src/components/settings/BillingSettingsPanel.tsx index 148aea5c..4bc5b540 100644 --- a/apps/local-dashboard/src/components/settings/BillingSettingsPanel.tsx +++ b/apps/local-dashboard/src/components/settings/BillingSettingsPanel.tsx @@ -1,9 +1,16 @@ -import { ExternalLinkIcon, LogInIcon, RefreshCwIcon } from "lucide-react"; import { useState } from "react"; import { toast } from "sonner"; - -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; +import { billingPlans } from "@selftune/runtime/billing-plans"; +import { PricingCards } from "@selftune/dashboard-core/screens/settings"; +import { + Alert, + AlertDescription, + AlertTitle, + Button, + Field, + FieldLabel, + Input, +} from "@selftune/ui/primitives"; import { useCloudBillingCheckout, useCloudBillingPortal, @@ -18,13 +25,6 @@ export interface BillingSettingsPanelProps { readonly openExternal?: (url: string) => void | Promise; } -function planName(id: "free" | "pro" | "team" | "enterprise"): string { - if (id === "free") return "Community"; - if (id === "enterprise") return "Enterprise"; - return id === "pro" ? "Pro" : "Team"; -} - -/** Desktop's Settings tab for the Cloud-owned billing journey. */ export function BillingSettingsPanel({ cloudConfigured, active, @@ -32,185 +32,176 @@ export function BillingSettingsPanel({ onConnect, openExternal, }: BillingSettingsPanelProps) { - const cloudBilling = useCloudBillingStatus(cloudConfigured && active); - const cloudBillingCheckout = useCloudBillingCheckout(); - const cloudBillingPortal = useCloudBillingPortal(); - const [teamSeats, setTeamSeats] = useState(1); + const billing = useCloudBillingStatus(cloudConfigured && active); + const checkout = useCloudBillingCheckout(); + const portal = useCloudBillingPortal(); + const [teamSeats, setTeamSeats] = useState(3); + const [checkoutOpened, setCheckoutOpened] = useState(false); + const data = cloudConfigured ? billing.data : undefined; + const currentName = + data?.availablePlans.find((plan) => plan.id === data.plan)?.name ?? + (data?.plan === "free" + ? "Community" + : data?.plan === "enterprise" + ? "Enterprise" + : data?.plan === "team" + ? "Team" + : "Pro"); + const busy = checkout.isPending || portal.isPending; + const grantedAccess = data && data.plan !== "free" && !data.hasStripeCustomer; - async function openBillingUrl(url: string) { - if (openExternal) { - await openExternal(url); - return; + async function openUrl(url: string) { + try { + if (openExternal) await openExternal(url); + else if (window.selftuneDesktop) await window.selftuneDesktop.openExternal(url); + else window.open(url, "_blank", "noopener,noreferrer"); + } catch { + toast.error("Could not open your browser. Please try again."); } - if (window.selftuneDesktop) { - await window.selftuneDesktop.openExternal(url); - return; - } - window.open(url, "_blank", "noopener,noreferrer"); } - - function startCheckout(plan: "pro" | "team", seats?: number) { - cloudBillingCheckout.mutate(seats === undefined ? { plan } : { plan, seats }, { - onSuccess: ({ url }) => void openBillingUrl(url), - onError: (error) => - toast.error("Checkout could not be started", { - description: error instanceof Error ? error.message : String(error), - }), - }); + function showError(error: Error) { + toast.error("Billing could not be opened", { description: error.message }); } - - function openBillingPortal() { - cloudBillingPortal.mutate(undefined, { - onSuccess: ({ url }) => void openBillingUrl(url), - onError: (error) => - toast.error("Billing portal could not be opened", { - description: error instanceof Error ? error.message : String(error), - }), - }); + function openPortal() { + portal.mutate(undefined, { onSuccess: ({ url }) => void openUrl(url), onError: showError }); + } + function choose(plan: "pro" | "team") { + const seats = Math.min(1000, Math.max(3, Math.trunc(teamSeats) || 3)); + setCheckoutOpened(true); + if (!cloudConfigured) { + void openUrl( + `https://cloud.selftune.dev/?billing=${plan}${plan === "team" ? `&seats=${seats}` : ""}`, + ); + } else if ( + data?.hasStripeCustomer && + data.plan !== "free" && + data.subscriptionStatus !== "canceled" + ) + openPortal(); + else + checkout.mutate(plan === "team" ? { plan, seats } : { plan }, { + onSuccess: ({ url }) => void openUrl(url), + onError: showError, + }); } return ( -
-
-

+
+
+

Billing

- Manage your SelfTune Cloud workspace plan and subscription. + Use SelfTune locally for free. Add controlled sharing or bring your team.

{!cloudConfigured ? ( -
-
-
-

Connect SelfTune Cloud

-

- Link a Cloud account to view your plan and securely manage billing. Your local - Library remains available without Cloud. -

-
- -
-
- ) : cloudBilling.isLoading ? ( -
- Loading billing… -
- ) : cloudBilling.isError || !cloudBilling.data ? ( -
-

- {cloudBilling.error instanceof Error - ? cloudBilling.error.message - : "Billing is unavailable right now."} -

-
- ) : ( -
-
-
-

- Current plan:{" "} - {cloudBilling.data.availablePlans.find( - (plan) => plan.id === cloudBilling.data?.plan, - )?.name ?? planName(cloudBilling.data.plan)} -

-

- {cloudBilling.data.subscriptionStatus === "none" - ? "No active subscription" - : cloudBilling.data.subscriptionStatus} -

-
- {cloudBilling.data.plan !== "free" && cloudBilling.data.canManageBilling ? ( - + + + ) : data ? ( +
+ Current plan: {currentName} + + {grantedAccess + ? "Internal access" + : data.subscriptionStatus === "none" + ? "No active subscription" + : `Subscription: ${data.subscriptionStatus}`} + +
+ {data.hasStripeCustomer && data.canManageBilling ? ( + ) : null} -
- {!cloudBilling.data.canManageBilling ? ( -

- Only workspace owners can manage billing. -

- ) : null} -
- {cloudBilling.data.availablePlans.map((plan) => { - const current = plan.id === cloudBilling.data?.plan; - const checkoutPlan = plan.id; - return ( -
-

{plan.name}

-

- {plan.price ? `${plan.price}${plan.period ?? ""}` : "Contact us"} -

-

{plan.description}

- {checkoutPlan === "team" && !current && cloudBilling.data?.plan === "free" ? ( - - ) : null} - {checkoutPlan === "pro" || checkoutPlan === "team" ? ( - - ) : null} -
- ); - })} +
+ ) : ( +

Loading billing…

)} + {checkoutOpened ? ( +

+ {data && (data.subscriptionStatus === "active" || data.subscriptionStatus === "trialing") + ? "Your plan is active. You can return to sharing." + : "Finish checkout in your browser, then return here. Your plan refreshes while Billing is open. If you are not linked yet, connect the same Cloud workspace afterward."} +

+ ) : null} + {data && !data.canManageBilling ? ( +

Only workspace owners can manage billing.

+ ) : null} + + plan.id === "team" && !grantedAccess && (!data || data.plan === "free") ? ( + + Team seats + setTeamSeats(Number(event.target.value))} + /> +

+ 3 members included; $15/month per additional member. +

+
+ ) : null + } + renderAction={(plan) => { + if (plan.id !== "pro" && plan.id !== "team") + return Free on this device; + const current = + plan.id === data?.plan && + (data.subscriptionStatus === "active" || data.subscriptionStatus === "trialing"); + return ( + + ); + }} + />
); } diff --git a/apps/local-dashboard/src/dashboard-host-sharing.test.tsx b/apps/local-dashboard/src/dashboard-host-sharing.test.tsx index 5c2ea9a1..2b09eabc 100644 --- a/apps/local-dashboard/src/dashboard-host-sharing.test.tsx +++ b/apps/local-dashboard/src/dashboard-host-sharing.test.tsx @@ -75,7 +75,7 @@ describe("local project and Library sharing capabilities", () => { }, }); } - expect(result.current.library.backup?.access).toBe("unavailable"); + expect(result.current.library.backup?.access).toBe("available"); expect(result.current.projects.publishRelease).toMatchObject({ preview: { access: "available" }, execute: { access: "available" }, diff --git a/apps/local-dashboard/src/dashboard-host.test.ts b/apps/local-dashboard/src/dashboard-host.test.ts index fbfc8bf5..13d22a41 100644 --- a/apps/local-dashboard/src/dashboard-host.test.ts +++ b/apps/local-dashboard/src/dashboard-host.test.ts @@ -444,6 +444,23 @@ describe("localDashboardModules", () => { }, }); expect(mapped.skills[0]?.sources).toHaveLength(1); + const firstQuarantine = portfolio.quarantined[0]; + const firstAudit = portfolio.audit.skills[0]; + if (!firstQuarantine || !firstAudit) throw new Error("Expected portfolio fixture rows"); + const duplicates = mapLocalLibraryInventory( + snapshot, + intelligence, + { + ...portfolio, + quarantined: [...portfolio.quarantined, { ...firstQuarantine, quarantine_id: "later" }], + audit: { + ...portfolio.audit, + skills: [...portfolio.audit.skills, { ...firstAudit, reason: "later" }], + }, + }, + mergeHarnesses, + ); + expect(duplicates).toEqual(mapped); const analyticsWithoutObservations: AnalyticsResponse = { pass_rate_trend: [], diff --git a/apps/local-dashboard/src/dashboard-host.ts b/apps/local-dashboard/src/dashboard-host.ts index f7a2a199..2f080247 100644 --- a/apps/local-dashboard/src/dashboard-host.ts +++ b/apps/local-dashboard/src/dashboard-host.ts @@ -1,4 +1,6 @@ // oxlint-disable max-lines -- Host capability composition is intentionally centralized here. +import { SkillHistory } from "./components/SkillHistory"; +import { SkillPackageInspector } from "./components/SkillPackageInspector"; import { capabilitiesFromModule, type DashboardLibraryActions, @@ -27,7 +29,8 @@ import type { } from "@selftune/dashboard-core/models"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { z } from "zod"; -import { fetchAnalytics } from "./api"; +import { fetchLibrary } from "./api"; +import { useLocalLibraryInventory } from "./use-local-library-inventory"; import { useManagePlugin, usePlugins } from "./hooks/usePlugins"; import { useApplySkillSourceMerge, @@ -40,7 +43,6 @@ import { } from "./hooks/useLibrary"; import { useBulkQuarantinePortfolioSkills, - usePortfolio, useQuarantinePortfolioSkill, useRestorePortfolioSkill, } from "./hooks/usePortfolio"; @@ -104,7 +106,6 @@ import { connectionNames, isLocalSkillCategoryId, localMergeConnections, - mapLocalLibraryInventory, resolveLocalMergeRequest, } from "./local-library-model"; import type { @@ -224,44 +225,7 @@ const LOCAL_FEATURES: DashboardHostModules["capability"]["features"] = { runtimeStatus: { access: "available" }, }; -function useLocalLibraryInventory() { - const query = useLibrary(); - const intelligence = useSkillIntelligence(); - const portfolio = usePortfolio(); - const settings = useSettings(); - const analytics = useQuery({ - queryKey: ["analytics"], - queryFn: fetchAnalytics, - staleTime: 30_000, - }); - const data = query.data - ? mapLocalLibraryInventory( - query.data, - intelligence.data ?? null, - portfolio.data ?? null, - settings.data?.harnesses ?? [], - analytics.data ?? null, - ) - : null; - - return { - data, - isLoading: query.isLoading, - error: - query.error instanceof Error ? query.error.message : query.error ? String(query.error) : null, - refresh: async () => { - await Promise.all([ - query.refetch(), - intelligence.refetch(), - portfolio.refetch(), - analytics.refetch(), - ]); - }, - }; -} - function useLocalLibraryActions(): DashboardLibraryActions { - const library = useLibrary(); const intelligence = useSkillIntelligence(); const settings = useSettings(); const updateCategory = useUpdateSkillClassification(); @@ -456,7 +420,7 @@ function useLocalLibraryActions(): DashboardLibraryActions { access: "available", isPending: prepareConsolidation.isPending || decideDecision.isPending, async execute(skillId) { - const skill = library.data?.skills.find((candidate) => candidate.skillId === skillId); + const skill = (await fetchLibrary({ skillId })).skills[0]; if (!skill) throw new Error("Refresh the Library and review this consolidation again."); const recommendation = recommendLibraryConsolidation(skill); if (!recommendation) { @@ -483,7 +447,7 @@ function useLocalLibraryActions(): DashboardLibraryActions { remove: { access: "available", async execute(skillId) { - const skill = library.data?.skills.find((candidate) => candidate.skillId === skillId); + const skill = (await fetchLibrary({ skillId })).skills[0]; if (!skill) throw new Error("Refresh the Library and try removing this skill again."); const locations = skill.locations .filter( @@ -1400,6 +1364,8 @@ export function createLocalDashboardModules( assignments: LOCAL_ASSIGNED_SKILL_SETS, }, skills: { + History: SkillHistory, + PackageInspector: SkillPackageInspector, host, library: LOCAL_LIBRARY, decisions: LOCAL_DECISIONS, diff --git a/apps/local-dashboard/src/dashboard-http.ts b/apps/local-dashboard/src/dashboard-http.ts index 5a5f4008..0f1f46b7 100644 --- a/apps/local-dashboard/src/dashboard-http.ts +++ b/apps/local-dashboard/src/dashboard-http.ts @@ -74,11 +74,13 @@ export async function schemaRequest( path: string, schema: Schema.Codec, body?: string, + signal?: AbortSignal, ): Promise { const response = await fetch(path, { method: body === undefined ? "GET" : "POST", headers: body === undefined ? undefined : { "Content-Type": "application/json" }, body, + signal, }); const text = await response.text(); if (!response.ok) throw responseError(response, text); diff --git a/apps/local-dashboard/src/hooks/useLibrary.ts b/apps/local-dashboard/src/hooks/useLibrary.ts index 69049d36..08e60cef 100644 --- a/apps/local-dashboard/src/hooks/useLibrary.ts +++ b/apps/local-dashboard/src/hooks/useLibrary.ts @@ -6,6 +6,7 @@ import { applySkillSourceUpdate, backupLibrarySkill, fetchLibrary, + fetchLibraryIndex, installLibrarySkill, shareLibrarySkill, prepareSkillSourceMerge, @@ -19,11 +20,23 @@ import { useSSEConnected, } from "../lib/reactivity"; -export function useLibrary() { +export function useLibrary(options: { enabled?: boolean } = {}) { const sseConnected = useSSEConnected(); return useQuery({ - queryKey: ["library"], - queryFn: fetchLibrary, + queryKey: ["library", "full"], + queryFn: () => fetchLibrary(), + enabled: options.enabled, + staleTime: 10_000, + refetchInterval: sseConnected ? false : 60_000, + }); +} + +export function useLibraryIndex(search: string, enabled: boolean) { + const sseConnected = useSSEConnected(); + return useQuery({ + queryKey: ["library", "index", search], + queryFn: ({ signal }) => fetchLibraryIndex(search, signal), + enabled, staleTime: 10_000, refetchInterval: sseConnected ? false : 60_000, }); diff --git a/apps/local-dashboard/src/hooks/useSettings.ts b/apps/local-dashboard/src/hooks/useSettings.ts index cafe138a..f934621a 100644 --- a/apps/local-dashboard/src/hooks/useSettings.ts +++ b/apps/local-dashboard/src/hooks/useSettings.ts @@ -96,6 +96,8 @@ export function useLinkCloudAccount() { }, onSuccess: ({ settings }) => { queryClient.setQueryData(["settings"], settings); + void queryClient.invalidateQueries({ queryKey: ["cloud-billing"] }); + void queryClient.invalidateQueries({ queryKey: ["workspace-members"] }); void queryClient.invalidateQueries({ queryKey: ["remote-library-status"] }); }, }); @@ -107,6 +109,8 @@ export function useCloudBillingStatus(enabled: boolean) { queryFn: fetchCloudBillingStatus, enabled, staleTime: 15_000, + refetchInterval: enabled ? 15_000 : false, + refetchOnWindowFocus: "always", }); } diff --git a/apps/local-dashboard/src/lib/reactivity.ts b/apps/local-dashboard/src/lib/reactivity.ts index 22e08626..531d24de 100644 --- a/apps/local-dashboard/src/lib/reactivity.ts +++ b/apps/local-dashboard/src/lib/reactivity.ts @@ -28,7 +28,7 @@ export { /** React Query knowledge stays at the dashboard boundary, not in the resource contract. */ export const dashboardQueryKeys = { [DashboardResource.libraryInventory]: [["library"], ["portfolio"]], - [DashboardResource.libraryDetail]: [["skill-report"]], + [DashboardResource.libraryDetail]: [["skill-report"], ["skill-history"]], [DashboardResource.skillIntelligence]: [["skill-intelligence"]], [DashboardResource.overview]: [["overview"]], [DashboardResource.sourceUpdate]: [["source-update"]], diff --git a/apps/local-dashboard/src/library-index-api.test.ts b/apps/local-dashboard/src/library-index-api.test.ts new file mode 100644 index 00000000..e0a6d8f5 --- /dev/null +++ b/apps/local-dashboard/src/library-index-api.test.ts @@ -0,0 +1,51 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { fetchLibraryIndex } from "./api"; + +afterEach(() => vi.unstubAllGlobals()); +function page(ids: string[], nextOffset: number | null, generatedAt = "one") { + return { + generatedAt, + counts: { total: 3, active: 3, library: 0, draft: 0, archived: 0 }, + total: 3, + nextOffset, + skills: ids.map((skillId) => ({ + skillId, + name: skillId, + lifecycle: "active", + lastUsedAt: null, + lastModifiedAt: "2026-10-20", + updateStatus: "unknown", + origins: [], + connections: [], + revisionHashes: [], + installedCount: 0, + consolidationAvailable: false, + })), + }; +} +describe("library index API", () => { + it("collects all bounded pages with a stable snapshot and passes cancellation", async () => { + const fetch = vi + .fn() + .mockResolvedValueOnce(Response.json(page(["a", "b"], 2))) + .mockResolvedValueOnce(Response.json(page(["c"], null))); + vi.stubGlobal("fetch", fetch); + const controller = new AbortController(); + const result = await fetchLibraryIndex("a path", controller.signal); + expect(result.skills.map((skill) => skill.skillId)).toEqual(["a", "b", "c"]); + expect(fetch.mock.calls[1]?.[0]).toContain("snapshot=one"); + expect(fetch.mock.calls[0]?.[1]?.signal).toBe(controller.signal); + }); + it("rejects mixed snapshots, duplicate rows, and non-advancing cursors", async () => { + for (const last of [page(["c"], null, "two"), page(["a"], null), page(["c"], 2)]) { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce(Response.json(page(["a", "b"], 2))) + .mockResolvedValueOnce(Response.json(last)), + ); + await expect(fetchLibraryIndex("")).rejects.toThrow(/library/); + } + }); +}); diff --git a/apps/local-dashboard/src/library-index.test.tsx b/apps/local-dashboard/src/library-index.test.tsx new file mode 100644 index 00000000..a6eb88b3 --- /dev/null +++ b/apps/local-dashboard/src/library-index.test.tsx @@ -0,0 +1,103 @@ +// @vitest-environment jsdom +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { ReactNode } from "react"; +import type { LibrarySnapshot } from "./types"; +import { libraryIndexPage } from "@selftune/control-plane/library-index"; +import { useLocalLibraryInventory } from "./use-local-library-inventory"; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +const location = { + sourceKind: "installed", + packagePath: "/projects/one/.agents/skills/marketing", + skillPath: "/projects/one/.agents/skills/marketing/SKILL.md", + harness: "codex", + scope: "project", + projectRoot: "/projects/one", + active: true, + modifiedAt: "2026-10-20T00:00:00Z", + lastUsedAt: null, + origin: null, + updateStatus: "untracked", +} satisfies LibrarySnapshot["skills"][number]["locations"][number]; +const snapshot: LibrarySnapshot = { + generatedAt: "2026-10-20T00:00:00Z", + counts: { total: 1, active: 1, library: 0, archived: 0, draft: 0 }, + skills: [ + { + skillId: "marketing", + name: "marketing", + lifecycle: "active", + origins: [], + locations: [ + location, + { + ...location, + packagePath: "/projects/two/marketing", + skillPath: "/projects/two/marketing/SKILL.md", + }, + ], + revisions: [{ contentHash: "hash", locations: [location] }], + updateStatus: "untracked", + lastUsedAt: null, + lastModifiedAt: location.modifiedAt, + }, + ], +}; +function setup() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } }); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const reads: URL[] = []; + vi.stubGlobal("fetch", async (input: string) => { + const url = new URL(input, "http://localhost"); + if (url.pathname === "/api/v2/library") { + reads.push(url); + return Response.json( + url.searchParams.get("view") === "index" + ? libraryIndexPage(snapshot, { offset: 0, limit: 50, search: "" }) + : snapshot, + ); + } + return Response.json({ error: "No optional report fixture" }, { status: 503 }); + }); + return { ...renderHook(() => useLocalLibraryInventory(), { wrapper }), reads }; +} +describe("lazy library inventory", () => { + it("does not request the full graph for browsing, and hydrates all selected locations", async () => { + const hook = setup(); + await waitFor(() => expect(hook.result.current.data?.skills).toHaveLength(1)); + expect(hook.reads.every((url) => url.searchParams.get("view") === "index")).toBe(true); + expect(hook.result.current.data?.skills[0]?.detailsLoaded).toBe(false); + await act(async () => { + const detail = await hook.result.current.loadDetails?.("marketing"); + expect(detail?.locations).toHaveLength(2); + expect(detail?.contextEntries).toHaveLength(2); + }); + expect(hook.reads.at(-1)?.searchParams.get("skill_id")).toBe("marketing"); + expect(hook.reads.at(-1)?.searchParams.get("snapshot")).toBe(snapshot.generatedAt); + expect(hook.result.current.data?.skills[0]?.locations).toHaveLength(2); + hook.unmount(); + }); + it("loads the complete inventory only for an explicit whole-library journey", async () => { + const hook = setup(); + await waitFor(() => expect(hook.result.current.data?.skills).toHaveLength(1)); + await act(async () => { + await hook.result.current.loadAll?.(); + }); + await waitFor(() => expect(hook.result.current.searchHandled).toBe(false)); + expect( + hook.reads.some( + (url) => url.searchParams.get("view") !== "index" && !url.searchParams.has("skill_id"), + ), + ).toBe(true); + expect(hook.result.current.data?.skills[0]?.locations).toHaveLength(2); + hook.unmount(); + }); +}); diff --git a/apps/local-dashboard/src/local-library-index-model.ts b/apps/local-dashboard/src/local-library-index-model.ts new file mode 100644 index 00000000..eac820a3 --- /dev/null +++ b/apps/local-dashboard/src/local-library-index-model.ts @@ -0,0 +1,97 @@ +import type { LibraryIndexPage } from "@selftune/control-plane/library-index"; +import type { LibraryInventoryModel } from "@selftune/dashboard-core/models"; +import { LOCAL_LIBRARY_CATEGORY_OPTIONS, uniqueSources } from "./local-library-model"; +import type { + AnalyticsResponse, + HarnessConnection, + PortfolioResponse, + SkillIntelligenceReport, +} from "./types"; + +export function mapLocalLibraryIndex( + index: LibraryIndexPage, + intelligence: SkillIntelligenceReport | null, + portfolio: PortfolioResponse | null, + harnesses: readonly HarnessConnection[], + analytics: AnalyticsResponse | null, +): LibraryInventoryModel { + const classifications = new Map( + intelligence?.classifications.map((item) => [item.skill_id.toLowerCase(), item]), + ); + const connections = new Map(harnesses.map((item) => [item.id, item])); + const trends = new Map( + analytics?.skill_trigger_trends?.map((item) => [item.skill_name.toLowerCase(), item.points]), + ); + const counts = new Map( + analytics?.skill_rankings.map((item) => [item.skill_name.toLowerCase(), item.triggered_count]), + ); + const quarantined = new Map(); + for (const item of portfolio?.quarantined ?? []) + if (item.status === "quarantined" && !quarantined.has(item.skill_name.toLowerCase())) + quarantined.set(item.skill_name.toLowerCase(), item.quarantine_id); + const candidates = new Map(); + for (const item of portfolio?.audit.skills ?? []) + if (!candidates.has(item.skill_name.toLowerCase())) + candidates.set( + item.skill_name.toLowerCase(), + item.classification === "inactive_candidate" && item.recommendation === "review_quarantine", + ); + return { + categoryOptions: LOCAL_LIBRARY_CATEGORY_OPTIONS, + skills: index.skills.map((skill) => { + const classification = classifications.get(skill.skillId.toLowerCase()); + return { + id: skill.skillId, + name: skill.name, + lifecycle: skill.lifecycle, + status: skill.lifecycle === "active" ? "Ready" : "Stored", + updateStatus: skill.updateStatus, + detailsLoaded: false, + consolidationAvailable: skill.consolidationAvailable, + archiveAvailable: + skill.installedCount === 1 && candidates.get(skill.name.toLowerCase()) === true, + category: classification + ? { + id: classification.category, + label: classification.category_label, + inferredId: classification.inferred_category, + source: classification.source, + confidence: classification.confidence, + reason: classification.reason, + overrideReason: classification.override_reason, + matchedTerms: classification.matched_terms, + } + : null, + sources: uniqueSources( + skill.origins.map((origin) => ({ + kind: origin.kind === "github" ? "github" : origin.kind === "local" ? "local" : "other", + label: origin.label, + href: origin.url, + path: origin.packagePath, + })), + ), + locations: skill.connections.map((location) => ({ + id: `${location.harness}:${location.packagePath}`, + label: location.scope === "global" ? "Global" : location.scope, + path: location.packagePath, + sourceKind: location.sourceKind, + connection: location.harness + ? (connections.get(location.harness)?.name ?? location.harness) + : null, + connectionIcon: location.harness + ? (connections.get(location.harness)?.icon ?? null) + : null, + removable: location.removable, + })), + revisionHashes: [...skill.revisionHashes], + lastUsedAt: skill.lastUsedAt, + modifiedAt: skill.lastModifiedAt, + instructionBytes: skill.instructionBytes ?? null, + triggerTrend: trends.get(skill.name.toLowerCase()) ?? [], + lifetimeTriggerCount: counts.get(skill.name.toLowerCase()) ?? (analytics ? 0 : null), + restoreId: quarantined.get(skill.name.toLowerCase()) ?? null, + detailHref: `/skills/${encodeURIComponent(skill.name)}`, + }; + }), + }; +} diff --git a/apps/local-dashboard/src/local-library-model.ts b/apps/local-dashboard/src/local-library-model.ts index fa92f88a..c41b41d7 100644 --- a/apps/local-dashboard/src/local-library-model.ts +++ b/apps/local-dashboard/src/local-library-model.ts @@ -31,7 +31,7 @@ const LOCAL_LIBRARY_CATEGORY_LABELS: Record = { general: "General", }; -const LOCAL_LIBRARY_CATEGORY_OPTIONS = Object.entries(LOCAL_LIBRARY_CATEGORY_LABELS).map( +export const LOCAL_LIBRARY_CATEGORY_OPTIONS = Object.entries(LOCAL_LIBRARY_CATEGORY_LABELS).map( ([id, label]) => ({ id, label }), ); @@ -101,7 +101,7 @@ function canonicalSourceKey(source: LibrarySourceModel): string { return `${source.kind}:${source.label.trim().toLowerCase()}`; } -function uniqueSources(sources: readonly LibrarySourceModel[]): LibrarySourceModel[] { +export function uniqueSources(sources: readonly LibrarySourceModel[]): LibrarySourceModel[] { const unique = new Map(); for (const source of sources) { const key = canonicalSourceKey(source); @@ -116,11 +116,9 @@ function projectRootForLocation( ): string | null { if (location.projectRoot) return location.projectRoot; return ( - projectRoots - .filter( - (root) => location.packagePath === root || location.packagePath.startsWith(`${root}/`), - ) - .sort((left, right) => right.length - left.length)[0] ?? null + projectRoots.find( + (root) => location.packagePath === root || location.packagePath.startsWith(`${root}/`), + ) ?? null ); } @@ -150,6 +148,19 @@ export function mapLocalLibraryInventory( ranking.triggered_count, ]), ); + const quarantinedByName = new Map(); + for (const entry of portfolio?.quarantined ?? []) { + const name = entry.skill_name.toLowerCase(); + if (entry.status === "quarantined" && !quarantinedByName.has(name)) + quarantinedByName.set(name, entry); + } + const auditByName = new Map(); + const auditByPath = new Map(); + for (const entry of portfolio?.audit.skills ?? []) { + const name = entry.skill_name.toLowerCase(); + if (!auditByName.has(name)) auditByName.set(name, entry); + if (!auditByPath.has(entry.skill_path)) auditByPath.set(entry.skill_path, entry); + } return { categoryOptions: LOCAL_LIBRARY_CATEGORY_OPTIONS, @@ -160,16 +171,10 @@ export function mapLocalLibraryInventory( location.projectRoot ? [location.projectRoot] : [], ), ), - ]; + ].toSorted((left, right) => right.length - left.length); const classification = classificationById.get(skill.skillId.toLowerCase()); - const archived = portfolio?.quarantined.find( - (entry) => - entry.skill_name.toLowerCase() === skill.name.toLowerCase() && - entry.status === "quarantined", - ); - const archiveEvidence = portfolio?.audit.skills.find( - (entry) => entry.skill_name.toLowerCase() === skill.name.toLowerCase(), - ); + const archived = quarantinedByName.get(skill.name.toLowerCase()); + const archiveEvidence = auditByName.get(skill.name.toLowerCase()); const installedLocations = skill.locations.filter( (location) => location.sourceKind === "installed", ); @@ -201,7 +206,7 @@ export function mapLocalLibraryInventory( })) : []; const inactiveEvidence = installedLocations.map((location) => - portfolio?.audit.skills.find((entry) => entry.skill_path === location.skillPath), + auditByPath.get(location.skillPath), ); return { id: skill.skillId, diff --git a/apps/local-dashboard/src/local-library-transfer-actions.ts b/apps/local-dashboard/src/local-library-transfer-actions.ts index 80758c7f..1f795030 100644 --- a/apps/local-dashboard/src/local-library-transfer-actions.ts +++ b/apps/local-dashboard/src/local-library-transfer-actions.ts @@ -26,7 +26,7 @@ export function useLocalLibraryTransferActions(): Pick< ); return { backup: - destination === "self_hosted" + destination !== "unconfigured" ? { access: "available", isPending: backup.isPending, @@ -41,10 +41,7 @@ export function useLocalLibraryTransferActions(): Pick< } : { access: "unavailable", - reason: - destination === "managed_cloud" - ? "SelfTune Cloud stores privacy-safe inventory metadata, not complete library backups." - : "Connect a self-hosted server to back up complete skill contents.", + reason: "Connect Cloud or a self-hosted server to back up skill files.", }, share: destination !== "unconfigured" @@ -59,7 +56,7 @@ export function useLocalLibraryTransferActions(): Pick< } : { access: "upgrade", - href: "/settings?section=remote-library", + href: "/settings?section=billing", }, installTargets: [ { id: "codex", label: "Codex" }, diff --git a/apps/local-dashboard/src/pages/LocalSkillReport.test.tsx b/apps/local-dashboard/src/pages/LocalSkillReport.test.tsx new file mode 100644 index 00000000..f7b42f87 --- /dev/null +++ b/apps/local-dashboard/src/pages/LocalSkillReport.test.tsx @@ -0,0 +1,136 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen, within } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { + DashboardHostProvider, + type DashboardLibraryContribution, +} from "@selftune/dashboard-core/host"; +import { LocalSkillReport } from "@selftune/dashboard-core/screens/skill-report"; +import type { LibrarySkillModel } from "@selftune/dashboard-core/models"; +import { localDashboardModules } from "../dashboard-host"; + +afterEach(cleanup); +const skill: LibrarySkillModel = { + id: "marketing", + name: "marketing", + lifecycle: "active", + status: "Ready", + updateStatus: "current", + sources: [{ kind: "github", label: "marketing-skills" }], + revisionHashes: ["hash"], + locations: [ + { + id: "installed", + label: "Global", + path: "/skills/marketing", + sourceKind: "installed", + connection: "Codex", + connectionIcon: { src: "/codex.svg", fit: "contain", inset: "sm" }, + removable: true, + }, + { + id: "backup", + label: "Backup", + path: "/archive/marketing", + sourceKind: "archived", + removable: false, + }, + ], + onDemandSource: { + skillPath: "/skills/marketing/SKILL.md", + packagePath: "/skills/marketing", + contentHash: "hash", + }, + contextEntries: [ + { + harness: "codex", + scope: "global", + projectRoot: null, + path: "/skills/marketing/SKILL.md", + state: "active", + metadata: { + name: "marketing", + description: "Write marketing campaigns.", + disableModelInvocation: false, + originalSkillPath: "/skills/marketing/SKILL.md", + }, + }, + ], +}; + +function setup(error: string | null = null) { + const execute = vi.fn().mockResolvedValue({ succeeded: 1, failed: 0, receipts: [] }); + const library: DashboardLibraryContribution = { + access: "available", + useInventory: () => ({ + data: error ? null : { skills: [skill], categoryOptions: [] }, + isLoading: false, + error, + refresh: vi.fn(), + }), + useActions: () => ({ + moveToLibraryMany: { access: "available", execute }, + updateCategory: { access: "unavailable", reason: "test" }, + openLocation: { access: "unavailable", reason: "test" }, + previewSourceUpdate: { access: "unavailable", reason: "test" }, + applySourceUpdate: { access: "unavailable", reason: "test" }, + mergeConnections: [], + prepareMerge: { access: "unavailable", reason: "test" }, + applyMerge: { access: "unavailable", reason: "test" }, + archive: { access: "unavailable", reason: "test" }, + remove: { access: "unavailable", reason: "test" }, + decideRemoval: { access: "unavailable", reason: "test" }, + restore: { access: "unavailable", reason: "test" }, + create: { access: "unavailable", reason: "test" }, + primary: [], + }), + }; + render( + + Skills} + checks={24} + sessions={12} + activity={() =>

Recorded activity

} + files={

Package viewer

} + history={

Revision history

} + testing={

Testing controls

} + diagnostics={

Diagnostics

} + /> +
, + ); + return execute; +} + +it("opens on local activity and navigates to files without mounting testing", () => { + setup(); + expect(screen.getByText("Write marketing campaigns.")).toBeTruthy(); + expect(screen.getByText("Recorded activity")).toBeTruthy(); + expect(screen.queryByText("Testing controls")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "View files" })); + expect(screen.getByRole("tabpanel", { name: "Files" }).textContent).toBe("Package viewer"); +}); + +it("shows real installations and previews context before any movement", () => { + const execute = setup(); + fireEvent.click(screen.getByRole("tab", { name: "Installations" })); + expect(screen.getByText("/skills/marketing")).toBeTruthy(); + expect(screen.queryByText("/archive/marketing")).toBeNull(); + expect(document.querySelector('img[src="/codex.svg"]')).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Choose skills" })); + fireEvent.click(screen.getByRole("checkbox", { name: "Keep marketing on demand" })); + const dialog = within(screen.getByRole("dialog")); + expect(dialog.getByText("Freed")).toBeTruthy(); + expect(dialog.getByText("1 skill will load only on request")).toBeTruthy(); + expect(execute).not.toHaveBeenCalled(); +}); + +it("keeps history reachable when installation inventory fails", () => { + setup("Inventory unavailable"); + expect(screen.getByRole("status").textContent).toBe("Inventory unavailable"); + fireEvent.click(screen.getByRole("tab", { name: "History" })); + expect(screen.getByText("Revision history")).toBeTruthy(); +}); diff --git a/apps/local-dashboard/src/pages/Settings.test.tsx b/apps/local-dashboard/src/pages/Settings.test.tsx index 0e6798ac..ccec48f2 100644 --- a/apps/local-dashboard/src/pages/Settings.test.tsx +++ b/apps/local-dashboard/src/pages/Settings.test.tsx @@ -15,6 +15,7 @@ function renderSettings(url: string, route = "/settings?section=remote-library") if (input === "/api/v2/settings") return Response.json(settingsFor(url)); if ( [ + "/api/v2/settings/billing/status", "/api/v2/settings/remote-library/status", "/api/v2/settings/remote-library/shares", "/api/v2/settings/workspace/members", @@ -45,6 +46,46 @@ afterEach(() => { }); describe("Settings remote-library capabilities", () => { + it("distinguishes enabled Cloud package backup from local operational data", async () => { + const cloud = renderSettings("https://cloud.selftune.dev"); + await screen.findByText( + "Skill packages back up to the destination you enable in Cloud. Prompts, sessions, and evaluations stay local.", + ); + expect(screen.queryByRole("switch", { name: "Decision history backup" })).toBeNull(); + + cloud.unmount(); + renderSettings("https://selftune.example.com"); + await screen.findByText("Raw transcripts are never synced."); + expect(screen.getByRole("switch", { name: "Decision history backup" })).not.toBeNull(); + }); + + it("does not claim a stored Cloud credential is connected when verification fails", async () => { + renderSettings("https://cloud.selftune.dev"); + await screen.findByText( + "Cloud could not verify this device. Reconnect your account and retry.", + ); + expect(screen.queryByText("SelfTune Cloud account connected")).toBeNull(); + expect(screen.queryByText("Checking SelfTune Cloud integrity...")).toBeNull(); + }); + + it("explains the paid sync requirement after verifying a free account", async () => { + renderSettings("https://cloud.selftune.dev"); + await screen.findByText( + "Cloud could not verify this device. Reconnect your account and retry.", + ); + act(() => + clients.at(-1)?.setQueryData(["cloud-billing"], { + plan: "free", + subscriptionStatus: "none", + }), + ); + await screen.findByText( + "Account connected. An active Pro or Team plan is required for inventory sync and sharing.", + ); + expect( + screen.getByText("Your device credential was verified by SelfTune Cloud."), + ).not.toBeNull(); + }); it("renders a newly available automation job before the draft synchronization effect runs", async () => { const url = "https://cloud.selftune.dev"; renderSettings(url, "/settings?section=automation"); @@ -74,14 +115,14 @@ describe("Settings remote-library capabilities", () => { expect(screen.getByRole("combobox", { name: "Collect frequency" })).not.toBeNull(); }); - it("shows backup controls only for self-hosting, even when remote status is unavailable", async () => { + it("shows backup controls for Cloud and self-hosting, even when remote status is unavailable", async () => { const cloud = renderSettings("https://cloud.selftune.dev"); await screen.findByRole("heading", { - name: "Cloud connection & self-hosted backup", + name: "Sync & Backup", }); - expect(screen.queryByTitle("Export complete backup")).toBeNull(); - expect(screen.queryByTitle("Restore into a new local directory")).toBeNull(); + expect(screen.getByTitle("Export complete backup")).not.toBeNull(); + expect(screen.getByTitle("Restore into a new local directory")).not.toBeNull(); cloud.unmount(); renderSettings("https://selftune.example.com"); diff --git a/apps/local-dashboard/src/pages/Settings.tsx b/apps/local-dashboard/src/pages/Settings.tsx index 2d8d24a5..5cdd5610 100644 --- a/apps/local-dashboard/src/pages/Settings.tsx +++ b/apps/local-dashboard/src/pages/Settings.tsx @@ -50,6 +50,7 @@ import { import { useExportRemoteLibrary, useLinkCloudAccount, + useCloudBillingStatus, usePreviewRemoteLibrary, useRemoteLibraryStatus, useRemoteLibraryShares, @@ -315,6 +316,10 @@ export function Settings() { const remoteStatus = useRemoteLibraryStatus( settingsQuery.data?.remote_library.configured ?? false, ); + const cloudConnection = useCloudBillingStatus( + (settingsQuery.data?.cloud_account.linked ?? false) && + syncDestinationFromUrl(settingsQuery.data?.remote_library.url ?? "") === "cloud", + ); const syncRemote = useSyncRemoteLibrary(); const exportRemote = useExportRemoteLibrary(); const restoreRemote = useRestoreRemoteLibrary(); @@ -386,6 +391,13 @@ export function Settings() { const remoteLibraryConfigured = settingsQuery.data?.remote_library.configured ?? false; const cloudAccountLinked = settingsQuery.data?.cloud_account.linked ?? false; + const cloudConnectionLabel = !cloudAccountLinked + ? "No Cloud account" + : cloudConnection.isError + ? "Cloud connection needs attention" + : cloudConnection.isSuccess + ? "SelfTune Cloud account connected" + : "Checking Cloud connection…"; const configuredDestination = syncDestinationFromUrl( settingsQuery.data?.remote_library.url ?? "", ); @@ -493,6 +505,8 @@ export function Settings() { toast.success("SelfTune Cloud connected", { description: `Cloud inventory updated: ${firstBackup.uploaded} reported, ${firstBackup.unchanged} unchanged.`, }); + } else if (firstBackup.status === "not_configured") { + toast.info("SelfTune Cloud connected", { description: firstBackup.message }); } else { toast.warning("SelfTune Cloud connected", { description: `The first inventory update did not finish: ${firstBackup.message}`, @@ -628,7 +642,7 @@ export function Settings() { @@ -640,15 +654,17 @@ export function Settings() {

- Cloud connection & self-hosted backup + Sync & Backup

- {settingsQuery.data.remote_library.configured - ? configuredDestinationCopy.connected - : draftDestinationCopy.notConnected} + {configuredDestination === "cloud" + ? cloudConnectionLabel + : settingsQuery.data.remote_library.configured + ? configuredDestinationCopy.connected + : draftDestinationCopy.notConnected} {credentialProviderLabel(settingsQuery.data.remote_library.credential_provider) && ( @@ -657,8 +673,8 @@ export function Settings() { )}

- Your Library stays local. Cloud receives only a privacy-safe inventory; a - self-hosted server can store a backup when you choose it. + Keep working locally and back up skill files to Cloud or your own server. In Cloud, + choose a personal or team destination for each device before syncing files.

@@ -763,13 +779,15 @@ export function Settings() {

- {cloudAccountLinked - ? "SelfTune Cloud account connected" - : "No Cloud account"} + {cloudConnectionLabel}

{cloudAccountLinked - ? "Your credential is stored securely by this device." + ? cloudConnection.isError + ? "Cloud could not verify this device. Reconnect your account and retry." + : cloudConnection.isSuccess + ? "Your device credential was verified by SelfTune Cloud." + : "Verifying the credential stored on this device." : "Create an account or sign in in your browser. Desktop remains usable without one."}

@@ -869,7 +887,7 @@ export function Settings() {
{remoteDraft.destination === "cloud" - ? "Skill contents, paths, prompts, sessions, and evaluations stay local." + ? "Skill packages back up to the destination you enable in Cloud. Prompts, sessions, and evaluations stay local." : "Raw transcripts are never synced."}
{previewRemote.data ? ( @@ -904,7 +922,18 @@ export function Settings() {
- {remoteStatus.data?.diagnostics ? ( + {configuredDestination === "cloud" ? ( + cloudConnection.isSuccess ? ( + cloudConnection.data.subscriptionStatus === "active" || + cloudConnection.data.subscriptionStatus === "trialing" ? ( + "Cloud connected. Enable a device backup destination in Cloud to sync and inspect skill files." + ) : ( + "Account connected. An active Pro or Team plan is required for inventory sync and sharing." + ) + ) : ( + cloudConnectionLabel + ) + ) : remoteStatus.data?.diagnostics ? ( <> {remoteStatus.data.diagnostics.objectCount} objects ·{" "} {remoteStatus.data.diagnostics.snapshotCount} snapshots ·{" "} @@ -940,7 +969,7 @@ export function Settings() { />{" "} Sync now - {selfHostedWorkspaceConfigured ? ( + {connectedWorkspaceConfigured ? ( <> +
+
+ +

{name}

+
+ + + Report unavailable + +

+ We couldn’t load this skill’s report. Retry, or return to Skills to check its + installation. +

+

{error instanceof Error ? error.message : "The report request failed."}

+ +
+
); } @@ -1215,265 +955,102 @@ export function SkillReport() { ); } - const isNotFound = - (coverage?.checks ?? data.usage.total_checks) === 0 && - data.evidence.length === 0 && - data.evolution.length === 0 && - (data.canonical_invocations?.length ?? 0) === 0 && - createReadiness == null; - - if (isNotFound) { - return ( -
-

No data found for skill "{name}".

- -
- ); - } - - const trustState = trust?.state ?? "low_sample"; - - const trustDrivenAction = deriveNextAction( - trustState, - routingQuality?.miss_rate, - evidenceQuality?.system_like_rate, - evolutionState?.has_pending_proposals ?? data.pending_proposals.length > 0, - hasEvolutionData, - ); - const proposalDrivenAction = - proposalFocus && activeProposal ? deriveProposalAction(evolution, activeProposal) : null; - const nextAction = - proposalDrivenAction ?? - (proposalFocus - ? trustDrivenAction - : showDraftPackageSection && createReadiness - ? deriveCreateAction(createReadiness) - : trustState === "rolled_back" || - !testingReadiness || - testingReadiness.next_step === "watch_deployment" - ? trustDrivenAction - : deriveTestingAction(testingReadiness)); - return ( - } - className="shrink-0" - > - - + + + Skills + + } + checks={operationalChecks} + sessions={coverage?.sessions ?? data.sessions_with_skill} + workspaces={coverage?.workspaces} + lastSeen={coverage?.last_seen} + initialTab={proposalFocus ? "history" : "overview"} + activity={(skill) => ( + + Recorded skill use is not a measure of task success.{" "} + {excludedChecks > 0 ? `${excludedChecks} internal or legacy rows are excluded.` : ""} +

+ } + /> + )} + files={ + resolvedSkillPath ? ( + + ) : ( +

+ No local package path is available for this skill. +

+ ) } - title={data.skill_name} - statusBadge={} - toolbarMeta={ + history={ <> -
- - - {coverage?.checks ?? data.usage.total_checks} - {" "} - checks - - | - - - {coverage?.sessions ?? data.sessions_with_skill} - {" "} - sessions - - | - - {coverage?.workspaces ?? "No data"}{" "} - workspaces - -
- {coverage?.first_seen || coverage?.last_seen ? ( -
- {coverage?.first_seen ? ( - {timeAgo(coverage.first_seen)} - ) : null} - {coverage?.first_seen && coverage?.last_seen ? - : null} - {coverage?.last_seen ? ( - {timeAgo(coverage.last_seen)} - ) : null} -
- ) : null} + {resolvedSkillPath && ( + + )} + + No reviewable improvement evidence recorded. +

+ } + /> } - summary={ - trust?.summary ? ( - <> -
- {trust.summary} - {evolutionState?.latest_action && evolutionState?.latest_timestamp ? ( - - Latest: {evolutionState.latest_action} ({timeAgo(evolutionState.latest_timestamp)} - ) - - ) : null} + testing={ + <> + +
+ Test setup and actions +
+ {showDraftPackageSection && createReadiness ? ( + + ) : ( + + )} +
- {excludedChecks > 0 ? ( -
- Based on {operationalChecks}{" "} - real checks. {excludedChecks}{" "} - internal or legacy rows are excluded from trust scoring. -
- ) : null} - - ) : undefined +
+ } - showOnboardingBanner={!proposalFocus} - guideButtonLabel="How this works" - nextAction={nextAction} - trustState={trustState} - coverage={coverage} - evidenceQuality={evidenceQuality} - routingQuality={routingQuality} - evolutionState={evolutionState} - dataHygiene={dataHygiene} - fallbackChecks={data.usage.total_checks} - fallbackSessions={data.sessions_with_skill} - fallbackEvidenceRows={data.evidence.length} - fallbackEvolutionRows={evolution.length} - fallbackLatestAction={evolution[0]?.action} - nextActionText={nextAction.text} - > - {!proposalFocus ? ( - showDraftPackageSection && createReadiness ? ( - - ) : ( - + - ) - ) : null} - - {!proposalFocus ? : null} - - { - if ( - value === "evidence" || - value === "missed" || - value === "invocations" || - value === "data-quality" - ) { - setActiveTab(value); - } - }} - tabs={[ - { - value: "evidence", - label: "Evidence", - tooltip: "Change history and validation results", - hidden: !hasEvolutionData, - contentClassName: "space-y-6", - content: ( - <> - - -
- -

- This skill is being observed but has no reviewable evolution evidence - yet. -

-
-
- - } - /> - - ), - }, - { - value: "invocations", - label: "Invocations", - tooltip: - "Real usage and repaired misses only. Internal selftune traffic and legacy residue are excluded from this working set.", - badge: ( - - {mergedInvocations.length} - - ), - content: ( - 0 ? ( -
- Showing{" "} - - {mergedInvocations.length} - {" "} - operational invocations.{" "} - {excludedChecks} internal - or legacy rows are tracked in Data Quality instead of being mixed into this - working set. -
- ) : undefined - } - /> - ), - }, - { - value: "missed", - label: "Missed Queries", - hidden: (examples?.missed.length ?? 0) === 0, - tooltip: "Queries that look like missed triggers from real usage.", - badge: - (examples?.missed.length ?? 0) > 0 ? ( - - {examples?.missed.length ?? 0} - - ) : undefined, - contentClassName: "pt-2", - content: ( - ({ - id: `${example.session_id}:${example.timestamp ?? index}`, - query: example.query_text, - confidence: example.confidence, - source: example.source ?? example.platform ?? null, - createdAt: example.timestamp ?? "", - }))} - /> - ), - }, - { - value: "data-quality", - label: "Data Quality", - tooltip: "Evidence quality metrics and data hygiene", - content: ( - - ), - }, - ]} - /> - + ({ + id: `${example.session_id}:${example.timestamp ?? index}`, + query: example.query_text, + confidence: example.confidence, + source: example.source ?? example.platform ?? null, + createdAt: example.timestamp ?? "", + }))} + /> + + } + /> ); } diff --git a/apps/local-dashboard/src/use-local-library-inventory.ts b/apps/local-dashboard/src/use-local-library-inventory.ts new file mode 100644 index 00000000..63d66adc --- /dev/null +++ b/apps/local-dashboard/src/use-local-library-inventory.ts @@ -0,0 +1,111 @@ +import { useCallback, useMemo, useState, useDeferredValue } from "react"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import type { DashboardLibraryQueryState } from "@selftune/dashboard-core/host"; +import { fetchAnalytics, fetchLibrary } from "./api"; +import { useLibrary, useLibraryIndex } from "./hooks/useLibrary"; +import { useSkillIntelligence } from "./hooks/useSkillIntelligence"; +import { usePortfolio } from "./hooks/usePortfolio"; +import { useSettings } from "./hooks/useSettings"; +import { mapLocalLibraryInventory } from "./local-library-model"; +import { mapLocalLibraryIndex } from "./local-library-index-model"; +import type { LibrarySnapshot } from "./types"; + +export function useLocalLibraryInventory( + options: { search?: string; full?: boolean } = {}, +): DashboardLibraryQueryState { + const [requestedFull, setRequestedFull] = useState(false); + const [details, setDetails] = useState([]); + const full = options.full || requestedFull; + const search = useDeferredValue(options.search ?? ""); + const index = useLibraryIndex(search, !full); + const complete = useLibrary({ enabled: full }); + const query = full ? complete : index; + const queryClient = useQueryClient(); + const intelligence = useSkillIntelligence(); + const portfolio = usePortfolio(); + const settings = useSettings(); + const analytics = useQuery({ + queryKey: ["analytics"], + queryFn: fetchAnalytics, + staleTime: 30_000, + }); + const mapComplete = useCallback( + (snapshot: LibrarySnapshot) => + mapLocalLibraryInventory( + snapshot, + intelligence.data ?? null, + portfolio.data ?? null, + settings.data?.harnesses ?? [], + analytics.data ?? null, + ), + [intelligence.data, portfolio.data, settings.data?.harnesses, analytics.data], + ); + const data = useMemo(() => { + if (full) return complete.data ? mapComplete(complete.data) : null; + if (!index.data) return null; + const model = mapLocalLibraryIndex( + index.data, + intelligence.data ?? null, + portfolio.data ?? null, + settings.data?.harnesses ?? [], + analytics.data ?? null, + ); + const hydrated = new Map( + details + .filter((snapshot) => snapshot.generatedAt === index.data?.generatedAt) + .flatMap((snapshot) => mapComplete(snapshot).skills) + .map((skill) => [skill.id, skill]), + ); + return { ...model, skills: model.skills.map((skill) => hydrated.get(skill.id) ?? skill) }; + }, [ + full, + complete.data, + index.data, + details, + intelligence.data, + portfolio.data, + settings.data?.harnesses, + analytics.data, + mapComplete, + ]); + const loadAll = useCallback(async () => { + await complete.refetch({ throwOnError: true }); + setRequestedFull(true); + }, [complete.refetch]); + return { + data, + isLoading: query.isLoading, + error: query.error ? query.error.message : null, + searchHandled: !full, + loadAll, + async loadDetails(skillId) { + const existing = data?.skills.find((skill) => skill.id === skillId); + if (existing && existing.detailsLoaded !== false) return existing; + if (!index.data) throw new Error("Wait for the library to finish loading."); + const generation = index.data.generatedAt; + const snapshot = await queryClient.fetchQuery({ + queryKey: ["library", "detail", generation, skillId], + queryFn: () => fetchLibrary({ skillId, snapshot: generation }), + staleTime: 10_000, + }); + const skill = mapComplete(snapshot).skills[0]; + if (!skill) throw new Error("The skill is no longer in the library. Refresh and try again."); + setDetails((previous) => [ + ...previous.filter( + (entry) => entry.generatedAt === generation && entry.skills[0]?.skillId !== skillId, + ), + snapshot, + ]); + return skill; + }, + async refresh() { + setDetails([]); + await Promise.all([ + query.refetch(), + intelligence.refetch(), + portfolio.refetch(), + analytics.refetch(), + ]); + }, + }; +} diff --git a/apps/local/package.json b/apps/local/package.json index 868c2c49..5f6e240c 100644 --- a/apps/local/package.json +++ b/apps/local/package.json @@ -14,7 +14,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@effect/platform-bun": "4.0.0-beta.66", + "@effect/platform-bun": "4.0.0-rc.115", "@selftune/dashboard-core": "workspace:*", "@selftune/harness-claude-code": "workspace:*", "@selftune/harness-core": "workspace:*", @@ -26,7 +26,7 @@ "@selftune/runtime": "workspace:*", "@selftune/skill-intelligence": "workspace:*", "@xmldom/xmldom": "^0.8.13", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@duckdb/node-api": "1.4.5-r.1", diff --git a/apps/local/src/cloud-account-link.ts b/apps/local/src/cloud-account-link.ts index 58ddd9c4..d19ba3f3 100644 --- a/apps/local/src/cloud-account-link.ts +++ b/apps/local/src/cloud-account-link.ts @@ -141,11 +141,10 @@ export function makeCloudAccountLinkManager(options: CloudAccountLinkManagerOpti let firstBackup: CompleteCloudAccountLinkResponse["first_backup"]; try { await options.sync(); - // Hosted sync publishes metadata, not the skill bytes counted by this legacy response. firstBackup = { - status: "completed", - uploaded: 0, - unchanged: 0, + status: "not_configured", + message: + "Account connected and inventory synced. Choose a private backup destination in Cloud, then run Sync & Backup to upload skill files.", }; } catch (cause) { firstBackup = { diff --git a/apps/local/src/cloud-billing.ts b/apps/local/src/cloud-billing.ts index 48da37b0..3e23d2e1 100644 --- a/apps/local/src/cloud-billing.ts +++ b/apps/local/src/cloud-billing.ts @@ -1,4 +1,5 @@ import * as Schema from "effect/Schema"; +import { billingPlans } from "@selftune/runtime/billing-plans"; import * as Predicate from "effect/Predicate"; import * as Context from "effect/Context"; import * as Layer from "effect/Layer"; @@ -17,6 +18,8 @@ const HostedState = Schema.Struct({ plan: Schema.Literals(["free", "pro", "team"]), status: Schema.Literals(["none", "active", "canceled", "past_due", "trialing", "unpaid"]), currentPeriodEnd: Schema.NullOr(Schema.Number), + hasStripeCustomer: Schema.optionalKey(Schema.Boolean), + seatCount: Schema.optionalKey(Schema.Number), }); const CloudBillingErrorResponse = Schema.Struct({ error: Schema.Union([ @@ -122,51 +125,10 @@ function decodeBillingStatus(body: string): DesktopBillingStatus { currentPeriodEnd: state.currentPeriodEnd === null ? null : new Date(state.currentPeriodEnd).toISOString(), trialEnd: null, - seatCount: 1, - hasStripeCustomer: state.status !== "none", + seatCount: state.seatCount ?? (state.plan === "team" ? 3 : 1), + hasStripeCustomer: state.hasStripeCustomer ?? false, canManageBilling: true, - availablePlans: [ - { - id: "free", - name: "Community", - price: "$0", - period: null, - description: "Find, review, package, and install skills on your machine.", - features: [ - "Unlimited local skills and Skill Sets", - "Discovery across supported agents and projects", - "Local evaluation and reviewable proposals", - ], - highlighted: false, - }, - { - id: "pro", - name: "Pro", - price: "$19", - period: "/month", - description: "Publish and manage reviewed Skill Sets as one owner.", - features: [ - "Explicit skill and Skill Set sharing", - "Expiring and revocable share links", - "Linked-device and revision status", - ], - highlighted: true, - }, - { - id: "team", - name: "Team", - price: "$49", - period: "/month", - description: "Distribute reviewed Skill Sets across a workspace.", - features: [ - "Everything in Pro", - "3 members included", - "Workspace membership and access roles", - ], - highlighted: false, - seats: { minimum: 3, label: "members" }, - }, - ], + availablePlans: billingPlans, }; } catch { throw new CLIError( @@ -214,7 +176,10 @@ export function makeCloudBillingOperations( }).then(decodeBillingStatus); }, checkout: async (input: DesktopBillingCheckoutRequest): Promise => { - return { url: `https://cloud.selftune.dev/?billing=${input.plan}` }; + const query = new URLSearchParams({ billing: input.plan }); + if (input.plan === "team" && input.seats !== undefined) + query.set("seats", String(input.seats)); + return { url: `https://cloud.selftune.dev/?${query}` }; }, portal: async (): Promise => { return { url: "https://cloud.selftune.dev/?billing=portal" }; diff --git a/apps/local/src/cloud-team-collaboration.ts b/apps/local/src/cloud-team-collaboration.ts index 76ff1a68..bf10836d 100644 --- a/apps/local/src/cloud-team-collaboration.ts +++ b/apps/local/src/cloud-team-collaboration.ts @@ -162,7 +162,7 @@ export interface TeamContributionDecisionResultModel { readonly rolloutPolicy?: TeamRolloutPolicyModel; } -export class CloudTeamCollaborationError extends Schema.TaggedErrorClass()( +export class CloudTeamCollaborationError extends Schema.TaggedError()( "CloudTeamCollaborationError", { code: Schema.String, diff --git a/apps/local/src/correction-study-service.ts b/apps/local/src/correction-study-service.ts index 3b475d0a..91763faa 100644 --- a/apps/local/src/correction-study-service.ts +++ b/apps/local/src/correction-study-service.ts @@ -125,7 +125,7 @@ export class ManagedCorrectionStudyRequest extends Schema.Class()( +export class CorrectionStudyServiceFailure extends Schema.TaggedError()( "CorrectionStudyServiceFailure", { code: Schema.Literals([ diff --git a/apps/local/src/daemon.ts b/apps/local/src/daemon.ts index 625edfc9..5f8b94f6 100644 --- a/apps/local/src/daemon.ts +++ b/apps/local/src/daemon.ts @@ -69,7 +69,7 @@ export interface RuntimeStopExpectation { readonly pid: number; } -export class DaemonFailure extends Schema.TaggedErrorClass()("DaemonFailure", { +export class DaemonFailure extends Schema.TaggedError()("DaemonFailure", { operation: Schema.String, message: Schema.String, }) {} diff --git a/apps/local/src/dashboard-events.ts b/apps/local/src/dashboard-events.ts index 520f95e9..772afb38 100644 --- a/apps/local/src/dashboard-events.ts +++ b/apps/local/src/dashboard-events.ts @@ -19,6 +19,7 @@ interface ActionEventHistoryEntry { } export interface DashboardEventHub { + readonly subscriberCount: () => number; readonly response: () => Response; readonly broadcastAction: (event: DashboardActionEvent) => void; readonly broadcastUpdate: (resources: readonly DashboardResource[]) => void; @@ -90,6 +91,11 @@ export function createDashboardEventHub(options: DashboardEventHubOptions): Dash ); for (const controller of clients) { try { + if ((controller.desiredSize ?? 0) < -128) { + clients.delete(controller); + controller.close(); + continue; + } controller.enqueue(bytes); } catch { clients.delete(controller); @@ -111,6 +117,11 @@ export function createDashboardEventHub(options: DashboardEventHubOptions): Dash const bytes = new TextEncoder().encode(": keepalive\n\n"); for (const controller of clients) { try { + if ((controller.desiredSize ?? 0) < -128) { + clients.delete(controller); + controller.close(); + continue; + } controller.enqueue(bytes); } catch { clients.delete(controller); @@ -144,21 +155,25 @@ export function createDashboardEventHub(options: DashboardEventHubOptions): Dash const actionStreamPoller = setInterval(flushActionStream, ACTION_STREAM_POLL_MS); const response = (): Response => { + let subscriber: ReadableStreamDefaultController | undefined; const stream = new ReadableStream({ start(controller) { + subscriber = controller; clients.add(controller); controller.enqueue(new TextEncoder().encode(": connected\n\n")); const events = [...actionHistory.values()] .sort((left, right) => left.updatedAt - right.updatedAt) .flatMap((entry) => entry.events); - for (const event of events) { + if (events.length > 0) { controller.enqueue( - new TextEncoder().encode(`event: action\ndata: ${JSON.stringify(event)}\n\n`), + new TextEncoder().encode( + events.map((event) => `event: action\ndata: ${JSON.stringify(event)}\n\n`).join(""), + ), ); } }, - cancel(controller) { - clients.delete(controller); + cancel() { + if (subscriber) clients.delete(subscriber); }, }); return new Response(stream, { @@ -190,6 +205,7 @@ export function createDashboardEventHub(options: DashboardEventHubOptions): Dash }; return { + subscriberCount: () => clients.size, response, broadcastAction, broadcastUpdate, diff --git a/apps/local/src/dashboard-operation-errors.ts b/apps/local/src/dashboard-operation-errors.ts index b3d838f0..3b297751 100644 --- a/apps/local/src/dashboard-operation-errors.ts +++ b/apps/local/src/dashboard-operation-errors.ts @@ -16,7 +16,7 @@ import { TeamSkillSetContributionError } from "@selftune/runtime/team-contributi import { CloudTeamCollaborationError } from "./cloud-team-collaboration.js"; -export class DashboardOperationError extends Schema.TaggedErrorClass()( +export class DashboardOperationError extends Schema.TaggedError()( "DashboardOperationError", { operation: Schema.String, diff --git a/apps/local/src/dashboard-operations.ts b/apps/local/src/dashboard-operations.ts index 6c162bf3..f83e9344 100644 --- a/apps/local/src/dashboard-operations.ts +++ b/apps/local/src/dashboard-operations.ts @@ -816,15 +816,11 @@ export function makeDashboardOperationsLayer(options: DashboardOperationOverride (async (action) => { if (!(await configuredHostedState.isCloudConnection())) return configuredRemoteLibrary.run(action); - if (action === "sync") return configuredHostedState.sync(); - if (action === "status") - return { - url: "https://cloud.selftune.dev", - mode: "privacy_safe_manifest", - }; - throw new Error( - "SelfTune Cloud does not store a library backup. Export and restore remain local.", - ); + if (action === "sync") { + await configuredHostedState.sync(); + return configuredRemoteLibrary.run("sync"); + } + return configuredRemoteLibrary.run(action); }); const cloudAccountLink = yield* CloudAccountLinkService; @@ -1375,10 +1371,7 @@ export function makeDashboardOperationsLayer(options: DashboardOperationOverride attempt("remote_library.skill.backup", () => options.remoteLibrarySkillBackup ? options.remoteLibrarySkillBackup(skillId) - : (async () => - (await configuredHostedState.isCloudConnection()) - ? configuredHostedState.sync() - : configuredRemoteLibrary.backupSkill(skillId))(), + : configuredRemoteLibrary.backupSkill(skillId), ), installLibrarySkill: (skillId, targetAgent) => attempt("remote_library.skill.install", () => diff --git a/apps/local/src/dashboard-server.ts b/apps/local/src/dashboard-server.ts index 44b5897c..9d14f301 100644 --- a/apps/local/src/dashboard-server.ts +++ b/apps/local/src/dashboard-server.ts @@ -69,6 +69,8 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as Option from "effect/Option"; import * as Layer from "effect/Layer"; +import { createSkillRevisionService } from "./skill-revision-service.js"; +import { installedSkillPackageInspector } from "./skill-package-inspector.js"; import * as ManagedRuntime from "effect/ManagedRuntime"; import * as Semaphore from "effect/Semaphore"; import { homedir } from "node:os"; @@ -76,7 +78,7 @@ import type { BlindBenchmarkExecutor } from "@selftune/skill-intelligence/blind- import { getCachedUpdateStatus } from "@selftune/runtime/auto-update"; import { DASHBOARD_ACTION_STREAM_LOG, LOG_DIR } from "@selftune/runtime/constants"; -import type { DashboardHostKind } from "@selftune/dashboard-core/host"; +import type { DashboardHostKind } from "@selftune/dashboard-core/host/capabilities"; import type { HealthResponse } from "@selftune/runtime/dashboard-contract"; import { resolveSelftunePaths } from "@selftune/config"; import { makeLocalDatabaseLive, LocalDatabaseService } from "@selftune/local-store"; @@ -95,6 +97,8 @@ import { dashboardCorsHeaders as corsHeaders } from "./dashboard-http.js"; import { createDashboardSpa } from "./dashboard-spa.js"; import { handleDashboardApplicationRoute } from "./routes/application.js"; import { createDashboardCoreRoutes, type DashboardCoreRouteOverrides } from "./routes/core.js"; +import { createInteractiveReportWorker } from "./interactive-report-worker.js"; +import { join } from "node:path"; import { CorrectionStudyServiceError, createCorrectionStudyRoutes, @@ -233,9 +237,11 @@ export async function startDashboardServer(options?: DashboardServerOptions): Pr cookieSecure: options?.authCookieSecure, }); const localDatabaseLayer = makeLocalDatabaseLive(storagePaths.localDatabasePath); + const reportSemaphore = options?.reportSemaphore ?? (await Effect.runPromise(Semaphore.make(1))); const operationsRuntime = ManagedRuntime.make( makeDashboardOperationsLayer({ ...options, + reportSemaphore, skillSetConfigRoot: storagePaths.configDir, }).pipe(Layer.provideMerge(localDatabaseLayer)), ); @@ -471,11 +477,59 @@ export async function startDashboardServer(options?: DashboardServerOptions): Pr actionStreamPath: process.env.SELFTUNE_DASHBOARD_ACTION_STREAM_LOG || DASHBOARD_ACTION_STREAM_LOG, }); + const reportOptions = { + storagePaths: { + configRoot: storagePaths.configDir, + localDatabasePath: storagePaths.localDatabasePath, + localAnalyticsPath: storagePaths.localAnalyticsPath, + }, + }; + const reportsDirectory = join(storagePaths.configDir, "cache", "reports"); + const reportProcessOptions = { semaphore: reportSemaphore }; + const readDatabaseVersion = () => { + const version = localDatabase + .query<{ changes: number; data_version: number }, []>( + "SELECT total_changes() AS changes, data_version FROM pragma_data_version", + ) + .get(); + return `${version?.changes}:${version?.data_version}`; + }; + const overviewWorker = createInteractiveReportWorker( + "overview", + reportOptions, + reportsDirectory, + reportProcessOptions, + ); + const skillReportWorker = createInteractiveReportWorker( + "skill-report", + reportOptions, + reportsDirectory, + reportProcessOptions, + ); + const shellWorker = createInteractiveReportWorker( + "shell", + reportOptions, + reportsDirectory, + reportProcessOptions, + readDatabaseVersion, + ); + const analyticsWorker = createInteractiveReportWorker( + "analytics", + reportOptions, + reportsDirectory, + reportProcessOptions, + () => `${readDatabaseVersion()}:${Math.floor(Date.now() / 30_000)}`, + ); const coreRoutes = createDashboardCoreRoutes({ + evaluationConfigRoot: storagePaths.configDir, ...options, database: localDatabase, onActionEvent: eventHub.broadcastAction, version: spa.version, + overviewResponse: overviewWorker, + skillReportResponse: skillReportWorker, + shellResponse: (version) => shellWorker(version, new URLSearchParams()), + analyticsResponse: () => analyticsWorker(spa.version(), new URLSearchParams()), }); const hookRoutes = createHookRoutes({ runners: options?.hookRunners }); const traceCandidateRoutes = createTraceCandidateRoutes(traceCandidateOperations); @@ -487,12 +541,24 @@ export async function startDashboardServer(options?: DashboardServerOptions): Pr recordLocalCorrectionReviewDecision(localDatabase, input), listReviews: async (limit) => ({ items: listCorrectionReviews(localDatabase, limit) }), }); + const skillRevisions = createSkillRevisionService(localDatabase, storagePaths.configDir, { + onChange: () => eventHub.broadcastUpdate(["library-inventory", "library-detail"]), + onError: (message) => console.error("Skill history:", message), + }); + const inspectSkillPackage = installedSkillPackageInspector(localDatabase); const proxiedSpaSockets = new Map(); let disposePromise: Promise | undefined; const disposeOwnedResources = (): Promise => { disposePromise ??= (async () => { + await Promise.all([ + overviewWorker.close(), + skillReportWorker.close(), + shellWorker.close(), + analyticsWorker.close(), + ]); if (backgroundRemoteSyncStartup) clearTimeout(backgroundRemoteSyncStartup); if (backgroundRemoteSyncInterval) clearInterval(backgroundRemoteSyncInterval); + skillRevisions.stop(); eventHub.stop(); for (const upstreamSocket of proxiedSpaSockets.values()) { try { @@ -696,6 +762,11 @@ export async function startDashboardServer(options?: DashboardServerOptions): Pr return eventHub.response(); } + const historyResponse = await skillRevisions.handle(req, url, allowedOrigins); + if (historyResponse) return historyResponse; + const packageResponse = inspectSkillPackage(req, url); + if (packageResponse) return packageResponse; + const applicationResponse = await operationsRuntime.runPromise( handleDashboardApplicationRoute(req, url, { allowedOrigins, @@ -730,6 +801,7 @@ export async function startDashboardServer(options?: DashboardServerOptions): Pr } boundPort = server.port ?? port; + if (runtimeMode !== "test") skillRevisions.start(); if (openBrowser) { const url = `http://${hostname}:${boundPort}`; diff --git a/apps/local/src/historical-skill-improve-cli.ts b/apps/local/src/historical-skill-improve-cli.ts index eea56f27..827183a1 100644 --- a/apps/local/src/historical-skill-improve-cli.ts +++ b/apps/local/src/historical-skill-improve-cli.ts @@ -8,6 +8,7 @@ import { import { LocalDatabaseService, makeLocalDatabaseLive } from "@selftune/local-store"; import { makeDuckDbNodeApiAnalyticalStoreLive } from "@selftune/observability/duckdb-node-api"; import { isLlmBackedAgent, type LlmBackedAgent } from "@selftune/runtime/utils/llm-call"; +import { CLIError } from "@selftune/runtime/utils/cli-error"; import { Effect, Layer } from "effect"; import { @@ -31,6 +32,46 @@ export interface HistoricalSkillImproveCliInput { readonly skill: string; readonly skillPath: string; readonly agent?: string; + readonly budgetRemainingUsd: number; + /** Caller estimate for the full run, including candidate generation and replay. */ + readonly estimatedCostUsd: number; +} + +interface HistoricalSpendPreflight { + readonly caller_reported_remaining_usd: number; + readonly caller_estimated_total_run_cost_usd: number; + readonly outcome: "estimate_within_remaining"; + readonly provider_spend_measured: false; +} + +function validateHistoricalSpendPreflight( + input: Pick, +): HistoricalSpendPreflight { + const { budgetRemainingUsd, estimatedCostUsd } = input; + if ( + !Number.isFinite(budgetRemainingUsd) || + budgetRemainingUsd < 0 || + !Number.isFinite(estimatedCostUsd) || + estimatedCostUsd < 0 + ) { + throw new CLIError( + "Historical replay requires finite, non-negative caller spend inputs.", + "INVALID_ARGUMENT", + ); + } + if (estimatedCostUsd > budgetRemainingUsd) { + throw new CLIError( + `Historical replay was not started: estimated total run cost ($${estimatedCostUsd}) exceeds caller-reported remaining spend ($${budgetRemainingUsd}).`, + "GUARD_BLOCKED", + "Review the total-run estimate and the remaining amount, then rerun with current caller-provided values.", + ); + } + return { + caller_reported_remaining_usd: budgetRemainingUsd, + caller_estimated_total_run_cost_usd: estimatedCostUsd, + outcome: "estimate_within_remaining", + provider_spend_measured: false, + }; } export interface HistoricalSkillImproveCliAttempt { @@ -79,6 +120,7 @@ export interface HistoricalSkillImproveCliAttempt { }[]; } | null; readonly applies_change: false; + readonly spend_preflight: HistoricalSpendPreflight; readonly before_after?: { readonly case_id: string; readonly task: string; @@ -112,10 +154,14 @@ function requestedAgent(value: string | undefined): LlmBackedAgent { export async function runHistoricalSkillImproveCli( input: HistoricalSkillImproveCliInput, ): Promise { + const spendPreflight = validateHistoricalSpendPreflight(input); const agent = requestedAgent(input.agent); const patternId = executionPatternIdForSkill(input.skill); const searchDirs = [dirname(dirname(input.skillPath))]; const taskQualityReplay = input.skill.trim().toLowerCase() === "to-issues"; + const qualifiedVerifier = taskQualityReplay + ? historicalTaskQualityVerifierQualification() + : historicalRoutingVerifierQualification(); const program = Effect.gen(function* () { const { sqlite } = yield* LocalDatabaseService; @@ -155,9 +201,7 @@ export async function runHistoricalSkillImproveCli( return yield* improvement.evaluate({ pattern_id: patternId, candidate_count: HISTORICAL_SEARCH_CANDIDATES, - qualified_verifier: taskQualityReplay - ? historicalTaskQualityVerifierQualification() - : historicalRoutingVerifierQualification(), + qualified_verifier: qualifiedVerifier, runtime: { harness: agent === "claude" ? "claude_code" : agent, model: agent === "codex" ? CODEX_STUDENT_MODEL : "configured-default", @@ -172,9 +216,7 @@ export async function runHistoricalSkillImproveCli( replay: taskQualityReplay ? "isolated-host-execution-quality" : "isolated-host-routing", - verifier: taskQualityReplay - ? "selftune.to-issues-draft-quality@v2" - : "selftune.skill-routing-selection@v1", + verifier: `${qualifiedVerifier.instrument.verifier_id}@${qualifiedVerifier.instrument.version}`, }), ), }, @@ -187,8 +229,8 @@ export async function runHistoricalSkillImproveCli( kill_switch_enabled: false, active_runs: 0, max_concurrency: 1, - budget_remaining_usd: 20, - estimated_cost_usd: 5, + budget_remaining_usd: input.budgetRemainingUsd, + estimated_cost_usd: input.estimatedCostUsd, }, recorded_at: new Date().toISOString(), }); @@ -229,6 +271,7 @@ export async function runHistoricalSkillImproveCli( cases: response.cases, search: response.search ?? null, applies_change: false, + spend_preflight: spendPreflight, before_after: response.before_after ?? null, }, }; diff --git a/apps/local/src/historical-skill-improvement-service.ts b/apps/local/src/historical-skill-improvement-service.ts index 4d6a1126..356e80aa 100644 --- a/apps/local/src/historical-skill-improvement-service.ts +++ b/apps/local/src/historical-skill-improvement-service.ts @@ -114,7 +114,7 @@ export interface HistoricalSkillImprovementResponse { } | null; } -export class HistoricalSkillImprovementFailure extends Schema.TaggedErrorClass()( +export class HistoricalSkillImprovementFailure extends Schema.TaggedError()( "HistoricalSkillImprovementFailure", { code: Schema.Literals([ diff --git a/apps/local/src/historical-skill-replay-executor.ts b/apps/local/src/historical-skill-replay-executor.ts index 1f67b2ab..24241972 100644 --- a/apps/local/src/historical-skill-replay-executor.ts +++ b/apps/local/src/historical-skill-replay-executor.ts @@ -5,21 +5,29 @@ import type { import { BlindBenchmarkExecutionFailure } from "@selftune/skill-intelligence/blind-benchmark"; import { qualifyVerifierInstrument, + type VerifierQualificationEvidence, type VerifierQualificationResult, } from "@selftune/skill-intelligence/verifier-instruments"; import { buildRoutingReplayFixture, + evaluateRuntimeReplayObservation, resolveRuntimeReplayPlatform, runCodexHostTaskReplay, runHostRuntimeReplayFixture, + type ReplayWorkspace, + type RuntimeReplayObservation, } from "@selftune/runtime/evolution/validate-host-replay"; -import type { RoutingReplayEntryResult } from "@selftune/runtime/types"; +import type { + EvalEntry, + RoutingReplayEntryResult, + RoutingReplayFixture, +} from "@selftune/runtime/types"; import { Context, Effect, Layer, Schema } from "effect"; import type { HistoricalTaskCalibrator } from "./historical-task-candidate.js"; export const HISTORICAL_ROUTING_VERIFIER_ID = "selftune.skill-routing-selection"; -export const HISTORICAL_ROUTING_VERIFIER_VERSION = "v1"; +export const HISTORICAL_ROUTING_VERIFIER_VERSION = "v2"; export const HISTORICAL_TASK_QUALITY_VERIFIER_ID = "selftune.to-issues-draft-quality"; export const HISTORICAL_TASK_QUALITY_VERIFIER_VERSION = "v2"; @@ -50,7 +58,7 @@ export interface HistoricalSkillReplayExecutorFactory { ) => Effect.Effect; } -export class HistoricalSkillReplayHarnessFailure extends Schema.TaggedErrorClass()( +export class HistoricalSkillReplayHarnessFailure extends Schema.TaggedError()( "HistoricalSkillReplayHarnessFailure", { code: Schema.Literals(["UNSUPPORTED_HARNESS", "UNSUPPORTED_VERIFIER", "HARNESS_UNAVAILABLE"]), @@ -159,31 +167,159 @@ export function verifyToIssuesDraftQuality(task: string, output: string): boolea /** Qualification for the exact deterministic decision made by host routing replay. */ export function historicalRoutingVerifierQualification(): VerifierQualificationResult { + const fixture: RoutingReplayFixture = { + fixture_id: "historical-routing-verifier-controls", + platform: "codex", + target_skill_name: "historical-target", + target_skill_path: "/historical-routing/skills/historical-target/SKILL.md", + competing_skill_paths: [ + "/historical-routing/skills/competing-a/SKILL.md", + "/historical-routing/skills/competing-b/SKILL.md", + ], + }; + const workspace: ReplayWorkspace = { + rootDir: "/historical-routing", + skillRegistryDir: "/historical-routing/.agents/skills", + targetSkillPath: "/historical-routing/.agents/skills/historical-target/SKILL.md", + competingSkillPaths: [ + "/historical-routing/.agents/skills/competing-a/SKILL.md", + "/historical-routing/.agents/skills/competing-b/SKILL.md", + ], + allowedReadRoots: [ + "/historical-routing/.agents/skills/historical-target", + "/historical-routing/.agents/skills/competing-a", + "/historical-routing/.agents/skills/competing-b", + ], + }; + const controls: ReadonlyArray<{ + readonly id: string; + readonly label: VerifierQualificationEvidence["label"]; + readonly expected: VerifierQualificationEvidence["expected_decision"]; + readonly shouldTrigger: boolean; + readonly triggeredSkillNames: readonly string[]; + readonly readSkillPaths?: readonly string[]; + readonly rawOutput?: string; + }> = [ + { + id: "known-failure-no-selection", + label: "known_failure", + expected: "reject", + shouldTrigger: true, + triggeredSkillNames: [], + }, + { + id: "known-good-target-selected-once", + label: "known_good", + expected: "accept", + shouldTrigger: true, + triggeredSkillNames: ["historical-target"], + readSkillPaths: ["/historical-routing/.agents/skills/historical-target/SKILL.md"], + }, + { + id: "boundary-target-selected-out-of-scope", + label: "boundary", + expected: "reject", + shouldTrigger: false, + triggeredSkillNames: ["historical-target"], + }, + { + id: "boundary-no-selection-out-of-scope", + label: "boundary", + expected: "accept", + shouldTrigger: false, + triggeredSkillNames: [], + }, + { + id: "boundary-competing-skill-out-of-scope", + label: "boundary", + expected: "accept", + shouldTrigger: false, + triggeredSkillNames: ["competing-a"], + readSkillPaths: ["/historical-routing/.agents/skills/competing-a/SKILL.md"], + }, + { + id: "boundary-selection-with-off-path-read", + label: "boundary", + expected: "reject", + shouldTrigger: true, + triggeredSkillNames: ["historical-target"], + readSkillPaths: ["/historical-routing/unrelated/SKILL.md"], + }, + { + id: "adversarial-repeated-target", + label: "adversarial", + expected: "reject", + shouldTrigger: true, + triggeredSkillNames: ["historical-target", "historical-target"], + }, + { + id: "adversarial-target-and-competing-selection", + label: "adversarial", + expected: "reject", + shouldTrigger: false, + triggeredSkillNames: ["historical-target", "competing-a"], + }, + { + id: "adversarial-in-scope-target-and-competing-selection", + label: "adversarial", + expected: "reject", + shouldTrigger: true, + triggeredSkillNames: ["historical-target", "competing-a"], + }, + { + id: "adversarial-multiple-competing-skills", + label: "adversarial", + expected: "reject", + shouldTrigger: false, + triggeredSkillNames: ["competing-a", "competing-b"], + }, + { + id: "adversarial-unrelated-skill", + label: "adversarial", + expected: "reject", + shouldTrigger: false, + triggeredSkillNames: ["unrelated-skill"], + }, + { + id: "adversarial-misleading-output-without-selection", + label: "adversarial", + expected: "reject", + shouldTrigger: true, + triggeredSkillNames: [], + rawOutput: "Selected the historical-target skill.", + }, + ]; + return qualifyVerifierInstrument({ instrument: { verifier_id: HISTORICAL_ROUTING_VERIFIER_ID, version: HISTORICAL_ROUTING_VERIFIER_VERSION, kind: "deterministic", success_contract: - "The isolated harness selects the target skill exactly once and selects no competing skill.", + "The live replay predicate accepts target selection for in-scope requests, rejects target selection out of scope, repeated, multiple, unrelated selections, and reads outside staged skill paths; output text alone is not selection evidence.", check_description: - "Stages one frozen skill arm and checks the harness routing events without an LLM judge.", + "Runs synthetic runtime event controls through the live replay decision function without invoking an agent or provider.", }, - evidence: ( - [ - { id: "known-failure", label: "known_failure", expected: "reject", observed: "reject" }, - { id: "known-good", label: "known_good", expected: "accept", observed: "accept" }, - { id: "boundary", label: "boundary", expected: "reject", observed: "reject" }, - { id: "adversarial", label: "adversarial", expected: "reject", observed: "reject" }, - ] as const - ).map((control) => ({ - evidence_id: `historical-routing-${control.id}`, - label: control.label, - expected_decision: control.expected, - observed_decision: control.observed, - partition: "verifier_calibration" as const, - candidate_strategy_reference: null, - })), + evidence: controls.map((control) => { + const entry: EvalEntry = { + query: control.id, + should_trigger: control.shouldTrigger, + }; + const observation: RuntimeReplayObservation = { + triggeredSkillNames: [...control.triggeredSkillNames], + readSkillPaths: [...(control.readSkillPaths ?? [])], + rawOutput: control.rawOutput ?? "", + }; + const result = evaluateRuntimeReplayObservation(entry, fixture, observation, workspace); + return { + evidence_id: `historical-routing-${control.id}`, + label: control.label, + expected_decision: control.expected, + observed_decision: result.passed ? "accept" : "reject", + partition: "verifier_calibration", + candidate_strategy_reference: null, + }; + }), }); } diff --git a/apps/local/src/historical-task-candidate.ts b/apps/local/src/historical-task-candidate.ts index 77c7385a..bb2c60da 100644 --- a/apps/local/src/historical-task-candidate.ts +++ b/apps/local/src/historical-task-candidate.ts @@ -3,6 +3,7 @@ import { createHash } from "node:crypto"; import { createOrGetPreparedEvaluationSubmissionDraft } from "@selftune/local-store"; import type { DuckDbAnalyticalStoreService } from "@selftune/observability"; +import { reconstructSourceTask } from "@selftune/orchestration/reconstruct-source-task"; import { CohortBodyTeacherOutput, type CohortBodyTeacher, @@ -238,22 +239,64 @@ export const prepareHistoricalTaskCandidate = Effect.fn( }), }); const rowsById = new Map(rows.map((row) => [row.skill_invocation_id, row])); + const reconstructedTasks = new Map(); + const reconstructionFailures = new Set(); + // Bound native I/O independently of the discovery page; do not scan 512 originals. + const reconstructionCandidates = references + .toSorted((left, right) => stableTaskRank(left).localeCompare(stableTaskRank(right))) + .filter((reference) => { + const row = rowsById.get(reference.skill_invocation_id); + return ( + row?.invocation_mode === "explicit" && + row.triggered && + row.skill_version_hash === options.revision && + row.source === "codex_rollout" && + historicalTaskWithContext(options.sqlite, row, options.installed.name) === null + ); + }) + .slice(0, 4); + for (const reference of reconstructionCandidates) { + const resolved = yield* options.analytical + .resolveSourceTask({ + ...reference, + skill_revision: options.revision, + pin_id: `historical-task-${stableTaskRank(reference)}-${createHash("sha256").update(reference.source_revision).digest("hex").slice(0, 16)}`, + replay: reconstructSourceTask, + }) + .pipe( + Effect.mapError((error) => new TraceCandidatePreparationError({ message: error.message })), + ); + if (resolved.state === "available") + reconstructedTasks.set(reference.skill_invocation_id, resolved.task); + else reconstructionFailures.add(resolved.reason); + } const seenTasks = new Set(); const tasks = references .toSorted((left, right) => stableTaskRank(left).localeCompare(stableTaskRank(right))) .flatMap((reference) => { const row = rowsById.get(reference.skill_invocation_id); if (!row || row.invocation_mode !== "explicit" || !row.triggered) return []; - if (row.source !== "claude_code_replay" && row.capture_mode !== "hook") return []; + if ( + row.source !== "claude_code_replay" && + row.capture_mode !== "hook" && + row.source !== "codex_rollout" + ) + return []; const occurredAt = row.occurred_at ? Date.parse(row.occurred_at) : Number.NaN; const exactRevision = row.skill_version_hash === options.revision || - (!row.skill_version_hash && + (row.source !== "codex_rollout" && + !row.skill_version_hash && Number.isFinite(occurredAt) && packageMtimeMs <= occurredAt && pathCanUseInstalledSnapshot(row.skill_path, options.installed.skill_path)); if (!exactRevision) return []; - const task = historicalTaskWithContext(options.sqlite, row, options.installed.name); + const task = + historicalTaskWithContext(options.sqlite, row, options.installed.name) ?? + boundedHistoricalTask( + reconstructedTasks.get(reference.skill_invocation_id), + options.installed.name, + ); if (!task || seenTasks.has(task)) return []; seenTasks.add(task); return [{ reference, task }]; @@ -267,7 +310,10 @@ export const prepareHistoricalTaskCandidate = Effect.fn( target_revision: options.revision, readiness: "not_ready", failure_reason: - "Historical skill links exist, but fewer than 3 unique explicit tasks resolve to the exact installed revision for separate calibration, selection, and audit partitions.", + "Historical skill links exist, but fewer than 3 unique explicit tasks resolve to the exact installed revision for separate calibration, selection, and audit partitions." + + (reconstructionFailures.size + ? ` Source reconstruction unavailable: ${[...reconstructionFailures].join(", ")}.` + : ""), evidence: { cohort_entries: tasks.length, resolved_entries: tasks.length }, candidate: null, } satisfies TraceCandidateReview; diff --git a/apps/local/src/hosted-state.ts b/apps/local/src/hosted-state.ts index 83693fd8..24a70569 100644 --- a/apps/local/src/hosted-state.ts +++ b/apps/local/src/hosted-state.ts @@ -95,7 +95,20 @@ const ShareReceipt = Schema.Struct({ expires_at: Schema.Number, }); -function cloudRequestError(operation: string, response: Response) { +function cloudRequestError( + operation: string, + response: Response, + requiredPlan: "pro" | "team" = "pro", +) { + if (response.status === 402) { + return new CLIError( + requiredPlan === "team" + ? "An active Team subscription is required to publish Skill Sets to a workspace." + : "An active Pro or Team subscription is required for Cloud sync and sharing.", + "API_ERROR", + "Your account is connected. Open Settings > Billing to manage your plan.", + ); + } return new CLIError( `${operation} failed (${response.status}).`, "API_ERROR", @@ -481,7 +494,8 @@ export function makeHostedStateOperations( body: JSON.stringify(intentBody), }, ); - if (!intentResponse.ok) throw cloudRequestError("Release publish intent", intentResponse); + if (!intentResponse.ok) + throw cloudRequestError("Release publish intent", intentResponse, "team"); const intent = Schema.decodeUnknownSync(HostedSkillSetPublishIntentReceipt)( await intentResponse.json(), ); @@ -506,7 +520,8 @@ export function makeHostedStateOperations( body: JSON.stringify(finalizeBody), }, ); - if (!finalizeResponse.ok) throw cloudRequestError("Release finalization", finalizeResponse); + if (!finalizeResponse.ok) + throw cloudRequestError("Release finalization", finalizeResponse, "team"); const release = Schema.decodeUnknownSync(HostedSkillSetReleaseReceipt)( await finalizeResponse.json(), ); diff --git a/apps/local/src/installed-skill-discovery.ts b/apps/local/src/installed-skill-discovery.ts new file mode 100644 index 00000000..c607088d --- /dev/null +++ b/apps/local/src/installed-skill-discovery.ts @@ -0,0 +1,51 @@ +import type { Database } from "bun:sqlite"; +import { realpathSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { queryKnownWorkspacePaths } from "@selftune/runtime/localdb/queries"; +import { + extendSkillSearchDirsForWorkspaces, + findInstalledSkillPackages, + getDefaultSkillSearchDirs, +} from "@selftune/runtime/utils/skill-discovery"; + +export function installedSkillSearchDirs(database: Database): string[] { + return extendSkillSearchDirsForWorkspaces( + getDefaultSkillSearchDirs(), + queryKnownWorkspacePaths(database), + ); +} + +/** Prefer the requested registry, but preserve canonical symlink authorization. */ +export function installedSkillPathsForSelection( + database: Database, + selectedPath: string, +): string[] { + const original = resolve(selectedPath); + const root = realpathSync(original); + const isRequestedRegistry = (directory: string) => + directory === dirname(original) || directory === dirname(dirname(original)); + const matchingPath = (directories: readonly string[]) => { + for (const directory of directories) { + for (const skill of findInstalledSkillPackages([directory])) { + try { + if (realpathSync(skill.package_path) === root) return skill.package_path; + } catch { + // Disappearing and broken links cannot authorize a package. + } + } + } + return null; + }; + const defaults = getDefaultSkillSearchDirs().filter(isRequestedRegistry); + const direct = matchingPath(defaults); + if (direct) return [direct]; + const directories = installedSkillSearchDirs(database).filter( + (directory) => !defaults.includes(directory), + ); + const preferred = directories.filter( + (directory) => directory === dirname(original) || directory === dirname(dirname(original)), + ); + const remaining = directories.filter((directory) => !preferred.includes(directory)); + const found = matchingPath([...preferred, ...remaining]); + return found ? [found] : []; +} diff --git a/apps/local/src/interactive-report-worker.ts b/apps/local/src/interactive-report-worker.ts new file mode 100644 index 00000000..ffacb16c --- /dev/null +++ b/apps/local/src/interactive-report-worker.ts @@ -0,0 +1,107 @@ +import { join } from "node:path"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Exit from "effect/Exit"; +import { + computeReportInWorker, + type ReportComputeOptions, + type ReportWorkerProcessOptions, +} from "./report-compute.js"; + +/** One active request per report route; identical reads share the serialized result. */ +export function createInteractiveReportWorker( + report: "overview" | "skill-report" | "shell" | "analytics", + options: ReportComputeOptions, + reportsDir: string, + processOptions: ReportWorkerProcessOptions = {}, + readDatabaseVersion?: () => string, +) { + let closed = false; + let cachedDatabaseReply: { key: string; status: number; body: string } | undefined; + let active: + | { + key: string; + result: Promise<{ status: number; body: string } | null>; + cancel: () => Promise; + } + | undefined; + const handle = async (identity: string, searchParams: URLSearchParams): Promise => { + if (closed) return Response.json({ error: "Dashboard is shutting down" }, { status: 503 }); + const search = searchParams.toString(); + if (search.length > 8192 || identity.length > 512) + return Response.json({ error: "Report query is too large" }, { status: 400 }); + const dataVersion = + report === "shell" || report === "analytics" ? readDatabaseVersion?.() : undefined; + const key = JSON.stringify([identity, search, dataVersion]); + if (cachedDatabaseReply?.key === key) + return new Response(cachedDatabaseReply.body, { + status: cachedDatabaseReply.status, + headers: { "Content-Type": "application/json" }, + }); + if (active && active.key !== key) { + return Response.json( + { error: "Report computation is busy; retry shortly" }, + { + status: 503, + headers: { "Retry-After": "1" }, + }, + ); + } + if (!active) { + const fiber = Effect.runFork( + computeReportInWorker( + report, + { + ...options, + ...(report === "shell" + ? { shell: { version: identity } } + : report === "overview" + ? { overview: { version: identity, search } } + : report === "skill-report" + ? { skillReport: { skillName: identity, search } } + : {}), + }, + join(reportsDir, report), + processOptions, + ).pipe( + Effect.tapError(() => Effect.logError(`${report} worker failed`)), + Effect.match({ + onSuccess: (json) => json, + onFailure: () => null, + }), + ), + ); + const result = Effect.runPromise(Fiber.await(fiber)).then((exit) => + Exit.isSuccess(exit) ? exit.value : null, + ); + active = { key, result, cancel: () => Effect.runPromise(Fiber.interrupt(fiber)) }; + } + const pending = active; + try { + const json = await pending.result; + if ( + json?.status === 200 && + dataVersion !== undefined && + readDatabaseVersion?.() === dataVersion + ) + cachedDatabaseReply = { key, ...json }; + return json === null + ? Response.json( + { error: "Report worker failed; retry shortly" }, + { status: 503, headers: { "Retry-After": "1" } }, + ) + : new Response(json.body, { + status: json.status, + headers: { "Content-Type": "application/json" }, + }); + } finally { + if (active === pending) active = undefined; + } + }; + return Object.assign(handle, { + close: async () => { + closed = true; + await active?.cancel(); + }, + }); +} diff --git a/apps/local/src/operation-cache.ts b/apps/local/src/operation-cache.ts index d073950f..e923e932 100644 --- a/apps/local/src/operation-cache.ts +++ b/apps/local/src/operation-cache.ts @@ -5,6 +5,7 @@ import * as Effect from "effect/Effect"; import * as Latch from "effect/Latch"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; +import { preservingJsonDecoder } from "@selftune/runtime/utils/preserving-schema"; import * as Context from "effect/Context"; import * as Layer from "effect/Layer"; import type * as Scope from "effect/Scope"; @@ -65,16 +66,12 @@ interface Artifact { function readArtifact(options: MaterializedCacheOptions): { readonly value: A } | null { if (options.artifactPath === undefined) return null; try { - const schema = Schema.fromJsonString( - Schema.Struct({ - schema_version: Schema.Literal(1), - generated_at: Schema.String, - data: options.schema, - }), - ); - const envelope = Schema.decodeUnknownSync(schema)(readFileSync(options.artifactPath, "utf8"), { - onExcessProperty: "preserve", + const schema = Schema.Struct({ + schema_version: Schema.Literal(1), + generated_at: Schema.String, + data: options.schema, }); + const envelope = preservingJsonDecoder(schema)(readFileSync(options.artifactPath, "utf8")); return { value: envelope.data }; } catch { // Missing or corrupt artifact — recomputed by the refresh loop. @@ -117,13 +114,15 @@ export function makeMaterializedCache( const refreshIntervalMs = options.refreshIntervalMs ?? 60_000; const refreshTtlMs = options.refreshTtlMs ?? 5 * 60 * 1_000; return Effect.gen(function* () { - let latest = readArtifact(options); + let latest: { readonly value: A } | null = null; + let artifactLoaded = false; let version: string | null = null; let refreshedAt = 0; let pendingRefreshGeneration = 0; const record = (value: A, versionBeforeCompute: string) => Effect.sync(() => { + artifactLoaded = true; latest = { value }; refreshedAt = Date.now(); // A report may write one of its own dependent tables as part of its work. Record @@ -182,6 +181,10 @@ export function makeMaterializedCache( ); const read: Effect.Effect = Effect.suspend(() => { + if (!artifactLoaded) { + latest = readArtifact(options); + artifactLoaded = true; + } started.openUnsafe(); if (latest !== null) return Effect.succeed(latest.value); return sharedCompute.pipe(Effect.onError(() => invalidateShared)); @@ -191,6 +194,7 @@ export function makeMaterializedCache( read, invalidate: Effect.flatMap( Effect.sync(() => { + artifactLoaded = true; latest = null; version = null; pendingRefreshGeneration = 0; diff --git a/apps/local/src/private-library-sync.ts b/apps/local/src/private-library-sync.ts new file mode 100644 index 00000000..e6c1063b --- /dev/null +++ b/apps/local/src/private-library-sync.ts @@ -0,0 +1,85 @@ +import { RemoteArtifact, sha256, type LibrarySnapshot } from "@selftune/control-plane"; +import { commitRemoteArtifacts } from "@selftune/library/remote/sync"; +import type { RemoteLibraryHandle } from "@selftune/library/remote/transport"; +import { encodePackageBundle } from "@selftune/runtime/remote-library-sync"; +import { computePortableSkillVersionHash } from "@selftune/library/hash"; +import { + decodePortablePackageBundleSync, + encodePortablePackageBundleSync, + DISTRIBUTION_PACKAGE_BUNDLE_PROFILE, +} from "@selftune/control-plane"; + +function privatePackage(packagePath: string) { + const bundle = decodePortablePackageBundleSync( + encodePackageBundle(packagePath, true), + DISTRIBUTION_PACKAGE_BUNDLE_PROFILE, + ); + const files = bundle.files.filter( + (file) => + !["evals/generated.json", "evals/release.json", "selftune.synthesis.json"].includes( + file.path, + ), + ); + const bytes = encodePortablePackageBundleSync({ files }, DISTRIBUTION_PACKAGE_BUNDLE_PROFILE); + if (bytes.byteLength > 4 * 1024 * 1024) throw new Error("exceeds the 4 MiB cloud backup limit"); + return { bytes, objectHash: sha256(bytes), revisionHash: computePortableSkillVersionHash(files) }; +} + +export async function syncPrivateLibrary(input: { + library: LibrarySnapshot; + handle: RemoteLibraryHandle; + selectedSkillIds?: readonly string[]; +}) { + await input.handle.capabilities(); + if ( + input.selectedSkillIds?.some( + (id) => !input.library.skills.some((skill) => skill.skillId === id), + ) + ) + throw new Error("Selected skill not found. Refresh your library and try again."); + const objects = []; + const seen = new Set(); + let uploaded = 0; + let unchanged = 0; + const failures: string[] = []; + for (const skill of input.library.skills) { + if (input.selectedSkillIds && !input.selectedSkillIds.includes(skill.skillId)) continue; + for (const revision of skill.revisions) { + const location = revision.locations[0]; + if (!location) continue; + let prepared: ReturnType; + try { + prepared = privatePackage(location.packagePath); + } catch (cause) { + failures.push( + `${skill.name}: ${cause instanceof Error ? cause.message : "package could not be read"}`, + ); + continue; + } + const { bytes, objectHash, revisionHash } = prepared; + const artifactId = `backup-skill-object/${objectHash}/${skill.name}/${revisionHash}`; + if (seen.has(artifactId)) continue; + seen.add(artifactId); + if (await input.handle.hasObject(objectHash)) unchanged += 1; + else { + await input.handle.putObject(objectHash, bytes); + uploaded += 1; + } + objects.push( + RemoteArtifact.make({ + artifactId, + artifactType: "skill_revision", + objectHash, + revisionHash, + updatedAt: new Date().toISOString(), + }), + ); + } + } + const failureMessage = () => + `Backup incomplete: ${failures.length} package(s) need attention. ${uploaded} uploaded, ${unchanged} already stored. ${failures.slice(0, 5).join("; ")}`; + if (failures.length && !objects.length) throw new Error(failureMessage()); + const snapshot = await commitRemoteArtifacts({ handle: input.handle, artifacts: objects }); + if (failures.length) throw new Error(failureMessage()); + return { snapshot, uploaded, unchanged }; +} diff --git a/apps/local/src/proactive-correction-e2-service.ts b/apps/local/src/proactive-correction-e2-service.ts index 0f8de997..d2e81263 100644 --- a/apps/local/src/proactive-correction-e2-service.ts +++ b/apps/local/src/proactive-correction-e2-service.ts @@ -106,7 +106,7 @@ export interface ProactiveCandidateEvaluationRecord { readonly applies_change: false; } -export class ProactiveCandidateEvaluationPersistenceFailure extends Schema.TaggedErrorClass()( +export class ProactiveCandidateEvaluationPersistenceFailure extends Schema.TaggedError()( "ProactiveCandidateEvaluationPersistenceFailure", { message: Schema.String }, ) {} @@ -175,7 +175,7 @@ export function makeLocalStoreProactiveCandidateEvaluationPersistence( }; } -export class ProactiveCorrectionE2Failure extends Schema.TaggedErrorClass()( +export class ProactiveCorrectionE2Failure extends Schema.TaggedError()( "ProactiveCorrectionE2Failure", { code: Schema.Literals(["INVALID_REQUEST", "PERSISTENCE_FAILED"]), message: Schema.String }, ) {} diff --git a/apps/local/src/remote-library-operations.ts b/apps/local/src/remote-library-operations.ts index 2897d538..08398e01 100644 --- a/apps/local/src/remote-library-operations.ts +++ b/apps/local/src/remote-library-operations.ts @@ -44,6 +44,9 @@ import { } from "@selftune/runtime/remote-library-sync"; import { CLIError } from "@selftune/runtime/utils/cli-error"; import { DEFAULT_CLOUD_API_URL } from "@selftune/runtime/auth/device-code"; +import { loadLibraryCatalog } from "@selftune/runtime/library/catalog"; +import { syncPrivateLibrary } from "./private-library-sync"; +import { isSelfTuneCloudUrl } from "./hosted-state"; export type RemoteLibraryAction = "status" | "sync" | "export" | "restore"; export type RemoteLibraryShareAction = "list" | "create" | "accept" | "import" | "revoke"; @@ -93,6 +96,12 @@ export function makeRemoteLibraryOperations(configRootInput: string) { return { url: config.url, capabilities, head, diagnostics }; } if (action === "sync") { + if (isSelfTuneCloudUrl(config.url)) { + return syncPrivateLibrary({ + handle, + library: await loadLibraryCatalog({ skillSetConfigRoot: configRoot }), + }); + } return syncRemoteLibrary({ handle, configRoot, @@ -121,6 +130,13 @@ export function makeRemoteLibraryOperations(configRootInput: string) { apiKey: config.apiKey, }); try { + if (isSelfTuneCloudUrl(config.url)) { + return await syncPrivateLibrary({ + handle, + library: await loadLibraryCatalog({ skillSetConfigRoot: configRoot }), + selectedSkillIds: [skillId], + }); + } return await syncRemoteLibrary({ handle, configRoot, diff --git a/apps/local/src/report-caches.ts b/apps/local/src/report-caches.ts index e4d0331a..a479d806 100644 --- a/apps/local/src/report-caches.ts +++ b/apps/local/src/report-caches.ts @@ -3,6 +3,7 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Semaphore from "effect/Semaphore"; import { LocalDatabaseService } from "@selftune/local-store"; import { makeMaterializedCacheLayer, @@ -14,11 +15,11 @@ import { computeReportInWorker, resolveReportComputeOptions } from "./report-com import { dashboardReportDependencyVersion } from "./report-version.js"; import { reportPayloadSchemas, - type DashboardReportName, + type CachedDashboardReportName, type DashboardReportPayloads, } from "./report-contract.js"; -type ReportCache = CachedOperation< +type ReportCache = CachedOperation< DashboardReportPayloads[Name], DashboardOperationError, never @@ -39,10 +40,11 @@ export class LibraryCache extends Context.Service string>>; + readonly reportVersionReaders?: Partial string>>; readonly portfolioLoader?: () => DashboardReportPayloads["portfolio-audit"]; readonly skillIntelligenceLoader?: () => | DashboardReportPayloads["skill-intelligence"] @@ -70,6 +72,7 @@ function cacheLayer( export function makeDashboardReportCachesLayer(options: DashboardReportCacheOptions) { return Layer.unwrap( Effect.gen(function* () { + const semaphore = options.reportSemaphore ?? (yield* Semaphore.make(1)); const database = Option.getOrUndefined( yield* Effect.serviceOption(LocalDatabaseService), )?.sqlite; @@ -79,11 +82,11 @@ export function makeDashboardReportCachesLayer(options: DashboardReportCacheOpti quarantineRoot: options.quarantineRoot, }); const reportsDir = join(reportOptions.storagePaths.configRoot, "cache", "reports"); - const readVersion = (name: DashboardReportName) => + const readVersion = (name: CachedDashboardReportName) => options.reportVersionReaders?.[name] ?? (() => dashboardReportDependencyVersion(name, database)); - const compute = (name: Name, operation: string) => - computeReportInWorker(name, reportOptions, reportsDir).pipe( + const compute = (name: Name, operation: string) => + computeReportInWorker(name, reportOptions, reportsDir, { semaphore }).pipe( Effect.mapError((cause) => operationError(operation, cause)), ); return Layer.mergeAll( diff --git a/apps/local/src/report-compute.ts b/apps/local/src/report-compute.ts index 2c2ce256..52ac2659 100644 --- a/apps/local/src/report-compute.ts +++ b/apps/local/src/report-compute.ts @@ -5,7 +5,11 @@ import { join } from "node:path"; import { fileURLToPath } from "node:url"; import * as Effect from "effect/Effect"; +import type * as Semaphore from "effect/Semaphore"; import { resolveSelftunePaths } from "@selftune/config"; +import { INTERNAL_REPORT_WORKER_COMMAND } from "./report-worker-command.js"; + +declare const SELFTUNE_DESKTOP_SIDECAR_BUILD: boolean; import { decodeReportOutput, @@ -26,6 +30,7 @@ const WORKER_TIMEOUT_MS = 180_000; export interface ReportWorkerProcessOptions { readonly command?: readonly string[]; readonly timeoutMs?: number; + readonly semaphore?: Semaphore.Semaphore; } export function resolveReportComputeOptions( @@ -67,12 +72,13 @@ export function reportWorkerCommand( ): readonly string[] { if (desktopResourceDirectory) { return [ - join( - desktopResourceDirectory, - process.platform === "win32" ? "selftune-report-worker.exe" : "selftune-report-worker", - ), + join(desktopResourceDirectory, process.platform === "win32" ? "selftune.exe" : "selftune"), + INTERNAL_REPORT_WORKER_COMMAND, ]; } + if (typeof SELFTUNE_DESKTOP_SIDECAR_BUILD !== "undefined" && SELFTUNE_DESKTOP_SIDECAR_BUILD) { + return [process.execPath, INTERNAL_REPORT_WORKER_COMMAND]; + } return [process.execPath, fileURLToPath(new URL("./report-worker.ts", import.meta.url))]; } @@ -80,8 +86,8 @@ export function reportWorkerCommand( * Compute a dashboard report in a short-lived bun subprocess so the multi-second * synchronous computation never occupies the daemon's event loop. The worker writes its * JSON result to `outPath` (stdout stays free for stray library logging). npm/dev runs - * the sibling TypeScript entry through Bun; Desktop runs the separately compiled worker - * staged in its resource directory. A failed worker deliberately remains a failure: the + * the sibling TypeScript entry through Bun; Desktop runs the shared executable's private + * report mode. A failed worker deliberately remains a failure: the * materialized cache retains its last successful artifact instead of recreating this * heavyweight work in the long-lived dashboard daemon. */ @@ -92,7 +98,7 @@ export function computeReportInWorker( processOptions: ReportWorkerProcessOptions = {}, ): Effect.Effect { const outPath = join(reportsDir, `${report}.compute-${process.pid}-${randomUUID()}.json`); - return computeReportInSubprocess(report, options, outPath, processOptions).pipe( + const compute = computeReportInSubprocess(report, options, outPath, processOptions).pipe( Effect.ensuring( Effect.sync(() => { try { @@ -103,6 +109,7 @@ export function computeReportInWorker( }), ), ); + return processOptions.semaphore ? processOptions.semaphore.withPermit(compute) : compute; } export function computeReportInSubprocess( @@ -111,37 +118,52 @@ export function computeReportInSubprocess( outPath: string, processOptions: ReportWorkerProcessOptions = {}, ): Effect.Effect { - return Effect.tryPromise({ - try: async () => { - const workerCommand = processOptions.command ?? reportWorkerCommand(); - const child = Bun.spawn( - [...workerCommand, ...reportWorkerArguments(report, options, outPath)], - { + return Effect.acquireUseRelease( + Effect.try({ + try: () => { + const workerCommand = processOptions.command ?? reportWorkerCommand(); + return Bun.spawn([...workerCommand, ...reportWorkerArguments(report, options, outPath)], { stdout: "ignore", stderr: "pipe", + env: { + ...process.env, + SELFTUNE_CONFIG_DIR: resolveReportComputeOptions(options).storagePaths.configRoot, + }, + }); + }, + catch: (cause) => ReportComputeError.fromCause(report, cause), + }), + (child) => + Effect.tryPromise({ + try: async (signal) => { + signal.throwIfAborted(); + const killTimer = setTimeout( + () => child.kill("SIGKILL"), + processOptions.timeoutMs ?? WORKER_TIMEOUT_MS, + ); + try { + const [stderrText, exitCode] = await Promise.all([ + new Response(child.stderr).text(), + child.exited, + ]); + if (exitCode !== 0) { + throw new ReportComputeError({ + report, + exitCode, + message: `SelfTune report worker for ${report} exited with ${exitCode}: ${stderrText.slice(-500)}`, + }); + } + return decodeReportOutput(report, await Bun.file(outPath).text()); + } finally { + clearTimeout(killTimer); + } }, - ); - const killTimer = setTimeout( - () => child.kill(), - processOptions.timeoutMs ?? WORKER_TIMEOUT_MS, - ); - try { - const [stderrText, exitCode] = await Promise.all([ - new Response(child.stderr).text(), - child.exited, - ]); - if (exitCode !== 0) { - throw new ReportComputeError({ - report, - exitCode, - message: `SelfTune report worker for ${report} exited with ${exitCode}: ${stderrText.slice(-500)}`, - }); - } - return decodeReportOutput(report, await Bun.file(outPath).text()); - } finally { - clearTimeout(killTimer); - } - }, - catch: (cause) => ReportComputeError.fromCause(report, cause), - }); + catch: (cause) => ReportComputeError.fromCause(report, cause), + }), + (child) => + Effect.promise(async () => { + if (child.exitCode === null) child.kill("SIGKILL"); + await child.exited; + }), + ); } diff --git a/apps/local/src/report-contract.ts b/apps/local/src/report-contract.ts index 3972c053..298507f2 100644 --- a/apps/local/src/report-contract.ts +++ b/apps/local/src/report-contract.ts @@ -1,4 +1,5 @@ import * as Schema from "effect/Schema"; +import { preservingJsonDecoder } from "@selftune/runtime/utils/preserving-schema"; import { LibrarySnapshot } from "@selftune/control-plane"; import { InsightsResponseSchema, @@ -11,8 +12,16 @@ export const DashboardReportNameSchema = Schema.Literals([ "skill-intelligence", "insights", "library", + "overview", + "skill-report", + "shell", + "analytics", ]); export type DashboardReportName = typeof DashboardReportNameSchema.Type; +export type CachedDashboardReportName = Exclude< + DashboardReportName, + "overview" | "skill-report" | "shell" | "analytics" +>; export const ReportComputeStoragePathsSchema = Schema.Struct({ configRoot: Schema.NonEmptyString, @@ -26,6 +35,11 @@ export const ReportComputeOptionsSchema = Schema.Struct({ searchDirs: Schema.optionalKey(Schema.mutable(Schema.Array(Schema.String))), quarantineRoot: Schema.optionalKey(Schema.String), storagePaths: Schema.optionalKey(ReportComputeStoragePathsSchema), + overview: Schema.optionalKey(Schema.Struct({ version: Schema.String, search: Schema.String })), + shell: Schema.optionalKey(Schema.Struct({ version: Schema.String })), + skillReport: Schema.optionalKey( + Schema.Struct({ skillName: Schema.String, search: Schema.String }), + ), }); export type ReportComputeOptions = typeof ReportComputeOptionsSchema.Type; @@ -41,20 +55,25 @@ export const ReportWorkerArgumentsSchema = Schema.Tuple([ Schema.NonEmptyString, ]); +const SerializedReportResponse = Schema.Struct({ + status: Schema.Number.check(Schema.isInt(), Schema.isBetween({ minimum: 100, maximum: 599 })), + body: Schema.String, +}); export const reportPayloadSchemas = { "portfolio-audit": PortfolioAuditResultSchema, "skill-intelligence": SkillIntelligenceReportSchema, insights: InsightsResponseSchema, library: LibrarySnapshot, + overview: SerializedReportResponse, + "skill-report": SerializedReportResponse, + shell: SerializedReportResponse, + analytics: SerializedReportResponse, }; export type DashboardReportPayloads = { [Name in DashboardReportName]: (typeof reportPayloadSchemas)[Name]["Type"]; }; -function reportDecoder(schema: Schema.Codec) { - const decode = Schema.decodeUnknownSync(Schema.fromJsonString(schema)); - return (text: string): A => decode(text, { onExcessProperty: "preserve" }); -} +const reportDecoder = preservingJsonDecoder; type DashboardReportDecoders = { [Name in DashboardReportName]: (text: string) => DashboardReportPayloads[Name]; @@ -64,6 +83,10 @@ const reportDecoders: DashboardReportDecoders = { "skill-intelligence": reportDecoder(reportPayloadSchemas["skill-intelligence"]), insights: reportDecoder(reportPayloadSchemas.insights), library: reportDecoder(reportPayloadSchemas.library), + overview: reportDecoder(reportPayloadSchemas.overview), + "skill-report": reportDecoder(reportPayloadSchemas["skill-report"]), + shell: reportDecoder(reportPayloadSchemas.shell), + analytics: reportDecoder(reportPayloadSchemas.analytics), }; export function decodeReportOutput( @@ -73,13 +96,13 @@ export function decodeReportOutput( return reportDecoders[report](text); } -export class ReportComputeError extends Schema.TaggedErrorClass()( +export class ReportComputeError extends Schema.TaggedError()( "ReportComputeError", { report: DashboardReportNameSchema, message: Schema.String, exitCode: Schema.optionalKey(Schema.Number), - cause: Schema.optionalKey(Schema.Defect), + cause: Schema.optionalKey(Schema.Defect()), }, ) { static fromCause(report: DashboardReportName, cause: unknown) { diff --git a/apps/local/src/report-version.ts b/apps/local/src/report-version.ts index 52137ad6..09853e78 100644 --- a/apps/local/src/report-version.ts +++ b/apps/local/src/report-version.ts @@ -1,6 +1,6 @@ import type { Database } from "bun:sqlite"; import { getDb } from "@selftune/local-store"; -import type { DashboardReportName } from "./report-contract.js"; +import type { CachedDashboardReportName } from "./report-contract.js"; interface ReportDependency { readonly table: string; @@ -8,7 +8,7 @@ interface ReportDependency { readonly cursorColumn?: string; } -const REPORT_DEPENDENCIES: Record = { +const REPORT_DEPENDENCIES: Record = { "portfolio-audit": [ { table: "session_telemetry", cursorColumn: "timestamp" }, { table: "skill_invocations", cursorColumn: "occurred_at" }, @@ -60,7 +60,7 @@ function dependencyCursor(db: Database, dependency: ReportDependency): string { } export function dashboardReportDependencyVersion( - report: DashboardReportName, + report: CachedDashboardReportName, database?: Database, ): string { const dependencies = REPORT_DEPENDENCIES[report]; diff --git a/apps/local/src/report-worker-command.ts b/apps/local/src/report-worker-command.ts new file mode 100644 index 00000000..4da84b16 --- /dev/null +++ b/apps/local/src/report-worker-command.ts @@ -0,0 +1,2 @@ +/** Private Desktop subprocess protocol, not an agent-facing CLI command. */ +export const INTERNAL_REPORT_WORKER_COMMAND = "__selftune_report_worker"; diff --git a/apps/local/src/report-worker.ts b/apps/local/src/report-worker.ts index f6ae63b8..6b55a447 100644 --- a/apps/local/src/report-worker.ts +++ b/apps/local/src/report-worker.ts @@ -5,7 +5,7 @@ */ import { mkdirSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import type { Database } from "bun:sqlite"; +import { Database } from "bun:sqlite"; import { openDb } from "@selftune/local-store"; import * as Schema from "effect/Schema"; @@ -23,6 +23,38 @@ async function computeReport( db: Database, ) { const storagePaths = options.storagePaths; + if (report === "analytics") { + const { handleAnalytics } = await import("./routes/analytics.js"); + const response = handleAnalytics(db); + return { status: response.status, body: await response.text() }; + } + if (report === "shell") { + if (!options.shell) throw new Error("Shell worker requires a version"); + const { handleDashboardShell } = await import("./routes/overview.js"); + const response = handleDashboardShell(db, options.shell.version); + return { status: response.status, body: await response.text() }; + } + if (report === "skill-report") { + if (!options.skillReport) throw new Error("Skill report worker requires a selected skill"); + const { handleSkillReport } = await import("./routes/skill-report.js"); + const response = handleSkillReport( + db, + options.skillReport.skillName, + new URLSearchParams(options.skillReport.search), + ); + return { status: response.status, body: await response.text() }; + } + if (report === "overview") { + if (!options.overview) + throw new Error("Overview worker requires version and pagination options"); + const { handleOverview } = await import("./routes/overview.js"); + const response = handleOverview( + db, + options.overview.version, + new URLSearchParams(options.overview.search), + ); + return { status: response.status, body: await response.text() }; + } const workerOptions = { ...options, configRoot: storagePaths.configRoot, @@ -79,7 +111,13 @@ async function main(): Promise { const options = Schema.decodeUnknownSync( Schema.fromJsonString(ResolvedReportComputeOptionsSchema), )(optionsJson); - const db = openDb(options.storagePaths.localDatabasePath); + const db = + report === "overview" || + report === "skill-report" || + report === "shell" || + report === "analytics" + ? new Database(options.storagePaths.localDatabasePath, { readonly: true }) + : openDb(options.storagePaths.localDatabasePath); try { const result = await computeReport(report, options, db); mkdirSync(dirname(outPath), { recursive: true }); diff --git a/apps/local/src/routes/core.ts b/apps/local/src/routes/core.ts index 55f67493..f6832105 100644 --- a/apps/local/src/routes/core.ts +++ b/apps/local/src/routes/core.ts @@ -1,4 +1,5 @@ import type { Database } from "bun:sqlite"; +import { handleEvaluations } from "./evaluations.js"; import { Schema } from "effect"; import type { @@ -56,6 +57,11 @@ export interface DashboardCoreRoutes { } interface DashboardCoreRouteOptions extends DashboardCoreRouteOverrides { + readonly evaluationConfigRoot?: string; + readonly overviewResponse?: (version: string, search: URLSearchParams) => Promise; + readonly shellResponse?: (version: string) => Promise; + readonly analyticsResponse?: () => Promise; + readonly skillReportResponse?: (skillName: string, search: URLSearchParams) => Promise; readonly database?: Database; readonly onActionEvent: (event: DashboardActionEvent) => void; readonly version: () => string; @@ -138,6 +144,12 @@ export function createDashboardCoreRoutes(options: DashboardCoreRouteOptions): D url: URL, allowedOrigins: ReadonlySet, ): Promise => { + if (url.pathname === "/api/v2/evaluations") { + const origin = request.headers.get("origin"); + if (request.method === "POST" && origin && !allowedOrigins.has(origin)) + return Response.json({ error: "Origin not allowed" }, { status: 403 }); + return withDashboardCors(await handleEvaluations(request, url, options.evaluationConfigRoot)); + } if (url.pathname === "/api/v2/doctor" && request.method === "GET") { return withDashboardCors(await handleDoctor()); } @@ -217,6 +229,8 @@ export function createDashboardCoreRoutes(options: DashboardCoreRouteOptions): D headers: dashboardCorsHeaders(), }); } + if (options.shellResponse) + return withDashboardCors(await options.shellResponse(options.version())); return database ? withDashboardCors(handleDashboardShell(database, options.version())) : unavailableResponse(); @@ -226,6 +240,11 @@ export function createDashboardCoreRoutes(options: DashboardCoreRouteOptions): D if (options.overviewLoader) { return Response.json(options.overviewLoader(), { headers: dashboardCorsHeaders() }); } + if (options.overviewResponse) { + return withDashboardCors( + await options.overviewResponse(options.version(), url.searchParams), + ); + } return database ? withDashboardCors(handleOverview(database, options.version(), url.searchParams)) : unavailableResponse(); @@ -255,6 +274,7 @@ export function createDashboardCoreRoutes(options: DashboardCoreRouteOptions): D } if (url.pathname === "/api/v2/analytics" && request.method === "GET") { + if (options.analyticsResponse) return withDashboardCors(await options.analyticsResponse()); return database ? withDashboardCors(handleAnalytics(database)) : unavailableResponse(); } @@ -275,6 +295,8 @@ export function createDashboardCoreRoutes(options: DashboardCoreRouteOptions): D { status: 404, headers: dashboardCorsHeaders() }, ); } + if (options.skillReportResponse) + return withDashboardCors(await options.skillReportResponse(skillName, url.searchParams)); return database ? withDashboardCors(handleSkillReport(database, skillName, url.searchParams)) : unavailableResponse(); diff --git a/apps/local/src/routes/evaluations.ts b/apps/local/src/routes/evaluations.ts new file mode 100644 index 00000000..27c5e184 --- /dev/null +++ b/apps/local/src/routes/evaluations.ts @@ -0,0 +1,45 @@ +import { + readEvaluationHistory, + saveEvaluationReport, + MAX_EVALUATION_BYTES, +} from "@selftune/runtime/eval/history"; + +export async function handleEvaluations( + request: Request, + url: URL, + root?: string, +): Promise { + const skill = url.searchParams.get("skill"); + if (!skill || skill.length > 256) + return Response.json({ error: "A skill name is required" }, { status: 400 }); + try { + if (request.method === "GET") return Response.json(readEvaluationHistory(skill, root)); + if (request.method !== "POST") return new Response(null, { status: 405 }); + if (!request.headers.get("content-type")?.startsWith("application/json")) + return Response.json({ error: "Use application/json" }, { status: 415 }); + const reader = request.body?.getReader(); + if (!reader) return Response.json({ error: "Report JSON is required" }, { status: 400 }); + const chunks: Uint8Array[] = []; + let size = 0; + try { + for (;;) { + const next = await reader.read(); + if (next.done) break; + size += next.value.byteLength; + if (size > MAX_EVALUATION_BYTES) { + await reader.cancel(); + return Response.json({ error: "Report exceeds 2 MiB" }, { status: 413 }); + } + chunks.push(next.value); + } + } finally { + reader.releaseLock(); + } + return Response.json(saveEvaluationReport(skill, Buffer.concat(chunks).toString("utf8"), root)); + } catch (cause) { + return Response.json( + { error: cause instanceof Error ? cause.message : "Unable to read evaluation" }, + { status: 400 }, + ); + } +} diff --git a/apps/local/src/routes/library-transfer.ts b/apps/local/src/routes/library-transfer.ts index e99bc20e..ab66d8a3 100644 --- a/apps/local/src/routes/library-transfer.ts +++ b/apps/local/src/routes/library-transfer.ts @@ -2,11 +2,25 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { Option, flow } from "effect"; import { RemoteArtifact, RemoteSnapshot } from "@selftune/control-plane"; +import { compactLibrarySnapshot } from "@selftune/control-plane/library-transport"; +import type { LibrarySnapshot } from "@selftune/control-plane"; +import { libraryIndexPage } from "@selftune/control-plane/library-index"; import { DashboardOperationError, type DashboardOperations } from "../dashboard-operations.js"; import { dashboardCorsHeaders, sameOriginFailure } from "../dashboard-http.js"; const BackupBody = Schema.Struct({ skill_id: Schema.String }); +const libraryJson = new WeakMap(); +export function librarySnapshotResponse(snapshot: LibrarySnapshot, compact: boolean): Response { + const cached = libraryJson.get(snapshot) ?? {}; + const key = compact ? "compact" : "full"; + const json = cached[key] ?? JSON.stringify(compact ? compactLibrarySnapshot(snapshot) : snapshot); + cached[key] = json; + libraryJson.set(snapshot, cached); + return new Response(json, { + headers: { ...dashboardCorsHeaders(), "Content-Type": "application/json" }, + }); +} const InstallBody = Schema.Struct({ skill_id: Schema.String, target_agent: Schema.Literals(["codex", "claude_code", "opencode", "openclaw", "pi"]), @@ -120,10 +134,68 @@ export const routeLibraryTransfer = Effect.fn("DashboardApplication.routeLibrary operations: DashboardOperations["Service"], ) { if (url.pathname === "/api/v2/library" && request.method === "GET") { + let snapshot = yield* operations.library; + const expected = url.searchParams.get("snapshot"); + if (expected !== null && expected !== snapshot.generatedAt) + return { + response: Response.json( + { error: "The library changed. Refresh and try again." }, + { status: 409, headers: dashboardCorsHeaders() }, + ), + installed: false, + }; + if (url.searchParams.get("view") === "index") { + const offset = Number(url.searchParams.get("offset") ?? 0); + const limit = Number(url.searchParams.get("limit") ?? 50); + const search = url.searchParams.get("search") ?? ""; + if ( + !Number.isSafeInteger(offset) || + offset < 0 || + !Number.isSafeInteger(limit) || + limit < 1 || + limit > 100 || + search.length > 1024 + ) + return yield* invalidBody( + "library.index", + "Use an offset >= 0, limit 1..100, and a search under 1024 characters.", + ); + const classificationText = new Map(); + if (search.trim()) { + const report = yield* operations.skillIntelligence; + for (const classification of report.classifications) + classificationText.set( + classification.skill_id.toLowerCase(), + [classification.category_label, ...classification.matched_terms].join(" "), + ); + } + return { + response: Response.json( + libraryIndexPage(snapshot, { offset, limit, search, classificationText }), + { headers: dashboardCorsHeaders() }, + ), + installed: false, + }; + } + const selectedId = url.searchParams.get("skill_id"); + if (selectedId !== null) { + const skill = snapshot.skills.find((item) => item.skillId === selectedId); + if (!skill) + return { + response: Response.json( + { error: "Skill is no longer in the library. Refresh and try again." }, + { status: 404, headers: dashboardCorsHeaders() }, + ), + installed: false, + }; + snapshot = { + generatedAt: snapshot.generatedAt, + skills: [skill], + counts: { total: 1, active: 0, library: 0, draft: 0, archived: 0, [skill.lifecycle]: 1 }, + }; + } return { - response: Response.json(yield* operations.library, { - headers: dashboardCorsHeaders(), - }), + response: librarySnapshotResponse(snapshot, url.searchParams.get("format") === "compact"), installed: false, }; } diff --git a/apps/local/src/routes/overview.ts b/apps/local/src/routes/overview.ts index 3b4b2889..27acf900 100644 --- a/apps/local/src/routes/overview.ts +++ b/apps/local/src/routes/overview.ts @@ -60,7 +60,22 @@ export function summarizeTrayStatus( return { autonomy_status: response.autonomy_status }; } +const shellCache = new WeakMap< + Database, + { databaseVersion: string; version: string; json: string } +>(); + export function handleDashboardShell(db: Database, version: string): Response { + const changes = db + .query<{ changes: number; data_version: number }, []>( + "SELECT total_changes() AS changes, data_version FROM pragma_data_version", + ) + .get(); + const databaseVersion = `${changes?.changes}:${changes?.data_version}`; + const cached = shellCache.get(db); + if (cached?.databaseVersion === databaseVersion && cached.version === version) { + return new Response(cached.json, { headers: { "Content-Type": "application/json" } }); + } const skills = getSkillsList(db, []); const latestEvolutions = db .query<{ skill_name: string; timestamp: string }, []>( @@ -78,7 +93,9 @@ export function handleDashboardShell(db: Database, version: string): Response { latest_evolutions: latestEvolutions, pending_proposals: pendingProposals, }; - return Response.json(response); + const json = JSON.stringify(response); + shellCache.set(db, { databaseVersion, version, json }); + return new Response(json, { headers: { "Content-Type": "application/json" } }); } export function handleOverview( @@ -87,9 +104,9 @@ export function handleOverview( searchParams?: URLSearchParams, ): Response { // -- Autonomy-first enrichment fields ---------------------------------------- - const attentionQueue = getAttentionQueue(db); - const recentDecisions = getRecentDecisions(db); const trustSummaries = getSkillTrustSummaries(db); + const attentionQueue = getAttentionQueue(db, trustSummaries); + const recentDecisions = getRecentDecisions(db); const testingReadiness = listSkillTestingReadiness(db); const skills = getSkillsList(db, testingReadiness); const pendingReviews = attentionQueue.filter((a) => a.category === "needs_review").length; diff --git a/apps/local/src/service-contract.ts b/apps/local/src/service-contract.ts index 864e0c9f..8f96ed90 100644 --- a/apps/local/src/service-contract.ts +++ b/apps/local/src/service-contract.ts @@ -98,7 +98,7 @@ export class WindowsRuntimeRecoveryProvider extends Context.Service< WindowsRuntimeRecovery >()("SelfTune/WindowsRuntimeRecovery") {} -export class ServiceFailure extends Schema.TaggedErrorClass()("ServiceFailure", { +export class ServiceFailure extends Schema.TaggedError()("ServiceFailure", { operation: Schema.String, message: Schema.String, }) {} diff --git a/apps/local/src/service/launchd/backend.ts b/apps/local/src/service/launchd/backend.ts index b90b0b72..c8834dec 100644 --- a/apps/local/src/service/launchd/backend.ts +++ b/apps/local/src/service/launchd/backend.ts @@ -90,6 +90,8 @@ export function generateLaunchdPlist(options: LaunchdPlistOptions): string { const associatedBundleIdentifiers = bundleIdentifier ? ` AssociatedBundleIdentifiers\n ${xmlEscape(bundleIdentifier)}\n` : ""; + // This service answers the desktop's HTTP requests. Background throttles its + // SQLite reads; Adaptive requires XPC activity that our loopback HTTP cannot supply. return ` @@ -109,7 +111,7 @@ ${environmentXml} KeepAlive SuccessfulExit ProcessType - Background + Interactive WorkingDirectory ${xmlEscape(options.workingDirectory)} StandardOutPath diff --git a/apps/local/src/service/windows/installation/controller.ts b/apps/local/src/service/windows/installation/controller.ts index 703ef6fd..918b7018 100644 --- a/apps/local/src/service/windows/installation/controller.ts +++ b/apps/local/src/service/windows/installation/controller.ts @@ -89,7 +89,7 @@ export interface WindowsServiceInstallationPlan { export type { WindowsServiceInstallationArtifactStore } from "../artifact-store.js"; -export class WindowsServiceInstallationControllerError extends Schema.TaggedErrorClass()( +export class WindowsServiceInstallationControllerError extends Schema.TaggedError()( "WindowsServiceInstallationControllerError", { message: Schema.String, diff --git a/apps/local/src/service/windows/installation/io-error.ts b/apps/local/src/service/windows/installation/io-error.ts index 49058e2e..a9ccb28f 100644 --- a/apps/local/src/service/windows/installation/io-error.ts +++ b/apps/local/src/service/windows/installation/io-error.ts @@ -1,6 +1,6 @@ import * as Schema from "effect/Schema"; -export class WindowsInstallationIOError extends Schema.TaggedErrorClass()( +export class WindowsInstallationIOError extends Schema.TaggedError()( "WindowsInstallationIOError", { operation: Schema.Literals([ @@ -16,7 +16,7 @@ export class WindowsInstallationIOError extends Schema.TaggedErrorClass()( +export class WindowsServiceLegacyCleanupControllerError extends Schema.TaggedError()( "WindowsServiceLegacyCleanupControllerError", { message: Schema.String, diff --git a/apps/local/src/service/windows/installation/store.ts b/apps/local/src/service/windows/installation/store.ts index 3573bbf2..97d64af8 100644 --- a/apps/local/src/service/windows/installation/store.ts +++ b/apps/local/src/service/windows/installation/store.ts @@ -128,7 +128,7 @@ function matchesReceiptExpectation( return receipt !== null && sameWindowsServiceInstallationReceipt(receipt, expected.receipt); } -export class WindowsServiceInstallationStoreError extends Schema.TaggedErrorClass()( +export class WindowsServiceInstallationStoreError extends Schema.TaggedError()( "WindowsServiceInstallationStoreError", { message: Schema.String, diff --git a/apps/local/src/service/windows/lock-compatibility.ts b/apps/local/src/service/windows/lock-compatibility.ts index 85b1dfb7..52f6538b 100644 --- a/apps/local/src/service/windows/lock-compatibility.ts +++ b/apps/local/src/service/windows/lock-compatibility.ts @@ -174,14 +174,14 @@ export interface WindowsServiceLockCompatibilityDependencies { ) => Effect.Effect; } -export class WindowsServiceLockCompatibilityError extends Schema.TaggedErrorClass()( +export class WindowsServiceLockCompatibilityError extends Schema.TaggedError()( "WindowsServiceLockCompatibilityError", { message: Schema.String, operation: Schema.String }, ) {} -export class WindowsServiceLockFileError extends Schema.TaggedErrorClass()( +export class WindowsServiceLockFileError extends Schema.TaggedError()( "WindowsServiceLockFileError", - { message: Schema.String, code: Schema.NullOr(Schema.String), cause: Schema.Defect }, + { message: Schema.String, code: Schema.NullOr(Schema.String), cause: Schema.Defect() }, ) {} export interface WindowsServiceLockCompatibility { diff --git a/apps/local/src/service/windows/mutation-lock.ts b/apps/local/src/service/windows/mutation-lock.ts index ad97afff..bcecb0b6 100644 --- a/apps/local/src/service/windows/mutation-lock.ts +++ b/apps/local/src/service/windows/mutation-lock.ts @@ -39,7 +39,7 @@ export interface WindowsUserServiceMutationLockDependencies { readonly openDatabase: (path: string) => WindowsUserServiceMutationLockDatabase; } -export class WindowsServiceMutationLockError extends Schema.TaggedErrorClass()( +export class WindowsServiceMutationLockError extends Schema.TaggedError()( "WindowsServiceMutationLockError", { message: Schema.String, diff --git a/apps/local/src/skill-package-inspector.ts b/apps/local/src/skill-package-inspector.ts new file mode 100644 index 00000000..7886fad5 --- /dev/null +++ b/apps/local/src/skill-package-inspector.ts @@ -0,0 +1,159 @@ +import type { Database } from "bun:sqlite"; +import { + constants, + lstatSync, + openSync, + closeSync, + readSync, + fstatSync, + opendirSync, + realpathSync, +} from "node:fs"; +import { dirname, join, relative, resolve, isAbsolute } from "node:path"; +import { installedSkillPathsForSelection } from "./installed-skill-discovery.js"; + +const MAX_ENTRIES = 2000; +const MAX_PREVIEW_BYTES = 256 * 1024; + +export function createSkillPackageInspector( + installedPaths: (selectedPath: string) => readonly string[], +) { + function rootFor(skillPath: string) { + const root = realpathSync(dirname(skillPath)); + const installed = installedPaths(dirname(skillPath)).some((path) => { + try { + return realpathSync(path) === root; + } catch { + return false; + } + }); + if (!installed) throw new Error("Select an installed skill package."); + return root; + } + return (request: Request, url: URL): Response | null => { + if (url.pathname !== "/api/v2/skill-package") return null; + if (request.method !== "GET") return new Response("Method not allowed", { status: 405 }); + try { + const skillPath = url.searchParams.get("skillPath"); + if (!skillPath) throw new Error("Select a skill package."); + const root = rootFor(skillPath); + const file = url.searchParams.get("file"); + if (file !== null) { + if ( + !file || + isAbsolute(file) || + file + .split(/[\\/]/) + .some( + (part) => + !part || + part === "." || + part === ".." || + part === ".git" || + part === "node_modules", + ) + ) + throw new Error("Invalid package-relative file path."); + const target = resolve(root, file); + if (relative(root, target).startsWith("..") || isAbsolute(relative(root, target))) + throw new Error("File is outside the skill package."); + let current = root; + for (const part of file.split("/")) { + current = join(current, part); + if (lstatSync(current).isSymbolicLink()) + return Response.json({ path: file, size: 0, content: null, reason: "symlink" }); + } + const descriptor = openSync( + target, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + try { + const stat = fstatSync(descriptor); + if (!stat.isFile()) throw new Error("Select a regular file."); + if (stat.size > MAX_PREVIEW_BYTES) + return Response.json({ + path: file, + size: stat.size, + content: null, + reason: "too_large", + }); + const bytes = Buffer.alloc(MAX_PREVIEW_BYTES + 1); + let length = 0; + while (length < bytes.length) { + const count = readSync(descriptor, bytes, length, bytes.length - length, null); + if (!count) break; + length += count; + } + if (length > MAX_PREVIEW_BYTES) + return Response.json({ path: file, size: length, content: null, reason: "too_large" }); + const body = bytes.subarray(0, length); + let content: string | null = null; + if (!body.includes(0)) { + try { + content = new TextDecoder("utf-8", { fatal: true }).decode(body); + } catch { + /* Binary data has no text preview. */ + } + } + return Response.json({ + path: file, + size: length, + content, + reason: content === null ? "binary" : null, + }); + } finally { + closeSync(descriptor); + } + } + const files: { path: string; size: number; symlink: boolean }[] = []; + let visited = 0; + let limited = false; + function walk(directory: string, depth: number) { + if (depth > 20) { + limited = true; + return; + } + const dir = opendirSync(directory); + try { + while (true) { + const entry = dir.readSync(); + if (!entry) break; + if (++visited > MAX_ENTRIES) { + limited = true; + return; + } + if (entry.name === ".git" || entry.name === "node_modules") continue; + const path = join(directory, entry.name); + if (entry.isSymbolicLink()) + files.push({ path: relative(root, path), size: 0, symlink: true }); + else if (entry.isDirectory()) walk(path, depth + 1); + else if (entry.isFile()) + files.push({ + path: relative(root, path), + size: lstatSync(path).size, + symlink: false, + }); + if (limited && visited > MAX_ENTRIES) return; + } + } finally { + dir.closeSync(); + } + } + walk(root, 0); + files.sort((a, b) => a.path.localeCompare(b.path)); + return Response.json({ files, limited }); + } catch { + return Response.json( + { + error: + "This file or installed skill package is no longer available, or its path is not allowed.", + }, + { status: 400 }, + ); + } + }; +} + +export function installedSkillPackageInspector(database: Database) { + return createSkillPackageInspector((path) => installedSkillPathsForSelection(database, path)); +} diff --git a/apps/local/src/skill-revision-service.ts b/apps/local/src/skill-revision-service.ts new file mode 100644 index 00000000..8d960e1a --- /dev/null +++ b/apps/local/src/skill-revision-service.ts @@ -0,0 +1,188 @@ +import type { Database } from "bun:sqlite"; +import { realpathSync } from "node:fs"; +import { dirname } from "node:path"; +import { createSkillRevisionHistory } from "@selftune/runtime/skill-revision-history"; +import { findInstalledSkillPackages } from "@selftune/runtime/utils/skill-discovery"; +import { Schema } from "effect"; +import { sameOriginFailure } from "./dashboard-http.js"; +import { + installedSkillPathsForSelection, + installedSkillSearchDirs, +} from "./installed-skill-discovery.js"; + +const RestoreBody = Schema.Struct({ + path: Schema.String, + revision: Schema.Number, + expectedHash: Schema.String, +}); + +export function createSkillRevisionService( + database: Database, + configRoot: string, + options: { + paths?: () => string[]; + onChange?: () => void; + onError?: (message: string) => void; + } = {}, +) { + const history = createSkillRevisionHistory(database, configRoot); + const searchDirs = () => installedSkillSearchDirs(database); + function* pathGroups() { + if (options.paths) { + yield options.paths(); + return; + } + for (const directory of searchDirs()) + yield findInstalledSkillPackages([directory]).map((skill) => skill.package_path); + } + const pending = new Map(); + const captured = new Map(); + const failures = new Map(); + const installed = () => { + const roots = new Set(); + for (const paths of pathGroups()) + for (const path of paths) { + try { + roots.add(realpathSync(path)); + } catch { + // A package may disappear between discovery and capture. + } + } + return roots; + }; + const authorize = (path: string) => { + const root = realpathSync(path); + if (!options.paths) { + if (installedSkillPathsForSelection(database, path).length) return root; + throw new Error("Select an installed skill package."); + } + if (!installed().has(root)) throw new Error("Select an installed skill package."); + return root; + }; + function* scanPackages() { + let changed = false; + const roots = new Set(); + try { + for (const paths of pathGroups()) { + yield; + for (const path of paths) { + yield; + let root: string; + try { + root = realpathSync(path); + } catch { + continue; + } + if (roots.has(root)) continue; + roots.add(root); + try { + const hash = history.fingerprint(root); + if ( + !captured.has(root) || + (captured.get(root) !== hash && pending.get(root) === hash) + ) { + const revision = history.capture(root); + captured.set(root, revision.content_hash); + changed = true; + } + pending.set(root, hash); + failures.delete(root); + } catch (error) { + pending.delete(root); + const message = error instanceof Error ? error.message : String(error); + if (failures.get(root) !== message) options.onError?.(`${root}: ${message}`); + failures.set(root, message); + } + } + } + } catch (error) { + options.onError?.(String(error)); + return; + } + for (const root of captured.keys()) + if (!roots.has(root)) { + captured.delete(root); + pending.delete(root); + failures.delete(root); + } + if (changed) options.onChange?.(); + } + const scan = () => { + for (const _ of scanPackages()) { + /* Explicit scans complete synchronously. */ + } + }; + let timer: ReturnType | undefined; + let scanning = false; + let generation = 0; + const scanInBackground = async () => { + if (scanning) return; + scanning = true; + const started = generation; + try { + for (const _ of scanPackages()) { + await new Promise((resolve) => setImmediate(resolve)); + if (generation !== started) return; + } + } finally { + scanning = false; + } + }; + return { + scan, + start: () => { + if (!timer) { + void scanInBackground(); + timer = setInterval(() => void scanInBackground(), 5_000); + timer.unref(); + } + }, + stop: () => { + generation += 1; + if (timer) clearInterval(timer); + timer = undefined; + }, + handle: async ( + request: Request, + url: URL, + allowedOrigins: ReadonlySet, + ): Promise => { + if (url.pathname !== "/api/v2/skill-history") return null; + try { + if (request.method === "POST") { + const forbidden = sameOriginFailure(request, allowedOrigins); + if (forbidden) return forbidden; + const input = Schema.decodeUnknownSync(RestoreBody)(await request.json()); + if (!Number.isSafeInteger(input.revision) || input.revision < 1) + throw new Error("Invalid revision."); + const revision = history.restore( + authorize(input.path), + input.revision, + input.expectedHash, + ); + options.onChange?.(); + return Response.json(revision); + } + if (request.method !== "GET") return new Response("Method not allowed", { status: 405 }); + const path = url.searchParams.get("path"); + if (!path) throw new Error("Select a skill path."); + const root = authorize(dirname(path)); + const revision = url.searchParams.get("revision"); + if (revision) { + const number = Number(revision); + if (!Number.isSafeInteger(number) || number < 1) throw new Error("Invalid revision."); + return Response.json({ files: history.diff(root, number) }); + } + const before = Number(url.searchParams.get("before") ?? Number.MAX_SAFE_INTEGER); + if (!Number.isSafeInteger(before) || before < 1) throw new Error("Invalid history cursor."); + history.capture(root); + return Response.json({ revisions: history.list(root, before) }); + } catch (error) { + return Response.json( + { error: error instanceof Error ? error.message : "Skill history failed." }, + { status: 400 }, + ); + } + }, + }; +} diff --git a/apps/local/src/trace-candidate-contract.ts b/apps/local/src/trace-candidate-contract.ts index fdb254bd..a501170d 100644 --- a/apps/local/src/trace-candidate-contract.ts +++ b/apps/local/src/trace-candidate-contract.ts @@ -64,7 +64,7 @@ export interface TraceCandidateReview { } | null; } -export class TraceCandidatePreparationError extends Schema.TaggedErrorClass()( +export class TraceCandidatePreparationError extends Schema.TaggedError()( "TraceCandidatePreparationError", { message: Schema.String }, ) {} diff --git a/apps/local/tests/cloud-billing.test.ts b/apps/local/tests/cloud-billing.test.ts index 6f5088f0..049222a7 100644 --- a/apps/local/tests/cloud-billing.test.ts +++ b/apps/local/tests/cloud-billing.test.ts @@ -35,6 +35,26 @@ const billingStatus = { }; describe("Cloud billing sidecar transport", () => { + test("does not mistake internal Team access for a Stripe customer", async () => { + const billing = makeCloudBillingOperations("/unused", { + fetch: async () => + Response.json({ + workspaceId: "internal", + plan: "team", + status: "active", + currentPeriodEnd: null, + hasStripeCustomer: false, + seatCount: 3, + }), + loadRemoteLibraryConfig: () => cloudConfig(), + }); + expect(await billing.status()).toMatchObject({ + plan: "team", + subscriptionStatus: "active", + hasStripeCustomer: false, + seatCount: 3, + }); + }); test("presents Team checkout as three included members", async () => { const billing = makeCloudBillingOperations("/unused", { fetch: async () => @@ -72,7 +92,7 @@ describe("Cloud billing sidecar transport", () => { await billing.status(); await expect(billing.checkout({ plan: "team", seats: 3 })).resolves.toEqual({ - url: "https://cloud.selftune.dev/?billing=team", + url: "https://cloud.selftune.dev/?billing=team&seats=3", }); await expect(billing.portal()).resolves.toEqual({ url: "https://cloud.selftune.dev/?billing=portal", diff --git a/apps/local/tests/dashboard-events.test.ts b/apps/local/tests/dashboard-events.test.ts index f9c5981f..ffadc5e5 100644 --- a/apps/local/tests/dashboard-events.test.ts +++ b/apps/local/tests/dashboard-events.test.ts @@ -8,6 +8,53 @@ import { sourceUpdateResources } from "@selftune/runtime/dashboard-reactivity"; import { createDashboardEventHub } from "../src/dashboard-events.js"; describe("DashboardEventHub", () => { + test("bounded history replay does not disconnect a new subscriber as stalled", async () => { + const root = mkdtempSync(join(tmpdir(), "selftune-sse-replay-")); + const hub = createDashboardEventHub({ + databasePath: join(root, "db"), + actionStreamPath: join(root, "actions"), + }); + try { + for (let i = 0; i < 200; i++) + hub.broadcastAction({ + event_id: "replay", + action: "eval-generate", + stage: "stdout", + skill_name: null, + skill_path: null, + ts: i, + chunk: String(i), + }); + const reader = hub.response().body?.getReader(); + hub.broadcastUpdate(sourceUpdateResources.apply); + expect(hub.subscriberCount()).toBe(1); + await reader?.read(); + const replay = new TextDecoder().decode((await reader?.read())?.value); + expect(replay.match(/event: action/g)).toHaveLength(200); + expect(new TextDecoder().decode((await reader?.read())?.value)).toContain("event: update"); + await reader?.cancel(); + expect(hub.subscriberCount()).toBe(0); + } finally { + hub.stop(); + rmSync(root, { recursive: true, force: true }); + } + }); + test("disconnects stalled subscribers instead of growing their queue indefinitely", () => { + const root = mkdtempSync(join(tmpdir(), "selftune-sse-backpressure-")); + const hub = createDashboardEventHub({ + databasePath: join(root, "db"), + actionStreamPath: join(root, "actions"), + }); + try { + hub.response(); + expect(hub.subscriberCount()).toBe(1); + for (let i = 0; i < 200; i += 1) hub.broadcastUpdate(sourceUpdateResources.apply); + expect(hub.subscriberCount()).toBe(0); + } finally { + hub.stop(); + rmSync(root, { recursive: true, force: true }); + } + }); test("broadcasts the semantic resources changed by a source update", async () => { const root = mkdtempSync(join(tmpdir(), "selftune-dashboard-events-")); const hub = createDashboardEventHub({ @@ -32,6 +79,7 @@ describe("DashboardEventHub", () => { expect(payload).toContain('"projects"'); } finally { await reader?.cancel(); + expect(hub.subscriberCount()).toBe(0); hub.stop(); rmSync(root, { recursive: true, force: true }); } diff --git a/apps/local/tests/dashboard-shell-cache.test.ts b/apps/local/tests/dashboard-shell-cache.test.ts new file mode 100644 index 00000000..7eca8d11 --- /dev/null +++ b/apps/local/tests/dashboard-shell-cache.test.ts @@ -0,0 +1,32 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { openDb } from "@selftune/local-store"; +import { handleDashboardShell } from "../src/routes/overview"; + +test("shell cache observes writes on its own connection and other connections", async () => { + const root = mkdtempSync(join(tmpdir(), "shell-cache-")); + const path = join(root, "test.db"); + const db = openDb(path); + const writer = openDb(path); + try { + const initial = await handleDashboardShell(db, "1").json(); + expect(await handleDashboardShell(db, "1").json()).toEqual(initial); + db.run( + "INSERT INTO evolution_audit (timestamp, skill_name, action, proposal_id) VALUES (?, ?, ?, ?)", + ["2026-09-11", "one", "deployed", "one"], + ); + expect((await handleDashboardShell(db, "1").json()).latest_evolutions).toHaveLength(1); + writer.run( + "INSERT INTO evolution_audit (timestamp, skill_name, action, proposal_id) VALUES (?, ?, ?, ?)", + ["2026-09-12", "two", "deployed", "two"], + ); + expect((await handleDashboardShell(db, "1").json()).latest_evolutions).toHaveLength(2); + expect((await handleDashboardShell(db, "2").json()).version).toBe("2"); + } finally { + writer.close(); + db.close(); + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/local/tests/evaluations.test.ts b/apps/local/tests/evaluations.test.ts new file mode 100644 index 00000000..6ff55675 --- /dev/null +++ b/apps/local/tests/evaluations.test.ts @@ -0,0 +1,54 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { handleEvaluations } from "../src/routes/evaluations.js"; + +test("evaluation imports persist, deduplicate, remain skill-scoped, and reject malformed reports", async () => { + const root = mkdtempSync(join(tmpdir(), "evaluation-routes-")); + const url = new URL("http://localhost/api/v2/evaluations?skill=example"); + const raw = JSON.stringify({ + skill_name: "example", + agent: "codex", + threshold: 0.8, + baseline: "without_skill", + cases: [ + { + id: 1, + with_skill_pass_rate: 0.8, + baseline_pass_rate: 0, + with_skill_assertions: [ + { + text: "Correct result", + passed: true, + scored: true, + evidence: "Produced the requested output", + }, + ], + }, + ], + }); + const send = (body: string) => + handleEvaluations( + new Request(url, { method: "POST", headers: { "content-type": "application/json" }, body }), + url, + root, + ); + try { + expect((await send(raw)).status).toBe(200); + const imported = await (await send(raw)).json(); + expect(imported).toHaveLength(1); + expect(imported[0].result.harness).toBe("codex"); + expect(imported[0].result.threshold).toBe(0.8); + expect(imported[0].result.exitCode).toBe(0); + expect(imported[0].result.cases[0].assertions[0].evidence).toBe( + "Produced the requested output", + ); + const other = new URL("http://localhost/api/v2/evaluations?skill=other"); + expect(await (await handleEvaluations(new Request(other), other, root)).json()).toEqual([]); + expect((await send("{}")).status).toBe(400); + expect((await send("x".repeat(2 * 1024 * 1024 + 1))).status).toBe(413); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/local/tests/fixtures/report-worker.ts b/apps/local/tests/fixtures/report-worker.ts index df22eb09..2f8c1656 100644 --- a/apps/local/tests/fixtures/report-worker.ts +++ b/apps/local/tests/fixtures/report-worker.ts @@ -1,11 +1,18 @@ -import { mkdirSync, writeFileSync } from "node:fs"; -import { dirname } from "node:path"; +import { mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs"; +import { dirname, join } from "node:path"; import { buildPortfolioAudit } from "@selftune/runtime/skill-portfolio"; const [, , mode, , , outputPath] = process.argv; if (!outputPath) throw new Error("Expected report output path"); mkdirSync(dirname(outputPath), { recursive: true }); switch (mode) { + case "counted-shell": { + const path = join(dirname(outputPath), "counter"); + const count = (existsSync(path) ? Number(readFileSync(path, "utf8")) : 0) + 1; + writeFileSync(path, String(count)); + writeFileSync(outputPath, JSON.stringify({ status: 200, body: JSON.stringify({ count }) })); + break; + } case "exit": process.stderr.write("x".repeat(2048)); process.exit(7); @@ -14,6 +21,12 @@ switch (mode) { writeFileSync(outputPath, "unfinished"); await Bun.sleep(15_000); break; + case "uncooperative": + process.on("SIGTERM", () => {}); + writeFileSync(join(dirname(outputPath), "worker.pid"), String(process.pid)); + writeFileSync(outputPath, "unfinished"); + await Bun.sleep(15_000); + break; case "invalid-json": writeFileSync(outputPath, "{"); break; diff --git a/apps/local/tests/historical-skill-improve-cli.test.ts b/apps/local/tests/historical-skill-improve-cli.test.ts new file mode 100644 index 00000000..826f01d6 --- /dev/null +++ b/apps/local/tests/historical-skill-improve-cli.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, test } from "bun:test"; + +import { runHistoricalSkillImproveCli } from "../src/historical-skill-improve-cli.js"; + +describe("historical skill improve CLI spend preflight", () => { + test("rejects invalid amounts before opening stores or starting model work", async () => { + await expect( + runHistoricalSkillImproveCli({ + skill: "to-issues", + skillPath: "/tmp/skills/to-issues/SKILL.md", + budgetRemainingUsd: -1, + estimatedCostUsd: 0, + }), + ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" }); + + await expect( + runHistoricalSkillImproveCli({ + skill: "to-issues", + skillPath: "/tmp/skills/to-issues/SKILL.md", + budgetRemainingUsd: 1, + estimatedCostUsd: Number.POSITIVE_INFINITY, + }), + ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" }); + }); + + test("rejects an over-budget total-run estimate before opening stores or starting model work", async () => { + await expect( + runHistoricalSkillImproveCli({ + skill: "to-issues", + skillPath: "/tmp/skills/to-issues/SKILL.md", + budgetRemainingUsd: 1, + estimatedCostUsd: 1.01, + }), + ).rejects.toMatchObject({ + code: "GUARD_BLOCKED", + message: expect.stringContaining("Historical replay was not started"), + }); + }); +}); diff --git a/apps/local/tests/historical-skill-replay-executor.test.ts b/apps/local/tests/historical-skill-replay-executor.test.ts index 8a927502..bb91e924 100644 --- a/apps/local/tests/historical-skill-replay-executor.test.ts +++ b/apps/local/tests/historical-skill-replay-executor.test.ts @@ -54,6 +54,18 @@ describe("historical host replay executor", () => { ).toBe(false); }); + test("qualifies historical routing with executed live-predicate controls", () => { + const qualification = historicalRoutingVerifierQualification(); + expect(qualification.status).toBe("qualified"); + expect(qualification.instrument.version).toBe("v2"); + expect(qualification.control_counts).toEqual({ + known_failure: 1, + known_good: 1, + boundary: 4, + adversarial: 6, + }); + }); + test("runs the execution-quality arms with Luna max and records bounded outputs", async () => { const calls: Array<{ body: string; @@ -302,7 +314,7 @@ describe("historical host replay executor", () => { expect(result._tag).toBe("Failure"); if (result._tag === "Failure") { expect(String(result.cause)).toContain( - "requires verifier selftune.skill-routing-selection@v1", + "requires verifier selftune.skill-routing-selection@v2", ); } }); diff --git a/apps/local/tests/historical-task-candidate.test.ts b/apps/local/tests/historical-task-candidate.test.ts index bca39f16..faf9dd48 100644 --- a/apps/local/tests/historical-task-candidate.test.ts +++ b/apps/local/tests/historical-task-candidate.test.ts @@ -71,6 +71,7 @@ describe("historical task-quality candidate", () => { const analytical = Layer.succeed( DuckDbAnalyticalStore, DuckDbAnalyticalStore.of({ + resolveSourceTask: () => Effect.die("unused"), hasExactBatchReceipt: () => Effect.succeed(false), ingest: () => Effect.die("unused"), querySkillSignals: () => diff --git a/apps/local/tests/hosted-state.test.ts b/apps/local/tests/hosted-state.test.ts index 11b99f46..c4d6c0a2 100644 --- a/apps/local/tests/hosted-state.test.ts +++ b/apps/local/tests/hosted-state.test.ts @@ -354,6 +354,7 @@ describe("Desktop hosted-state adapter", () => { let intentBody: unknown; let finalizeBody: unknown; let uploadedBytes = new Uint8Array(); + let subscriptionRequired = false; let preview: Awaited< ReturnType["previewSkillSetPublish"]> >; @@ -375,6 +376,16 @@ describe("Desktop hosted-state adapter", () => { const request = new Request(input, init); requests.push(request.clone()); if (request.url.endsWith("/releases/publish-intent")) { + if (subscriptionRequired) + return Response.json( + { + error: { + code: "SUBSCRIPTION_REQUIRED", + message: "Active Team subscription required", + }, + }, + { status: 402 }, + ); intentBody = await request.json(); return Response.json({ publish_intent_id: "intent_123", @@ -439,6 +450,21 @@ describe("Desktop hosted-state adapter", () => { expect(requests[0]?.headers.get("authorization")).toBe("Bearer st_live_secret"); expect(requests[2]?.headers.get("authorization")).toBe("Bearer st_live_secret"); expect(JSON.stringify(intentBody)).not.toContain(skillRoot); + subscriptionRequired = true; + const requestsBeforeDenial = requests.length; + await expect( + operations.publishSkillSet({ + setId: set.set_id, + expectedSkillSetRevisionSha256: preview.skillSetRevisionSha256, + expectedEnvelopeSha256: preview.envelopeSha256, + dependencyResolution: dependencies, + expectedDependencyLock: preview.dependencies.lock, + confirmPublish: true, + }), + ).rejects.toThrow( + "An active Team subscription is required to publish Skill Sets to a workspace.", + ); + expect(requests.length).toBe(requestsBeforeDenial + 1); }); test("rejects local package drift after preview before requesting an upload", async () => { diff --git a/apps/local/tests/overview-worker.test.ts b/apps/local/tests/overview-worker.test.ts new file mode 100644 index 00000000..b38a8a1e --- /dev/null +++ b/apps/local/tests/overview-worker.test.ts @@ -0,0 +1,137 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { openDb } from "@selftune/local-store"; +import { createInteractiveReportWorker } from "../src/interactive-report-worker.js"; +import * as Semaphore from "effect/Semaphore"; + +test("overview worker preserves pagination and shares concurrent identical requests", async () => { + const root = mkdtempSync(join(tmpdir(), "overview-worker-")); + const dbPath = join(root, "db.sqlite"); + const db = openDb(dbPath); + db.close(); + const worker = createInteractiveReportWorker( + "overview", + { + storagePaths: { + configRoot: root, + localDatabasePath: dbPath, + localAnalyticsPath: join(root, "analytics"), + }, + }, + root, + ); + try { + const search = new URLSearchParams("telemetry_limit=1&skills_limit=1"); + const first = worker("fixture", search); + const second = worker("fixture", search); + expect((await worker("fixture", new URLSearchParams("skills_limit=2"))).status).toBe(503); + const [a, b] = await Promise.all([first, second]); + expect(a.status).toBe(200); + const body = await a.json(); + expect(await b.json()).toEqual(body); + expect(body.version).toBe("fixture"); + expect(body.overview.skills_page.items).toEqual([]); + expect(body.overview.telemetry_page.items).toEqual([]); + expect(readdirSync(join(root, "overview"))).toEqual([]); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("selected skill workers retain 404 semantics and coalesce identical reads", async () => { + const root = mkdtempSync(join(tmpdir(), "skill-report-worker-")); + const path = join(root, "db.sqlite"); + const db = openDb(path); + db.close(); + const worker = createInteractiveReportWorker( + "skill-report", + { + storagePaths: { + configRoot: root, + localDatabasePath: path, + localAnalyticsPath: join(root, "analytics"), + }, + }, + root, + ); + try { + const first = worker("missing-worker-fixture", new URLSearchParams("invocations_limit=1")); + const second = worker("missing-worker-fixture", new URLSearchParams("invocations_limit=1")); + const [a, b] = await Promise.all([first, second]); + expect(a.status).toBe(404); + expect(b.status).toBe(404); + expect(await a.json()).toEqual(await b.json()); + expect(readdirSync(join(root, "skill-report"))).toEqual([]); + } finally { + await worker.close(); + rmSync(root, { recursive: true, force: true }); + } +}); + +test("shell cache is versioned and never accepts a result changed during compute", async () => { + const root = mkdtempSync(join(tmpdir(), "shell-worker-cache-")); + let version = "one"; + const worker = createInteractiveReportWorker( + "shell", + { configRoot: root }, + root, + { + command: [ + process.execPath, + join(import.meta.dir, "fixtures", "report-worker.ts"), + "counted-shell", + ], + }, + () => version, + ); + try { + const request = () => worker("fixture", new URLSearchParams()); + expect(await (await request()).json()).toEqual({ count: 1 }); + expect(await (await request()).json()).toEqual({ count: 1 }); + version = "two"; + expect(await (await request()).json()).toEqual({ count: 2 }); + version = "three"; + const inFlight = request(); + version = "four"; + expect(await (await inFlight).json()).toEqual({ count: 3 }); + expect(await (await request()).json()).toEqual({ count: 4 }); + await worker.close(); + expect((await request()).status).toBe(503); + } finally { + await worker.close(); + rmSync(root, { recursive: true, force: true }); + } +}); + +test("worker timeout releases its slot and does not fall back to blocking computation", async () => { + const root = mkdtempSync(join(tmpdir(), "overview-timeout-")); + const worker = createInteractiveReportWorker("overview", { configRoot: root }, root, { + command: [process.execPath, "-e", "setInterval(() => {}, 1000)"], + timeoutMs: 30, + }); + try { + expect((await worker("test", new URLSearchParams())).status).toBe(503); + expect((await worker("new-version", new URLSearchParams())).status).toBe(503); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("shutdown cancels a queued overview and refuses new report work", async () => { + const root = mkdtempSync(join(tmpdir(), "overview-shutdown-")); + const worker = createInteractiveReportWorker("overview", { configRoot: root }, root, { + semaphore: Semaphore.makeUnsafe(0), + }); + try { + const response = worker("test", new URLSearchParams()); + await worker.close(); + expect((await response).status).toBe(503); + expect((await worker("test", new URLSearchParams())).status).toBe(503); + expect(readdirSync(root)).toEqual([]); + } finally { + await worker.close(); + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/local/tests/report-contract.test.ts b/apps/local/tests/report-contract.test.ts index 577ef4ad..9df7831f 100644 --- a/apps/local/tests/report-contract.test.ts +++ b/apps/local/tests/report-contract.test.ts @@ -213,6 +213,33 @@ describe("report subprocess transport", () => { }); describe("persisted report cache decoding", () => { + test("defers artifact reads until first use and never reloads one after invalidation", async () => { + const dir = temporaryDirectory(); + const artifactPath = join(dir, "lazy.json"); + const write = (data: number) => + writeFileSync( + artifactPath, + JSON.stringify({ schema_version: 1, generated_at: "today", data }), + ); + write(1); + const observed = await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const cache = yield* makeMaterializedCache(Effect.succeed(3), { + artifactPath, + schema: Schema.Number, + readVersion: () => "fixed", + }); + write(2); + const initial = yield* cache.read; + yield* cache.invalidate; + const fresh = yield* cache.read; + return [initial, fresh]; + }), + ), + ); + expect(observed).toEqual([2, 3]); + }); test.each([ "{", "null", diff --git a/apps/local/tests/report-lifecycle.test.ts b/apps/local/tests/report-lifecycle.test.ts new file mode 100644 index 00000000..410a298d --- /dev/null +++ b/apps/local/tests/report-lifecycle.test.ts @@ -0,0 +1,61 @@ +import { expect, test } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Semaphore from "effect/Semaphore"; +import { computeReportInWorker } from "../src/report-compute"; + +const fixture = join(import.meta.dir, "fixtures", "report-worker.ts"); + +test("report interruption reaps a real worker before deleting its artifact", async () => { + const root = mkdtempSync(join(tmpdir(), "selftune-worker-cancel-")); + const pidPath = join(root, "worker.pid"); + const ready = async () => { + while (!existsSync(pidPath)) await new Promise((resolve) => setImmediate(resolve)); + return Number(readFileSync(pidPath, "utf8")); + }; + const fiber = Effect.runFork( + computeReportInWorker("portfolio-audit", { configRoot: root }, root, { + command: [process.execPath, fixture, "uncooperative"], + }), + ); + try { + const pid = await ready(); + expect(pid).toBeGreaterThan(0); + await Effect.runPromise(Fiber.interrupt(fiber)); + expect(() => process.kill(pid, 0)).toThrow(); + expect(readdirSync(root)).toEqual(["worker.pid"]); + } finally { + await Effect.runPromise(Fiber.interrupt(fiber)); + rmSync(root, { recursive: true, force: true }); + } +}); + +test("queued reports do not spawn until a host-owned permit is available", async () => { + const root = mkdtempSync(join(tmpdir(), "selftune-worker-permit-")); + try { + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const semaphore = yield* Semaphore.make(0); + const fiber = yield* Effect.forkScoped( + computeReportInWorker("portfolio-audit", { configRoot: root }, root, { + semaphore, + command: [process.execPath, fixture, "valid"], + }), + ); + yield* Effect.yieldNow; + expect(readdirSync(root)).toEqual([]); + yield* semaphore.release(1); + const report = yield* Fiber.join(fiber); + expect(report.installed_count).toBe(0); + expect(readdirSync(root)).toEqual([]); + }), + ), + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/local/tests/report-process-boundary.test.ts b/apps/local/tests/report-process-boundary.test.ts index 99535444..79defcd4 100644 --- a/apps/local/tests/report-process-boundary.test.ts +++ b/apps/local/tests/report-process-boundary.test.ts @@ -34,10 +34,12 @@ describe("report process boundary", () => { test("runs the compiled report worker directly in the packaged Desktop runtime", () => { const resourceRoot = "/tmp/selftune-desktop-resource"; - const worker = - process.platform === "win32" ? "selftune-report-worker.exe" : "selftune-report-worker"; + const worker = process.platform === "win32" ? "selftune.exe" : "selftune"; - expect(reportWorkerCommand(resourceRoot)).toEqual([join(resourceRoot, worker)]); + expect(reportWorkerCommand(resourceRoot)).toEqual([ + join(resourceRoot, worker), + "__selftune_report_worker", + ]); }); test("serializes host-owned SQLite and DuckDB paths instead of inheriting worker defaults", () => { diff --git a/apps/local/tests/skill-package-inspector.test.ts b/apps/local/tests/skill-package-inspector.test.ts new file mode 100644 index 00000000..0669ac1c --- /dev/null +++ b/apps/local/tests/skill-package-inspector.test.ts @@ -0,0 +1,74 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createSkillPackageInspector } from "../src/skill-package-inspector"; + +const fixtures: string[] = []; +afterEach(() => { + for (const path of fixtures.splice(0)) rmSync(path, { recursive: true, force: true }); +}); +function fixture() { + const parent = mkdtempSync(join(tmpdir(), "selftune-package-inspector-")); + fixtures.push(parent); + const root = join(parent, "skill"); + mkdirSync(root); + writeFileSync(join(root, "SKILL.md"), "# Useful skill\n\nRead [the guide](references/guide.md)."); + mkdirSync(join(root, "references")); + writeFileSync(join(root, "references/guide.md"), "## Guide\nActual package text."); + const handler = createSkillPackageInspector(() => [root]); + const request = (file?: string, skillPath = join(root, "SKILL.md"), method = "GET") => { + const url = new URL("http://localhost/api/v2/skill-package"); + url.searchParams.set("skillPath", skillPath); + if (file !== undefined) url.searchParams.set("file", file); + const response = handler(new Request(url, { method }), url); + if (!response) throw new Error("Expected package route"); + return response; + }; + return { root, parent, request }; +} +describe("read-only installed package inspector", () => { + it("lists nested files and returns exact Markdown and source", async () => { + const { request } = fixture(); + expect((await request().json()).files.map((file: { path: string }) => file.path)).toEqual([ + "references/guide.md", + "SKILL.md", + ]); + expect(await request("references/guide.md").json()).toMatchObject({ + content: "## Guide\nActual package text.", + reason: null, + }); + }); + it("rejects traversal, absolute paths, unknown roots and writes", async () => { + const { request, parent } = fixture(); + expect(request("../secret").status).toBe(400); + expect(request("/etc/passwd").status).toBe(400); + expect(request(undefined, join(parent, "SKILL.md")).status).toBe(400); + expect(request(undefined, undefined, "POST").status).toBe(405); + }); + it("does not follow symlink files or directories", async () => { + const { request, root, parent } = fixture(); + writeFileSync(join(parent, "secret"), "private"); + symlinkSync(join(parent, "secret"), join(root, "linked")); + symlinkSync(parent, join(root, "outside")); + expect(await request("linked").json()).toMatchObject({ content: null, reason: "symlink" }); + expect(await request("outside/secret").json()).toMatchObject({ + content: null, + reason: "symlink", + }); + expect( + (await request().json()).files.some( + (file: { path: string }) => file.path === "outside/secret", + ), + ).toBe(false); + }); + it("bounds previews and identifies binary and empty files", async () => { + const { request, root } = fixture(); + writeFileSync(join(root, "large.txt"), "x".repeat(256 * 1024 + 1)); + writeFileSync(join(root, "binary.dat"), Buffer.from([0, 255])); + writeFileSync(join(root, "empty.txt"), ""); + expect(await request("large.txt").json()).toMatchObject({ reason: "too_large", content: null }); + expect(await request("binary.dat").json()).toMatchObject({ reason: "binary", content: null }); + expect(await request("empty.txt").json()).toMatchObject({ reason: null, content: "" }); + }); +}); diff --git a/apps/local/tests/skill-revision-history.test.ts b/apps/local/tests/skill-revision-history.test.ts new file mode 100644 index 00000000..827bd584 --- /dev/null +++ b/apps/local/tests/skill-revision-history.test.ts @@ -0,0 +1,233 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { + chmodSync, + mkdtempSync, + mkdirSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, + statSync, + realpathSync, + utimesSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { openDb } from "@selftune/local-store"; +import { createSkillRevisionHistory } from "@selftune/runtime/skill-revision-history"; +import { createSkillRevisionService } from "../src/skill-revision-service"; + +let root: string; +let skill: string; +let db: ReturnType; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "selftune-history-")); + skill = join(root, "skill"); + mkdirSync(skill); + writeFileSync(join(skill, "SKILL.md"), "first"); + db = openDb(join(root, "history.db")); +}); +afterEach(() => { + db.close(); + rmSync(root, { recursive: true, force: true }); +}); +const history = () => createSkillRevisionHistory(db, join(root, "config")); + +test("background scan yields between packages and stop cancels remaining work", async () => { + const paths = [skill]; + for (let i = 0; i < 3; i += 1) { + const path = join(root, `skill-${i}`); + mkdirSync(path); + writeFileSync(join(path, "SKILL.md"), "skill"); + paths.push(path); + } + const service = createSkillRevisionService(db, join(root, "config"), { paths: () => paths }); + service.start(); + await new Promise((resolve) => setImmediate(resolve)); + service.stop(); + const count = db + .query<{ count: number }, []>("SELECT COUNT(*) AS count FROM skill_local_revisions") + .get()!.count; + expect(count).toBeLessThan(paths.length); + await new Promise((resolve) => setImmediate(resolve)); + expect( + db.query<{ count: number }, []>("SELECT COUNT(*) AS count FROM skill_local_revisions").get()! + .count, + ).toBe(count); +}); + +test("selected registry aliases authorize their current target and reject removed links", async () => { + const previous = process.env.SELFTUNE_HOME; + process.env.SELFTUNE_HOME = join(root, "home"); + const registry = join(root, "home", ".agents", "skills"); + mkdirSync(registry, { recursive: true }); + const alias = join(registry, "renamed-alias"); + symlinkSync(skill, alias, "dir"); + const service = createSkillRevisionService(db, join(root, "config")); + const url = new URL( + `http://localhost/api/v2/skill-history?path=${encodeURIComponent(join(alias, "SKILL.md"))}`, + ); + try { + const response = await service.handle(new Request(url), url, new Set()); + if (!response) throw new Error("History route did not handle the fixture"); + expect(response.status).toBe(200); + expect((await response.json()).revisions[0].package_path).toBe(realpathSync(skill)); + rmSync(alias); + expect((await service.handle(new Request(url), url, new Set()))?.status).toBe(400); + } finally { + if (previous === undefined) delete process.env.SELFTUNE_HOME; + else process.env.SELFTUNE_HOME = previous; + } +}); + +test("fingerprint cache detects same-size edits with restored mtime and permission changes", () => { + const tracker = history(); + const path = join(skill, "SKILL.md"); + const before = statSync(path); + const first = tracker.fingerprint(skill); + expect(tracker.fingerprint(skill)).toBe(first); + writeFileSync(path, "other"); + utimesSync(path, before.atime, before.mtime); + const edited = tracker.fingerprint(skill); + expect(edited).not.toBe(first); + chmodSync(path, 0o755); + expect(tracker.fingerprint(skill)).not.toBe(edited); +}); + +test("captures whole-package revisions, deduplicates unchanged files, and survives restart", () => { + const first = history().capture(skill); + expect(first.revision).toBe(1); + expect(history().capture(skill).revision).toBe(1); + mkdirSync(join(skill, "scripts")); + writeFileSync(join(skill, "scripts/run.sh"), "echo hello", { mode: 0o755 }); + expect(history().capture(skill).revision).toBe(2); + db.close(); + db = openDb(join(root, "history.db")); + expect( + history() + .list(skill) + .map((entry) => entry.revision), + ).toEqual([2, 1]); + expect(history().diff(skill, 2)[0]?.path).toBe("scripts/run.sh"); +}); + +test("restores deleted and changed files, removes additions, and appends history", () => { + history().capture(skill); + writeFileSync(join(skill, "SKILL.md"), "second"); + writeFileSync(join(skill, "extra.txt"), "extra"); + const second = history().capture(skill); + const restored = history().restore(skill, 1, second.content_hash); + expect(restored.revision).toBe(3); + expect(restored.restored_from).toBe(1); + expect(readFileSync(join(skill, "SKILL.md"), "utf8")).toBe("first"); + expect( + history() + .diff(skill, 3) + .map((file) => file.change) + .sort(), + ).toEqual(["deleted", "modified"]); +}); + +test("stale restore preserves unobserved edits and rejects overwrite", () => { + const first = history().capture(skill); + writeFileSync(join(skill, "SKILL.md"), "unobserved"); + expect(() => history().restore(skill, 1, first.content_hash)).toThrow("changed since review"); + expect(readFileSync(join(skill, "SKILL.md"), "utf8")).toBe("unobserved"); + expect(history().list(skill)).toHaveLength(2); +}); + +test("deduplicates linked installations and rejects internal symlinks", () => { + const alias = join(root, "alias"); + symlinkSync(skill, alias); + history().capture(alias); + history().capture(skill); + expect(history().list(alias)).toHaveLength(1); + symlinkSync(join(root, "history.db"), join(skill, "external")); + expect(() => history().capture(skill)).toThrow("does not follow links"); +}); + +test("rejects corrupted snapshots before touching installed files", () => { + const first = history().capture(skill); + db.query("UPDATE skill_local_revisions SET snapshot_json = ?").run( + JSON.stringify([{ path: "../escape", content: "", mode: 420 }]), + ); + expect(() => history().restore(skill, 1, first.content_hash)).toThrow("integrity"); + expect(readFileSync(join(skill, "SKILL.md"), "utf8")).toBe("first"); +}); + +test("automatic scan waits for stable edits and records later reversions", () => { + const service = createSkillRevisionService(db, join(root, "config"), { paths: () => [skill] }); + service.scan(); + writeFileSync(join(skill, "SKILL.md"), "second"); + service.scan(); + expect(history().list(skill)).toHaveLength(1); + service.scan(); + expect(history().list(skill)).toHaveLength(2); + writeFileSync(join(skill, "SKILL.md"), "first"); + service.scan(); + service.scan(); + expect(history().list(skill)).toHaveLength(3); +}); + +test("HTTP rejects foreign origins and paths outside discovered installations", async () => { + const service = createSkillRevisionService(db, join(root, "config"), { paths: () => [skill] }); + const url = new URL("http://localhost:8787/api/v2/skill-history"); + const origins = new Set([url.origin]); + const denied = await service.handle( + new Request(url, { method: "POST", body: "{}" }), + url, + origins, + ); + expect(denied?.status).toBe(403); + url.searchParams.set("path", join(root, "SKILL.md")); + expect((await service.handle(new Request(url), url, origins))?.status).toBe(400); + url.searchParams.set("path", join(skill, "SKILL.md")); + const response = await service.handle(new Request(url), url, origins); + expect(response?.status).toBe(200); + expect(await response?.json()).toMatchObject({ revisions: [{ revision: 1 }] }); +}); + +test("rejects oversized packages without recording a partial revision", () => { + writeFileSync(join(skill, "large.bin"), Buffer.alloc(8 * 1024 * 1024)); + expect(() => history().capture(skill)).toThrow("8 MiB"); + expect(history().list(skill)).toHaveLength(0); +}); + +test("keeps executable permissions and binary bytes through restore", () => { + const bytes = Buffer.from([0, 255, 1, 2]); + writeFileSync(join(skill, "run"), bytes, { mode: 0o755 }); + history().capture(skill); + rmSync(join(skill, "run")); + const second = history().capture(skill); + history().restore(skill, 1, second.content_hash); + expect(readFileSync(join(skill, "run"))).toEqual(bytes); + expect(history().diff(skill, 3)[0]).toMatchObject({ after: null, afterMode: 0o755 }); +}); + +test("keeps immutable Library packages untouched", () => { + const immutable = join(root, "config/library/packages/hash/skill"); + mkdirSync(immutable, { recursive: true }); + writeFileSync(join(immutable, "SKILL.md"), "immutable"); + expect(() => history().capture(immutable)).toThrow("Immutable Library"); +}); + +test("running service captures external edits without a history request", async () => { + const initial = Promise.withResolvers(); + const service = createSkillRevisionService(db, join(root, "config"), { + paths: () => [skill], + onChange: () => initial.resolve(), + }); + service.start(); + try { + await initial.promise; + writeFileSync(join(skill, "SKILL.md"), "edited by an external agent"); + await Bun.sleep(10_500); + expect( + history() + .list(skill) + .map((entry) => entry.revision), + ).toEqual([2, 1]); + } finally { + service.stop(); + } +}, 15_000); diff --git a/apps/local/tests/source-task-reconstruction.test.ts b/apps/local/tests/source-task-reconstruction.test.ts new file mode 100644 index 00000000..eb5aafee --- /dev/null +++ b/apps/local/tests/source-task-reconstruction.test.ts @@ -0,0 +1,322 @@ +import { expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DuckDBInstance } from "@duckdb/node-api"; +import { openDb } from "@selftune/local-store"; +import { + DuckDbAnalyticalStore, + type DuckDbAnalyticalStoreService, + type SourceTaskRequest, +} from "@selftune/observability/duckdb-store"; +import { makeDuckDbNodeApiAnalyticalStoreLive } from "@selftune/observability/duckdb-node-api"; +import { sourceIdentityKey } from "@selftune/observability/source-identity"; +import { + SourceSnapshot, + sourceDigest, + CODEX_RECONSTRUCTION_PARSER, +} from "@selftune/observability/source-reconstruction"; +import { + LocalTraceImporter, + LocalTraceImportRequest, +} from "@selftune/observability/local-trace-importer"; +import { makeLocalTraceImporterLive } from "@selftune/orchestration/sync/local-trace-importer"; +import { reconstructSourceTask } from "@selftune/orchestration/reconstruct-source-task"; +import { NORMALIZER_VERSION } from "@selftune/runtime/normalization"; +import { computeSkillVersionHash } from "@selftune/runtime/utils/skill-discovery"; +import { parseRolloutText } from "../../../packages/harnesses/codex/src/ingestors/codex-rollout.js"; +import { buildLocalTelemetryBatchFromRollout } from "../../../packages/harnesses/codex/src/ingestors/codex-trace-projection.js"; +import { Effect, Layer } from "effect"; +import { compactFixture } from "../../../tests/observability/compact-fixture.js"; +import { + TraceCandidatePreparation, + executionPatternIdForSkill, + makeTraceCandidatePreparationLayer, +} from "../src/trace-candidate-service.js"; + +test("production candidate preparation reconstructs missing tasks from exact originals and pins recipes", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-source-task-")); + const sqlite = openDb(":memory:"); + let path = join(directory, "analytics.duckdb"); + const skillDir = join(directory, "skills", "to-issues"); + mkdirSync(skillDir, { recursive: true }); + const skillPath = join(skillDir, "SKILL.md"); + writeFileSync( + skillPath, + "---\nname: to-issues\ndescription: Break plans into issues.\n---\n# To Issues\nBreak plans into vertical issue slices.\n", + ); + const revision = computeSkillVersionHash(skillPath); + if (!revision) throw new Error("fixture skill revision unavailable"); + const storeLayer = () => makeDuckDbNodeApiAnalyticalStoreLive(path); + const query = (run: (store: DuckDbAnalyticalStoreService) => Effect.Effect) => + Effect.runPromise( + Effect.gen(function* () { + return yield* run(yield* DuckDbAnalyticalStore); + }).pipe(Effect.provide(storeLayer()), Effect.scoped), + ); + const fixtureSql = async (statements: string[]) => { + const db = await DuckDBInstance.create(path); + const connection = await db.connect(); + try { + for (const sql of statements) await connection.run(sql); + } finally { + connection.closeSync(); + db.closeSync(); + } + }; + const requests: LocalTraceImportRequest[] = []; + const sources: string[] = []; + const tasks = [ + "Use to-issues to split the billing rollout into tracked issues", + "Use to-issues to plan the desktop update workflow", + "Use to-issues to decompose the skill sharing feature", + ]; + const importRequest = (request: LocalTraceImportRequest) => + Effect.runPromise( + Effect.gen(function* () { + return yield* (yield* LocalTraceImporter).importTrace(request); + }).pipe( + Effect.provide(Layer.provide(makeLocalTraceImporterLive(sqlite), storeLayer())), + Effect.scoped, + ), + ); + const prepare = () => + Effect.runPromise( + Effect.gen(function* () { + return yield* (yield* TraceCandidatePreparation).prepare({ + pattern_id: executionPatternIdForSkill("to-issues"), + }); + }).pipe( + Effect.provide( + Layer.provide( + makeTraceCandidatePreparationLayer({ + sqlite, + searchDirs: [join(directory, "skills")], + teacher: async () => { + throw new Error("Uncalibrated evidence must not invoke a teacher"); + }, + }), + storeLayer(), + ), + ), + Effect.scoped, + ), + ); + try { + for (let index = 0; index < tasks.length; index++) { + const source = join(directory, `rollout-${index}.jsonl`); + const session = `fixture-${index}`; + const text = [ + { + type: "session_meta", + timestamp: "2026-09-01T00:00:00Z", + payload: { id: session, cwd: directory }, + }, + { + type: "event_msg", + timestamp: "2026-09-01T00:00:01Z", + payload: { type: "user_message", message: tasks[index] }, + }, + { + type: "turn.completed", + timestamp: "2026-09-01T00:00:02Z", + usage: { input_tokens: 100, output_tokens: 20 }, + }, + ] + .map((item) => JSON.stringify(item)) + .join("\n"); + writeFileSync(source, text); + sources.push(source); + const parsed = parseRolloutText(source, text, new Set(["to-issues"]), () => new Set()); + const batch = parsed && buildLocalTelemetryBatchFromRollout(parsed); + const link = batch?.links?.[0]; + if (!parsed || !batch || !link) throw new Error("fixture must produce a linked trace"); + sqlite.run( + "INSERT INTO sessions (session_id, platform, capture_mode) VALUES (?, 'codex', 'rollout')", + [session], + ); + sqlite.run( + `INSERT INTO skill_invocations (skill_invocation_id, session_id, skill_name, skill_version_hash, + skill_path, invocation_mode, triggered, source, platform, capture_mode) + VALUES (?, ?, 'to-issues', ?, ?, 'explicit', 1, 'codex_rollout', 'codex', 'rollout')`, + [link.skill_invocation_id, session, revision, skillPath], + ); + const snapshot = SourceSnapshot.make({ + parser: CODEX_RECONSTRUCTION_PARSER, + path: source, + sha256: sourceDigest(Buffer.from(text)), + bytes: Buffer.byteLength(text), + skill_names: ["to-issues"], + task_sha256: sourceDigest(Buffer.from(parsed.query)), + workspace_skills: [{ cwd: directory, names: [] }], + }); + const request = LocalTraceImportRequest.make({ + source_kind: "codex", + source_session_ids: [session], + source_revision: snapshot.sha256, + normalizer_version: NORMALIZER_VERSION, + source_snapshot: snapshot, + batch, + }); + requests.push(request); + await importRequest(request); + } + await fixtureSql([ + "DELETE FROM observability_spans", + "DELETE FROM observability_metrics", + "UPDATE observability_source_reconstruction SET detail_state = 'evicted'", + ]); + const result = await prepare(); + expect(result.evidence.resolved_entries).toBe(3); + expect(result.failure_reason).toContain("neutral until"); + expect((await query((store) => store.health())).span_count).toBe(0); + const first = requests[0]; + const link = first.batch.links?.[0]; + if (!link) throw new Error("fixture link missing"); + const read: SourceTaskRequest = { + ...link, + source_revision: first.source_revision, + skill_revision: revision, + pin_id: "exact-fixture-pin", + replay: reconstructSourceTask, + }; + expect(await query((store) => store.resolveSourceTask(read))).toMatchObject({ + state: "available", + task: tasks[0], + }); + const beforeCompaction = await prepare(); + const originalDigests = sources.map((source) => sourceDigest(readFileSync(source))); + const compactedPath = join(directory, "compacted.duckdb"); + await compactFixture(path, compactedPath); + path = compactedPath; + expect(await prepare()).toEqual(beforeCompaction); + expect(await query((store) => store.resolveSourceTask(read))).toMatchObject({ + state: "available", + task: tasks[0], + }); + expect(sources.map((source) => sourceDigest(readFileSync(source)))).toEqual(originalDigests); + const allocated = statSync(path).blocks * 512; + for (let retry = 0; retry < 10; retry++) { + await importRequest(first); + expect(await query((store) => store.resolveSourceTask(read))).toMatchObject({ + state: "available", + }); + } + expect((await query((store) => store.health())).span_count).toBe(0); + console.info("source-reconstruction fixture allocated bytes", { + beforeRetries: allocated, + after10Retries: statSync(path).blocks * 512, + }); + expect(statSync(path).blocks * 512 - allocated).toBeLessThan(4 * 1024 * 1024); + expect(statSync(path).blocks * 512).toBeLessThan(32 * 1024 * 1024); + expect( + await query((store) => store.resolveSourceTask({ ...read, skill_revision: "different" })), + ).toEqual({ state: "unavailable", reason: "unverified_skill_revision" }); + expect( + await query((store) => + store.resolveSourceTask({ + ...read, + replay: async (input) => { + const replayed = await reconstructSourceTask(input); + return replayed.state === "reconstructed" + ? { ...replayed, batch: { ...replayed.batch, links: [] } } + : replayed; + }, + }), + ), + ).toEqual({ state: "unavailable", reason: "projection_changed" }); + const original = readFileSync(sources[0]); + writeFileSync(sources[0], "changed original"); + expect((await prepare()).failure_reason).toContain("source_changed"); + rmSync(sources[0]); + expect(await query((store) => store.resolveSourceTask(read))).toEqual({ + state: "unavailable", + reason: "source_missing", + }); + writeFileSync(sources[0], original); + await importRequest({ + ...first, + source_revision: "revised", + normalizer_version: NORMALIZER_VERSION, + }); + // Pin still names the old exact recipe; updating discovery does not silently retarget it. + expect(await query((store) => store.resolveSourceTask(read))).toMatchObject({ + state: "available", + task: tasks[0], + }); + expect((await query((store) => store.health())).span_count).toBe(0); + expect( + await query((store) => + store.resolveSourceTask({ ...read, trace_id: "f".repeat(32), pin_id: "missing-source" }), + ), + ).toEqual({ state: "unavailable", reason: "missing" }); + const started = Promise.withResolvers(); + const unblock = Promise.withResolvers(); + const controller = new AbortController(); + const interrupted = Effect.runPromiseExit( + Effect.gen(function* () { + return yield* (yield* DuckDbAnalyticalStore).resolveSourceTask({ + ...read, + source_revision: "revised", + pin_id: "interrupted", + replay: async (input) => { + started.resolve(); + await unblock.promise; + return reconstructSourceTask(input); + }, + }); + }).pipe(Effect.provide(storeLayer()), Effect.scoped), + { signal: controller.signal }, + ); + await started.promise; + controller.abort(); + expect((await interrupted)._tag).toBe("Failure"); + unblock.resolve(); + const inspection = await DuckDBInstance.create(path); + const inspectionConnection = await inspection.connect(); + try { + expect( + await ( + await inspectionConnection.run( + "SELECT pin_id FROM observability_source_evidence_pins WHERE pin_id = 'interrupted'", + ) + ).getRowObjects(), + ).toEqual([]); + } finally { + inspectionConnection.closeSync(); + inspection.closeSync(); + } + await importRequest({ + ...first, + source_revision: "future-normalizer", + normalizer_version: "unsupported", + }); + expect( + await query((store) => + store.resolveSourceTask({ + ...read, + source_revision: "future-normalizer", + pin_id: "future-normalizer", + }), + ), + ).toEqual({ state: "unavailable", reason: "normalizer_changed" }); + await fixtureSql([ + `INSERT INTO observability_expired_sources VALUES ('${sourceIdentityKey({ provider: "codex", session_id: "fixture-0" })}')`, + "DELETE FROM observability_source_reconstruction", + ]); + const expiredCopy = join(directory, "expired-compacted.duckdb"); + await compactFixture(path, expiredCopy); + path = expiredCopy; + expect(await query((store) => store.resolveSourceTask(read))).toEqual({ + state: "unavailable", + reason: "expired", + }); + await expect( + importRequest({ ...first, source_revision: "force-reimport", normalizer_version: "next" }), + ).rejects.toThrow("cannot resurrect"); + expect((await query((store) => store.health())).span_count).toBe(0); + } finally { + sqlite.close(); + rmSync(directory, { recursive: true }); + } +}); diff --git a/apps/selfhost/package.json b/apps/selfhost/package.json index dc400d31..18561926 100644 --- a/apps/selfhost/package.json +++ b/apps/selfhost/package.json @@ -13,7 +13,7 @@ "@selftune/control-plane": "workspace:*", "@selftune/local": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/apps/selfhost/src/config.ts b/apps/selfhost/src/config.ts index f4b66779..c80d3aac 100644 --- a/apps/selfhost/src/config.ts +++ b/apps/selfhost/src/config.ts @@ -17,7 +17,7 @@ const ConfiguredUserInput = Schema.Struct({ const ConfiguredUsersInput = Schema.Array(ConfiguredUserInput); -export class SelfHostConfigFailure extends Schema.TaggedErrorClass()( +export class SelfHostConfigFailure extends Schema.TaggedError()( "SelfHostConfigFailure", { message: Schema.String }, ) {} diff --git a/apps/selfhost/src/remote-dashboard.ts b/apps/selfhost/src/remote-dashboard.ts index 5430cd9d..67f469ce 100644 --- a/apps/selfhost/src/remote-dashboard.ts +++ b/apps/selfhost/src/remote-dashboard.ts @@ -49,7 +49,7 @@ const StoredSkillSet = Schema.Struct({ updated_at: Schema.String, }); -class RemoteDashboardFailure extends Schema.TaggedErrorClass()( +class RemoteDashboardFailure extends Schema.TaggedError()( "RemoteDashboardFailure", { operation: Schema.String, diff --git a/apps/selfhost/src/repository.ts b/apps/selfhost/src/repository.ts index cbfce92f..2e9fd4ee 100644 --- a/apps/selfhost/src/repository.ts +++ b/apps/selfhost/src/repository.ts @@ -47,7 +47,7 @@ const ArtifactArray = Schema.Array(RemoteArtifactSchema); const decodeArtifacts = Schema.decodeUnknownSync(ArtifactArray); const decodeSetManifest = Schema.decodeUnknownSync(SharedSetManifest); -export class SelfHostFailure extends Schema.TaggedErrorClass()("SelfHostFailure", { +export class SelfHostFailure extends Schema.TaggedError()("SelfHostFailure", { code: Schema.String, message: Schema.String, status: Schema.Number, diff --git a/apps/use-once-helper/package.json b/apps/use-once-helper/package.json index d5fdd002..3d4dc619 100644 --- a/apps/use-once-helper/package.json +++ b/apps/use-once-helper/package.json @@ -19,7 +19,7 @@ }, "dependencies": { "@selftune/control-plane": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/bun.lock b/bun.lock index 0fe21dea..abb8e427 100644 --- a/bun.lock +++ b/bun.lock @@ -6,8 +6,8 @@ "name": "selftune", "dependencies": { "@duckdb/node-api": "1.4.5-r.1", - "@effect/platform-bun": "4.0.0-beta.66", - "@effect/platform-node-shared": "4.0.0-beta.66", + "@effect/platform-bun": "4.0.0-rc.115", + "@effect/platform-node-shared": "4.0.0-rc.115", "@selftune/config": "workspace:*", "@selftune/control-plane": "workspace:*", "@selftune/dashboard-core": "workspace:*", @@ -31,7 +31,7 @@ "@selftune/ui": "workspace:*", "@xmldom/xmldom": "^0.8.13", "drizzle-orm": "^0.45.0", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", "react-markdown": "^10.1.0", "sonner": "^2.0.7", "zod": "^4.3.6", @@ -39,8 +39,7 @@ "devDependencies": { "@changesets/changelog-github": "^0.7.0", "@changesets/cli": "^2.30.0", - "@effect/tsgo": "^0.24.1", - "@effect/vitest": "4.0.0-beta.66", + "@effect/tsgo": "0.45.0", "@evilmartians/lefthook": "^1.13.6", "@oxlint/plugins": "1.78.0", "@types/bun": "^1.3.11", @@ -56,15 +55,15 @@ "react-dom": "^19.1.0", "turbo": "^2.5.6", "typescript": "^5.9.3", - "vitest": "^4.0.18", + "vitest": "4.1.10", }, }, "apps/cli": { "name": "@selftune/cli", "version": "1.0.0", "dependencies": { - "@effect/platform-bun": "4.0.0-beta.66", - "@effect/platform-node-shared": "4.0.0-beta.66", + "@effect/platform-bun": "4.0.0-rc.115", + "@effect/platform-node-shared": "4.0.0-rc.115", "@selftune/control-plane": "workspace:*", "@selftune/harness-claude-code": "workspace:*", "@selftune/harness-cline": "workspace:*", @@ -76,7 +75,7 @@ "@selftune/local-store": "workspace:*", "@selftune/orchestration": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -86,12 +85,12 @@ }, "apps/desktop": { "name": "@selftune/desktop", - "version": "0.4.12", + "version": "0.5.1", "dependencies": { "@selftune/config": "workspace:*", "@sentry/electron": "^7.8.0", "@zip.js/zip.js": "^2.8.17", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", "electron-log": "^5.4.3", "electron-updater": "^6.6.2", }, @@ -113,7 +112,7 @@ "name": "@selftune/local", "version": "1.0.0", "dependencies": { - "@effect/platform-bun": "4.0.0-beta.66", + "@effect/platform-bun": "4.0.0-rc.115", "@selftune/dashboard-core": "workspace:*", "@selftune/harness-claude-code": "workspace:*", "@selftune/harness-core": "workspace:*", @@ -125,7 +124,7 @@ "@selftune/runtime": "workspace:*", "@selftune/skill-intelligence": "workspace:*", "@xmldom/xmldom": "^0.8.13", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@duckdb/node-api": "1.4.5-r.1", @@ -155,7 +154,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", "lucide-react": "^0.577.0", "next-themes": "^0.4.6", "react": "^19.1.0", @@ -190,7 +189,7 @@ "@selftune/control-plane": "workspace:*", "@selftune/local": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -206,7 +205,7 @@ }, "dependencies": { "@selftune/control-plane": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -240,28 +239,28 @@ "name": "@selftune/config", "version": "1.0.0", "dependencies": { - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { - "@effect/platform-bun": "4.0.0-beta.66", - "@effect/vitest": "4.0.0-beta.66", + "@effect/platform-bun": "4.0.0-rc.115", + "@effect/vitest": "4.0.0-rc.115", "@types/bun": "^1.3.11", "bun-types": "^1.3.11", "typescript": "^5.9.3", - "vitest": "^4.0.18", + "vitest": "5.0.1", }, }, "packages/control-plane": { "name": "@selftune/control-plane", "version": "1.0.0", "dependencies": { - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { - "@effect/vitest": "4.0.0-beta.66", + "@effect/vitest": "4.0.0-rc.115", "@types/node": "^20", "typescript": "^5.9.3", - "vitest": "^4.0.18", + "vitest": "5.0.1", }, }, "packages/dashboard-core": { @@ -294,7 +293,7 @@ "@selftune/local-store": "workspace:*", "@selftune/observability": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -325,7 +324,7 @@ "@selftune/local-store": "workspace:*", "@selftune/observability": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -337,7 +336,7 @@ "name": "@selftune/harness-core", "version": "1.0.0", "dependencies": { - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -366,7 +365,7 @@ "@selftune/harness-core": "workspace:*", "@selftune/observability": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -382,7 +381,7 @@ "@selftune/harness-core": "workspace:*", "@selftune/observability": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -415,7 +414,7 @@ "@selftune/control-plane": "workspace:*", "@selftune/local-store": "workspace:*", "@selftune/telemetry-contract": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -429,7 +428,7 @@ "dependencies": { "@selftune/config": "workspace:*", "drizzle-orm": "^0.45.0", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -445,7 +444,7 @@ "@duckdb/node-api": "1.4.5-r.1", "@opentelemetry/otlp-transformer": "0.206.0", "@selftune/config": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -471,14 +470,14 @@ "@selftune/skill-intelligence": "workspace:*", "@selftune/source-management": "workspace:*", "@selftune/telemetry-contract": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { - "@effect/vitest": "4.0.0-beta.66", + "@effect/vitest": "4.0.0-rc.115", "@types/bun": "^1.3.11", "bun-types": "^1.3.11", "typescript": "^5.9.3", - "vitest": "^4.0.18", + "vitest": "5.0.1", }, }, "packages/runtime": { @@ -495,7 +494,7 @@ "@selftune/source-management": "workspace:*", "@selftune/telemetry-contract": "workspace:*", "drizzle-orm": "^0.45.0", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -518,7 +517,7 @@ "version": "1.0.0", "dependencies": { "@selftune/control-plane": "workspace:*", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", }, "devDependencies": { "@types/bun": "^1.3.11", @@ -719,27 +718,27 @@ "@duckdb/node-bindings-win32-x64": ["@duckdb/node-bindings-win32-x64@1.4.5-r.1", "", { "os": "win32", "cpu": "x64" }, "sha512-4a1FmopqCbJgtUwDswEAzozCbSOR+waiJyAl4K9LHfACV897e72w/XZQT9kHEw36GJE03uWJIyqHlcV+WA+tXA=="], - "@effect/platform-bun": ["@effect/platform-bun@4.0.0-beta.66", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.66" }, "peerDependencies": { "effect": "^4.0.0-beta.66" } }, "sha512-egxbmAEtJZ8FYTaPMrYu3VwjgVuzHj3VdUyPyZ/QhSFP/DW2Yunlk/ouChi1JzX/m+Gj8tdMma7NiqO59J9d5Q=="], + "@effect/platform-bun": ["@effect/platform-bun@4.0.0-rc.115", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-rc.115" }, "peerDependencies": { "effect": "^4.0.0-rc.115" } }, "sha512-ilTFcs66ghInP8WHCJYa4bx/yzohYM9dRR//qjmVBBpSKu1hrCTiRWpEcc1N6zrnOEPk2kyVaKg5ykSMgiBMqQ=="], - "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.66", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.66" } }, "sha512-+ymrhBnESv/hmn5SKTe2//IY9Ox/hGPeoogEWhW47ZGyhFI5eMYFxdEUBa+3IAV05rrBzrxON9lynu68n0DM7w=="], + "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-rc.115", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.21.3" }, "peerDependencies": { "effect": "^4.0.0-rc.115" } }, "sha512-rcBwhDIfb82akJoTv7Vwh8K5x9vC/XfuePS7JjOr+z+dORXzsmKqI1BUQF27ARCN9fTAbDh7I6YvBlWhLjnqNg=="], - "@effect/tsgo": ["@effect/tsgo@0.24.1", "", { "optionalDependencies": { "@effect/tsgo-darwin-arm64": "0.24.1", "@effect/tsgo-darwin-x64": "0.24.1", "@effect/tsgo-linux-arm": "0.24.1", "@effect/tsgo-linux-arm64": "0.24.1", "@effect/tsgo-linux-x64": "0.24.1", "@effect/tsgo-win32-arm64": "0.24.1", "@effect/tsgo-win32-x64": "0.24.1" }, "bin": { "effect-tsgo": "dist/effect-tsgo.js" } }, "sha512-ACAFRn2tk61Dy66sA2Kt5TFswmTdql/fhKjka6xU0rAyc5Uug9mgrdcxtSXt3j8MPNZee2Ulz5XzXNiXs6cqag=="], + "@effect/tsgo": ["@effect/tsgo@0.45.0", "", { "optionalDependencies": { "@effect/tsgo-darwin-arm64": "0.45.0", "@effect/tsgo-darwin-x64": "0.45.0", "@effect/tsgo-linux-arm": "0.45.0", "@effect/tsgo-linux-arm64": "0.45.0", "@effect/tsgo-linux-x64": "0.45.0", "@effect/tsgo-win32-arm64": "0.45.0", "@effect/tsgo-win32-x64": "0.45.0" }, "bin": { "effect-tsgo": "dist/effect-tsgo.cjs" } }, "sha512-gPG0ixVHgtYBUe5DbKX9vzHlhqd9+ZEfs4m/XWy0808av0A2XqMzaG3F5rnPBN7EUJRPlo9TluIi8WHx/pBV+A=="], - "@effect/tsgo-darwin-arm64": ["@effect/tsgo-darwin-arm64@0.24.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-/Xyv6kbcf5+jHL2RjOq+F6v/lo92MXqtpYukr9deNPYGFsuXwMgpJhh5LBLo5sfGGiZZXZRqy465SqlgH8VmrA=="], + "@effect/tsgo-darwin-arm64": ["@effect/tsgo-darwin-arm64@0.45.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-WUoiEVcm8E19QK6fl63lsssM4dkT9IFnULbmqQ6LBfv7H9uRkpE9S3thj8ZtZ+vl/QY8atwfuaTf+3A1m/kGtQ=="], - "@effect/tsgo-darwin-x64": ["@effect/tsgo-darwin-x64@0.24.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-lKs6FgwibSdN1BNKs4OCvaNiqhd/zzwvnj0+ohFItiRj0cPvAXEuXQWtZx6tVk0uSTE4OoVbfCXB1hNpf5OiGQ=="], + "@effect/tsgo-darwin-x64": ["@effect/tsgo-darwin-x64@0.45.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-s3yz7ZfIzvObXJ/r5xd9sEPxHKC3L+D+yedS1BV2Kpn47Je2svYCNYKxzXIpqFLkNjK+RcOQrcfYbYEpKZZa6g=="], - "@effect/tsgo-linux-arm": ["@effect/tsgo-linux-arm@0.24.1", "", { "os": "linux", "cpu": "arm" }, "sha512-EqwZRmyH1X/g1yFlWxBxlGdSs88gKwAF+PYEuz4ZzXpZjgYx58fsgMw7JtAz8wL8qAJ7tyLyB1OK5qbkKBnL7w=="], + "@effect/tsgo-linux-arm": ["@effect/tsgo-linux-arm@0.45.0", "", { "os": "linux", "cpu": "arm" }, "sha512-f6zL6YbWA9lXdfJ//KOjUz/U3CdGtajKi5NsR/lcQaKfZiJwHfeeLBB3yetF3qbPGSA149/kuMoDMWL13RUH3A=="], - "@effect/tsgo-linux-arm64": ["@effect/tsgo-linux-arm64@0.24.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-q5vOx+Lysx8tzbM9gFwOpO6P2rwRtsq625BRpsCs5W8+xcF35sxl+yZgLUYeZdgt2x7ZyuooMfnC9qky9su5aw=="], + "@effect/tsgo-linux-arm64": ["@effect/tsgo-linux-arm64@0.45.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-N+lyzixtylOOn49demDaqg0kb/U8ISxM10Gphs1pIMSGlqlfqC4inYEoFpYej+f4T/cRlkA11Ue7wJzNz83ePA=="], - "@effect/tsgo-linux-x64": ["@effect/tsgo-linux-x64@0.24.1", "", { "os": "linux", "cpu": "x64" }, "sha512-SfqKYx5CBGqyWimVaDdjtIdbPg9KkBi3XlL3libPmRPLX74k4zSdFXqKzx0a6BhjYAhGnRcZLhZEdjoMt7E5Ow=="], + "@effect/tsgo-linux-x64": ["@effect/tsgo-linux-x64@0.45.0", "", { "os": "linux", "cpu": "x64" }, "sha512-aWt0G8celAxJOis4+xiILkyMP/3J+vukimUhSoCmUAPt8zoT9qhZcN64XYZE7jfqp88ByRdgN9GK1/C7YfPtcQ=="], - "@effect/tsgo-win32-arm64": ["@effect/tsgo-win32-arm64@0.24.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-FAJ6REixAqXAWtH8odFU6qjcHJVXdrbmsDczj5OREnZYdjh+4Yk5eN1r4ZplaJjDDLeck+Pmf2yB4aQpmqwC7Q=="], + "@effect/tsgo-win32-arm64": ["@effect/tsgo-win32-arm64@0.45.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-EAdeV366ja+M4XCx6xjXMv4Xkc0Fgzy4bapa0saDWcGhllNLqJDfOk4lk0BgAEjBUI8+0xC+PXKVB5SMz4EpVA=="], - "@effect/tsgo-win32-x64": ["@effect/tsgo-win32-x64@0.24.1", "", { "os": "win32", "cpu": "x64" }, "sha512-Gpv559gMtlTo6Q14Cj0rhV47cIGHhYgC+VkMJKPBYRps5Uy7v4/yNNqLWu1QH1/4IQ6gFqXHPEGenQgUb4iiow=="], + "@effect/tsgo-win32-x64": ["@effect/tsgo-win32-x64@0.45.0", "", { "os": "win32", "cpu": "x64" }, "sha512-1Hsr/sT5dmIafoY9L0ASJo4VqGyPNzM1nwTb4Wj1Lmjq6kGuwO/PVozFg3WZZ0piChFmgiU3nx1AKZfyqgjGUw=="], - "@effect/vitest": ["@effect/vitest@4.0.0-beta.66", "", { "peerDependencies": { "effect": "^4.0.0-beta.66", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-UHPNtU0xXkKtNgyRQEh2c8jh4nIIm8Mzp3xc4j2ZdFU4nq5ZSySnpovjPMdoWbVClg1ki8UbpNGEZUfxEJo+6Q=="], + "@effect/vitest": ["@effect/vitest@4.0.0-rc.115", "", { "peerDependencies": { "effect": "^4.0.0-rc.115", "vitest": ">=5.0.0 <6.0.0" } }, "sha512-DJR0hfdr3HNXAkzW8AzfvUz6VmrNFLrKk9tZGDURi33faMyxkc7ZewxELMMZwGpOTGN4mfqYVbX2CXgI+ZJBeQ=="], "@electron/asar": ["@electron/asar@3.4.1", "", { "dependencies": { "commander": "^5.0.0", "glob": "^7.1.6", "minimatch": "^3.0.4" }, "bin": { "asar": "bin/asar.js" } }, "sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA=="], @@ -859,18 +858,6 @@ "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="], - "@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ=="], - - "@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w=="], - - "@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4", "", { "os": "linux", "cpu": "arm" }, "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw=="], - - "@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw=="], - - "@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ=="], - - "@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4", "", { "os": "win32", "cpu": "x64" }, "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ=="], - "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.6", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg=="], "@noble/hashes": ["@noble/hashes@2.2.0", "", {}, "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg=="], @@ -1255,7 +1242,7 @@ "@shikijs/types": ["@shikijs/types@3.23.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ=="], - "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.0.2", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="], + "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.1.0", "", {}, "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ=="], "@sindresorhus/is": ["@sindresorhus/is@4.6.0", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="], @@ -1271,7 +1258,7 @@ "@storybook/global": ["@storybook/global@5.0.0", "", {}, "sha512-FcOqPAXACP0I3oJ/ws6/rrPT9WGhu915Cg8D02a9YxLo0DE9zI+a9A5gRGvmQ09fiWPukqI8ZAEoQEdWUKMQdQ=="], - "@storybook/icons": ["@storybook/icons@2.1.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Fxh9vYpX9bQqFeHRiY8h2ApeRGDzRSMLwJwNZ/AIRqnyOKHxRKL+yFe+ctEkVJmuptRE9u1Hrn8ZZNHyfDKKNg=="], + "@storybook/icons": ["@storybook/icons@2.2.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-FpUB/xizIrV1ILhCIYFo+TtQNN9YEoLjfcnAW0JtOXL+BcM2aisSysI0B54JMWDnljriXySBHgN6ps4s9lb75A=="], "@storybook/react": ["@storybook/react@10.5.7", "", { "dependencies": { "@storybook/global": "^5.0.0", "@storybook/react-dom-shim": "10.5.7", "react-docgen": "^8.0.2", "react-docgen-typescript": "^2.2.2" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "@types/react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.5.7", "typescript": ">= 4.9.x" }, "optionalPeers": ["@types/react", "@types/react-dom", "typescript"] }, "sha512-uFvty2MMdFXzW5PcQe1JqDAZkz6cQq7q/9G/cbGVnBEvP6zsOVeL+bmrQ0/WBlFQN0Ko9+ZoCTvaQ9s65zBa5g=="], @@ -1329,13 +1316,13 @@ "@tanstack/table-core": ["@tanstack/table-core@8.21.3", "", {}, "sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg=="], - "@testing-library/dom": ["@testing-library/dom@10.4.1", "", { "dependencies": { "@babel/code-frame": "^7.10.4", "@babel/runtime": "^7.12.5", "@types/aria-query": "^5.0.1", "aria-query": "5.3.0", "dom-accessibility-api": "^0.5.9", "lz-string": "^1.5.0", "picocolors": "1.1.1", "pretty-format": "^27.0.2" } }, "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg=="], + "@testing-library/dom": ["@testing-library/dom@10.4.2", "", { "dependencies": { "@babel/code-frame": "^7.10.4", "@babel/runtime": "^7.12.5", "@types/aria-query": "^5.0.1", "aria-query": "5.3.0", "dom-accessibility-api": "^0.5.9", "lz-string": "^1.5.0", "picocolors": "1.1.1", "pretty-format": "^27.0.2" } }, "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q=="], "@testing-library/jest-dom": ["@testing-library/jest-dom@6.9.1", "", { "dependencies": { "@adobe/css-tools": "^4.4.0", "aria-query": "^5.0.0", "css.escape": "^1.5.1", "dom-accessibility-api": "^0.6.3", "picocolors": "^1.1.1", "redent": "^3.0.0" } }, "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA=="], "@testing-library/react": ["@testing-library/react@16.3.3", "", { "dependencies": { "@babel/runtime": "^7.12.5" }, "peerDependencies": { "@testing-library/dom": "^10.0.0", "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg=="], - "@testing-library/user-event": ["@testing-library/user-event@14.6.7", "", { "peerDependencies": { "@testing-library/dom": ">=7.21.4" } }, "sha512-MPCpX8bxe8zS+JmmTwLp8jd0dy1rAm60Te/SL8JrQM3qvQJcBOs1d7IefJMyZzqM3EWBrDn/LWDt1BCGu4ASfg=="], + "@testing-library/user-event": ["@testing-library/user-event@14.6.8", "", { "peerDependencies": { "@testing-library/dom": ">=7.21.4" } }, "sha512-vgSSqnANMnkcYR/vUNDbwS7aM3OErRLNUG8vCVVlj4oc6cKffUrccX7UAS5AmJQQNZTSibi9z5GvvRZ0aYgUCQ=="], "@ts-morph/common": ["@ts-morph/common@0.27.0", "", { "dependencies": { "fast-glob": "^3.3.3", "minimatch": "^10.0.1", "path-browserify": "^1.0.1" } }, "sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ=="], @@ -1499,7 +1486,7 @@ "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], - "acorn": ["acorn@8.18.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="], + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], @@ -1781,7 +1768,7 @@ "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], - "effect": ["effect@4.0.0-beta.66", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.6.0", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.9", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^13.0.0", "yaml": "^2.8.3" } }, "sha512-4arEr62cziFa8BBVDUwJCJJmaVepXf/kRg7KtC0h8+bufngscrHbwWFhr9c+HonwOF+31U3iD3xUJmw9KzX7Dw=="], + "effect": ["effect@4.0.0-rc.115", "", {}, "sha512-ogYulZ5ffeOzrJqQrG0XOkDO5lKn2s9KNHhoxJy/6wKUkF0i12dlVXWA9TgsgQ+zV/JzizyG0+XMPepZEQX6vw=="], "ejs": ["ejs@3.1.10", "", { "dependencies": { "jake": "^10.8.5" }, "bin": { "ejs": "bin/cli.js" } }, "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA=="], @@ -1805,7 +1792,7 @@ "emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], - "empathic": ["empathic@2.0.1", "", {}, "sha512-YGRs8knHhKHVShLkFET/rWAU8kmHbOV5LwN938RHI0pljAJ1Gf6SzXsSmRaEzcXTtOOmVqJ5+WtQPL5uigY50Q=="], + "empathic": ["empathic@2.1.0", "", {}, "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw=="], "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], @@ -1879,8 +1866,6 @@ "extract-zip": ["extract-zip@2.0.1", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="], - "fast-check": ["fast-check@4.9.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg=="], - "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], @@ -1901,8 +1886,6 @@ "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], - "find-my-way-ts": ["find-my-way-ts@0.1.6", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="], - "find-up": ["find-up@4.1.0", "", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="], "form-data": ["form-data@4.0.6", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.4", "mime-types": "^2.1.35" } }, "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ=="], @@ -2011,8 +1994,6 @@ "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], - "ini": ["ini@6.0.0", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="], - "inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="], "internmap": ["internmap@2.0.3", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="], @@ -2027,7 +2008,7 @@ "is-arrayish": ["is-arrayish@0.2.1", "", {}, "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg=="], - "is-core-module": ["is-core-module@2.16.2", "", { "dependencies": { "hasown": "^2.0.3" } }, "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA=="], + "is-core-module": ["is-core-module@2.17.0", "", { "dependencies": { "hasown": "^2.0.4" } }, "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA=="], "is-decimal": ["is-decimal@2.0.1", "", {}, "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="], @@ -2107,8 +2088,6 @@ "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], - "kubernetes-types": ["kubernetes-types@1.30.0", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="], - "lazy-val": ["lazy-val@1.0.5", "", {}, "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q=="], "lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], @@ -2277,12 +2256,6 @@ "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - "msgpackr": ["msgpackr@1.12.1", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-4EUH9tQHnMmEgzW/MdAP0KIfa1T9AF+htl0ffe2n5vb2EKn9y2co8ccpgWko6S52Jy1PQZKwRnx5/KkYjtd9MQ=="], - - "msgpackr-extract": ["msgpackr-extract@3.0.4", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw=="], - - "multipasta": ["multipasta@0.2.8", "", {}, "sha512-ZPWuMKyv0cSO29f7hozp+k6+crZbQijV8ipMvxNxRf2SwtYGTX1ZX89Kd20VV4H9Znonx+EQn+iy1wGQsJ+b+Q=="], - "nanoid": ["nanoid@3.3.16", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="], "negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="], @@ -2297,8 +2270,6 @@ "node-gyp": ["node-gyp@12.4.0", "", { "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", "graceful-fs": "^4.2.6", "nopt": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "tar": "^7.5.4", "tinyglobby": "^0.2.12", "undici": "^6.25.0", "which": "^6.0.0" }, "bin": { "node-gyp": "bin/node-gyp.js" } }, "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw=="], - "node-gyp-build-optional-packages": ["node-gyp-build-optional-packages@5.2.2", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="], - "node-int64": ["node-int64@0.4.0", "", {}, "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw=="], "node-releases": ["node-releases@2.0.51", "", {}, "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ=="], @@ -2447,8 +2418,6 @@ "pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="], - "pure-rand": ["pure-rand@8.4.2", "", {}, "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng=="], - "pvtsutils": ["pvtsutils@1.3.6", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg=="], "pvutils": ["pvutils@1.1.5", "", {}, "sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA=="], @@ -2467,7 +2436,7 @@ "react": ["react@19.2.7", "", {}, "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ=="], - "react-docgen": ["react-docgen@8.0.3", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/traverse": "^7.28.0", "@babel/types": "^7.28.2", "@types/babel__core": "^7.20.5", "@types/babel__traverse": "^7.20.7", "@types/doctrine": "^0.0.9", "@types/resolve": "^1.20.2", "doctrine": "^3.0.0", "resolve": "^1.22.1", "strip-indent": "^4.0.0" } }, "sha512-aEZ9qP+/M+58x2qgfSFEWH1BxLyHe5+qkLNJOZQb5iGS017jpbRnoKhNRrXPeA6RfBrZO5wZrT9DMC1UqE1f1w=="], + "react-docgen": ["react-docgen@8.0.4", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/traverse": "^7.28.0", "@babel/types": "^7.28.2", "@types/babel__core": "^7.20.5", "@types/babel__traverse": "^7.20.7", "@types/doctrine": "^0.0.9", "@types/resolve": "^1.20.2", "doctrine": "^3.0.0", "resolve": "^1.22.1", "strip-indent": "^4.0.0" } }, "sha512-gIYjtVTU4NCWZnb/LXVSWfClZXnjzX3+xxi69Tkfu4YsmYuqiOk8giLkKt/WwxWqh+U66CTh8Kqbha1uPv8/qQ=="], "react-docgen-typescript": ["react-docgen-typescript@2.4.0", "", { "peerDependencies": { "typescript": ">= 4.3.x" } }, "sha512-ZtAp5XTO5HRzQctjPU0ybY0RRCQO19X/8fxn3w7y2VVTUbGHDKULPTL4ky3vB05euSgG5NpALhEhDPvQ56wvXg=="], @@ -2525,7 +2494,7 @@ "reselect": ["reselect@5.2.0", "", {}, "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw=="], - "resolve": ["resolve@1.22.12", "", { "dependencies": { "es-errors": "^1.3.0", "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA=="], + "resolve": ["resolve@1.22.13", "", { "dependencies": { "es-errors": "^1.3.0", "is-core-module": "^2.17.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA=="], "resolve-alpn": ["resolve-alpn@1.2.1", "", {}, "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g=="], @@ -2707,8 +2676,6 @@ "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], - "toml": ["toml@4.3.0", "", {}, "sha512-lVb8X9BsPVuH0M4BKeS91tXAmJvCjQ5UIyAbQFaxkKGyUFK2RPkhwaFSQH8vbpl1d23eu/IBH+dwVMHWaq9A5A=="], - "tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], "tree-kill": ["tree-kill@1.2.2", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="], @@ -2777,8 +2744,6 @@ "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], - "uuid": ["uuid@13.0.2", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-vzi9uRZ926x4XV73S/4qQaTwPXM2JBj6/6lI/byHH1jOpCzb0zDbfytgA9LcN/hzb2l7WQSQnxITOVx5un/wGw=="], - "validate-npm-package-name": ["validate-npm-package-name@7.0.2", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="], "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], @@ -2811,7 +2776,7 @@ "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], - "ws": ["ws@8.21.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw=="], + "ws": ["ws@8.22.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg=="], "wsl-utils": ["wsl-utils@0.3.1", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.1.0" } }, "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg=="], @@ -2909,14 +2874,22 @@ "@rollup/pluginutils/estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], + "@rollup/pluginutils/picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + "@selftune/app-core/@types/react": ["@types/react@19.2.17", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw=="], + "@selftune/config/vitest": ["vitest@5.0.1", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.0.1", "chai": "^6.2.2", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", "magic-string": "^1.2.3", "obug": "^2.1.4", "picomatch": "^4.0.7", "std-env": "^4.2.0", "tinybench": "6.1.4", "tinyexec": "1.3.0", "tinyglobby": "^0.2.17", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "5.0.1", "@vitest/browser-preview": "5.0.1", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", "@vitest/coverage-istanbul": "5.0.1", "@vitest/coverage-v8": "5.0.1", "@vitest/ui": "5.0.1", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-iA95lQbKEkvrtTkdAgnWbXfbipWiiWe/hDl2P5tMi6WFwD76G0NxXAGp/M9EOcYupeGJRr6wppMc7CoA41TQjg=="], + + "@selftune/control-plane/vitest": ["vitest@5.0.1", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.0.1", "chai": "^6.2.2", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", "magic-string": "^1.2.3", "obug": "^2.1.4", "picomatch": "^4.0.7", "std-env": "^4.2.0", "tinybench": "6.1.4", "tinyexec": "1.3.0", "tinyglobby": "^0.2.17", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "5.0.1", "@vitest/browser-preview": "5.0.1", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", "@vitest/coverage-istanbul": "5.0.1", "@vitest/coverage-v8": "5.0.1", "@vitest/ui": "5.0.1", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-iA95lQbKEkvrtTkdAgnWbXfbipWiiWe/hDl2P5tMi6WFwD76G0NxXAGp/M9EOcYupeGJRr6wppMc7CoA41TQjg=="], + "@selftune/dashboard-core/@types/react": ["@types/react@19.2.17", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw=="], "@selftune/local-dashboard/@types/react": ["@types/react@19.2.17", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw=="], "@selftune/observability/@types/react": ["@types/react@19.2.17", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw=="], + "@selftune/orchestration/vitest": ["vitest@5.0.1", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.0.1", "chai": "^6.2.2", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", "magic-string": "^1.2.3", "obug": "^2.1.4", "picomatch": "^4.0.7", "std-env": "^4.2.0", "tinybench": "6.1.4", "tinyexec": "1.3.0", "tinyglobby": "^0.2.17", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "5.0.1", "@vitest/browser-preview": "5.0.1", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", "@vitest/coverage-istanbul": "5.0.1", "@vitest/coverage-v8": "5.0.1", "@vitest/ui": "5.0.1", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-iA95lQbKEkvrtTkdAgnWbXfbipWiiWe/hDl2P5tMi6WFwD76G0NxXAGp/M9EOcYupeGJRr6wppMc7CoA41TQjg=="], + "@selftune/ui/@testing-library/react": ["@testing-library/react@16.3.2", "", { "dependencies": { "@babel/runtime": "^7.12.5" }, "peerDependencies": { "@testing-library/dom": "^10.0.0", "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g=="], "@selftune/ui/@types/react": ["@types/react@19.2.17", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw=="], @@ -2935,6 +2908,8 @@ "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "@testing-library/jest-dom/aria-query": ["aria-query@5.3.2", "", {}, "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw=="], + "@testing-library/jest-dom/dom-accessibility-api": ["dom-accessibility-api@0.6.3", "", {}, "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w=="], "@types/cacheable-request/@types/node": ["@types/node@24.13.3", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q=="], @@ -3035,7 +3010,7 @@ "parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="], - "path-scurry/lru-cache": ["lru-cache@11.5.2", "", {}, "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g=="], + "path-scurry/lru-cache": ["lru-cache@11.5.3", "", {}, "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg=="], "pkg-up/find-up": ["find-up@3.0.0", "", { "dependencies": { "locate-path": "^3.0.0" } }, "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg=="], @@ -3075,6 +3050,8 @@ "storybook/open": ["open@10.2.0", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="], + "storybook/ws": ["ws@8.21.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw=="], + "string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], "temp-file/fs-extra": ["fs-extra@10.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="], @@ -3085,6 +3062,8 @@ "type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "unplugin/picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + "unzipper/fs-extra": ["fs-extra@11.3.1", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g=="], "vite/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], @@ -3185,6 +3164,42 @@ "@rolldown/binding-wasm32-wasi/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], + "@selftune/config/vitest/@vitest/mocker": ["@vitest/mocker@5.0.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.31", "@vitest/spy": "5.0.1", "estree-walker": "^3.0.3", "magic-string": "^1.2.3" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-6K1DoBNAPGvuOcSsGA4D6x+5zEEff/KmOOP3uetT2TrGpVfI+HRHRnJJfKi5ib/g1vx8IYHQD8s0pbJz8WQI7Q=="], + + "@selftune/config/vitest/es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], + + "@selftune/config/vitest/magic-string": ["magic-string@1.4.3", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ=="], + + "@selftune/config/vitest/picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "@selftune/config/vitest/tinybench": ["tinybench@6.1.4", "", {}, "sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ=="], + + "@selftune/config/vitest/tinyexec": ["tinyexec@1.3.0", "", {}, "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ=="], + + "@selftune/control-plane/vitest/@vitest/mocker": ["@vitest/mocker@5.0.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.31", "@vitest/spy": "5.0.1", "estree-walker": "^3.0.3", "magic-string": "^1.2.3" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-6K1DoBNAPGvuOcSsGA4D6x+5zEEff/KmOOP3uetT2TrGpVfI+HRHRnJJfKi5ib/g1vx8IYHQD8s0pbJz8WQI7Q=="], + + "@selftune/control-plane/vitest/es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], + + "@selftune/control-plane/vitest/magic-string": ["magic-string@1.4.3", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ=="], + + "@selftune/control-plane/vitest/picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "@selftune/control-plane/vitest/tinybench": ["tinybench@6.1.4", "", {}, "sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ=="], + + "@selftune/control-plane/vitest/tinyexec": ["tinyexec@1.3.0", "", {}, "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ=="], + + "@selftune/orchestration/vitest/@vitest/mocker": ["@vitest/mocker@5.0.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.31", "@vitest/spy": "5.0.1", "estree-walker": "^3.0.3", "magic-string": "^1.2.3" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-6K1DoBNAPGvuOcSsGA4D6x+5zEEff/KmOOP3uetT2TrGpVfI+HRHRnJJfKi5ib/g1vx8IYHQD8s0pbJz8WQI7Q=="], + + "@selftune/orchestration/vitest/es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], + + "@selftune/orchestration/vitest/magic-string": ["magic-string@1.4.3", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ=="], + + "@selftune/orchestration/vitest/picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "@selftune/orchestration/vitest/tinybench": ["tinybench@6.1.4", "", {}, "sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ=="], + + "@selftune/orchestration/vitest/tinyexec": ["tinyexec@1.3.0", "", {}, "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ=="], + "@sentry/node/@opentelemetry/sdk-trace-base/@opentelemetry/core": ["@opentelemetry/core@2.9.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-m2nckMT80NnmjTYSPjJQObBJ+8dgkoajEOUbznL8AHZ3T3yHRk2P7gI1PhEBc1+lOnrYE9UWrWHqJDsmqjmNbw=="], "@sentry/node/@opentelemetry/sdk-trace-base/@opentelemetry/resources": ["@opentelemetry/resources@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg=="], @@ -3343,6 +3358,18 @@ "@electron/universal/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], + "@selftune/config/vitest/@vitest/mocker/@vitest/spy": ["@vitest/spy@5.0.1", "", {}, "sha512-rbto/mF/SGERxEgYOek7Xm6B9b+y+mVoo+f4b2LymYO8zM1b7uB5nHuhVMTP2hxdzgxvGiZYGxGIaMvL5y180Q=="], + + "@selftune/config/vitest/magic-string/@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], + + "@selftune/control-plane/vitest/@vitest/mocker/@vitest/spy": ["@vitest/spy@5.0.1", "", {}, "sha512-rbto/mF/SGERxEgYOek7Xm6B9b+y+mVoo+f4b2LymYO8zM1b7uB5nHuhVMTP2hxdzgxvGiZYGxGIaMvL5y180Q=="], + + "@selftune/control-plane/vitest/magic-string/@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], + + "@selftune/orchestration/vitest/@vitest/mocker/@vitest/spy": ["@vitest/spy@5.0.1", "", {}, "sha512-rbto/mF/SGERxEgYOek7Xm6B9b+y+mVoo+f4b2LymYO8zM1b7uB5nHuhVMTP2hxdzgxvGiZYGxGIaMvL5y180Q=="], + + "@selftune/orchestration/vitest/magic-string/@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], + "dir-compare/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], "drizzle-kit/tsx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.1", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ=="], diff --git a/docs/design-docs/evolution-pipeline.md b/docs/design-docs/evolution-pipeline.md index cdcf1a86..6363bc38 100644 --- a/docs/design-docs/evolution-pipeline.md +++ b/docs/design-docs/evolution-pipeline.md @@ -264,6 +264,17 @@ Each entry includes: `timestamp`, `proposal_id`, `action`, `details`, optional ` Extends evolution beyond descriptions to routing tables and complete skill bodies. Uses a teacher-student model where a stronger LLM generates proposals and a cheaper LLM validates them. +### Historical Routing Verifier Qualification + +The historical replay path uses routing verifier v2. Qualification runs +synthetic runtime observations through the same decision predicate used by live +host replay, including known-good, known-failure, boundary, and adversarial +cases. It covers repeated and multiple skill selections, no selection, +misleading output text, and reads outside the staged skill paths. Off-path reads +fail even when the target skill was also selected. These controls qualify the +predicate's decision mapping; they do not establish host harness or provider +integration behavior. + ### Evolution Targets | Target | What changes | Generator | Validator | diff --git a/e2e/src/services.ts b/e2e/src/services.ts index ca4ffa83..6953c9ae 100644 --- a/e2e/src/services.ts +++ b/e2e/src/services.ts @@ -2,7 +2,7 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -export class CapabilityUnavailable extends Schema.TaggedErrorClass()( +export class CapabilityUnavailable extends Schema.TaggedError()( "CapabilityUnavailable", { capability: Schema.String, @@ -10,7 +10,7 @@ export class CapabilityUnavailable extends Schema.TaggedErrorClass()("ScenarioFailure", { +export class ScenarioFailure extends Schema.TaggedError()("ScenarioFailure", { step: Schema.String, message: Schema.String, }) {} diff --git a/package.json b/package.json index e1f9a711..ec5e8fbd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "selftune", - "version": "0.4.12", + "version": "0.5.1", "description": "Skill-level observability and self-improvement for AI agents — monitors skill routing, detects missed triggers, and evolves descriptions automatically", "keywords": [ "agent", @@ -109,8 +109,8 @@ }, "dependencies": { "@duckdb/node-api": "1.4.5-r.1", - "@effect/platform-bun": "4.0.0-beta.66", - "@effect/platform-node-shared": "4.0.0-beta.66", + "@effect/platform-bun": "4.0.0-rc.115", + "@effect/platform-node-shared": "4.0.0-rc.115", "@selftune/config": "workspace:*", "@selftune/control-plane": "workspace:*", "@selftune/dashboard-core": "workspace:*", @@ -134,7 +134,7 @@ "@selftune/ui": "workspace:*", "@xmldom/xmldom": "^0.8.13", "drizzle-orm": "^0.45.0", - "effect": "4.0.0-beta.66", + "effect": "4.0.0-rc.115", "react-markdown": "^10.1.0", "sonner": "^2.0.7", "zod": "^4.3.6" @@ -142,8 +142,7 @@ "devDependencies": { "@changesets/changelog-github": "^0.7.0", "@changesets/cli": "^2.30.0", - "@effect/tsgo": "^0.24.1", - "@effect/vitest": "4.0.0-beta.66", + "@effect/tsgo": "0.45.0", "@evilmartians/lefthook": "^1.13.6", "@oxlint/plugins": "1.78.0", "@types/bun": "^1.3.11", @@ -159,7 +158,7 @@ "react-dom": "^19.1.0", "turbo": "^2.5.6", "typescript": "^5.9.3", - "vitest": "^4.0.18" + "vitest": "4.1.10" }, "bundledDependencies": [ "@selftune/config", diff --git a/packages/config/package.json b/packages/config/package.json index a03e7594..3bddbc4d 100644 --- a/packages/config/package.json +++ b/packages/config/package.json @@ -17,14 +17,14 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { - "@effect/platform-bun": "4.0.0-beta.66", - "@effect/vitest": "4.0.0-beta.66", + "@effect/platform-bun": "4.0.0-rc.115", + "@effect/vitest": "4.0.0-rc.115", "@types/bun": "^1.3.11", "bun-types": "^1.3.11", "typescript": "^5.9.3", - "vitest": "^4.0.18" + "vitest": "5.0.1" } } diff --git a/packages/config/src/load.ts b/packages/config/src/load.ts index 01bd152f..79dc4311 100644 --- a/packages/config/src/load.ts +++ b/packages/config/src/load.ts @@ -4,13 +4,10 @@ import { readFileSync } from "node:fs"; import { SelftuneFileConfig } from "./schema.js"; -export class ConfigParseError extends Schema.TaggedErrorClass()( - "ConfigParseError", - { - path: Schema.String, - message: Schema.String, - }, -) {} +export class ConfigParseError extends Schema.TaggedError()("ConfigParseError", { + path: Schema.String, + message: Schema.String, +}) {} export const loadConfig = Effect.fn("Config.loadConfig")(function* ( path: string, diff --git a/packages/control-plane/package.json b/packages/control-plane/package.json index acfc0068..102eba8d 100644 --- a/packages/control-plane/package.json +++ b/packages/control-plane/package.json @@ -9,10 +9,16 @@ "exports": { ".": "./index.ts", "./domain": "./src/domain/index.ts", + "./domain/library": "./src/domain/library.ts", + "./domain/remote-library": "./src/domain/remote-library.ts", + "./domain/synthesis": "./src/domain/synthesis.ts", + "./domain/evaluation-report": "./src/domain/evaluation-report.ts", "./evidence": "./src/evidence.ts", "./orchestration": "./src/orchestration.ts", "./library-consolidation": "./src/library-consolidation.ts", "./library-selection": "./src/library-selection.ts", + "./library-transport": "./src/library-transport.ts", + "./library-index": "./src/library-index.ts", "./services": "./src/services/index.ts", "./programs": "./src/programs/index.ts", "./review/portable": "./src/review/portable.ts", @@ -21,16 +27,16 @@ "./layers/remote-http": "./src/layers/remote-http.ts" }, "scripts": { - "test": "vitest run", + "test": "node scripts/test.mjs", "typecheck": "tsc --noEmit" }, "dependencies": { - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { - "@effect/vitest": "4.0.0-beta.66", + "@effect/vitest": "4.0.0-rc.115", "@types/node": "^20", "typescript": "^5.9.3", - "vitest": "^4.0.18" + "vitest": "5.0.1" } } diff --git a/packages/control-plane/scripts/test.mjs b/packages/control-plane/scripts/test.mjs new file mode 100644 index 00000000..84c69ccc --- /dev/null +++ b/packages/control-plane/scripts/test.mjs @@ -0,0 +1,13 @@ +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; +import { spawnSync } from "node:child_process"; + +// The embedded mirror shares the monorepo install, where Storybook uses Vitest 4. +// Run the version qualified by the Effect adapter in either repository layout. +const require = createRequire(import.meta.resolve("@effect/vitest")); +const runner = join(dirname(require.resolve("vitest/package.json")), "vitest.mjs"); +const result = spawnSync(process.execPath, [runner, "run", ...process.argv.slice(2)], { + stdio: "inherit", +}); +if (result.error) throw result.error; +process.exitCode = result.status ?? 1; diff --git a/packages/control-plane/src/domain/adjacent-instructions.ts b/packages/control-plane/src/domain/adjacent-instructions.ts index d24f6e6e..ff783ea1 100644 --- a/packages/control-plane/src/domain/adjacent-instructions.ts +++ b/packages/control-plane/src/domain/adjacent-instructions.ts @@ -33,7 +33,7 @@ export const AdjacentInstructionActivation = Schema.Literals([ ]); export type AdjacentInstructionActivation = typeof AdjacentInstructionActivation.Type; -export class AdjacentInstructionError extends Schema.TaggedErrorClass()( +export class AdjacentInstructionError extends Schema.TaggedError()( "AdjacentInstructionError", { code: Schema.String, message: Schema.String }, ) {} diff --git a/packages/control-plane/src/domain/errors.ts b/packages/control-plane/src/domain/errors.ts index 0385a0df..24a6b287 100644 --- a/packages/control-plane/src/domain/errors.ts +++ b/packages/control-plane/src/domain/errors.ts @@ -1,6 +1,6 @@ import * as Schema from "effect/Schema"; -export class CatalogUnavailable extends Schema.TaggedErrorClass()( +export class CatalogUnavailable extends Schema.TaggedError()( "CatalogUnavailable", { operation: Schema.String, diff --git a/packages/control-plane/src/domain/evaluation-report.ts b/packages/control-plane/src/domain/evaluation-report.ts new file mode 100644 index 00000000..7c1b1eb8 --- /dev/null +++ b/packages/control-plane/src/domain/evaluation-report.ts @@ -0,0 +1,39 @@ +import { Schema } from "effect"; + +const Score = Schema.Number.check(Schema.isFinite(), Schema.isBetween({ minimum: 0, maximum: 1 })); +export const EvaluationAssertion = Schema.Struct({ + arm: Schema.Literals(["with", "baseline"]), + name: Schema.String, + passed: Schema.Boolean, + scored: Schema.Boolean, + evidence: Schema.String, +}); +export const EvaluationSummary = Schema.Struct({ + engine: Schema.Literals(["claude-plugin", "selftune-skill"]), + harness: Schema.Union([Schema.String, Schema.Null]), + model: Schema.Union([Schema.String, Schema.Null]), + recordedAt: Schema.Union([Schema.String, Schema.Null]), + threshold: Score, + exitCode: Schema.Literals([0, 1, 2]), + cases: Schema.Array( + Schema.Struct({ + name: Schema.String, + score: Score, + baseline: Schema.Union([Score, Schema.Null]), + delta: Schema.Union([Schema.Number, Schema.Null]), + incomplete: Schema.Boolean, + errors: Schema.Array(Schema.String), + prompt: Schema.Union([Schema.String, Schema.Null]), + assertions: Schema.Array(EvaluationAssertion), + }), + ), +}); +export type EvaluationSummary = typeof EvaluationSummary.Type; +export const EvaluationHistory = Schema.Array( + Schema.Struct({ + id: Schema.String, + importedAt: Schema.String, + result: EvaluationSummary, + }), +); +export type EvaluationHistory = typeof EvaluationHistory.Type; diff --git a/packages/control-plane/src/domain/package-bundle.ts b/packages/control-plane/src/domain/package-bundle.ts index 7a89f444..9995c8f6 100644 --- a/packages/control-plane/src/domain/package-bundle.ts +++ b/packages/control-plane/src/domain/package-bundle.ts @@ -63,7 +63,7 @@ export const PortablePackageBundleErrorReason = Schema.Literals([ ]); export type PortablePackageBundleErrorReason = typeof PortablePackageBundleErrorReason.Type; -export class PortablePackageBundleError extends Schema.TaggedErrorClass()( +export class PortablePackageBundleError extends Schema.TaggedError()( "PortablePackageBundleError", { reason: PortablePackageBundleErrorReason, @@ -226,7 +226,7 @@ const decodePackageBundleReleaseAuthorityPreflight = Schema.decodeUnknownOption( const isTraversableContainer = Schema.is(TraversableContainer); const isJsonArray = Schema.is(Schema.Array(Schema.Json)); const isJsonObject = Schema.is(JsonObject); -const decodeJsonText = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString); +const decodeJsonText = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); interface PortablePackageBundleErrorFields { reason: PortablePackageBundleErrorReason; diff --git a/packages/control-plane/src/domain/plugin-capability-bundle.ts b/packages/control-plane/src/domain/plugin-capability-bundle.ts index 69c5d402..fb5cd876 100644 --- a/packages/control-plane/src/domain/plugin-capability-bundle.ts +++ b/packages/control-plane/src/domain/plugin-capability-bundle.ts @@ -84,7 +84,7 @@ export const PluginCapabilityBundleErrorReason = Schema.Literals([ "missing_risk_acceptance", ]); -export class PluginCapabilityBundleError extends Schema.TaggedErrorClass()( +export class PluginCapabilityBundleError extends Schema.TaggedError()( "PluginCapabilityBundleError", { reason: PluginCapabilityBundleErrorReason, diff --git a/packages/control-plane/src/domain/portable-plugin-export.ts b/packages/control-plane/src/domain/portable-plugin-export.ts index 44baae35..dd4b4ee9 100644 --- a/packages/control-plane/src/domain/portable-plugin-export.ts +++ b/packages/control-plane/src/domain/portable-plugin-export.ts @@ -17,7 +17,7 @@ export interface PortablePluginProjection { readonly files: ReadonlyArray; } -export class PortablePluginExportError extends Schema.TaggedErrorClass()( +export class PortablePluginExportError extends Schema.TaggedError()( "PortablePluginExportError", { message: Schema.String }, ) {} diff --git a/packages/control-plane/src/domain/portable-skill-set.ts b/packages/control-plane/src/domain/portable-skill-set.ts index 7bc0c930..e381c9a3 100644 --- a/packages/control-plane/src/domain/portable-skill-set.ts +++ b/packages/control-plane/src/domain/portable-skill-set.ts @@ -52,7 +52,7 @@ export const PortableSkillSetErrorReason = Schema.Literals([ ]); export type PortableSkillSetErrorReason = typeof PortableSkillSetErrorReason.Type; -export class PortableSkillSetError extends Schema.TaggedErrorClass()( +export class PortableSkillSetError extends Schema.TaggedError()( "PortableSkillSetError", { reason: PortableSkillSetErrorReason, @@ -137,7 +137,7 @@ const PortableSkillSetEnvelopeCardinality = Schema.Struct({ const decodePortableSkillSetEnvelopeCardinality = Schema.decodeUnknownOption( PortableSkillSetEnvelopeCardinality, ); -const decodeJsonText = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString); +const decodeJsonText = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); export class PortableSkillSetEnvelopeComponent extends Schema.Class( "PortableSkillSetEnvelopeComponent", diff --git a/packages/control-plane/src/domain/remote-errors.ts b/packages/control-plane/src/domain/remote-errors.ts index 3fc57e1f..3ddc1ed6 100644 --- a/packages/control-plane/src/domain/remote-errors.ts +++ b/packages/control-plane/src/domain/remote-errors.ts @@ -1,6 +1,6 @@ import * as Schema from "effect/Schema"; -export class RemoteIntegrityFailure extends Schema.TaggedErrorClass()( +export class RemoteIntegrityFailure extends Schema.TaggedError()( "RemoteIntegrityFailure", { expectedHash: Schema.String, @@ -8,17 +8,17 @@ export class RemoteIntegrityFailure extends Schema.TaggedErrorClass()("RemoteConflict", { +export class RemoteConflict extends Schema.TaggedError()("RemoteConflict", { expectedParentId: Schema.NullOr(Schema.String), actualParentId: Schema.NullOr(Schema.String), }) {} -export class RemoteObjectMissing extends Schema.TaggedErrorClass()( +export class RemoteObjectMissing extends Schema.TaggedError()( "RemoteObjectMissing", { objectHash: Schema.String }, ) {} -export class RemoteLibraryUnavailable extends Schema.TaggedErrorClass()( +export class RemoteLibraryUnavailable extends Schema.TaggedError()( "RemoteLibraryUnavailable", { operation: Schema.String, message: Schema.String }, ) {} diff --git a/packages/control-plane/src/domain/skill-set-dependencies.ts b/packages/control-plane/src/domain/skill-set-dependencies.ts index 2f564974..cfed6576 100644 --- a/packages/control-plane/src/domain/skill-set-dependencies.ts +++ b/packages/control-plane/src/domain/skill-set-dependencies.ts @@ -120,7 +120,7 @@ export const SkillSetDependencyErrorReason = Schema.Literals([ ]); export type SkillSetDependencyErrorReason = typeof SkillSetDependencyErrorReason.Type; -export class SkillSetDependencyError extends Schema.TaggedErrorClass()( +export class SkillSetDependencyError extends Schema.TaggedError()( "SkillSetDependencyError", { reason: SkillSetDependencyErrorReason, diff --git a/packages/control-plane/src/domain/skill-set-pack.ts b/packages/control-plane/src/domain/skill-set-pack.ts index 999fb11b..8373d6fc 100644 --- a/packages/control-plane/src/domain/skill-set-pack.ts +++ b/packages/control-plane/src/domain/skill-set-pack.ts @@ -58,7 +58,7 @@ export class SkillSetPackManagementList extends Schema.Class()( +export class SkillSetPackUrlError extends Schema.TaggedError()( "SkillSetPackUrlError", { message: Schema.String }, ) {} diff --git a/packages/control-plane/src/domain/skill-set-source-composer.ts b/packages/control-plane/src/domain/skill-set-source-composer.ts index b5fcddc2..14670e4e 100644 --- a/packages/control-plane/src/domain/skill-set-source-composer.ts +++ b/packages/control-plane/src/domain/skill-set-source-composer.ts @@ -59,7 +59,7 @@ export class SkillSetSourceComposerPreview extends Schema.Class()( +export class SkillSetSourceComposerError extends Schema.TaggedError()( "SkillSetSourceComposerError", { reason: Schema.Literals([ diff --git a/packages/control-plane/src/domain/synthesis.ts b/packages/control-plane/src/domain/synthesis.ts index 5a3dddb2..74f9d133 100644 --- a/packages/control-plane/src/domain/synthesis.ts +++ b/packages/control-plane/src/domain/synthesis.ts @@ -85,12 +85,12 @@ export const CandidateSnapshot = Schema.Struct({ }); export type CandidateSnapshot = typeof CandidateSnapshot.Type; -export class CandidateNotFound extends Schema.TaggedErrorClass()( +export class CandidateNotFound extends Schema.TaggedError()( "CandidateNotFound", { candidateId: Schema.String }, ) {} -export class CandidateStoreUnavailable extends Schema.TaggedErrorClass()( +export class CandidateStoreUnavailable extends Schema.TaggedError()( "CandidateStoreUnavailable", { operation: Schema.String, message: Schema.String }, ) {} diff --git a/packages/control-plane/src/library-index.test.ts b/packages/control-plane/src/library-index.test.ts new file mode 100644 index 00000000..dc6a3ed8 --- /dev/null +++ b/packages/control-plane/src/library-index.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, test } from "vitest"; +import * as Schema from "effect/Schema"; +import type { LibrarySnapshot } from "./domain/library"; +import { LibraryIndexPage, libraryIndexPage } from "./library-index"; + +const snapshot: LibrarySnapshot = { + generatedAt: "2026-10-20T00:00:00Z", + counts: { total: 123, active: 123, library: 0, draft: 0, archived: 0 }, + skills: Array.from({ length: 123 }, (_, index) => ({ + skillId: `skill-${index}`, + name: `skill-${index}`, + lifecycle: "active", + origins: [], + updateStatus: "unknown", + lastUsedAt: null, + lastModifiedAt: "2026-10-20T00:00:00Z", + revisions: [], + locations: ["first", "last"].map((part) => ({ + sourceKind: "installed", + packagePath: `/projects/${part}/${index}`, + skillPath: `/projects/${part}/${index}/SKILL.md`, + harness: "codex", + scope: "project", + projectRoot: `/projects/${part}`, + active: part === "last", + modifiedAt: "2026-10-20T00:00:00Z", + lastUsedAt: null, + origin: null, + updateStatus: "unknown", + })), + })), +}; + +describe("library index", () => { + test.each([100, 1000, 10000])( + "bounds generated %i-skill pages while retaining the full inventory", + (count) => { + const template = snapshot.skills[0]; + if (!template) throw new Error("Fixture skill missing"); + const generated: LibrarySnapshot = { + ...snapshot, + counts: { ...snapshot.counts, total: count, active: count }, + skills: Array.from({ length: count }, (_, index) => ({ + ...template, + skillId: `skill-${index}`, + name: `skill-${index}`, + })), + }; + const ids = new Set(); + for (let offset = 0; offset < count; offset += 50) { + const page = libraryIndexPage(generated, { offset, limit: 50, search: "" }); + expect(page.skills.length).toBeLessThanOrEqual(50); + expect(Buffer.byteLength(JSON.stringify(page))).toBeLessThan(250_000); + for (const skill of page.skills) ids.add(skill.skillId); + } + expect(ids.size).toBe(count); + const last = libraryIndexPage(generated, { + offset: 0, + limit: 50, + search: `skill-${count - 1}`, + }); + expect(last.skills.map((skill) => skill.skillId)).toEqual([`skill-${count - 1}`]); + }, + ); + test("pages beyond 100 skills without losing or duplicating any skill", () => { + const pages = [0, 50, 100].map((offset) => + Schema.decodeUnknownSync(LibraryIndexPage)( + libraryIndexPage(snapshot, { offset, limit: 50, search: "" }), + ), + ); + expect(pages.map((page) => page.skills.length)).toEqual([50, 50, 23]); + expect(pages.map((page) => page.nextOffset)).toEqual([50, 100, null]); + expect(pages.flatMap((page) => page.skills.map((skill) => skill.skillId))).toEqual( + snapshot.skills.map((skill) => skill.skillId), + ); + expect(pages.every((page) => page.total === 123 && page.counts.total === 123)).toBe(true); + }); + test("searches all original paths and category terms before paging", () => { + const byPath = libraryIndexPage(snapshot, { offset: 0, limit: 50, search: "/last/122" }); + expect(byPath.skills.map((skill) => skill.skillId)).toEqual(["skill-122"]); + const classified = libraryIndexPage(snapshot, { + offset: 0, + limit: 50, + search: "MARKETING", + classificationText: new Map([["skill-121", "Product & Business marketing"]]), + }); + expect(classified.skills.map((skill) => skill.skillId)).toEqual(["skill-121"]); + }); + test("projects representative connections, not incomplete revision or location graphs", () => { + const original = JSON.stringify(snapshot); + const page = libraryIndexPage(snapshot, { offset: 0, limit: 1, search: "" }); + expect(page.skills[0]?.connections).toHaveLength(1); + expect(page.skills[0]?.connections[0]).toMatchObject({ + packagePath: "/projects/first/0", + removable: true, + }); + expect(page.skills[0]).not.toHaveProperty("locations"); + expect(page.skills[0]).not.toHaveProperty("revisions"); + expect(page.skills[0]?.installedCount).toBe(2); + expect(JSON.stringify(snapshot)).toBe(original); + }); +}); diff --git a/packages/control-plane/src/library-index.ts b/packages/control-plane/src/library-index.ts new file mode 100644 index 00000000..0b94a4d3 --- /dev/null +++ b/packages/control-plane/src/library-index.ts @@ -0,0 +1,144 @@ +import * as Schema from "effect/Schema"; +import { + LibraryCounts, + LibraryLocation, + LibraryOrigin, + LibrarySkill, + LibrarySnapshot, +} from "./domain/library"; +import { recommendLibraryConsolidation } from "./library-consolidation"; + +const Connection = Schema.Struct({ + harness: LibraryLocation.fields.harness, + packagePath: LibraryLocation.fields.packagePath, + scope: LibraryLocation.fields.scope, + sourceKind: LibraryLocation.fields.sourceKind, + removable: Schema.Boolean, +}); +const Origin = Schema.Struct({ + ...LibraryOrigin.fields, + packagePath: Schema.NullOr(Schema.String), +}); +export const LibraryIndexSkill = Schema.Struct({ + skillId: LibrarySkill.fields.skillId, + name: LibrarySkill.fields.name, + lifecycle: LibrarySkill.fields.lifecycle, + lastUsedAt: LibrarySkill.fields.lastUsedAt, + lastModifiedAt: LibrarySkill.fields.lastModifiedAt, + updateStatus: LibrarySkill.fields.updateStatus, + instructionBytes: LibrarySkill.fields.instructionBytes, + origins: Schema.Array(Origin), + connections: Schema.Array(Connection), + revisionHashes: Schema.Array(Schema.String), + installedCount: Schema.Number, + consolidationAvailable: Schema.Boolean, +}); +export type LibraryIndexSkill = typeof LibraryIndexSkill.Type; +export const LibraryIndexPage = Schema.Struct({ + generatedAt: LibrarySnapshot.fields.generatedAt, + counts: LibraryCounts, + total: Schema.Number, + nextOffset: Schema.NullOr(Schema.Number), + skills: Schema.Array(LibraryIndexSkill), +}); +export type LibraryIndexPage = typeof LibraryIndexPage.Type; + +const indexes = new WeakMap(); +const harnessNames = { + codex: "Codex", + claude_code: "Claude Code", + opencode: "OpenCode", + openclaw: "OpenClaw", + pi: "Pi", +}; + +export function libraryIndexPage( + snapshot: LibrarySnapshot, + options: { + offset: number; + limit: number; + search: string; + classificationText?: ReadonlyMap; + }, +): LibraryIndexPage { + let rows = indexes.get(snapshot); + if (!rows) { + rows = snapshot.skills.map((skill) => { + const connections = new Map(); + let installedCount = 0; + for (const location of skill.locations) { + if (location.sourceKind === "installed") installedCount++; + const previous = connections.get(location.harness); + connections.set(location.harness, { + harness: location.harness, + packagePath: previous?.packagePath ?? location.packagePath, + scope: previous?.scope ?? location.scope, + sourceKind: previous?.sourceKind ?? location.sourceKind, + removable: + Boolean(previous?.removable) || + (skill.name.toLowerCase() !== "selftune" && + location.active && + location.sourceKind === "installed" && + location.scope !== "admin" && + location.scope !== "system"), + }); + } + return { + skillId: skill.skillId, + name: skill.name, + lifecycle: skill.lifecycle, + lastUsedAt: skill.lastUsedAt, + lastModifiedAt: skill.lastModifiedAt, + updateStatus: skill.updateStatus, + instructionBytes: skill.instructionBytes, + origins: skill.origins.map((origin) => ({ + ...origin, + packagePath: + skill.locations.find( + (location) => + location.origin?.kind === origin.kind && location.origin.label === origin.label, + )?.packagePath ?? + skill.locations[0]?.packagePath ?? + null, + })), + connections: [...connections.values()], + revisionHashes: skill.revisions.map((revision) => revision.contentHash), + installedCount, + consolidationAvailable: recommendLibraryConsolidation(skill) !== null, + }; + }); + indexes.set(snapshot, rows); + } + const query = options.search.trim().toLowerCase(); + const matching = query + ? new Set( + snapshot.skills + .filter((skill) => + [ + skill.name, + skill.lifecycle === "active" ? "Ready" : "Stored", + options.classificationText?.get(skill.skillId.toLowerCase()) ?? "", + ...skill.origins.map((origin) => origin.label), + ...skill.locations.flatMap((location) => [ + location.packagePath, + location.scope, + location.harness ? harnessNames[location.harness] : "", + ]), + ] + .join(" ") + .toLowerCase() + .includes(query), + ) + .map((skill) => skill.skillId), + ) + : null; + const filtered = matching ? rows.filter((row) => matching.has(row.skillId)) : rows; + const end = options.offset + options.limit; + return { + generatedAt: snapshot.generatedAt, + counts: snapshot.counts, + total: filtered.length, + nextOffset: end < filtered.length ? end : null, + skills: filtered.slice(options.offset, end), + }; +} diff --git a/packages/control-plane/src/library-transport.test.ts b/packages/control-plane/src/library-transport.test.ts new file mode 100644 index 00000000..b5f25553 --- /dev/null +++ b/packages/control-plane/src/library-transport.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, test } from "vitest"; +import * as Schema from "effect/Schema"; +import { + CompactLibrarySnapshot, + compactLibrarySnapshot, + expandLibrarySnapshot, +} from "./library-transport"; +import type { LibrarySnapshot } from "./domain/library"; + +const location = { + sourceKind: "installed", + packagePath: "/skills/test", + skillPath: "/skills/test/SKILL.md", + harness: "codex", + scope: "global", + projectRoot: null, + active: true, + modifiedAt: "2026-10-20T00:00:00Z", + lastUsedAt: null, + origin: null, + updateStatus: "unknown", +} satisfies LibrarySnapshot["skills"][number]["locations"][number]; +const snapshot: LibrarySnapshot = { + generatedAt: "2026-10-20T00:00:00Z", + counts: { total: 1, active: 1, library: 0, draft: 0, archived: 0 }, + skills: [ + { + skillId: "test", + name: "test", + lifecycle: "active", + origins: [], + updateStatus: "unknown", + lastUsedAt: null, + lastModifiedAt: "2026-10-20T00:00:00Z", + locations: [location], + revisions: [{ contentHash: "hash", locations: [{ ...location }] }], + }, + ], +}; + +describe("library transport", () => { + test("round trips all fields and preserves revision/location identity", () => { + const compact = Schema.decodeUnknownSync(CompactLibrarySnapshot)( + JSON.parse(JSON.stringify(compactLibrarySnapshot(snapshot))), + ); + expect(compact.locations).toHaveLength(1); + const expanded = expandLibrarySnapshot(compact); + expect(expanded).toEqual(snapshot); + expect(expanded.skills[0]?.locations[0]).toBe(expanded.skills[0]?.revisions[0]?.locations[0]); + }); + test("does not merge different revisions at the same path", () => { + const skill = snapshot.skills[0]; + if (!skill) throw new Error("Fixture skill missing"); + const changed = { + ...snapshot, + skills: [ + { + ...skill, + revisions: [{ contentHash: "older", locations: [{ ...location, active: false }] }], + }, + ], + }; + expect(compactLibrarySnapshot(changed).locations).toHaveLength(2); + expect(expandLibrarySnapshot(compactLibrarySnapshot(changed))).toEqual(changed); + }); + test("rejects dangling, negative and non-integer references", () => { + const compact = compactLibrarySnapshot(snapshot); + expect(() => expandLibrarySnapshot({ ...compact, locations: [] })).toThrow( + "invalid location reference", + ); + const skill = compact.skills[0]; + expect(() => + Schema.decodeUnknownSync(CompactLibrarySnapshot)({ + ...compact, + skills: [{ ...skill, locations: [-1] }], + }), + ).toThrow(); + expect(() => + Schema.decodeUnknownSync(CompactLibrarySnapshot)({ + ...compact, + skills: [{ ...skill, locations: [0.5] }], + }), + ).toThrow(); + }); +}); diff --git a/packages/control-plane/src/library-transport.ts b/packages/control-plane/src/library-transport.ts new file mode 100644 index 00000000..b8e61d01 --- /dev/null +++ b/packages/control-plane/src/library-transport.ts @@ -0,0 +1,73 @@ +import * as Schema from "effect/Schema"; +import { LibraryLocation, LibraryRevision, LibrarySkill, LibrarySnapshot } from "./domain/library"; + +const LocationId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); +const Revision = Schema.Struct({ + ...LibraryRevision.fields, + locations: Schema.Array(LocationId), +}); +const Skill = Schema.Struct({ + ...LibrarySkill.fields, + locations: Schema.Array(LocationId), + revisions: Schema.Array(Revision), +}); + +/** Local transport only. The canonical library/export contract remains unchanged. */ +export const CompactLibrarySnapshot = Schema.Struct({ + format: Schema.Literal("locations-v1"), + generatedAt: LibrarySnapshot.fields.generatedAt, + counts: LibrarySnapshot.fields.counts, + skills: Schema.Array(Skill), + locations: Schema.Array(LibraryLocation), +}); +export type CompactLibrarySnapshot = typeof CompactLibrarySnapshot.Type; + +export function compactLibrarySnapshot(snapshot: LibrarySnapshot): CompactLibrarySnapshot { + const locations: LibraryLocation[] = []; + const ids = new Map(); + const intern = (location: LibraryLocation): number => { + const key = JSON.stringify(location); + const existing = ids.get(key); + if (existing !== undefined) return existing; + const id = locations.length; + ids.set(key, id); + locations.push(location); + return id; + }; + const skills = snapshot.skills.map((skill) => ({ + ...skill, + locations: skill.locations.map(intern), + revisions: skill.revisions.map((revision) => ({ + ...revision, + locations: revision.locations.map(intern), + })), + })); + return { + format: "locations-v1", + generatedAt: snapshot.generatedAt, + counts: snapshot.counts, + skills, + locations, + }; +} + +export function expandLibrarySnapshot(snapshot: CompactLibrarySnapshot): LibrarySnapshot { + const resolve = (id: number): LibraryLocation => { + const location = snapshot.locations[id]; + if (location === undefined) + throw new Error("Library response contains an invalid location reference."); + return location; + }; + return { + generatedAt: snapshot.generatedAt, + counts: snapshot.counts, + skills: snapshot.skills.map((skill) => ({ + ...skill, + locations: skill.locations.map(resolve), + revisions: skill.revisions.map((revision) => ({ + ...revision, + locations: revision.locations.map(resolve), + })), + })), + }; +} diff --git a/packages/control-plane/src/science/evaluation.ts b/packages/control-plane/src/science/evaluation.ts index 8ab1e0b8..9029b842 100644 --- a/packages/control-plane/src/science/evaluation.ts +++ b/packages/control-plane/src/science/evaluation.ts @@ -30,26 +30,6 @@ export function generateCandidateEvals( heldOut: false, }), ); - cases.push( - GeneratedEvalCase.make({ - evalId: `negative-${id(`${candidate.candidateId}:near-neighbor`)}`, - kind: "negative", - query: `A related request outside the boundaries of ${candidate.title}`, - expectedSkillNames: [], - sourceSessionIds: [], - evidenceSnapshotId: snapshotId, - heldOut: false, - }), - GeneratedEvalCase.make({ - evalId: `boundary-${id(`${candidate.candidateId}:boundary`)}`, - kind: "boundary", - query: `Decide whether this ambiguous request belongs to ${candidate.title}`, - expectedSkillNames: expected, - sourceSessionIds: [], - evidenceSnapshotId: snapshotId, - heldOut: false, - }), - ); const heldOutExamples = candidate.heldOutExamples ?? []; cases.push( ...heldOutExamples.map((example) => @@ -69,6 +49,13 @@ export function generateCandidateEvals( export function evaluateReleaseGate(input: ReleaseGateInput): typeof ReleaseRecommendation.Type { const blockers: string[] = []; + const measuredCaseCounts = [ + input.draft.caseCount, + ...input.baselines.map((baseline) => baseline.caseCount), + ]; + if (measuredCaseCounts.some((caseCount) => !Number.isInteger(caseCount) || caseCount <= 0)) { + blockers.push("Every evaluation arm must include at least one measured case."); + } if (!input.packageValid) blockers.push("Package validation has not passed."); if (!input.replayPassed) blockers.push("Package replay has not passed."); if (input.draft.regressions.length > 0) blockers.push("Draft evaluation contains regressions."); diff --git a/packages/control-plane/tests/evaluation-science.test.ts b/packages/control-plane/tests/evaluation-science.test.ts index 3e4f02c8..5eeb300b 100644 --- a/packages/control-plane/tests/evaluation-science.test.ts +++ b/packages/control-plane/tests/evaluation-science.test.ts @@ -40,7 +40,7 @@ const releaseInput = (overrides: Partial = {}) => }); describe("scientific release gate", () => { - it("generates positive, negative, boundary, and execution evals with provenance", () => { + it("generates only observed support and held-out eval cases", () => { const sourceQueries = new Map([ ["one", "Prepare release notes."], ["two", "prepare release notes!"], @@ -63,7 +63,7 @@ describe("scientific release gate", () => { const evals = generateCandidateEvals(snapshot.snapshotId, candidate); assert.deepStrictEqual( new Set(evals.map((item) => item.kind)), - new Set(["positive", "negative", "boundary", "execution"]), + new Set(["positive", "execution"]), ); assert.ok(evals.every((item) => item.evidenceSnapshotId === snapshot.snapshotId)); const positiveCases = evals.filter((item) => item.kind === "positive"); @@ -99,6 +99,29 @@ describe("scientific release gate", () => { assert.ok(result.blockers.some((blocker) => blocker.includes("outcome lift"))); }); + it("blocks recommendation when any evaluation arm has no measured cases", () => { + const emptyCaseBlocker = "Every evaluation arm must include at least one measured case."; + const emptyDraft = evaluateReleaseGate( + releaseInput({ + draft: baseline({ baseline: "composite", caseCount: 0 }), + }), + ); + assert.strictEqual(emptyDraft.recommended, false); + assert.ok(emptyDraft.blockers.includes(emptyCaseBlocker)); + + const emptyBaseline = evaluateReleaseGate( + releaseInput({ + baselines: [ + baseline({ baseline: "no_skill", caseCount: 0 }), + baseline({ baseline: "existing_skills" }), + baseline({ baseline: "sibling_bundle" }), + ], + }), + ); + assert.strictEqual(emptyBaseline.recommended, false); + assert.ok(emptyBaseline.blockers.includes(emptyCaseBlocker)); + }); + it("blocks recommendation on regressions or missing validation", () => { const result = evaluateReleaseGate( releaseInput({ diff --git a/packages/control-plane/vitest.config.ts b/packages/control-plane/vitest.config.ts index 28e3aea5..fe0811a0 100644 --- a/packages/control-plane/vitest.config.ts +++ b/packages/control-plane/vitest.config.ts @@ -1,6 +1,18 @@ import { defineConfig } from "vitest/config"; +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; + +const effectRequire = createRequire(import.meta.resolve("@effect/vitest")); export default defineConfig({ + resolve: { + alias: [ + { + find: /^vitest$/, + replacement: join(dirname(effectRequire.resolve("vitest/package.json")), "dist/index.js"), + }, + ], + }, test: { environment: "node", exclude: ["**/node_modules/**", "**/dist/**"], diff --git a/packages/dashboard-core/package.json b/packages/dashboard-core/package.json index ceb3f493..620fa19c 100644 --- a/packages/dashboard-core/package.json +++ b/packages/dashboard-core/package.json @@ -14,6 +14,7 @@ "exports": { ".": "./index.ts", "./host": "./src/host/index.ts", + "./host/capabilities": "./src/host/capabilities.ts", "./models": "./src/models/index.ts", "./routes": "./src/routes/index.ts", "./chrome": "./src/chrome/index.ts", diff --git a/packages/dashboard-core/src/chrome/DashboardSidebar.test.tsx b/packages/dashboard-core/src/chrome/DashboardSidebar.test.tsx index 1d958606..b358d9c1 100644 --- a/packages/dashboard-core/src/chrome/DashboardSidebar.test.tsx +++ b/packages/dashboard-core/src/chrome/DashboardSidebar.test.tsx @@ -33,6 +33,8 @@ it("renders an accessible icon update action and invokes it on click", () => { }); expect(button.querySelector("svg")).not.toBeNull(); expect(button.textContent).toBe("Update"); + expect(button.className).toContain("rounded-full"); + expect(button.className).toContain("bg-primary-accent"); fireEvent.click(button); expect(onClick).toHaveBeenCalledOnce(); }); diff --git a/packages/dashboard-core/src/chrome/DashboardSidebar.tsx b/packages/dashboard-core/src/chrome/DashboardSidebar.tsx index bb773b6c..985e66db 100644 --- a/packages/dashboard-core/src/chrome/DashboardSidebar.tsx +++ b/packages/dashboard-core/src/chrome/DashboardSidebar.tsx @@ -206,7 +206,7 @@ export function DashboardSidebar({ aria-label={brand.footerAction.ariaLabel ?? brand.footerAction.label} title={brand.footerAction.ariaLabel ?? brand.footerAction.label} disabled={brand.footerAction.disabled} - className="group/update relative min-w-16 text-sidebar-primary hover:text-sidebar-primary" + className="group/update relative min-w-16 rounded-full bg-primary-accent text-black hover:bg-primary-accent/85 hover:text-black" onClick={() => { onMobileOpenChange(false); brand.footerAction?.onClick(); diff --git a/packages/dashboard-core/src/chrome/ServerProfileSwitcher.interaction.test.tsx b/packages/dashboard-core/src/chrome/ServerProfileSwitcher.interaction.test.tsx index cab35d00..8da2551d 100644 --- a/packages/dashboard-core/src/chrome/ServerProfileSwitcher.interaction.test.tsx +++ b/packages/dashboard-core/src/chrome/ServerProfileSwitcher.interaction.test.tsx @@ -55,6 +55,7 @@ describe("Desktop sidebar Cloud account actions", () => { state: "linked", connect: vi.fn(async () => {}), manage: vi.fn(), + openWorkspace: vi.fn(), openDashboard: vi.fn(async () => {}), }; @@ -63,6 +64,12 @@ describe("Desktop sidebar Cloud account actions", () => { fireEvent.click(screen.getByRole("button", { name: /This Mac/ })); fireEvent.click(await screen.findByText("SelfTune Cloud")); + expect(connection.openWorkspace).toHaveBeenCalledOnce(); + expect(connection.manage).not.toHaveBeenCalled(); + expect(select).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole("button", { name: /This Mac/ })); + fireEvent.click(await screen.findByText("Manage connection")); expect(connection.manage).toHaveBeenCalledOnce(); expect(select).not.toHaveBeenCalled(); diff --git a/packages/dashboard-core/src/chrome/ServerProfileSwitcher.test.ts b/packages/dashboard-core/src/chrome/ServerProfileSwitcher.test.ts index fa2473c7..07836dbd 100644 --- a/packages/dashboard-core/src/chrome/ServerProfileSwitcher.test.ts +++ b/packages/dashboard-core/src/chrome/ServerProfileSwitcher.test.ts @@ -34,6 +34,7 @@ function cloudConnection( state, connect, manage: vi.fn(), + openWorkspace: vi.fn(), openDashboard: vi.fn(async () => {}), }; } @@ -62,17 +63,20 @@ describe("sidebar Cloud profile", () => { await activateServerProfile(controller, cloudProfile, connection); expect(events).toEqual(["connect"]); + expect(connection.openWorkspace).toHaveBeenCalledOnce(); + expect(connection.manage).not.toHaveBeenCalled(); expect(controller.select).not.toHaveBeenCalled(); }); - it("opens in-app Cloud management when the Desktop account is already linked", async () => { + it("opens the Team workspace when the Desktop account is already linked", async () => { const connection = cloudConnection("linked"); const controller = { select: vi.fn(async () => {}) }; await activateServerProfile(controller, cloudProfile, connection); expect(connection.connect).not.toHaveBeenCalled(); - expect(connection.manage).toHaveBeenCalledOnce(); + expect(connection.openWorkspace).toHaveBeenCalledOnce(); + expect(connection.manage).not.toHaveBeenCalled(); expect(controller.select).not.toHaveBeenCalled(); }); @@ -83,4 +87,20 @@ describe("sidebar Cloud profile", () => { expect(controller.select).toHaveBeenCalledWith("cloud:selftune"); }); + + it("does not open Team when connecting fails", async () => { + const connection = cloudConnection( + "unlinked", + vi.fn(async () => { + throw new Error("Connection cancelled"); + }), + ); + const controller = { select: vi.fn(async () => {}) }; + await expect(activateServerProfile(controller, cloudProfile, connection)).rejects.toThrow( + "Connection cancelled", + ); + expect(connection.openWorkspace).not.toHaveBeenCalled(); + expect(connection.manage).not.toHaveBeenCalled(); + expect(controller.select).not.toHaveBeenCalled(); + }); }); diff --git a/packages/dashboard-core/src/chrome/ServerProfileSwitcher.tsx b/packages/dashboard-core/src/chrome/ServerProfileSwitcher.tsx index 0d124276..63ba1091 100644 --- a/packages/dashboard-core/src/chrome/ServerProfileSwitcher.tsx +++ b/packages/dashboard-core/src/chrome/ServerProfileSwitcher.tsx @@ -7,6 +7,7 @@ import { ExternalLinkIcon, PlusIcon, ServerIcon, + SettingsIcon, Trash2Icon, } from "lucide-react"; import { useState, useSyncExternalStore } from "react"; @@ -56,8 +57,9 @@ export async function activateServerProfile( if (profile.kind === "cloud" && cloudConnection) { if (cloudConnection.state === "unlinked" || cloudConnection.state === "unavailable") { await cloudConnection.connect(); + cloudConnection.openWorkspace(); } else if (cloudConnection.state === "linked") { - cloudConnection.manage(); + cloudConnection.openWorkspace(); } return; } @@ -167,6 +169,11 @@ export function ServerProfileSwitcher({ {serverProfileStatusLabel(cloudProfile, cloudConnection)} + {cloudConnection.state === "linked" ? ( + + Manage connection + + ) : null} {cloudConnection.state === "linked" ? ( void run(cloudConnection.openDashboard)}> Open Cloud dashboard diff --git a/packages/dashboard-core/src/chrome/types.ts b/packages/dashboard-core/src/chrome/types.ts index 730b039d..53acf7a6 100644 --- a/packages/dashboard-core/src/chrome/types.ts +++ b/packages/dashboard-core/src/chrome/types.ts @@ -59,6 +59,7 @@ export interface DashboardCloudProfileConnection { state: "checking" | "unlinked" | "connecting" | "linked" | "unavailable"; connect(): Promise; manage(): void; + openWorkspace(): void; openDashboard(): Promise; } diff --git a/packages/dashboard-core/src/gates/CloudFeatureGateDialog.tsx b/packages/dashboard-core/src/gates/CloudFeatureGateDialog.tsx index 1c6df8a1..9afaa2e7 100644 --- a/packages/dashboard-core/src/gates/CloudFeatureGateDialog.tsx +++ b/packages/dashboard-core/src/gates/CloudFeatureGateDialog.tsx @@ -207,6 +207,10 @@ export function CloudFeatureGateDialog({
+

+ Pro: $19/month for share links. Team: $49/month for publishing and team access, + including 3 members. +

diff --git a/packages/dashboard-core/src/host/adapter.ts b/packages/dashboard-core/src/host/adapter.ts index 1ac0bbf6..5f8dd147 100644 --- a/packages/dashboard-core/src/host/adapter.ts +++ b/packages/dashboard-core/src/host/adapter.ts @@ -5,6 +5,7 @@ import type { AnalyticsModel, DashboardDecisionModel, LibraryInventoryModel, + LibrarySkillModel, LibraryMergeModel, LibraryMergeConnectionModel, LibraryPrepareMergeInput, @@ -134,6 +135,9 @@ export interface DashboardLibraryQueryState { isLoading: boolean; error: string | null; refresh(): void | Promise; + loadDetails?(skillId: string): Promise; + loadAll?(): Promise; + searchHandled?: boolean; } export type DashboardLibraryAction = @@ -210,7 +214,7 @@ export interface DashboardLibraryActions { export type DashboardLibraryContribution = | { readonly access: "available"; - useInventory(): DashboardLibraryQueryState; + useInventory(options?: { search?: string; full?: boolean }): DashboardLibraryQueryState; useActions(): DashboardLibraryActions; } | { readonly access: "upgrade"; readonly href: string } @@ -376,6 +380,8 @@ export interface DashboardSkillSetsModule { /** The complete host interface needed by the shared Skills Library journey. */ export interface DashboardSkillsModule { + readonly PackageInspector?: ComponentType<{ skillPath: string }>; + readonly History?: ComponentType<{ skillPath: string }>; readonly host: DashboardHostKind; readonly library: DashboardLibraryContribution; readonly decisions: DashboardDecisionsContribution; diff --git a/packages/dashboard-core/src/models/library.ts b/packages/dashboard-core/src/models/library.ts index fa96258a..fc07b32d 100644 --- a/packages/dashboard-core/src/models/library.ts +++ b/packages/dashboard-core/src/models/library.ts @@ -113,6 +113,9 @@ export interface LibrarySkillModel { sources: LibrarySourceModel[]; locations: LibraryLocationModel[]; revisionHashes: string[]; + detailsLoaded?: boolean; + consolidationAvailable?: boolean; + archiveAvailable?: boolean; modifiedAt?: string | null; lastUsedAt?: string | null; triggerTrend?: LibraryTriggerTrendPointModel[]; diff --git a/packages/dashboard-core/src/screens/settings/PricingCards.tsx b/packages/dashboard-core/src/screens/settings/PricingCards.tsx new file mode 100644 index 00000000..f370eb6c --- /dev/null +++ b/packages/dashboard-core/src/screens/settings/PricingCards.tsx @@ -0,0 +1,74 @@ +import type { ReactNode } from "react"; +import { CheckIcon } from "lucide-react"; +import { + Badge, + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@selftune/ui/primitives"; + +export interface PricingPlan { + readonly id: "free" | "pro" | "team" | "enterprise"; + readonly name: string; + readonly price: string | null; + readonly period?: string | null; + readonly description: string; + readonly features: readonly string[]; +} + +export function PricingCards({ + plans, + currentPlan, + renderAction, + renderOptions, +}: { + readonly plans: readonly PricingPlan[]; + readonly currentPlan?: string; + readonly renderAction: (plan: PricingPlan) => ReactNode; + readonly renderOptions?: (plan: PricingPlan) => ReactNode; +}) { + return ( +
+ {plans + .filter((plan) => plan.id !== "enterprise") + .map((plan) => ( + + +
+ {plan.name} + {currentPlan === plan.id ? Current plan : null} +
+

+ {plan.price} + + {plan.period === "forever" ? " forever" : plan.period} + +

+ {plan.description} +
+ +
    + {plan.features.map((feature) => ( +
  • +
  • + ))} +
+ {renderOptions?.(plan)} +
+ {renderAction(plan)} +
+ ))} +
+ ); +} diff --git a/packages/dashboard-core/src/screens/settings/index.ts b/packages/dashboard-core/src/screens/settings/index.ts index 70b96c3b..68b454fd 100644 --- a/packages/dashboard-core/src/screens/settings/index.ts +++ b/packages/dashboard-core/src/screens/settings/index.ts @@ -1 +1,2 @@ export { SettingsShell, type SettingsShellProps, type SettingsShellSection } from "./SettingsShell"; +export { PricingCards, type PricingPlan } from "./PricingCards"; diff --git a/packages/dashboard-core/src/screens/skill-report/EvaluationCaseInspector.tsx b/packages/dashboard-core/src/screens/skill-report/EvaluationCaseInspector.tsx new file mode 100644 index 00000000..c744d18d --- /dev/null +++ b/packages/dashboard-core/src/screens/skill-report/EvaluationCaseInspector.tsx @@ -0,0 +1,108 @@ +import type { EvaluationSummary } from "@selftune/control-plane/domain/evaluation-report"; +import { + Badge, + Sheet, + SheetContent, + SheetHeader, + SheetTitle, + SheetDescription, + Separator, +} from "@selftune/ui/primitives"; +type Case = EvaluationSummary["cases"][number]; +export const percent = (value: number | null) => + value === null ? "—" : `${Math.round(value * 100)}%`; +export const change = (value: number | null) => + value === null ? "—" : `${value > 0 ? "+" : ""}${Math.round(value * 100)} pp`; +export const caseStatus = (entry: Case, threshold: number) => + entry.incomplete ? "Incomplete" : entry.score >= threshold ? "Passed" : "Below threshold"; +const arms: readonly ("with" | "baseline")[] = ["with", "baseline"]; +export function EvaluationCaseInspector({ + entry, + threshold, + onClose, +}: { + entry: Case | undefined; + threshold: number; + onClose(): void; +}) { + return ( + { + if (!open) onClose(); + }} + > + + + {entry?.name ?? "Case evidence"} + Prompt and recorded assertion evidence + + {entry && ( +
+
+ + {caseStatus(entry, threshold)} + + Threshold {percent(threshold)} + Change {change(entry.incomplete ? null : entry.delta)} +
+
+

Prompt

+

+ {entry.prompt ?? "Prompt was not included in this report."} +

+
+ {entry.errors.map((message) => ( +

+ {message} +

+ ))} + +
+ {arms.map((arm) => ( +
+
+

{arm === "with" ? "With skill" : "Baseline"}

+ + {percent( + entry.incomplete ? null : arm === "with" ? entry.score : entry.baseline, + )} + +
+ {entry.assertions + .filter((assertion) => assertion.arm === arm) + .map((assertion, index) => ( +
+
+ + {assertion.passed ? "Pass" : "Fail"} + + {!assertion.scored && Not scored} +
+

{assertion.name}

+

+ {assertion.evidence} +

+
+ ))} + {!entry.assertions.some((assertion) => assertion.arm === arm) && ( +

+ No assertion evidence recorded for this arm. +

+ )} +
+ ))} +
+
+ )} +
+
+ ); +} diff --git a/packages/dashboard-core/src/screens/skill-report/LocalSkillReport.tsx b/packages/dashboard-core/src/screens/skill-report/LocalSkillReport.tsx new file mode 100644 index 00000000..e5ed2923 --- /dev/null +++ b/packages/dashboard-core/src/screens/skill-report/LocalSkillReport.tsx @@ -0,0 +1,331 @@ +import { useState, type ReactNode } from "react"; +import { + Badge, + Button, + Card, + CardHeader, + CardTitle, + CardDescription, + CardContent, + Tabs, + TabsList, + TabsTrigger, + TabsContent, +} from "@selftune/ui/primitives"; +import { + HarnessLabel, + Empty, + EmptyHeader, + EmptyTitle, + EmptyDescription, +} from "@selftune/ui/components"; +import { timeAgo } from "@selftune/ui/lib"; +import { + useOptionalDashboardHost, + type DashboardLibraryContribution, + type DashboardLibraryActions, +} from "../../host"; +import type { LibrarySkillModel } from "../../models"; +import { LibraryConnections } from "../skills/LibraryConnections"; +import { ContextSavings } from "../skills/ContextSavings"; +import { OnDemandSkillsReview } from "../skills/OnDemandSkillsReview"; + +export interface LocalSkillReportProps { + name: string; + backLink: ReactNode; + checks: number; + sessions: number; + workspaces?: number; + lastSeen?: string | null; + initialTab?: "overview" | "history"; + activity(skill?: LibrarySkillModel): ReactNode; + files: ReactNode; + history: ReactNode; + testing: ReactNode; + diagnostics: ReactNode; +} + +function UnavailablePackage() { + return ( + + + Installation not found + + Usage history is still available. Return to Skills to check the package’s current + location. + + + + ); +} + +function ReportLayout({ + report, + skill, + actions, + refresh, + inventoryMessage, +}: { + report: LocalSkillReportProps; + skill?: LibrarySkillModel; + actions?: DashboardLibraryActions; + refresh?: () => void | Promise; + inventoryMessage?: string; +}) { + const [tab, setTab] = useState(report.initialTab ?? "overview"); + const description = skill?.contextEntries?.find((entry) => entry.metadata?.description)?.metadata + ?.description; + const locations = (skill?.locations ?? []).filter((location) => + skill?.lifecycle === "library" + ? location.sourceKind === "cached" + : location.sourceKind === "installed", + ); + locations.sort((a, b) => Number(Boolean(b.connection)) - Number(Boolean(a.connection))); + const canMoveOnDemand = + skill?.lifecycle === "active" && + Boolean( + skill.onDemandSources?.length || + skill.onDemandSource?.contentHash || + skill.archiveRecommendation?.contentHash, + ); + return ( +
+
+ {report.backLink} +
+

{report.name}

+ {skill && ( + + {skill.lifecycle === "library" ? "On demand" : skill.status} + + )} +
+ +
+
+ {description && + (description.includes(". ") ? ( +
+ {description.split(/(?<=\.)\s/)[0]} +

{description}

+
+ ) : ( +

{description}

+ ))} + {skill && ( +
+ {skill.sources.map((source) => source.label).join(" · ")} + +
+ )} + {inventoryMessage && ( +

+ {inventoryMessage} +

+ )} +
+ + + Overview + Files + Installations + History + Testing + + +
+ {[ + ["Recorded checks", report.checks.toLocaleString()], + ["Sessions", report.sessions.toLocaleString()], + ["Workspaces", report.workspaces?.toLocaleString() ?? "Unknown"], + ["Last recorded use", report.lastSeen ? timeAgo(report.lastSeen) : "Not recorded"], + ].map(([label, value]) => ( +
+
{label}
+
{value}
+
+ ))} +
+
+
{report.activity(skill)}
+ +
+
+ + Diagnostics and data sources + +
{report.diagnostics}
+
+
+ {report.files} + + {skill ? ( + <> + + + Where this skill loads + + Installed locations reported by this Mac. Library copies remain available for + on-demand use. + + + +
+ + + + + + + + + + {locations.map((location) => ( + + + + + + ))} + +
HarnessLocationSource
+ + +

{location.label}

+

+ {location.path} +

+
{location.sourceKind ?? "Unknown"}
+
+
+
+ + + Context and on-demand use + + Estimates apply to new sessions, not existing conversations. + + + + + {canMoveOnDemand && actions && refresh && ( + + )} + + + + ) : ( + + )} +
+ + {report.history} + + + {report.testing} + +
+
+ ); +} + +function ReportWithLibrary({ + report, + library, +}: { + report: LocalSkillReportProps; + library: Extract; +}) { + const inventory = library.useInventory(); + const actions = library.useActions(); + const skill = inventory.data?.skills.find((item) => item.name === report.name); + return ( + + ); +} + +export function LocalSkillReport(report: LocalSkillReportProps) { + const host = useOptionalDashboardHost(); + const library = host?.modules.skills.library; + return library?.access === "available" ? ( + + ) : ( + + ); +} diff --git a/packages/dashboard-core/src/screens/skill-report/SkillEvaluations.test.tsx b/packages/dashboard-core/src/screens/skill-report/SkillEvaluations.test.tsx new file mode 100644 index 00000000..bbfe211e --- /dev/null +++ b/packages/dashboard-core/src/screens/skill-report/SkillEvaluations.test.tsx @@ -0,0 +1,107 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, expect, test, vi } from "vitest"; +import type { EvaluationHistory } from "@selftune/control-plane/domain/evaluation-report"; +import { SkillEvaluations } from "./SkillEvaluations"; + +afterEach(cleanup); +const history: EvaluationHistory = [ + { + id: "one", + importedAt: "2026-09-12T09:00:00Z", + result: { + engine: "selftune-skill", + harness: "codex", + model: "test-model", + recordedAt: null, + threshold: 0.8, + exitCode: 0, + cases: [ + { + name: "Completes task", + score: 1, + baseline: 0.5, + delta: 0.5, + incomplete: false, + errors: [], + prompt: "Review the change", + assertions: [ + { + arm: "with", + name: "Used skill", + passed: true, + scored: false, + evidence: "Invocation indicator", + }, + ], + }, + ], + }, + }, +]; +test("uses shared harness icons and reveals unscored assertion evidence", () => { + render( + , + ); + expect(screen.getAllByText("+50 pp")).toHaveLength(2); + expect(screen.getByTitle("Codex").getAttribute("src")).toBe("/codex.svg"); + fireEvent.click(screen.getByText("Completes task")); + expect(screen.getByText("Not scored")).toBeTruthy(); + expect(screen.getByText("Invocation indicator")).toBeTruthy(); + expect(screen.getByRole("dialog")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Close" })); +}); +test("paginates large suites and does not summarize incomplete results as successes", () => { + const source = history[0]; + if (!source) throw new Error("Missing fixture"); + const entry = source.result.cases[0]; + if (!entry) throw new Error("Missing case fixture"); + render( + ({ + ...entry, + name: `Case ${i + 1}`, + incomplete: i === 24, + })), + }, + }, + ]} + harnesses={[]} + busy={false} + onImport={vi.fn()} + />, + ); + expect(screen.queryByRole("button", { name: "Case 25" })).toBeNull(); + expect(screen.getByLabelText("Run summary").textContent).toContain("24 / 25"); + expect(screen.getByLabelText("Run summary").textContent).not.toContain("100%"); + fireEvent.click(screen.getByRole("button", { name: "Next", exact: true })); + fireEvent.click(screen.getByRole("button", { name: "Case 25", exact: true })); + expect(screen.getByRole("dialog").textContent).toContain("Incomplete"); +}); +test("does not fabricate results in the empty or error states", () => { + render( + , + ); + expect(screen.getByText("No evaluation runs yet")).toBeTruthy(); + expect(screen.getByText("Malformed report")).toBeTruthy(); + expect(screen.queryByRole("table")).toBeNull(); +}); diff --git a/packages/dashboard-core/src/screens/skill-report/SkillEvaluations.tsx b/packages/dashboard-core/src/screens/skill-report/SkillEvaluations.tsx new file mode 100644 index 00000000..4a50334a --- /dev/null +++ b/packages/dashboard-core/src/screens/skill-report/SkillEvaluations.tsx @@ -0,0 +1,252 @@ +import { useRef, useState } from "react"; +import type { EvaluationHistory } from "@selftune/control-plane/domain/evaluation-report"; +import { + Badge, + Button, + Alert, + AlertTitle, + AlertDescription, + Table, + TableHeader, + TableHead, + TableBody, + TableRow, + TableCell, + Select, + SelectTrigger, + SelectValue, + SelectContent, + SelectGroup, + SelectItem, +} from "@selftune/ui/primitives"; +import { + HarnessLabel, + Empty, + EmptyHeader, + EmptyTitle, + EmptyDescription, + type HarnessIconSpec, +} from "@selftune/ui/components"; +import { EvaluationCaseInspector, percent, change, caseStatus } from "./EvaluationCaseInspector"; +type Props = { + history: EvaluationHistory; + harnesses: readonly { id: string; name: string; icon?: HarnessIconSpec | null }[]; + busy: boolean; + error?: string; + onImport(file: File): void; +}; +const mean = (values: readonly (number | null)[]) => + values.length && values.every((value) => value !== null) + ? values.reduce((sum, value) => sum + (value ?? 0), 0) / values.length + : null; +export function SkillEvaluations({ history, harnesses, busy, error, onImport }: Props) { + const [selected, setSelected] = useState(); + const [page, setPage] = useState(0); + const [inspection, setInspection] = useState<{ run: string; index: number } | null>(null); + const upload = useRef(null); + const active = history.find((run) => run.id === selected) ?? history[0]; + const result = active?.result; + const harness = harnesses.find( + (entry) => + entry.id === result?.harness || (result?.harness === "claude" && entry.id === "claude_code"), + ); + const cases = result?.cases ?? []; + const visiblePage = Math.min(page, Math.max(0, Math.ceil(cases.length / 20) - 1)); + const complete = cases.length > 0 && cases.every((entry) => !entry.incomplete); + const inspected = inspection?.run === active?.id ? cases[inspection?.index ?? -1] : undefined; + const runs = history.map((run) => ({ + value: run.id, + label: + new Date(run.result.recordedAt ?? run.importedAt).toLocaleString() + + " · " + + (run.result.harness ?? "Harness not recorded"), + })); + return ( +
+
+
+

Evaluations

+ {active && ( + + )} +
+ { + const file = event.target.files?.[0]; + if (file) onImport(file); + event.target.value = ""; + }} + /> + +
+ {error && ( + + Could not load evaluation + {error} + + )} + {!result || !active ? ( + + + {busy ? "Loading evaluations…" : "No evaluation runs yet"} + + Import a SelfTune benchmark or Claude plugin report. Results stay on this device. + + + + ) : ( + <> +
+ + {result.model ?? "Model not recorded"} + Threshold {percent(result.threshold)} + + {result.exitCode === 2 + ? "Incomplete" + : result.exitCode === 1 + ? "Below threshold" + : "Passed"} + +
+
+ {[ + { + label: "Cases passed", + value: + cases.filter((entry) => caseStatus(entry, result.threshold) === "Passed").length + + " / " + + cases.length, + }, + { + label: "Mean with skill", + value: percent(complete ? mean(cases.map((entry) => entry.score)) : null), + }, + { + label: "Mean baseline", + value: percent(complete ? mean(cases.map((entry) => entry.baseline)) : null), + }, + { + label: "Mean change", + value: change(complete ? mean(cases.map((entry) => entry.delta)) : null), + }, + ].map((metric) => ( +
+
{metric.label}
+
{metric.value}
+
+ ))} +
+ + + + Case + With skill + Baseline + Change + Status + + + + {cases.slice(visiblePage * 20, (visiblePage + 1) * 20).map((entry, index) => ( + + + + + {percent(entry.incomplete ? null : entry.score)} + {percent(entry.incomplete ? null : entry.baseline)} + {change(entry.incomplete ? null : entry.delta)} + + + {caseStatus(entry, result.threshold)} + + + + ))} + +
+ {cases.length > 20 && ( + + )} +

+ Latest 20 runs · Compare only matching harness, model, cases, and grading rules. +

+ setInspection(null)} + /> + + )} +
+ ); +} diff --git a/packages/dashboard-core/src/screens/skill-report/SkillReportRecentActivity.tsx b/packages/dashboard-core/src/screens/skill-report/SkillReportRecentActivity.tsx new file mode 100644 index 00000000..ca149a7b --- /dev/null +++ b/packages/dashboard-core/src/screens/skill-report/SkillReportRecentActivity.tsx @@ -0,0 +1,115 @@ +import { useState } from "react"; +import { HarnessLabel } from "@selftune/ui/components"; +import { + Button, + Card, + CardHeader, + CardTitle, + CardDescription, + CardContent, + Badge, + Table, + TableHeader, + TableHead, + TableRow, + TableBody, + TableCell, +} from "@selftune/ui/primitives"; +import { timeAgo } from "@selftune/ui/lib"; +import { + SkillReportInvocationsSection, + type SkillReportInvocationsSectionProps, +} from "./SkillReportInvocationsSection"; +import type { LibrarySkillModel } from "../../models"; + +export function SkillReportRecentActivity({ + invocations, + sessionMetadata, + locations, + callout, +}: SkillReportInvocationsSectionProps & { locations?: LibrarySkillModel["locations"] }) { + const [showDetails, setShowDetails] = useState(false); + const sessions = new Map(sessionMetadata?.map((session) => [session.session_id, session])); + const recent = invocations + .toSorted((a, b) => (b.timestamp ?? "").localeCompare(a.timestamp ?? "")) + .slice(0, 8); + return ( + + +
+ Recent activity + Recorded routing and skill use on this device. +
+ {invocations.length > 0 && ( + + )} +
+ + {showDetails ? ( + + ) : recent.length ? ( + + + + When + Harness + Project + Activity + + + + {recent.map((invocation, index) => { + const session = invocation.session_id + ? sessions.get(invocation.session_id) + : undefined; + const harness = session?.agent_cli ?? session?.platform ?? "Unknown"; + const connection = locations?.find( + (location) => location.connection?.toLowerCase() === harness.toLowerCase(), + ); + return ( + + + {invocation.timestamp ? timeAgo(invocation.timestamp) : "Unknown"} + + + + + + {session?.workspace_path?.split("/").findLast(Boolean) ?? "Not recorded"} + + + + {invocation.triggered ? "Skill used" : "Routing check"} + + + + ); + })} + +
+ ) : ( +

+ No activity recorded yet. Files and installations are available independently of usage + history. +

+ )} + {callout} +
+
+ ); +} diff --git a/packages/dashboard-core/src/screens/skill-report/index.ts b/packages/dashboard-core/src/screens/skill-report/index.ts index 587fd6f9..30316eab 100644 --- a/packages/dashboard-core/src/screens/skill-report/index.ts +++ b/packages/dashboard-core/src/screens/skill-report/index.ts @@ -43,3 +43,6 @@ export { type SkillReportScaffoldProps, } from "./SkillReportScaffold"; export { SkillReportTrustBadge, getSkillReportTrustBadgeConfig } from "./SkillReportTrustBadge"; +export { LocalSkillReport } from "./LocalSkillReport"; +export { SkillEvaluations } from "./SkillEvaluations"; +export { SkillReportRecentActivity } from "./SkillReportRecentActivity"; diff --git a/packages/dashboard-core/src/screens/skills/ContextSavings.tsx b/packages/dashboard-core/src/screens/skills/ContextSavings.tsx index d703bd0b..f2baf6b8 100644 --- a/packages/dashboard-core/src/screens/skills/ContextSavings.tsx +++ b/packages/dashboard-core/src/screens/skills/ContextSavings.tsx @@ -1,4 +1,6 @@ import type { LibrarySkillModel } from "../../models"; +import { useMemo, useState } from "react"; +import { Button } from "@selftune/ui/primitives"; import { contextFootprint } from "./context-footprint"; import { HarnessLabel } from "@selftune/ui/components"; @@ -9,8 +11,24 @@ export function ContextSavings({ skills: readonly LibrarySkillModel[]; selectedIds?: ReadonlySet; }) { - const rows = contextFootprint(skills, selectedIds); - const baseline = new Map(contextFootprint(skills).map((row) => [row.key, row])); + const rows = useMemo(() => contextFootprint(skills, selectedIds), [skills, selectedIds]); + const baseline = useMemo( + () => new Map(contextFootprint(skills).map((row) => [row.key, row])), + [skills], + ); + const icons = useMemo(() => { + const result = new Map(); + for (const skill of skills) + for (const location of skill.locations) { + if (location.connection && location.connectionIcon && !result.has(location.connection)) { + result.set(location.connection, location.connectionIcon); + } + } + return result; + }, [skills]); + const [requestedPage, setPage] = useState(0); + const pageCount = Math.max(1, Math.ceil(rows.length / 10)); + const page = Math.min(requestedPage, pageCount - 1); const preview = selectedIds !== undefined; return (
@@ -32,20 +50,13 @@ export function ContextSavings({ - {rows.map((row) => ( + {rows.slice(page * 10, (page + 1) * 10).map((row) => ( skill.locations) - .find( - (location) => - location.connection === row.harness && location.connectionIcon, - )?.connectionIcon - } + icon={icons.get(row.harness)} /> {row.scope.split("/").filter(Boolean).at(-1) ?? row.scope} @@ -70,6 +81,34 @@ export function ContextSavings({ ))} + {pageCount > 1 ? ( + + ) : null}
) : (

diff --git a/packages/dashboard-core/src/screens/skills/InstalledSkillHistory.test.tsx b/packages/dashboard-core/src/screens/skills/InstalledSkillHistory.test.tsx new file mode 100644 index 00000000..8771ff61 --- /dev/null +++ b/packages/dashboard-core/src/screens/skills/InstalledSkillHistory.test.tsx @@ -0,0 +1,42 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, expect, test } from "vitest"; +import { DashboardHostProvider } from "../../host"; +import { hostModules } from "../../test/host-modules"; +import type { LibrarySkillModel } from "../../models"; +import { InstalledSkillHistory } from "./InstalledSkillHistory"; + +afterEach(cleanup); +test("53 installed copies mount one history reader, switching without losing locations", () => { + const modules = hostModules(); + modules.skills = { + ...modules.skills, + History: ({ skillPath }) =>

{skillPath}

, + }; + const skill: LibrarySkillModel = { + id: "test", + name: "test", + lifecycle: "active", + status: "Ready", + updateStatus: "untracked", + sources: [], + revisionHashes: [], + locations: Array.from({ length: 53 }, (_, index) => ({ + id: String(index), + label: "Global", + path: `/agents/${index}/test`, + sourceKind: "installed", + })), + }; + render( + + + , + ); + expect(screen.getAllByTestId("history-reader")).toHaveLength(1); + expect(screen.getByTestId("history-reader").textContent).toBe("/agents/0/test/SKILL.md"); + expect(screen.getAllByRole("option")).toHaveLength(53); + fireEvent.change(screen.getByLabelText("Installed copy history"), { target: { value: "52" } }); + expect(screen.getAllByTestId("history-reader")).toHaveLength(1); + expect(screen.getByTestId("history-reader").textContent).toBe("/agents/52/test/SKILL.md"); +}); diff --git a/packages/dashboard-core/src/screens/skills/InstalledSkillHistory.tsx b/packages/dashboard-core/src/screens/skills/InstalledSkillHistory.tsx new file mode 100644 index 00000000..93686e35 --- /dev/null +++ b/packages/dashboard-core/src/screens/skills/InstalledSkillHistory.tsx @@ -0,0 +1,35 @@ +import { useSkillsModule } from "../../host"; +import type { LibrarySkillModel } from "../../models"; + +export function InstalledSkillHistory({ skill }: { skill: LibrarySkillModel }) { + const History = useSkillsModule().History; + const [selected, setSelected] = useState(null); + if (!History) return null; + const locations = skill.locations.filter((location) => location.sourceKind === "installed"); + const location = locations.find((item) => item.id === selected) ?? locations[0]; + if (!location) return null; + return ( +
+ {locations.length > 1 ? ( + + Installed copy history + + + ) : null} + +
+ ); +} +import { useState } from "react"; +import { Field, FieldLabel } from "@selftune/ui/primitives"; diff --git a/packages/dashboard-core/src/screens/skills/InstalledSkillPackage.tsx b/packages/dashboard-core/src/screens/skills/InstalledSkillPackage.tsx new file mode 100644 index 00000000..160d6210 --- /dev/null +++ b/packages/dashboard-core/src/screens/skills/InstalledSkillPackage.tsx @@ -0,0 +1,34 @@ +import { useState } from "react"; +import { Field, FieldLabel } from "@selftune/ui/primitives"; +import { useSkillsModule } from "../../host"; +import type { LibrarySkillModel } from "../../models"; + +export function InstalledSkillPackage({ skill }: { readonly skill: LibrarySkillModel }) { + const Inspector = useSkillsModule().PackageInspector; + const [selected, setSelected] = useState(null); + const locations = skill.locations.filter((location) => location.sourceKind === "installed"); + const location = locations.find((item) => item.id === selected) ?? locations[0]; + if (!Inspector || !location) return null; + return ( +
+ {locations.length > 1 ? ( + + Installed copy to inspect + + + ) : null} + +
+ ); +} diff --git a/packages/dashboard-core/src/screens/skills/LibraryPagination.tsx b/packages/dashboard-core/src/screens/skills/LibraryPagination.tsx new file mode 100644 index 00000000..9203a11c --- /dev/null +++ b/packages/dashboard-core/src/screens/skills/LibraryPagination.tsx @@ -0,0 +1,37 @@ +import { useState } from "react"; +import { Button } from "@selftune/ui/primitives"; + +export function useLibraryPage(items: readonly T[], key: string) { + const [state, setState] = useState({ key, page: 0 }); + const pageCount = Math.max(1, Math.ceil(items.length / 50)); + const page = state.key === key ? Math.min(state.page, pageCount - 1) : 0; + return { + visibleSkills: items.slice(page * 50, (page + 1) * 50), + pagination: + pageCount > 1 ? ( + + ) : null, + }; +} diff --git a/packages/dashboard-core/src/screens/skills/OnDemandSkillsPanel.tsx b/packages/dashboard-core/src/screens/skills/OnDemandSkillsPanel.tsx index 9d0aec83..587d0a6a 100644 --- a/packages/dashboard-core/src/screens/skills/OnDemandSkillsPanel.tsx +++ b/packages/dashboard-core/src/screens/skills/OnDemandSkillsPanel.tsx @@ -24,10 +24,12 @@ export function OnDemandSkillsPanel({ skills, actions, refresh, + loadSkills, }: { skills: readonly LibrarySkillModel[]; actions?: DashboardLibraryActions; refresh?: () => void | Promise; + loadSkills?: () => Promise; }) { const [open, setOpen] = useState(() => { try { @@ -95,6 +97,7 @@ export function OnDemandSkillsPanel({ introduction={introduction} initialOpen={open} onDismiss={dismiss} + loadSkills={loadSkills} /> ); } diff --git a/packages/dashboard-core/src/screens/skills/OnDemandSkillsReview.test.tsx b/packages/dashboard-core/src/screens/skills/OnDemandSkillsReview.test.tsx index 4daadaff..a890fea0 100644 --- a/packages/dashboard-core/src/screens/skills/OnDemandSkillsReview.test.tsx +++ b/packages/dashboard-core/src/screens/skills/OnDemandSkillsReview.test.tsx @@ -6,6 +6,39 @@ import { OnDemandSkillsReview } from "./OnDemandSkillsReview"; afterEach(cleanup); +it("waits for complete inventory before showing context savings or enabling moves", async () => { + let finish: (() => void) | undefined; + const loadSkills = vi.fn( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const move = vi.fn(); + render( + Setup

} + initialOpen + loadSkills={loadSkills} + refresh={vi.fn()} + actions={{ + moveToLibraryMany: { access: "available", execute: move }, + restore: { access: "unavailable", reason: "test" }, + }} + />, + ); + expect(screen.getByRole("status").textContent).toContain("Loading installations"); + expect(screen.queryByRole("region", { name: "Context savings by harness" })).toBeNull(); + expect( + screen.getByRole("button", { name: "Move 0 skills to on-demand" }).hasAttribute("disabled"), + ).toBe(true); + finish?.(); + await waitFor(() => expect(screen.queryByRole("status")).toBeNull()); + expect(loadSkills).toHaveBeenCalledTimes(1); + expect(move).not.toHaveBeenCalled(); +}); + it("handles 125 skills with bounded pages and preserves selections across search", async () => { const execute = vi.fn().mockResolvedValue({ succeeded: 2, failed: 0, receipts: [] }); const skills = Array.from({ length: 125 }, (_, index): LibrarySkillModel => { diff --git a/packages/dashboard-core/src/screens/skills/OnDemandSkillsReview.tsx b/packages/dashboard-core/src/screens/skills/OnDemandSkillsReview.tsx index ee56cd95..7dbf68ab 100644 --- a/packages/dashboard-core/src/screens/skills/OnDemandSkillsReview.tsx +++ b/packages/dashboard-core/src/screens/skills/OnDemandSkillsReview.tsx @@ -1,6 +1,6 @@ "use client"; -import { useState, type ReactNode } from "react"; +import { useEffect, useState, type ReactNode } from "react"; import { LibraryIcon, Undo2Icon } from "lucide-react"; import { Button, @@ -23,6 +23,7 @@ export function OnDemandSkillsReview({ introduction, initialOpen = false, onDismiss, + loadSkills, }: { skills: readonly LibrarySkillModel[]; actions: Pick; @@ -30,6 +31,7 @@ export function OnDemandSkillsReview({ introduction?: ReactNode; initialOpen?: boolean; onDismiss?: () => void; + loadSkills?: () => Promise; }) { const [open, setOpen] = useState(initialOpen); const [selected, setSelected] = useState>(() => new Set()); @@ -37,6 +39,24 @@ export function OnDemandSkillsReview({ const [error, setError] = useState(null); const [notice, setNotice] = useState(null); const [receipts, setReceipts] = useState([]); + const [loading, setLoading] = useState(Boolean(initialOpen && loadSkills)); + const [loadError, setLoadError] = useState(null); + useEffect(() => { + if (!open || !loadSkills) return; + let active = true; + setLoading(true); + setLoadError(null); + void loadSkills() + .catch((cause) => { + if (active) setLoadError(cause instanceof Error ? cause.message : String(cause)); + }) + .finally(() => { + if (active) setLoading(false); + }); + return () => { + active = false; + }; + }, [open, loadSkills]); const eligible = skills.filter( (skill) => skill.lifecycle === "active" && @@ -229,55 +249,65 @@ export function OnDemandSkillsReview({ {introduction ? feedback : null} -
-
- - {introduction ? ( -
- How to load a saved skill later -
{introduction}
-
- ) : null} -
- +
+ )} {error ? (

{error} @@ -287,7 +317,10 @@ export function OnDemandSkillsReview({ - @@ -597,14 +590,19 @@ function AvailableSkillsLibrary({ Restore skill ) : null} - {skill.archiveRecommendation && archiveAction.access === "available" ? ( - setArchiveReview(skill)}> + {(skill.archiveRecommendation || skill.archiveAvailable) && + archiveAction.access === "available" ? ( + void reviewSkill(skill, setArchiveReview)} + > Review archive ) : null} - {skill.consolidationRecommendation && + {(skill.consolidationRecommendation || skill.consolidationAvailable) && consolidateAction?.access === "available" ? ( - setConsolidationReview(skill)}> + void reviewSkill(skill, setConsolidationReview)} + > Review consolidation ) : null} @@ -635,6 +633,7 @@ function AvailableSkillsLibrary({

+ {pagination} {blockedCount > 0 ? (

@@ -791,6 +790,8 @@ function AvailableSkillsLibrary({ } }} /> + + ) : null} diff --git a/packages/dashboard-core/src/screens/skills/table-interaction.ts b/packages/dashboard-core/src/screens/skills/table-interaction.ts new file mode 100644 index 00000000..379170dd --- /dev/null +++ b/packages/dashboard-core/src/screens/skills/table-interaction.ts @@ -0,0 +1,6 @@ +export function isInteractiveTableTarget(target: EventTarget | null): boolean { + return ( + target instanceof Element && + target.closest("a, button, input, textarea, select, [role=combobox], [role=menuitem]") !== null + ); +} diff --git a/packages/harnesses/claude-code/package.json b/packages/harnesses/claude-code/package.json index 4a837762..fbf31e52 100644 --- a/packages/harnesses/claude-code/package.json +++ b/packages/harnesses/claude-code/package.json @@ -17,7 +17,7 @@ "@selftune/local-store": "workspace:*", "@selftune/observability": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/packages/harnesses/claude-code/src/descriptor.ts b/packages/harnesses/claude-code/src/descriptor.ts index 785f59a4..6876d81b 100644 --- a/packages/harnesses/claude-code/src/descriptor.ts +++ b/packages/harnesses/claude-code/src/descriptor.ts @@ -4,10 +4,8 @@ import { join } from "node:path"; import type { HarnessPackageContribution, - HarnessPresentation, HarnessRuntimeContribution, } from "@selftune/harness-core/descriptor"; -import { svgHarnessIcon } from "@selftune/harness-core/descriptor"; import { ClaudeCodeSettings, missingClaudeCodeHookKeys } from "@selftune/runtime/utils/hooks"; function readHooks(path: string): NonNullable | null { @@ -22,15 +20,8 @@ function readHooks(path: string): NonNullable | nul } } -export const claudeCodePresentation: HarnessPresentation = { - id: "claude_code", - name: "Claude Code", - description: "Anthropic's coding agent with live hooks and transcript import.", - icon: svgHarnessIcon( - 'Claude\n', - ), - documentation_url: "https://docs.selftune.dev/guides/platform-hooks", -}; +export { claudeCodePresentation } from "./presentation.js"; +import { claudeCodePresentation } from "./presentation.js"; export const claudeCodeRuntime: HarnessRuntimeContribution = { id: "claude_code", diff --git a/packages/harnesses/claude-code/src/presentation.ts b/packages/harnesses/claude-code/src/presentation.ts new file mode 100644 index 00000000..a6a68864 --- /dev/null +++ b/packages/harnesses/claude-code/src/presentation.ts @@ -0,0 +1,12 @@ +import type { HarnessPresentation } from "@selftune/harness-core/descriptor"; +import { svgHarnessIcon } from "@selftune/harness-core/descriptor"; + +export const claudeCodePresentation: HarnessPresentation = { + id: "claude_code", + name: "Claude Code", + description: "Anthropic's coding agent with live hooks and transcript import.", + icon: svgHarnessIcon( + 'Claude\n', + ), + documentation_url: "https://docs.selftune.dev/guides/platform-hooks", +}; diff --git a/packages/harnesses/claude-code/src/source-sync.ts b/packages/harnesses/claude-code/src/source-sync.ts index 59411fb4..5b458e72 100644 --- a/packages/harnesses/claude-code/src/source-sync.ts +++ b/packages/harnesses/claude-code/src/source-sync.ts @@ -15,6 +15,7 @@ import { CLAUDE_CODE_MARKER, QUERY_LOG, TELEMETRY_LOG } from "@selftune/runtime/ import { NORMALIZER_VERSION } from "@selftune/runtime/normalization"; import { fingerprintIngestionFile, + fileIngestionRevision, isFileIngestionCurrent, loadFileIngestionMarker, saveFileIngestionMarker, @@ -123,7 +124,8 @@ const makeSyncClaudeCodeSource = (markerPath: string) => const importer = yield* LocalTraceImporter; const importRequest = LocalTraceImportRequest.make({ source_kind: "claude_code", - source_revision: `${CLAUDE_SOURCE_PROJECTION_VERSION}:${fingerprint.size}:${fingerprint.mtime_ms}`, + source_session_ids: [parsed.session_id], + source_revision: `${CLAUDE_SOURCE_PROJECTION_VERSION}:${fileIngestionRevision(fingerprint)}`, normalizer_version: NORMALIZER_VERSION, batch: buildLocalTelemetryBatchFromSession(parsed), }); diff --git a/packages/harnesses/cline/src/descriptor.ts b/packages/harnesses/cline/src/descriptor.ts index 9c9dec16..7abe7049 100644 --- a/packages/harnesses/cline/src/descriptor.ts +++ b/packages/harnesses/cline/src/descriptor.ts @@ -3,26 +3,14 @@ import { join } from "node:path"; import { type HarnessPackageContribution, - type HarnessPresentation, - type HarnessPresentationIcon, type HarnessRuntimeContribution, } from "@selftune/harness-core/descriptor"; const CLINE_HOOK_NAMES = ["PostToolUse", "TaskComplete", "TaskCancel"] as const; // Official product mark from https://github.com/cline/cline/blob/main/assets/icons/icon.png. -const clineIcon: HarnessPresentationIcon = { - src: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAgKADAAQAAAABAAAAgAAAAABIjgR3AAATIUlEQVR4Ae0daXSURbL6mxACRJAEHhBAwxGQw0iABZIZQAiJ+LyWU+5DF564Xu+x4o/FC9fniro/9nkgrEs4XEXE3fcWV0mISJJJJJDERUEhXItCkCMhEiCEzHxb9TETZiYzk+/sOfLVe9/Md3RXV1fV191fd1U1gzCF1OzsDm3qGrszi6W7CM6uTGQJIrDOTHQmAINOIhPiRacYzxjEYxU6MIA4EQ88b4sH/cdiuhgQ8YCmQ8BzTCod7nO8xFQATte/+7wRrxsxZSM+pfMGPOrxuIYI6jERnV8WRahjAqtDuuowXS3SVc1ArBGZiP/COdHhOHM9PubM/tzcy5g+7ICYETIYMfaeHk4mplgcjhSRsRQkJgUZm4IE9cGDBBtNcAkrcwLrWIl1rGSiWOmwWCoFkVWWFe6oClVFuSmA1Wq9pV5snw4WsIEo2rDCv8Ej2oSsVo51mHEvMFYEDiiKY1dK7HY7KYzhYKQCsLRx2WMFpzgNBT4Wm9JUrI3F8BpFRwEO7E72o0IUOgW2raIgtxCrRV2T7qC7AoyyZQ5wAJuPQp+HFUjWneLWiFAUTyAvN1tA3FRalH9YTxbopgDDrZOm4oBsBRI3Wk8CTVzNOLAHB56ry+07P2v2RMUNzQqAgh+D2vkWjnwzVJRvZlHJAfwiKsZWdjkqwjcqUUjZVCvAqHHZfRxO5+uIZYYWAsy8mjmw1SIIz5UW5B5Xg0mVAgy3ZU5mwD7GAjupKdTMozsHakUQZ5UX5X+pFLPiUfkIW9Zy1JocLKid0sLM9IZxIA5fyDlJt/W7XHXyWImSUmS3AEOGzIiNS7i4FvudhUoKMNNy5gBjG+qrb1164MBWmrlsEWiaVBaYwpfFptAnwhcUZUV0LJJDjKwugJp9nIegTzwTIoMDw7A7qJPTHbTYBbgGfJ9jvWnxxITI4YATB4b3tTQwDKoArk+9CqyzOdqPHMF7UlqLn4hpwT4Rg77VDqe42hS+Jz8j7ryTS4YBCQ/YAqRlZKYLAs42mRDxHHA6xYyK4ny/n4cBWwAmCG9GfM3NCkgcCCZLvy2Aa2FnW7TxLyYmBtJHp4M1IwMGDhgIXRITQRAEuFBdDceOHwV7SQkUFhVCfT0Z+0QX4ALSNH8LSH4VYIRtEi0wRNWq3lirDZY8ugR6JiUFlWx1TTVs2LwJtn++PWi6CHy4p6xo5xhfupspgGs9/5Bvwki9pjf8sSVLYdqUaYqq8HXBbnj9rTeg4do1RfnCOTHaEwz0tSdoNgaQjDnCuRYKaXvi8d8rFj4Vcfe48fDiH5/HLqLZO6KQgvBJ7k+2vgqAy/poyRMlkJ2VDQ/d/6Dq2owZNRrmz12gOn/YZbwhWy+N9lIAsuGLFjOuuLg4WPLIo5plMGvGTOjatatmPGGBgLFkScYexHgpgGTA6fEwkk8nZ98DCZ0TNFchNjYWZkxVNn7QXKiBCHxl7KUA2PyPNbBsrqhtOOrXC6wZ+uHSiybVeHxk3KQAZLfvMt1WjTucMg4ZPEQ3crp36wZdunTRDV9IEaF5viRrFxFNCiA5bUSJ3X7Hjh0htk0bXfncJTFKFABl7JK1xJ8mBZA8dnRlWeiQxcaSe6C+oLdC6UudQmzkneWCmwrg0ze4E0Ti/8WLNTic0deRphqni6MGPGR9UwEARkZLBRsbG+FU1WndqnOt/hqcPXdWN3xhgKhJ1pICpFmzaII8qhw1S3BhRy/YW7YPGq5f1wtdOOCJd8lc8pvHYQHrD2hAFM4Q27YtJCYk4JEo/dP3eTCora0FXAfXZSq36sxpyMqcFKw4aGx04KriBaCu4sKFC3C1/mrQ9CF/SDIHOC1ZBbv880NOky8B/fv1h4z0DLBlWKFf376+j7ldz5im3Pnp59OnoLi4GOzFdjj440FJGbkRLKMgkjkmK5AUgIIzyMjDLUl6ejosWfQI3H57Mrcy9S6oV1JPmDl9hnScO3cO1m/Mgbz8vLBRBLfMJQXA1QGKzBFyGDhgACxb+hjcOfTOkNOiJwG0lrBi+bMwY9p0WLPufdhXVqYnelW4SOaUUfIL6HFb35V43k0VJp0yTb5nMrz8/EvQo0cPnTCGH5rOt3aGSRMzkTCM/vD9d6EmsBH9Bt6TWgCkpE+oqFFrsBEqerWWyzCIwsL5C6XuLcQGJ5LMmRSN6wpGuAoRPP3kU/DgfQ+EqPTQFruntBRWvrQyZOOC6+2FeIFCsYWKDST41ip84vnoUaPQZmFJqNgPJHuB4vCFgoJUHOiRuVZrB/pSuDEu4M8Jkr1AQRh5F012ds9g02+xyPJN5U0e9/Ief2wZtG/fnnu5JHuBInDyLjl7UnZEf+Prza9OHTvBw9Nn6o22RXwke2wBWOcWU+qYgKZwFy8wY0z4snTG1Om6mLD54g12TbLHFgBj73KEkSNGonUN916HYw3VFdU2ri1MnDBRXWaVuUj2ApqBcXX9pnl9E/xzgFzWuALKHmMVC9yWgWnSZ8zoqPI401VeQ9GOkczZeAHJXqCQ67wK7JOcDDTgMcE/B+gFSb2T3zoIyV7AmUluCtDV7Pv9S97jbtdEfuMjkj1ZBHXwKN/Q00R0xzYhOAc486gDuT7S7hpcgPzxTQjOAZ48ItnjPAA/BYiLM4OLBhc/CqMdPx6R7OkzkFsL0FLlzeecOYCyp02V9Pei4FAPCtxQUroHyGL3lzNn4DqaglPzORQXmSgaCBmQ6gVXr16RwseUVZTD2bNnwelwSK5iw+4aBjarNXK/bFD2ZBAS3LxWLy7qiCfvq3xY98E6yfrWF+2u3V/D+2h2NeWhKbAIp5y1evT8e/t2yZ6v9tda36Lgq693wXvvr4GZ6EI+b/YcKd5Qs0ThfSM2BrsAagUiBt5Z8y589q9/BqW3oaEBtmzdAt8f+A5eXfUq3BKv/EuXTMpX/+UNyNuZF7QsMv/esGkDlvU9vPLCy0BTuhEDKHsBhe82Cwt7uj/a8nGLwvesxIGDB2HVn1ahxQ1tCagM1v19XYvC98RYVl4Gr71B+2dEEKDsaR6AmwLccccdqrlDdvY5+KYphfJvK+A/X36hKNvhykrYuu1TRXkocaG9EAqKChTn88yQgr4QHO0k+CnAiOEjgKyA1MLHn2xB75tGVdk3f/ShImdRpek9idr8jw89LxWfd+/eHbImZSnOpzKDpADUChgOixcsUl0G9cfkZaMWyDHj8OHDsrKTIyh9WaiFo8eOQVVVldrsUr75s+fyagVw9YFDGPj00WNgkIbmv7r6PPgbhSvh8rHjx2Qlp65Ga2xAUgItQK0ARTjjAJIC4IygcUB28PQ5pgWqa6QdMLSggOqL8nDU1NRoKocy64Fj3qw5QKFtDQZGLYChCmDDAEvk5KkFHDjxohXk4pCbLhg9Dqd2eqVWwPixgLEKQNa/ixcsCMYr81kQDszFsYDBrYCkAEFI0PZo4t0TTetfDSyk6GT3GDwWoC7AkHlA+padP2++huqbWYkDc40dC4ikAMqnyWTIhr5lyUfeBG0c6IatAEU9NQichrUA9C1rgj4cmP3wbH0QNccitQC6dwG9evYCGsWaoA8HaCxwW+/e+iDzxmJMF9C7Vy/vYswrzRzoaUx3KnUB6ibYg1Tpx0M/BnlqPlLDgUMyp7IV4m6kMYDuClCDs25hEAJFIS/CNznZGtBeRgYAKgDTXwGI0PU56w2gt3WizNmofBlcFqdQ9mQQonsLQIVTC6BlVU1WBVpBIuJjxX+/NaamKHvqAhqMwY6twAazFdDK2/UbcrSiCJa/gRSgPlgKLc9o4FJkt2tB0arz0pu//7v9RvKgnhTA0I3x1m/K0RwFKyZGeyiZGJnhaNq00b4Eq9cCjmF9/02VukauYYa1AFTOiRMnYNfuXTeLVHGWgAGitYJcnzs9NppK1GGzKjIypdG/kUCyJ9cwQxWAKkBm01rW2RM6dwa5AgzEsAEpKYEeed3vibOY7dqpD9hEBjApMsvyKtjnQo0BrA+KFi9J9tQFXG4xpcYEp06fhh15uaqxEFPH28apzt+7V2/ok9xHVn7qAqwYrFotDB40SPMGU6V7S+HgDz+oJUFJvssC7qzCJUroxg83adp04WH0vqE9A9TAwvnKlqXnzVFvlLlwnnYDmJzNG9VUU3Eekr3ABMZFAcgydxe6UqkF2rbtqWXKA0vSHsATxk9QVCy1GI8ufkRRHkr8wP33A5m/awEa9R86dEgLCtl5SfYUJYyLAhBVtIuHFrh38r2w9HdLZO8CQvsOPIdh2tUAxe2bM0v+MmwWRgF/ctkTaoryylP7669e10ZekOzJL7DWWLNQfatAgknpnyI5ZQYy9aY4RPPmzoUpD/4Wt0LGsa5KeBQ3rRg8cBCs+dta+PnUz36xkBcy+TyQckYcoOxjMFIUrjLgeDCCYPiwNFj77hppK5a9+/bBmV9+gUbc1CkRN3dMHToURg4fqZuTJrUiozGy2Xc4JUufZuQe7kBfQ+qShqUOg7S0NM0eyKFiPck+BveLr4ks8d9gF73ZQwYNkQ6jGUjRu+5KvUs6jC6LJ36SPcYJFA1ZZ+RZEbMsdRwg2eNMoHBOXXbluUTREPtT5YSEdQ5+7THJXhAdjjO8+FFby2+Ey6tOepdzsUbbl5ISekj2wvX4GG4KQBsrmhCcA9U1/HhEshf25+bSVDCXuQDaUdOE4Bw4z49Hl0j2tBZAcPzGn7G/5HptQnAO/HyKG49OECWSAuBUSWVwsvR5StPBgSZv9CkhsrFcqquDAwcPcKmEW+aSAuC4k4sCUM3sGiJ9cOFMCAvZg3EPtSybKyHdLfMbLYAoclOAItxM2QT/HOBpPsdcMpcUwGGxcFOAI0ePhMXeuf5FELq7J3/6CaOR8ns53DKXFAAc4hGeVV+LMfhEXIw24SYHPsj5QFU8w5sYlJ3hFLD00ksKUGHPO43ZuXwKEplHjx6F/F1fKaM4ilMf+OEAb+vpurLCHVIosxstwA3m7uXJ47ffewdOV5HetW64dOkS/Hn1at5MaJL1TQVgrIgnFVTx5198ASgSd2sFGvGvevUV/i+Ch6xvKoADuCoACf3Eyf/BK6+9qslWMFKVh8ZAf333baBQttzBQ9ZNChDHrpQgIQ7exNAW6stXLDfK+5V3dWSVRxHGX1j1Emz/fLus9DoncrhkLaFtUgC73X4JDYMM9UMKVBEygX78qSeAgjRHO5zBzS2efOZpKC4pDk1VUcaSrF2le/lcJd3ebzDeD8nOjleuXIEvdnwB58+fhwEDBkJ7jnvn8JDE5SuXYePmTfDam6txo4vzPIr0XwZjW6tOHvvS/dDLYjJtXPY4wenc7X4Yqn/adGEq7vgxaUImJCcnh4oMXcqlN552Mflk21b4laPFbyDinYIwvqIgt8D93EsB8CYbYc08hqa0ye4Eof5P6pEEtKcuedyQe1hiQhdIQEtcrVvB6F0vCmVPMYLJ5oGWvStxxpPWPcJq8UsUT5TZ8/ti3Ztm4XxdYXFHcbYZE6zUm0Fq8dFcgZrNG9SWF9X5bsi2SfhU16ZBoLviFhA3uc/N/+jigD/ZNlOA0qJ82llhT3RV3awNydQlWy9mNFMAeopzFNznJr2oMi9050AgmfoOApsKHm7LsqPjQEbTDfMkYjmAA7vi8qI8q78K+G0BKKHodP7BXwbzXgRyQBSXB6I6oAJUFOfT1PDWQBnN+xHDga3l9p3fBKI2oAJQBosgPId//DwVAlFp3lfLgVqXDAPmD6oApQW5x0UQZ2Fu06crIAvD9gFutifOIhkGo9BrLcBfwqqTx48k3daPnEey/T0374UrB9iz5UU7W5zTaVEBqHq4eFCCC0V98HRYuFbXpMuDA4xtKCvKo+67RQjaBXjmrq++dSleb/S8Z56HIQdQ+C5ZySIu4DxAoNwjbFn4SSHSRJFs5QmEy7yvKwdwnMZW4Jv/lhKsihWAkA+3ZU5mwD7G005KCjPTGsaBWhrwlRflN63zyy1J1VtMBeHnRRpqnPI91uVSZqaTyQH2KclCjfCpAFUtgCdlaRmZ6UwQ3jSnjT25Yvw5Te/SbK1rwk51gZoVwF3ycOukqRi3aQVeh8SkzE1HK/jfQws7OLv3mR511U0B3MSMsmUOcACbj0uK88LJsshNX0T+oyUPGerQer6/JV0tddJdATyIYWhjOFZwitNQGcZiZ5OKz2TNO3jgaK2nDslCm7FCp8C2oQ1fITLCy5JHL8YYqQBeNFqt1lvqxfbpqAI2SSEARmKCeK9ErfeC/DL34VteiJ4ZRWS372m6bSRbuCmAv0qkWbOSwML6WxyOFJGxFCQmBdU8BdP2wSPalIOEfBzrWIl1rCT/fMlFGz2zXc65/lhk+L2QKkCw2qVmZ3doU9fYnVks3UVwdmUiS8CRb2cMcJyA3UknDHMaLzrFeBx4kqJ0wIrEIWPj8FkcNpZt8V4snlMsZDJ8dR/02UsH1dt94KnUvFITSwctfNFBu6k1YqpGvEvnDXh+Dc/rMWM9JqzHe5dxQFZHUbeloNsYe5fCr0rRVzEII8Xho1BsFI3LFYwLs4QX/B+sF+kaJgBClQAAAABJRU5ErkJggg==", - fit: "cover", - inset: "none", -}; -export const clinePresentation: HarnessPresentation = { - id: "cline", - name: "Cline", - description: "AI coding agent with task lifecycle hooks for local telemetry.", - icon: clineIcon, - documentation_url: "https://docs.selftune.dev/guides/platform-hooks", -}; +export { clinePresentation } from "./presentation.js"; +import { clinePresentation } from "./presentation.js"; export const clineRuntime: HarnessRuntimeContribution = { id: "cline", diff --git a/packages/harnesses/cline/src/presentation.ts b/packages/harnesses/cline/src/presentation.ts new file mode 100644 index 00000000..8bc24c77 --- /dev/null +++ b/packages/harnesses/cline/src/presentation.ts @@ -0,0 +1,18 @@ +import type { + HarnessPresentation, + HarnessPresentationIcon, +} from "@selftune/harness-core/descriptor"; + +const clineIcon: HarnessPresentationIcon = { + src: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAgKADAAQAAAABAAAAgAAAAABIjgR3AAATIUlEQVR4Ae0daXSURbL6mxACRJAEHhBAwxGQw0iABZIZQAiJ+LyWU+5DF564Xu+x4o/FC9fniro/9nkgrEs4XEXE3fcWV0mISJJJJJDERUEhXItCkCMhEiCEzHxb9TETZiYzk+/sOfLVe9/Md3RXV1fV191fd1U1gzCF1OzsDm3qGrszi6W7CM6uTGQJIrDOTHQmAINOIhPiRacYzxjEYxU6MIA4EQ88b4sH/cdiuhgQ8YCmQ8BzTCod7nO8xFQATte/+7wRrxsxZSM+pfMGPOrxuIYI6jERnV8WRahjAqtDuuowXS3SVc1ArBGZiP/COdHhOHM9PubM/tzcy5g+7ICYETIYMfaeHk4mplgcjhSRsRQkJgUZm4IE9cGDBBtNcAkrcwLrWIl1rGSiWOmwWCoFkVWWFe6oClVFuSmA1Wq9pV5snw4WsIEo2rDCv8Ej2oSsVo51mHEvMFYEDiiKY1dK7HY7KYzhYKQCsLRx2WMFpzgNBT4Wm9JUrI3F8BpFRwEO7E72o0IUOgW2raIgtxCrRV2T7qC7AoyyZQ5wAJuPQp+HFUjWneLWiFAUTyAvN1tA3FRalH9YTxbopgDDrZOm4oBsBRI3Wk8CTVzNOLAHB56ry+07P2v2RMUNzQqAgh+D2vkWjnwzVJRvZlHJAfwiKsZWdjkqwjcqUUjZVCvAqHHZfRxO5+uIZYYWAsy8mjmw1SIIz5UW5B5Xg0mVAgy3ZU5mwD7GAjupKdTMozsHakUQZ5UX5X+pFLPiUfkIW9Zy1JocLKid0sLM9IZxIA5fyDlJt/W7XHXyWImSUmS3AEOGzIiNS7i4FvudhUoKMNNy5gBjG+qrb1164MBWmrlsEWiaVBaYwpfFptAnwhcUZUV0LJJDjKwugJp9nIegTzwTIoMDw7A7qJPTHbTYBbgGfJ9jvWnxxITI4YATB4b3tTQwDKoArk+9CqyzOdqPHMF7UlqLn4hpwT4Rg77VDqe42hS+Jz8j7ryTS4YBCQ/YAqRlZKYLAs42mRDxHHA6xYyK4ny/n4cBWwAmCG9GfM3NCkgcCCZLvy2Aa2FnW7TxLyYmBtJHp4M1IwMGDhgIXRITQRAEuFBdDceOHwV7SQkUFhVCfT0Z+0QX4ALSNH8LSH4VYIRtEi0wRNWq3lirDZY8ugR6JiUFlWx1TTVs2LwJtn++PWi6CHy4p6xo5xhfupspgGs9/5Bvwki9pjf8sSVLYdqUaYqq8HXBbnj9rTeg4do1RfnCOTHaEwz0tSdoNgaQjDnCuRYKaXvi8d8rFj4Vcfe48fDiH5/HLqLZO6KQgvBJ7k+2vgqAy/poyRMlkJ2VDQ/d/6Dq2owZNRrmz12gOn/YZbwhWy+N9lIAsuGLFjOuuLg4WPLIo5plMGvGTOjatatmPGGBgLFkScYexHgpgGTA6fEwkk8nZ98DCZ0TNFchNjYWZkxVNn7QXKiBCHxl7KUA2PyPNbBsrqhtOOrXC6wZ+uHSiybVeHxk3KQAZLfvMt1WjTucMg4ZPEQ3crp36wZdunTRDV9IEaF5viRrFxFNCiA5bUSJ3X7Hjh0htk0bXfncJTFKFABl7JK1xJ8mBZA8dnRlWeiQxcaSe6C+oLdC6UudQmzkneWCmwrg0ze4E0Ti/8WLNTic0deRphqni6MGPGR9UwEARkZLBRsbG+FU1WndqnOt/hqcPXdWN3xhgKhJ1pICpFmzaII8qhw1S3BhRy/YW7YPGq5f1wtdOOCJd8lc8pvHYQHrD2hAFM4Q27YtJCYk4JEo/dP3eTCora0FXAfXZSq36sxpyMqcFKw4aGx04KriBaCu4sKFC3C1/mrQ9CF/SDIHOC1ZBbv880NOky8B/fv1h4z0DLBlWKFf376+j7ldz5im3Pnp59OnoLi4GOzFdjj440FJGbkRLKMgkjkmK5AUgIIzyMjDLUl6ejosWfQI3H57Mrcy9S6oV1JPmDl9hnScO3cO1m/Mgbz8vLBRBLfMJQXA1QGKzBFyGDhgACxb+hjcOfTOkNOiJwG0lrBi+bMwY9p0WLPufdhXVqYnelW4SOaUUfIL6HFb35V43k0VJp0yTb5nMrz8/EvQo0cPnTCGH5rOt3aGSRMzkTCM/vD9d6EmsBH9Bt6TWgCkpE+oqFFrsBEqerWWyzCIwsL5C6XuLcQGJ5LMmRSN6wpGuAoRPP3kU/DgfQ+EqPTQFruntBRWvrQyZOOC6+2FeIFCsYWKDST41ip84vnoUaPQZmFJqNgPJHuB4vCFgoJUHOiRuVZrB/pSuDEu4M8Jkr1AQRh5F012ds9g02+xyPJN5U0e9/Ief2wZtG/fnnu5JHuBInDyLjl7UnZEf+Prza9OHTvBw9Nn6o22RXwke2wBWOcWU+qYgKZwFy8wY0z4snTG1Om6mLD54g12TbLHFgBj73KEkSNGonUN916HYw3VFdU2ri1MnDBRXWaVuUj2ApqBcXX9pnl9E/xzgFzWuALKHmMVC9yWgWnSZ8zoqPI401VeQ9GOkczZeAHJXqCQ67wK7JOcDDTgMcE/B+gFSb2T3zoIyV7AmUluCtDV7Pv9S97jbtdEfuMjkj1ZBHXwKN/Q00R0xzYhOAc486gDuT7S7hpcgPzxTQjOAZ48ItnjPAA/BYiLM4OLBhc/CqMdPx6R7OkzkFsL0FLlzeecOYCyp02V9Pei4FAPCtxQUroHyGL3lzNn4DqaglPzORQXmSgaCBmQ6gVXr16RwseUVZTD2bNnwelwSK5iw+4aBjarNXK/bFD2ZBAS3LxWLy7qiCfvq3xY98E6yfrWF+2u3V/D+2h2NeWhKbAIp5y1evT8e/t2yZ6v9tda36Lgq693wXvvr4GZ6EI+b/YcKd5Qs0ThfSM2BrsAagUiBt5Z8y589q9/BqW3oaEBtmzdAt8f+A5eXfUq3BKv/EuXTMpX/+UNyNuZF7QsMv/esGkDlvU9vPLCy0BTuhEDKHsBhe82Cwt7uj/a8nGLwvesxIGDB2HVn1ahxQ1tCagM1v19XYvC98RYVl4Gr71B+2dEEKDsaR6AmwLccccdqrlDdvY5+KYphfJvK+A/X36hKNvhykrYuu1TRXkocaG9EAqKChTn88yQgr4QHO0k+CnAiOEjgKyA1MLHn2xB75tGVdk3f/ShImdRpek9idr8jw89LxWfd+/eHbImZSnOpzKDpADUChgOixcsUl0G9cfkZaMWyDHj8OHDsrKTIyh9WaiFo8eOQVVVldrsUr75s+fyagVw9YFDGPj00WNgkIbmv7r6PPgbhSvh8rHjx2Qlp65Ga2xAUgItQK0ARTjjAJIC4IygcUB28PQ5pgWqa6QdMLSggOqL8nDU1NRoKocy64Fj3qw5QKFtDQZGLYChCmDDAEvk5KkFHDjxohXk4pCbLhg9Dqd2eqVWwPixgLEKQNa/ixcsCMYr81kQDszFsYDBrYCkAEFI0PZo4t0TTetfDSyk6GT3GDwWoC7AkHlA+padP2++huqbWYkDc40dC4ikAMqnyWTIhr5lyUfeBG0c6IatAEU9NQichrUA9C1rgj4cmP3wbH0QNccitQC6dwG9evYCGsWaoA8HaCxwW+/e+iDzxmJMF9C7Vy/vYswrzRzoaUx3KnUB6ibYg1Tpx0M/BnlqPlLDgUMyp7IV4m6kMYDuClCDs25hEAJFIS/CNznZGtBeRgYAKgDTXwGI0PU56w2gt3WizNmofBlcFqdQ9mQQonsLQIVTC6BlVU1WBVpBIuJjxX+/NaamKHvqAhqMwY6twAazFdDK2/UbcrSiCJa/gRSgPlgKLc9o4FJkt2tB0arz0pu//7v9RvKgnhTA0I3x1m/K0RwFKyZGeyiZGJnhaNq00b4Eq9cCjmF9/02VukauYYa1AFTOiRMnYNfuXTeLVHGWgAGitYJcnzs9NppK1GGzKjIypdG/kUCyJ9cwQxWAKkBm01rW2RM6dwa5AgzEsAEpKYEeed3vibOY7dqpD9hEBjApMsvyKtjnQo0BrA+KFi9J9tQFXG4xpcYEp06fhh15uaqxEFPH28apzt+7V2/ok9xHVn7qAqwYrFotDB40SPMGU6V7S+HgDz+oJUFJvssC7qzCJUroxg83adp04WH0vqE9A9TAwvnKlqXnzVFvlLlwnnYDmJzNG9VUU3Eekr3ABMZFAcgydxe6UqkF2rbtqWXKA0vSHsATxk9QVCy1GI8ufkRRHkr8wP33A5m/awEa9R86dEgLCtl5SfYUJYyLAhBVtIuHFrh38r2w9HdLZO8CQvsOPIdh2tUAxe2bM0v+MmwWRgF/ctkTaoryylP7669e10ZekOzJL7DWWLNQfatAgknpnyI5ZQYy9aY4RPPmzoUpD/4Wt0LGsa5KeBQ3rRg8cBCs+dta+PnUz36xkBcy+TyQckYcoOxjMFIUrjLgeDCCYPiwNFj77hppK5a9+/bBmV9+gUbc1CkRN3dMHToURg4fqZuTJrUiozGy2Xc4JUufZuQe7kBfQ+qShqUOg7S0NM0eyKFiPck+BveLr4ks8d9gF73ZQwYNkQ6jGUjRu+5KvUs6jC6LJ36SPcYJFA1ZZ+RZEbMsdRwg2eNMoHBOXXbluUTREPtT5YSEdQ5+7THJXhAdjjO8+FFby2+Ey6tOepdzsUbbl5ISekj2wvX4GG4KQBsrmhCcA9U1/HhEshf25+bSVDCXuQDaUdOE4Bw4z49Hl0j2tBZAcPzGn7G/5HptQnAO/HyKG49OECWSAuBUSWVwsvR5StPBgSZv9CkhsrFcqquDAwcPcKmEW+aSAuC4k4sCUM3sGiJ9cOFMCAvZg3EPtSybKyHdLfMbLYAoclOAItxM2QT/HOBpPsdcMpcUwGGxcFOAI0ePhMXeuf5FELq7J3/6CaOR8ns53DKXFAAc4hGeVV+LMfhEXIw24SYHPsj5QFU8w5sYlJ3hFLD00ksKUGHPO43ZuXwKEplHjx6F/F1fKaM4ilMf+OEAb+vpurLCHVIosxstwA3m7uXJ47ffewdOV5HetW64dOkS/Hn1at5MaJL1TQVgrIgnFVTx5198ASgSd2sFGvGvevUV/i+Ch6xvKoADuCoACf3Eyf/BK6+9qslWMFKVh8ZAf333baBQttzBQ9ZNChDHrpQgIQ7exNAW6stXLDfK+5V3dWSVRxHGX1j1Emz/fLus9DoncrhkLaFtUgC73X4JDYMM9UMKVBEygX78qSeAgjRHO5zBzS2efOZpKC4pDk1VUcaSrF2le/lcJd3ebzDeD8nOjleuXIEvdnwB58+fhwEDBkJ7jnvn8JDE5SuXYePmTfDam6txo4vzPIr0XwZjW6tOHvvS/dDLYjJtXPY4wenc7X4Yqn/adGEq7vgxaUImJCcnh4oMXcqlN552Mflk21b4laPFbyDinYIwvqIgt8D93EsB8CYbYc08hqa0ye4Eof5P6pEEtKcuedyQe1hiQhdIQEtcrVvB6F0vCmVPMYLJ5oGWvStxxpPWPcJq8UsUT5TZ8/ti3Ztm4XxdYXFHcbYZE6zUm0Fq8dFcgZrNG9SWF9X5bsi2SfhU16ZBoLviFhA3uc/N/+jigD/ZNlOA0qJ82llhT3RV3awNydQlWy9mNFMAeopzFNznJr2oMi9050AgmfoOApsKHm7LsqPjQEbTDfMkYjmAA7vi8qI8q78K+G0BKKHodP7BXwbzXgRyQBSXB6I6oAJUFOfT1PDWQBnN+xHDga3l9p3fBKI2oAJQBosgPId//DwVAlFp3lfLgVqXDAPmD6oApQW5x0UQZ2Fu06crIAvD9gFutifOIhkGo9BrLcBfwqqTx48k3daPnEey/T0374UrB9iz5UU7W5zTaVEBqHq4eFCCC0V98HRYuFbXpMuDA4xtKCvKo+67RQjaBXjmrq++dSleb/S8Z56HIQdQ+C5ZySIu4DxAoNwjbFn4SSHSRJFs5QmEy7yvKwdwnMZW4Jv/lhKsihWAkA+3ZU5mwD7G005KCjPTGsaBWhrwlRflN63zyy1J1VtMBeHnRRpqnPI91uVSZqaTyQH2KclCjfCpAFUtgCdlaRmZ6UwQ3jSnjT25Yvw5Te/SbK1rwk51gZoVwF3ycOukqRi3aQVeh8SkzE1HK/jfQws7OLv3mR511U0B3MSMsmUOcACbj0uK88LJsshNX0T+oyUPGerQer6/JV0tddJdATyIYWhjOFZwitNQGcZiZ5OKz2TNO3jgaK2nDslCm7FCp8C2oQ1fITLCy5JHL8YYqQBeNFqt1lvqxfbpqAI2SSEARmKCeK9ErfeC/DL34VteiJ4ZRWS372m6bSRbuCmAv0qkWbOSwML6WxyOFJGxFCQmBdU8BdP2wSPalIOEfBzrWIl1rCT/fMlFGz2zXc65/lhk+L2QKkCw2qVmZ3doU9fYnVks3UVwdmUiS8CRb2cMcJyA3UknDHMaLzrFeBx4kqJ0wIrEIWPj8FkcNpZt8V4snlMsZDJ8dR/02UsH1dt94KnUvFITSwctfNFBu6k1YqpGvEvnDXh+Dc/rMWM9JqzHe5dxQFZHUbeloNsYe5fCr0rRVzEII8Xho1BsFI3LFYwLs4QX/B+sF+kaJgBClQAAAABJRU5ErkJggg==", + fit: "cover", + inset: "none", +}; + +export const clinePresentation: HarnessPresentation = { + id: "cline", + name: "Cline", + description: "AI coding agent with task lifecycle hooks for local telemetry.", + icon: clineIcon, + documentation_url: "https://docs.selftune.dev/guides/platform-hooks", +}; diff --git a/packages/harnesses/codex/package.json b/packages/harnesses/codex/package.json index 60b99787..6c6c703b 100644 --- a/packages/harnesses/codex/package.json +++ b/packages/harnesses/codex/package.json @@ -18,7 +18,7 @@ "@selftune/local-store": "workspace:*", "@selftune/observability": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/packages/harnesses/codex/src/adapters/codex/install.ts b/packages/harnesses/codex/src/adapters/codex/install.ts index 57ff6ed5..ade731f9 100644 --- a/packages/harnesses/codex/src/adapters/codex/install.ts +++ b/packages/harnesses/codex/src/adapters/codex/install.ts @@ -12,6 +12,7 @@ */ import { Option, Schema } from "effect"; +import { isDeepStrictEqual } from "node:util"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; @@ -293,10 +294,7 @@ export function installHooks(options: { dryRun?: boolean } = {}): InstallResult const serializedMerged = serializeHooksByEvent(merged); // Compare the persisted shape; _selftune markers are internal only. - const existingJson = JSON.stringify(serializedExisting); - const mergedJson = JSON.stringify(serializedMerged); - - if (existingJson === mergedJson) { + if (isDeepStrictEqual(serializedExisting, serializedMerged)) { return { hooksPath, action: "no_change", diff --git a/packages/harnesses/codex/src/descriptor.ts b/packages/harnesses/codex/src/descriptor.ts index 5bd03a70..9e306ccb 100644 --- a/packages/harnesses/codex/src/descriptor.ts +++ b/packages/harnesses/codex/src/descriptor.ts @@ -5,10 +5,8 @@ import { CodexHooksFile } from "./adapters/codex/hooks-config.js"; import type { HarnessPackageContribution, - HarnessPresentation, HarnessRuntimeContribution, } from "@selftune/harness-core/descriptor"; -import { svgHarnessIcon } from "@selftune/harness-core/descriptor"; export function hasCodexHooksAt(path: string): boolean { try { @@ -33,16 +31,8 @@ export function hasCodexHooksAt(path: string): boolean { } } -export const codexPresentation: HarnessPresentation = { - id: "codex", - name: "Codex", - description: "OpenAI's coding agent with hooks and rollout import.", - icon: svgHarnessIcon( - '\n', - { fit: "contain", inset: "sm", invert_in_dark: true }, - ), - documentation_url: "https://docs.selftune.dev/guides/platform-hooks", -}; +export { codexPresentation } from "./presentation.js"; +import { codexPresentation } from "./presentation.js"; export const codexRuntime: HarnessRuntimeContribution = { id: "codex", diff --git a/packages/harnesses/codex/src/ingestors/codex-rollout.ts b/packages/harnesses/codex/src/ingestors/codex-rollout.ts index ea90a5a7..66fec98d 100644 --- a/packages/harnesses/codex/src/ingestors/codex-rollout.ts +++ b/packages/harnesses/codex/src/ingestors/codex-rollout.ts @@ -79,9 +79,12 @@ import { } from "@selftune/runtime/utils/skill-discovery"; export { buildLocalTelemetryBatchFromRollout } from "./codex-trace-projection.js"; import { decodeRolloutLine } from "./rollout-contract.js"; +import { createSkillReadEvidenceCollector, type SkillReadEvidence } from "./skill-read-evidence.js"; import { scanRolloutLines, scanRolloutLinesAsync, + scanRolloutText, + scanRolloutTextAsync, type RolloutLineScan, } from "./rollout-line-scanner.js"; @@ -187,6 +190,7 @@ export interface ParsedRollout { skills_triggered: string[]; skills_invoked: string[]; skill_evidence: Record; + skill_reads?: SkillReadEvidence[]; assistant_turns: number; errors_encountered: number; input_tokens: number; @@ -266,7 +270,11 @@ interface RolloutParser { readonly finish: (scan: RolloutLineScan | null) => ParsedRollout | null; } -function makeRolloutParser(path: string, skillNames: Set): RolloutParser { +function makeRolloutParser( + path: string, + skillNames: Set, + workspaceSkills: (cwd: string) => Set = findSkillNames, +): RolloutParser { const threadId = basename(path, ".jsonl").replace("rollout-", ""); let prompt = ""; let lastUserQuery = ""; @@ -277,6 +285,8 @@ function makeRolloutParser(path: string, skillNames: Set): RolloutParser const bashCommands: string[] = []; const skillsTriggered: string[] = []; const skillEvidence = new Map(); + const skillReads = createSkillReadEvidenceCollector(); + let sourceLine = 0; let errors = 0; let turns = 0; let inputTokens = 0; @@ -326,7 +336,7 @@ function makeRolloutParser(path: string, skillNames: Set): RolloutParser }; const rememberWorkspaceSkills = (cwd: string | undefined): void => { if (!cwd?.trim()) return; - for (const skillName of findSkillNames(cwd)) { + for (const skillName of workspaceSkills(cwd)) { sessionSkillNames.add(skillName); } }; @@ -425,6 +435,7 @@ function makeRolloutParser(path: string, skillNames: Set): RolloutParser }; const onLine = (line: string): void => { + sourceLine += 1; const isEventMessage = line.includes('"type":"event_msg"'); const isResponseItem = line.includes('"type":"response_item"'); const canSkipEventMessage = @@ -432,6 +443,8 @@ function makeRolloutParser(path: string, skillNames: Set): RolloutParser const canSkipResponseItem = isResponseItem && !line.includes('"type":"function_call"') && + !line.includes('"type":"function_call_output"') && + !line.includes('"type":"custom_tool_call_output"') && !line.includes('"type":"custom_tool_call"') && !line.includes('"type":"agent_reasoning"') && !line.includes('"role":"user"'); @@ -500,11 +513,15 @@ function makeRolloutParser(path: string, skillNames: Set): RolloutParser const payload = event.payload ?? {}; const itemType = payload.type ?? ""; if (itemType === "function_call") { + skillReads.call(payload.call_id, payload.name, payload.arguments); const fnName = payload.name ?? "function_call"; countTool(fnName); // Only path-based skill references count as triggers here. detectExplicitSkillReads(payload.arguments); + } else if (itemType === "function_call_output" || itemType === "custom_tool_call_output") { + skillReads.output(payload.call_id, payload.output, sourceLine); } else if (itemType === "custom_tool_call") { + skillReads.customCall(payload.call_id, payload.input); const toolName = optionalString(payload.name) ?? "custom_tool_call"; countTool(toolName); // Codex Desktop sends its executable tool program in `input` rather @@ -606,6 +623,7 @@ function makeRolloutParser(path: string, skillNames: Set): RolloutParser (skillName) => skillEvidence.get(skillName) === "explicit", ), skill_evidence: Object.fromEntries(skillEvidence), + skill_reads: skillReads.reads, assistant_turns: turns, errors_encountered: errors, input_tokens: inputTokens, @@ -630,6 +648,27 @@ export function parseRolloutFile(path: string, skillNames: Set): ParsedR return parser.finish(scanRolloutLines(path, parser.onLine)); } +export function parseRolloutText( + path: string, + text: string, + skillNames: Set, + workspaceSkills: (cwd: string) => Set = findSkillNames, +): ParsedRollout | null { + const parser = makeRolloutParser(path, skillNames, workspaceSkills); + return parser.finish(scanRolloutText(text, parser.onLine)); +} + +export async function parseRolloutTextAsync( + path: string, + text: string, + skillNames: Set, + workspaceSkills: (cwd: string) => Set, + signal: AbortSignal, +): Promise { + const parser = makeRolloutParser(path, skillNames, workspaceSkills); + return parser.finish(await scanRolloutTextAsync(text, parser.onLine, signal)); +} + /** Parse a rollout through bounded, interruptible source-sync I/O. */ export async function parseRolloutFileAsync( path: string, @@ -783,6 +822,10 @@ export function buildCanonicalRecordsFromRollout(parsed: ParsedRollout): Canonic // Skill invocation records for (let i = 0; i < parsed.skills_triggered.length; i++) { const skillName = parsed.skills_triggered[i]; + const reads = (parsed.skill_reads ?? []).filter( + (read) => read.skill_name.toLowerCase() === skillName.toLowerCase(), + ); + const paths = new Set(reads.map((read) => read.skill_path)); const isExplicit = parsed.skill_evidence[skillName] === "explicit"; const { invocation_mode, confidence } = deriveInvocationMode( isExplicit ? { has_skill_md_read: true } : { is_text_mention_only: true }, @@ -799,7 +842,14 @@ export function buildCanonicalRecordsFromRollout(parsed: ParsedRollout): Canonic occurred_at: parsed.timestamp, matched_prompt_id: promptId, skill_name: skillName, - skill_path: `(codex:${skillName})`, + skill_path: paths.size === 1 ? reads[0]?.skill_path : `(codex:${skillName})`, + raw_source_ref: { + ...baseInput.raw_source_ref, + metadata: { + package_version_status: "unknown", + skill_reads: reads.map((read) => ({ ...read })), + }, + }, invocation_mode, triggered: true, confidence, diff --git a/packages/harnesses/codex/src/ingestors/rollout-contract.ts b/packages/harnesses/codex/src/ingestors/rollout-contract.ts index 6715e05d..6716ad3a 100644 --- a/packages/harnesses/codex/src/ingestors/rollout-contract.ts +++ b/packages/harnesses/codex/src/ingestors/rollout-contract.ts @@ -34,6 +34,8 @@ const Payload = Schema.Struct({ token_count: optionalEvidence(Tokens), name: Text, arguments: Text, + call_id: Text, + output: Text, input: Text, role: Text, content: optionalEvidence(Schema.Array(ContentPart)), diff --git a/packages/harnesses/codex/src/ingestors/rollout-line-scanner.ts b/packages/harnesses/codex/src/ingestors/rollout-line-scanner.ts index bfd0e80a..93bf6167 100644 --- a/packages/harnesses/codex/src/ingestors/rollout-line-scanner.ts +++ b/packages/harnesses/codex/src/ingestors/rollout-line-scanner.ts @@ -83,6 +83,30 @@ function openRollout(filePath: string): number | null { } } +/** Uses the identical line rules on already bounded, verified source bytes. */ +export function scanRolloutText(text: string, onLine: (line: string) => void): RolloutLineScan { + const consumer = makeLineConsumer(onLine); + consumer.consume(text); + return consumer.finish(); +} + +export async function scanRolloutTextAsync( + text: string, + onLine: (line: string) => void, + signal: AbortSignal, +): Promise { + const consumer = makeLineConsumer(onLine); + const chunkChars = 1024 * 1024; + for (let offset = 0; offset < text.length; offset += chunkChars) { + signal.throwIfAborted(); + consumer.consume(text.slice(offset, offset + chunkChars)); + // oxlint-disable-next-line no-await-in-loop -- preserve cooperative parsing for bounded in-memory replay. + await yieldToEventLoop(); + } + signal.throwIfAborted(); + return consumer.finish(); +} + /** Synchronous compatibility scanner used by the standalone Codex ingestor. */ export function scanRolloutLines( filePath: string, diff --git a/packages/harnesses/codex/src/ingestors/skill-read-evidence.ts b/packages/harnesses/codex/src/ingestors/skill-read-evidence.ts new file mode 100644 index 00000000..e5ca2643 --- /dev/null +++ b/packages/harnesses/codex/src/ingestors/skill-read-evidence.ts @@ -0,0 +1,67 @@ +import { createHash } from "node:crypto"; +import { basename, dirname } from "node:path"; +import { Option, Schema } from "effect"; + +const ReadArguments = Schema.Struct({ + file_path: Schema.optionalKey(Schema.String), + cmd: Schema.optionalKey(Schema.String), + command: Schema.optionalKey(Schema.String), +}); +const decodeArguments = Schema.decodeUnknownOption(Schema.fromJsonString(ReadArguments)); + +export interface SkillReadEvidence { + skill_name: string; + skill_path: string; + call_id: string; + output_sha256: string; + output_chars: number; + output_line: number; + version_scope: "captured_tool_output"; +} + +/** Captures source evidence, not a claim that the complete package was read. */ +export function createSkillReadEvidenceCollector() { + const pending = new Map(); + const reads: SkillReadEvidence[] = []; + return { + customCall(id: string | undefined, input: string | undefined) { + if (!id || !input) return; + const paths = new Set(input.match(/\/[^\s"'`\\<>;()]+\/SKILL\.md\b/g) ?? []); + pending.delete(id); + if (paths.size === 1) for (const path of paths) pending.set(id, path); + }, + call(id: string | undefined, name: string | undefined, args: string | undefined) { + if (!id || !args) return; + pending.delete(id); + const decoded = decodeArguments(args); + if (Option.isNone(decoded)) return; + const input = decoded.value; + let path: string | undefined; + if (name === "Read" || name === "read_file") path = input.file_path; + else if (name === "exec_command" || name === "shell_command") { + // Only a single cat operand establishes which file the output belongs to. + const match = /^cat\s+(?:"([^"\n$`]+)"|'([^'\n]+)'|([^\s;&|<>$`]+))\s*$/.exec( + input.cmd ?? input.command ?? "", + ); + path = match?.[1] ?? match?.[2] ?? match?.[3]; + } + if (path?.startsWith("/") && basename(path) === "SKILL.md") pending.set(id, path); + }, + output(id: string | undefined, output: string | undefined, line: number) { + if (!id) return; + const path = pending.get(id); + pending.delete(id); + if (!path || !output || reads.length >= 256) return; + reads.push({ + skill_name: basename(dirname(path)), + skill_path: path, + call_id: id, + output_sha256: createHash("sha256").update(output).digest("hex"), + output_chars: output.length, + output_line: line, + version_scope: "captured_tool_output", + }); + }, + reads, + }; +} diff --git a/packages/harnesses/codex/src/presentation.ts b/packages/harnesses/codex/src/presentation.ts new file mode 100644 index 00000000..1b5abb83 --- /dev/null +++ b/packages/harnesses/codex/src/presentation.ts @@ -0,0 +1,13 @@ +import type { HarnessPresentation } from "@selftune/harness-core/descriptor"; +import { svgHarnessIcon } from "@selftune/harness-core/descriptor"; + +export const codexPresentation: HarnessPresentation = { + id: "codex", + name: "Codex", + description: "OpenAI's coding agent with hooks and rollout import.", + icon: svgHarnessIcon( + '\n', + { fit: "contain", inset: "sm", invert_in_dark: true }, + ), + documentation_url: "https://docs.selftune.dev/guides/platform-hooks", +}; diff --git a/packages/harnesses/codex/src/source-sync.ts b/packages/harnesses/codex/src/source-sync.ts index 4a11998d..87e6bb4d 100644 --- a/packages/harnesses/codex/src/source-sync.ts +++ b/packages/harnesses/codex/src/source-sync.ts @@ -1,7 +1,7 @@ import { existsSync } from "node:fs"; import { join } from "node:path"; -import { Effect } from "effect"; +import { Effect, Option, Schema } from "effect"; import type { HarnessSourceAdapter, @@ -12,10 +12,17 @@ import type { } from "@selftune/harness-core/source-adapter"; import { harnessSourceSyncFailure } from "@selftune/harness-core/source-adapter"; import { LocalTraceImporter } from "@selftune/observability"; +import { + CODEX_RECONSTRUCTION_PARSER, + SourceSnapshot, + readBoundedSource, + sourceDigest, +} from "@selftune/observability/source-reconstruction"; import { CODEX_INGEST_MARKER, QUERY_LOG, TELEMETRY_LOG } from "@selftune/runtime/constants"; import { NORMALIZER_VERSION } from "@selftune/runtime/normalization"; import { fingerprintIngestionFile, + fileIngestionRevision, isFileIngestionCurrent, loadFileIngestionMarker, saveFileIngestionMarker, @@ -27,12 +34,13 @@ import { findSkillNames, ingestFile, parseRolloutFileAsync, + parseRolloutTextAsync, type ParsedRollout, } from "./ingestors/codex-rollout.js"; import { buildLocalTelemetryBatchFromRollout } from "./ingestors/codex-trace-projection.js"; const adapterId = "codex"; -const CODEX_SOURCE_PROJECTION_VERSION = "codex-source-v5"; +const CODEX_SOURCE_PROJECTION_VERSION = "codex-source-v7"; const sourceFailure = (operation: string, cause: unknown) => harnessSourceSyncFailure(adapterId, operation, cause); @@ -48,6 +56,7 @@ const ingestParsedRollout = Effect.fn("Codex.syncSource.ingestParsedRollout")(fu fingerprint: FileIngestionFingerprint, request: HarnessSourceSyncRequest, onDryRunMessage: HarnessSourceProgressCallback, + snapshot?: SourceSnapshot, ): Effect.fn.Return { const canonicalSucceeded = yield* Effect.try({ try: () => @@ -68,12 +77,16 @@ const ingestParsedRollout = Effect.fn("Codex.syncSource.ingestParsedRollout")(fu try: () => { const batch = buildLocalTelemetryBatchFromRollout(parsed); if (batch === null) return null; - return { + const input = { source_kind: "codex" as const, - source_revision: `${CODEX_SOURCE_PROJECTION_VERSION}:${fingerprint.size}:${fingerprint.mtime_ms}`, + source_session_ids: [parsed.session_id], + source_revision: snapshot + ? `${CODEX_SOURCE_PROJECTION_VERSION}:${snapshot.sha256}:${sourceDigest(Buffer.from(JSON.stringify([snapshot.parser, snapshot.skill_names, snapshot.workspace_skills, snapshot.task_sha256])))}` + : `${CODEX_SOURCE_PROJECTION_VERSION}:${fileIngestionRevision(fingerprint)}`, normalizer_version: NORMALIZER_VERSION, batch, }; + return snapshot ? { ...input, source_snapshot: snapshot } : input; }, catch: (cause) => sourceFailure("prepare Codex analytical import", cause), }); @@ -149,6 +162,14 @@ const makeSyncCodexSource = (markerPath: string) => `found ${source.rolloutFiles.length} rollouts, ${pending.length} pending`, ); + if (pending.length === 0) + return { + available: true, + scanned: source.rolloutFiles.length, + synced: 0, + skipped: 0, + authoritativeFiles: source.rolloutFiles, + }; const skillNames = yield* Effect.try({ try: () => findSkillNames(), catch: (cause) => sourceFailure("discover Codex skills", cause), @@ -163,8 +184,47 @@ const makeSyncCodexSource = (markerPath: string) => // Parsing is explicitly asynchronous and yields every bounded byte // batch. This makes a large source replay interruptible instead of // trapping the desktop/CLI event loop in a long synchronous scan. + let snapshot: SourceSnapshot | undefined; const parsed = yield* Effect.tryPromise({ - try: (signal) => parseRolloutFileAsync(rolloutFile, skillNames, signal), + try: async (signal) => { + const source = skillNames.size <= 1024 ? await readBoundedSource(rolloutFile) : null; + if (source?.state === "available") { + signal.throwIfAborted(); + const workspaces = new Map(); + const parsed = await parseRolloutTextAsync( + rolloutFile, + source.bytes.toString("utf8"), + skillNames, + (cwd) => { + const names = findSkillNames(cwd); + workspaces.set(cwd, [...names].toSorted()); + return names; + }, + signal, + ); + if ( + workspaces.size <= 16 && + [...workspaces.values()].reduce( + (count, names) => count + names.length, + skillNames.size, + ) <= 1024 + ) { + snapshot = Option.getOrUndefined( + Schema.decodeUnknownOption(SourceSnapshot)({ + parser: CODEX_RECONSTRUCTION_PARSER, + path: rolloutFile, + sha256: sourceDigest(source.bytes), + bytes: source.bytes.length, + task_sha256: sourceDigest(Buffer.from(parsed?.query ?? "")), + skill_names: [...skillNames].toSorted(), + workspace_skills: [...workspaces].map(([cwd, names]) => ({ cwd, names })), + }), + ); + } + return parsed; + } + return parseRolloutFileAsync(rolloutFile, skillNames, signal); + }, catch: (cause) => sourceFailure("parse Codex rollout", cause), }); if (parsed === null) { @@ -174,7 +234,13 @@ const makeSyncCodexSource = (markerPath: string) => } skipped += 1; } else { - const ingested = yield* ingestParsedRollout(parsed, fingerprint, request, onDryRunMessage); + const ingested = yield* ingestParsedRollout( + parsed, + fingerprint, + request, + onDryRunMessage, + snapshot, + ); if (!ingested) { skipped += 1; yield* reportProgress( diff --git a/packages/harnesses/core/package.json b/packages/harnesses/core/package.json index d2a3968e..ddcc22de 100644 --- a/packages/harnesses/core/package.json +++ b/packages/harnesses/core/package.json @@ -13,7 +13,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/packages/harnesses/core/src/source-adapter.ts b/packages/harnesses/core/src/source-adapter.ts index 90be93ab..fcd659b3 100644 --- a/packages/harnesses/core/src/source-adapter.ts +++ b/packages/harnesses/core/src/source-adapter.ts @@ -31,7 +31,7 @@ export interface HarnessSourceSyncResult { readonly authoritativeFiles?: ReadonlyArray; } -export class HarnessSourceSyncFailure extends Schema.TaggedErrorClass()( +export class HarnessSourceSyncFailure extends Schema.TaggedError()( "HarnessSourceSyncFailure", { adapter_id: Schema.String, diff --git a/packages/harnesses/openclaw/src/descriptor.ts b/packages/harnesses/openclaw/src/descriptor.ts index 551597d7..5a7a274b 100644 --- a/packages/harnesses/openclaw/src/descriptor.ts +++ b/packages/harnesses/openclaw/src/descriptor.ts @@ -3,24 +3,11 @@ import { join } from "node:path"; import type { HarnessPackageContribution, - HarnessPresentation, - HarnessPresentationIcon, HarnessRuntimeContribution, } from "@selftune/harness-core/descriptor"; -const openClawIcon: HarnessPresentationIcon = { - src: "data:image/jpeg;base64,/9j/2wCEAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDIBCQkJDAsMGA0NGDIhHCEyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMv/AABEIAMgAyAMBIgACEQEDEQH/xAGiAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgsQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+gEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoLEQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/AOOooorwj9rCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK19C0GXWXmleZLTT7ZfMuryU4SJf8fata/tfDFz4JbVtIgu0UXf2e1urh8NeY++wT+FRzg9cjnFaxoylFz6Hm1s1w9LERw285dunqclRRRWR6QUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFWdPsZ9T1C3sbZd007hFH17/Sq1dHpd2fDHhDV/FAGLviw07189xyw91Xn860pQ55pHBmWMWEw0qvXp6vYzfHeq+e8Hgnw+d1nBcLakqcG8vCQGY+oU8D3+gxqeMWhsbmy8O2Tf6Ho1utsuP4pMAu31J6+4rC+G1jG/j1Lmcb7XQLKS9lJ6NIBxz67mz/wGmXNxJdXUtxK26SVy7n1JOTXViJWgkuv5HzWQ4Z1MZOrPVw0v3k9yKiiiuE+0CiiigAooooAKKKKACiiigAooqzZafealOILK2luJT/DGhY/pQk3sTOcYLmk7IrUV0s/hS30aMS+J9d0/R1xnyWfzZyPaNeTWXN4x+H+lnZY6Vquuzg4DXEgt4mPsBlvwIrohhakuljxMTxHgaLspcz8v89jOpyRySfcjZvoM10Fn4j8d36g+Hfh3YWMJ+7NJZHP/fyQgGr3n/GeXiXWtJ08f882ktBj8lb+dbLBd5HlS4tu/wB3Rv6v/gHIujxnDoyn/aGKbXaeb8YIUP8AxNdD1lcc2+63bd7fdUn86zNJ1fS/G2oy6FqOkRaD4nUsIjApSGaResbIfuNwf88GZ4RpXi7muH4qpymo16bj57/omc9RTpI3hleKRSroxVlPUEdRTa4z6xNNXQUUUUDCtXx84tX8K+GFOEs7U6hdD/prJkgH3AH5NVfRrP8AtDW7GyxkT3CRn6FgD+may/GuonUfiF4tvg2RAzWqegCDyxj/AL4rrw8bRlL5Hy+fVebEUKL2V5P5a/5mz4GzbfDrxRrJGJdSvYrJD6BfnYfiG/Ss2tm2j+xfB7wxb9GvLi5u3HuG2A/lisapxT9+3Y34ahbBuo95Nv8AT9AooormPoQooooAKKKKACiiigAq1p+m3uq3a2thbSXEzfwoM49yew9zWrpvh6P+zW1rXbxdL0WPrPIPnmP92NerH/PNc9r3xIu76JtC8G2j6VpbcO6H/Sbj3kcdB7A/iRxXTSwzmry0R87mWf08NL2NBc9T8F/n6HRX48KeDMjxBfHU9UX/AJhentkIfSSTt7gc/WubvviT4p12JrLQYY9D03p5VgNhx/tSfeJ+mM+lc7b6JaafF9p1SVWP9zPGf60HVrvUZPsulQ+VGON+MYH8hXTGUYr90vmfP16VevJSzGo7vaEdX92y+Yo0iytHNxq9150jHcVLH5j7/wARrf03Wby1Uf2LaixTp5yIIWI/3gN5/E1SsdFhtSJZiZ7g8l35wfaup8Pa0mg6ib02EF44UiMTdEP94e9YSrXdrntUMpdOlzqkl2jo5P1k7pfI0/CnhjVPGNxLLf6mVtoCDNLIxJ55wASefc8V0+qXvgrwhaNb6VZ2+qanjAklxKqH1J6Z9l/SvPta1i717U5L+8ZfNfAwgwqgdAPaqFZ+2UV7q17nZ/ZVStJOvNqK+wtvm93+A64uGlkluJmGWJdzgADueOgrC8FvNq3xY0SSDcWbUopPfYjBm/8AHVNUvEOsq4Nlbtkf8tHHf2rtPhjpf/COaHfeNbtdszo1npSsOWkPDyD2UZH/AH0K6sPD2cXOR85nuLWMrwweGV7O3z2+5In8RyRzeJ9Vkix5bXcpUjuN55rMoJJJJOSeporz5O7bPu6MPZ04w7JIKKKKRodN8PYBceO9LUjIV2f8kYj9QK8ve5N3Ya7fE5a4n3k/Vs/1r27wT4V1vSNcTVb6xa2tYYZMySuqkEqQOM5/SvCLH5vDOoL3DKf1Fd9KLjS17nw2aV4VswbpyTSpy272kep6yPK8HeDIB90aUsn4ucmufrtm8Oar4l8G+FLrSbdblINKjhkAlQFWHsSK5+88L67p4LXOk3aIOriIso/EZFYYiEvaN2PZyHF4dYKnTc1za6XV92ZNFHQ4IwaK5z6AKKKKACiinIjyyLHGrO7EBVUZJJ7CgTaSuxoBJAAJJ6V0stvpHgfTo9V8Up59/Ku+z0dTh39Gk/urnt/PkU3UdQ0/4Z2aTXUcV54qmXdb2jfMlkD0eT1b0H/6682it9Q8T6lLq+s3Ek7ytueSQ/NIfb0A6ew4FdtOjGnHnqHx+YZtWxtX6nl/zl/Wy8yxq2r678QNV+26nNtt0+WONBiKFf7qL+Xv6mluLuy8P2/kWyBpyOnf6sadq+rR6XCLW1CiXGAAOEH+NcxZ2s+qXojUksxy7nsO5rVJ1fenpE86bp5a1hsJ79d6OXbyRbtre81+9Lyu2wfeY9FHoK7C0s4bKAQwoFUdT3J9TRZ2kVlbLBCuFXv3J9TU9clatz6R0R9RlOVRwkfa1feqPd/ogooruNH8JeGPEfhi61S/fVNKW0+WWS3uAEc4/h3KTnpx7iop0/aO1zqzDHrBU1UcHK7tp+BwFze21mm6eVU9ieT+FcvqniOS5VobUGOI8Fv4m/wqr4gt7W11WSKzkmeIHI85gzD0BIAycYr1Gy8HeE/CFrYXWsw3Os6tPaxXQtHxHbxFhnDYyWwePQ9xzXbTo06a55M+QxubY/HVnhKMeXuk9fvOW8D+AG1pDretu1j4cgOZJ24a4I/gj9Seme3ua6jxDrZ1m6iWCEW2n2qCGztV+7FGOB+PrTNa1++12ZDdOqQRDbDbxLtjiXsFWsuueviPaaR2PcyXI1gv3tbWb/D+u4UUUVzH0YUUUUAcvNo+tanJ5uo37yv3M8rSNn8c/wA6g0qJlt9Vsm++Iyce65/+tXWoSyKSNpIBI9KzDpjx60L2Ir5cikSqa7FiHK6mfJVchp4d06mGTfR+kla/yuR+EvBEPiDT/treJrHS5llKLHcBgSAB824cDrj8K7uz8FfE7S087w34vt9SiXkRW2olx/3xINlcnYWS2Ft5KMWG4tk+9XY5ZIZBJE7I46MpwRVvGWdraHNDhPnopufLPqt1+BpX/jzXtLuFtPiF4Nhudxx9p8k20zepWRflb8MfWrtlYeHPFq7vCmrlbwjP9l6jiOY+yN91v85NTWXjrVI7Y2WqLFrGnuMSW16ofI+p5/PNYmv/AA+0zW7OXW/ArSJPAPMuNHkYmSPHVoj1YD06+nPFaJ0a2jWpw1KWaZO+eMrw+9fNdP61Ir2xutOuntry3kgnT7ySLg//AKveq9SeG/iTDqMEeh+OFe6tB8kGpDm4tT/tHq6+uefr0rQ13Q59Du0R3Se2mUSW11EcpMh6Mp/KuSth3T1WqPpspzynjv3cvdn27+n+RmKrOwVVLMxwAByTXQ6pqdt8MtNWR0jn8WXUeYYW+ZbBD/Gw/vnsP6dVN3a/D/w/H4gv4km1m7UjSrN/4B/z2ceg7evH1HltrFeeJdYn1DUZnmZ3LzyueXY9v89BW9CiqcfaTPIzjM6mMrLAYPW+jff/AIC6kunWFzrd7JqepySTGRy7PIctKxPJJro7lmgs5GhTLIh2qB7VKiLGgRAFUDAA7U6uarWc5Xex7+X5VTwWHdOD95rWXW//AAOh57DbXWpXZCqzyMcsx7e5rtNL02PTbbYvzSNy7+p/wq6FC5wAM+gp7I6WxuXVlgDbTKRhQfTPTNVVryqLlSsjmy3JaOXydapLml3elv8AgjaKrNqFmo5uoP8Av4KrTa7p0I5uAx9EBNYqnN7I9WpjsNTV51EvmjptK0lLv/Sb64FnpyH95O3Jb/ZQfxN9OnU1F418cx/YIdN0+L7Np1uMW1rnLMf78nqf8+9cTf8Ai6WVdlujDaNqvIckD2FZuk6Pq/irV0s9Pt5by8lPQdh6seij3PFd1HDtL3tD4/NM8pOV6L5pLZ9I+a7vz6dDR8F+HpvGPjC0085MUknm3Un9yIHLsT244HuRXoPivVU1nxNe3kQAgL7IQBgbFG1f0Gfxq0lrY+AdAn0HTrhLrWbwBdSvY/uoP+eMZ9PX1/RecrPF1U/cXQ7OGcunSUsXWWstr9t7/MKK6G38KSQ2C6nr19b6Lpx+7LdHDyf7idWNZtz418AaS3l2Ojalrkg/5a3M/wBmjJ9VCgnH1FZQw1Seux6WL4gwWGfLzcz8tfx2KFFX4PHfg2/mS31bwpd6Mr8C6tbppSvuUYDI+mTU2vaI2jXMRjnS6srmMTWt1H92WM9CPf2oq4edNXZeX55hcdP2cLqXZmVRRRWB7IUVT0+9+3pJKqMsQbahbqeOTVynKLi7Myo1oVqaqQ2YVmpdXOsa1baHo3lveXMgiWRzhVJ9/br+FVdTs9SNvOUvS0IUsI9vzY9M96wNF0/VL+/QaVFMbiNgwkjbZ5Z7MXyAv1JFdmHoQfvN3Pk88zjFU7UKcHBvr1fpY6G80a68NeObnRdXnjubqHA82KRiuSoYYzg9D3FdHYX9zpl9DeWcrRTxNuVh/L3HtVex+HTSXa6hrfjHS4bkv5jKkjXTluvzMOM575NW9Rs4LK48u3v4L1MZ3wqwA9vmApYpWkpRZrw3NyozoV4vV9VumZfxV0yxefTfFGmxrDFrCO1xbp0juEIDkezZz+Z71d+HPjjSbbSLjRPFgabTrQG8se7LIvJiHs/p0zn14xvFV0z+HIrVzmOKcvGO4LAA/wDoNcOiF3CKMknAFddKaqQuz5bM8I8Bi3Cm/NfPY2vEfiDUPGXiSbUbs5mncLHGD8sSZ+VF9h/ie9dTYWiWNmkCfwj5j6nua5rQrIJr0iNz9nDc+p6f1rrq5MXUu1FH03C2BUITxE1q3ZfLf8QooorjPrwrZ8PeJtQ8N3TS2bhopOJYJOUkHuPX3rG74rtND0iw8Oxx634l4cAPaad1klPZmHZfr/8AWOlJScrrQ4MwqUY0XCrHm5to9W/669Dq/FcXhj/hDU1XVPC+nR6jdx/uYXgTzA57lgAcDqfy6181+IIrO3ukgtIgjKMyEEnk9q7Txx48uNV1CS4ndWuMbYoVOVhX0+v8682dnldpGyzE5Jr0YOU5cz2/M+AxsaGFofVopOpJ3l15e0U/zPSPhj4M07W9L1XWNX0261CG2kigtbaCRk8+Vj8y5HPA2n8a9H1C+0nwrppsL/UNP8LWzjLaZpS+ddy/9dHHI+p/OvLNK+J3iGw8Hw+FdEt4LIhm3XVuCJnDHJ5J4P8AtDsBjGKq2NnoWmSfavECz6peyHd9mEpRSTz8xHzt+a89zWk3G9m/kceFp1nBypQWn2n0+/T9TpZfHnw+tGKW/hvVr9enmXN2ISfwTNIfid4a06B7rQPC8serHiJryfzoof8AaA6lvrWhpXjuayQJp3g3w9Y2/q9qS7fXByT9TVDxLqia/PDcDRtKtbmPpJbW4Qk+rHqcdhWDqUY7LU9elgc3xKfPN8r31f4Lqc+dmuXv9teOtYvJXk+5awjMzj0GfljX6A/Qda7fw/4rSwuIbbwn4L06waQhEluczXLk9Pm4P68VyFvYRQyGViZZz1lfr+HpXXaXe2vh7SpL2J1l1m5UxwBeRaoeC5/2z2HYc98Vm8S5Oy2PQhw/ToxU5x5pPRLz8+lur/Mr/EXxlqOp6DqGk6qljdCOQCOaOLDRyKwyUOfYj3FV/Dk7aj8F4/OJZ9O1doYSecRugcj/AL6JNcJ4qvstHZqc4+d/r2/z713+mwHSfg9o9q42y6pfS35B67VAjX88A1d26DcjiVOnHOqdLDq3LZO3dLUyKKKK84/QBFVUUKoCqOgAwBS1mPr+mqM+eW9lQ/4VXPiAzfLZ2M8x9SMD+taKjUfQ82ea4KmrKafktfyNusi/v0sYxa2Aj+0M3EarnGep471AbfWtQ4nlW0hPVU6n/P1rRsdLttPBMS5kPWRuSatKNPd38jmnUxGN0pQ5F/NLR28lv99hLZdSSRftDQSRnrgFWH9DV6iqGqanHp1sWbBlbhE9T6/Ss9akrJHe3TwVFzqTfKu7uYfiq8Dyx2iHOz5m+vb/AD71l6dEU1Sz8xSoaRSMjrzWjoennUrqS9u8ugbof4m/wqPxG7Q6yjrxtRSuO2K9GDS/crsfBYynVrf8KlXROSsvL/hka2nx/Z/Ed/Gesi+YPfJ/+vW5WXkXX2XVLcZZV2yKOpU9R9Qea1AcjI6VwVndpn2uVxVOEoLZvmXmpa/8AKpXGqW1qcTeYv8A2zNXaCM9azi1fU7q0aso/upJPzV/1MuHxtHpshlsoGaf+GRkGV/3c5wffGRWfc6pr+uzO4WRfMOWkYnLfVjXQiNAchVB+lPrdVoxVoxPHnlOJrzcq1bR/wAqS/HVmBY+GYoz5l4/nP8A3R93/wCvW5FDFCm2KNUX0UYp9FZTqzm7tno4TLsNhI2pQ+fX7yE20YZnjVY5GGC6qM4pIbOCBi0cY3nq55Y/ianoqeZ2tc2+r0ubm5VdBRRRSNwqtf3kdhaPPIen3R6n0qaWVIImkkYKijJJrh9Y1R9SueMiFPuL/U+9b0KLqS12PFzrNYYGjaL997L9Sz4e0e88YeK7TTYSTPeTAM+M7F6s30Cgn8K9R8X6hb3etC1sONO0+JLO1UdNiDGfxOf0qDwppf8Awg3gxtVuF2a9rcWy2U/et7U9X9i3GPbHvWPW+LqL+GjxuF8DJyljanXRfq/0+8KKKK4T7MjEEQ6RIPooqQDFICCMg5HrUM17bW4/fTxp7Fufyp+82Yt0aS5naK+SJ6KxLjxNap8tvG879sDA/wAapOdb1fK7Dbwn/gPH8zWyw8t5aHmVs7oJ8mHTqS7RX6mjqevW9kCkREs/oDwPqa5e6S7uYf7QuW4dtqk9/p7VLa6aG11bGRtwVyGI745NbnieDGmRGNcLG44HYYrqhyUpKMd31PmMTLFZlQq4itpGnoorv1v6Iv6LEItItwO67j9TWN4rtzvguQOMbG/mP61p6NextpNtvYDnyyewI6D8qt6jZrf2MkB4JGVPoe1c6k4Vrs9+rh4Y3KlRpbqKa9UrmRp8yWVpHdwZNnJxNH1MTeo9v/rVvo6SIrowZCMgjoa4nTb59Ku5Le5QmFjtlQjp71ps0+j4ubJvtGnSHOzOdv8AhWlajeX5ef8AwTz8rzVUaKuvdWkl1i+6X8r69mdLRVCx1izvwBHIFk/uPwf/AK9X645RcXZn1dDEUq8OelJNeQUUUUjYKKKKACiimSSxwoXldUUd2OKErkykoq8nZD6guruCyhMs7hV7DufpWNf+J4YwUtF8xv77cKP8a50te6veIgEtxcSMFSNFLFiegAH8q66WFlLWWiPmsy4loUE4Yf3pd+i/zLGq6zLqMm0ZSAfdT19zXc+AvBVvBaJ4t8URbdKiObO0bhr6QdOP7g7+v0zV/Qfh7p/hWGPVvGoWa7ID22iI2Wb0MxHQf7P59xUmt65ea9e/abtgAo2xRIMJEvZVHYV0Va0aMeWO54GX5Xic1rfWMQ3y9X38l/Vhmsatda5qk1/dtmSQ8KOiL2UewqhRRXmttu7P0KnTjTgoQVkgooopGgjKGGGAI9CMioDYWZOTaQE/9cxViimm1sZzpU5/HFP1RHHBFF/q40T/AHVAqSigkAZJwKV2xqMYLRWRyN0/9n+K/ObhCwJPsRz/ADNdPdQJeWkkLY2yLgH+Rrn9caHVLqC1sI5Lm9LbFWFSxbP8IA6n6VWXUbvT92n36XMEsBK9CskZH8LKev0Nd7pSqRjJaNHxVLMaGCxFfDz96Em3p57r+upDZTDTrmfT75T5EnyuP7p7MKuT/wBsWCD7LcNPa9UdQG496xL25kup98kplIGAxGDipbC6v45RFZPMXY8RoC2T9K6HTvroeHTx0IXp3koq9mnaSXZ9GiG4kuby4Mk295Tx92rFteXmlPtAIV+sUg4I+lddD4N+I+pQq0ei6gEccb4xCf8Ax7FXLf4MeIgRLr1/pmjRHlmurpWf8Aucn8RV20tLY5XO1TmoSk5d+v5u5wFzLbznzIYmgkJ5UHK/h6VPa65f2oCiYuo/hk5r1az0fwH4YjZEtJfEt442yTXOYYFHfYvXPuc+xqvceF/hzq5LRSatoMx/hBFzCPpn5z+dZupRfutnfDA5pTX1inCUb9tPw/4Bw0Pi08Ca1B9SjY/Q1bXxVYkfNHOP+Ag/1rdk+EdlPk6Z440aUdvtitbk/h81QH4L62T+713w3IPVb84/Val4ejLb8zojnebUdJX+cTKPimwHRZj9FH+NV5fFkIH7q2dj/tECt9fgxqi83HiXwzAvctfnP/oNWYvhXoNsc6n46swB1WytXmJ/HI/lU/V6C3/Mv+283q6QX3R/4BxFx4nvZeIhHEPYZP61not/q92sMSXF3cOcJGil2PsAK9Wg0L4caTgix1bW5Rz/AKTMIYj9Anzfgc1ojxnc2Nu1toOn2GiW7DBFlAA7D/ac8k+9P2tGn8Illmb493rN2/vO34f8A5TSfhFqYiS98T3sGgWJ5xOd87j/AGYxz+eD7V1NrquieEoGt/B+nGO4I2yareYe4f129kH0/KsG4uZ7udprmaSaVvvPIxYn8TUVc1TFylpHQ97AcMYeg1Ou+d/h/wAEknnluZnmnleWVzlndiSx9yajoorlPpoxUVZBRRRQMKKKKAMhPEVkeJFmib0ZKU+IrEkBDLIx4Cqhya0opYrmFZI2DxtyD2qzBdXFr/x7zyxf9c3K/wAq2vTT1T+88lU8fKN4Vovz5f8AJlaz0/xTrJC6R4X1CUN0lmiMaf8AfTYH61tx/C+9wJvGfiax0qDqbS3cSzEemBx+PzVUk1fU5l2y6jdyL/dadiP51T5JyTk1oq1OHwxOCrk2MxTticQ+XslY6yLWvDvhO1e08F6X5dwylZNUuxumYd9uen6D2ry/xfDJLJHfMS7sSJHJySeuT+tdDJLHDGXkdUQdSxwKbp2g6z47d7HQ7Ldag4mvp8pDHj37n2GT7VVKpVqVFLoc+Z4PLsFgZ0E7Se3Vto82AJ6V7V4D+KGn2fhyPw/qUzaHdRAJFqltaq4dewkXGc/7Q69Tjv5g0c3hfX7i3nEU7QO0bNG25XAP3lPofWtjT7S31cLqGoAzksQtuCVRVHYkck/Qj8eg7J1FH4tj5XB4GVdqNJ/vb/C1okurb0+Vj0qZ7DUpSB8TbCeVjwLi4eNfzJwKy9Z8L6vpEYurmJZrWT7t3A/mRN/wIdPxxWQ83g+zhH9oeFLEQ9MxXdwkn4Eu2T+Bqtpniv8A4RzVxN4MttXutElGL3Tb9BJE/qAVz26NgH1yMisPZU6qvG57TzPH5ZUUMRGLXZWv+H6ktFbdnq/gLxJO1tFLeeHL9mwi3pD25P8Ad3dV+pwBVXWdDv8AQbv7PfQ7SwyjqcpIPVT3FcdShOnqz6jAZxhca+Wm7S7PczqKKKyPUsFFFFAwooooAKKKKACiiigAooooAKKKKAPP7LU7rTpCYmwCeUPT8q6GHxHIYleawl2kcMnINcrN/rW+proIv+QNbfT+tevVpQk9Ufl+XY/FUVKFOo0ktt/zNBNdkm4g026kP04rSs7HWNRwz3Gm6XAf+WlxN5jY9lQE/mKp6B95v9w1p+lcc+WGqifT4SWKxtO86zXpZfoa1npPg3S2FxqEl/4mvF5VJB9ntgf93O4/jwfSrWr+MdT1S2Wyj8qx05BtSztE8uML6HHUe3T2rnx1/Cisp4ico9kephslwlCftLc0u8tX/kZusafbXlqXmYRNGMiQ9vr7VzFje3mkESBGa3k6BgQre4rqta/5BFx/u1zuqf8AIC076V04fWPK9Vc+d4gXscV7al7slG9111tqaOivHqd3Le3WySZD8kLDKoPXB4NdrbeJtds9vkaveoqjCr5zFR+BOK8/8K/8fU3+7/WurrGu3Go4p7HrZFSpYjBqpVinJt3bV2zqZvEmmeJIvsnjLSIL5WGFvoEEdzF7hh1+nT60yO4TwibbQtbvDq/gjUiRp2pf8tLJ/wCmO69McgdVrme9X/H3/JJ/DX/X7N/I1vhqkql4y1PH4hy+jg1HE4dcsr2026u47XNHuNC1aWxuCG28pIvSRD0YfWs6uw+JH/Iw2v8A14xf1rj646sVGbSPrMtrzxGEp1Z7tahRRRWZ2hRRRQAUUUUAFFFFABRRRQAUUUUAf//Z", - fit: "cover", - inset: "none", -}; - -export const openClawPresentation: HarnessPresentation = { - id: "openclaw", - name: "OpenClaw", - description: "Agent runtime with local session import support.", - icon: openClawIcon, - documentation_url: "https://docs.selftune.dev/guides/platform-hooks", -}; +export { openClawPresentation } from "./presentation.js"; +import { openClawPresentation } from "./presentation.js"; export const openClawRuntime: HarnessRuntimeContribution = { id: "openclaw", diff --git a/packages/harnesses/openclaw/src/presentation.ts b/packages/harnesses/openclaw/src/presentation.ts new file mode 100644 index 00000000..550c09cc --- /dev/null +++ b/packages/harnesses/openclaw/src/presentation.ts @@ -0,0 +1,18 @@ +import type { + HarnessPresentation, + HarnessPresentationIcon, +} from "@selftune/harness-core/descriptor"; + +const openClawIcon: HarnessPresentationIcon = { + src: "data:image/jpeg;base64,/9j/2wCEAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDIBCQkJDAsMGA0NGDIhHCEyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMv/AABEIAMgAyAMBIgACEQEDEQH/xAGiAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgsQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+gEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoLEQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/AOOooorwj9rCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK19C0GXWXmleZLTT7ZfMuryU4SJf8fata/tfDFz4JbVtIgu0UXf2e1urh8NeY++wT+FRzg9cjnFaxoylFz6Hm1s1w9LERw285dunqclRRRWR6QUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFWdPsZ9T1C3sbZd007hFH17/Sq1dHpd2fDHhDV/FAGLviw07189xyw91Xn860pQ55pHBmWMWEw0qvXp6vYzfHeq+e8Hgnw+d1nBcLakqcG8vCQGY+oU8D3+gxqeMWhsbmy8O2Tf6Ho1utsuP4pMAu31J6+4rC+G1jG/j1Lmcb7XQLKS9lJ6NIBxz67mz/wGmXNxJdXUtxK26SVy7n1JOTXViJWgkuv5HzWQ4Z1MZOrPVw0v3k9yKiiiuE+0CiiigAooooAKKKKACiiigAooqzZafealOILK2luJT/DGhY/pQk3sTOcYLmk7IrUV0s/hS30aMS+J9d0/R1xnyWfzZyPaNeTWXN4x+H+lnZY6Vquuzg4DXEgt4mPsBlvwIrohhakuljxMTxHgaLspcz8v89jOpyRySfcjZvoM10Fn4j8d36g+Hfh3YWMJ+7NJZHP/fyQgGr3n/GeXiXWtJ08f882ktBj8lb+dbLBd5HlS4tu/wB3Rv6v/gHIujxnDoyn/aGKbXaeb8YIUP8AxNdD1lcc2+63bd7fdUn86zNJ1fS/G2oy6FqOkRaD4nUsIjApSGaResbIfuNwf88GZ4RpXi7muH4qpymo16bj57/omc9RTpI3hleKRSroxVlPUEdRTa4z6xNNXQUUUUDCtXx84tX8K+GFOEs7U6hdD/prJkgH3AH5NVfRrP8AtDW7GyxkT3CRn6FgD+may/GuonUfiF4tvg2RAzWqegCDyxj/AL4rrw8bRlL5Hy+fVebEUKL2V5P5a/5mz4GzbfDrxRrJGJdSvYrJD6BfnYfiG/Ss2tm2j+xfB7wxb9GvLi5u3HuG2A/lisapxT9+3Y34ahbBuo95Nv8AT9AooormPoQooooAKKKKACiiigAq1p+m3uq3a2thbSXEzfwoM49yew9zWrpvh6P+zW1rXbxdL0WPrPIPnmP92NerH/PNc9r3xIu76JtC8G2j6VpbcO6H/Sbj3kcdB7A/iRxXTSwzmry0R87mWf08NL2NBc9T8F/n6HRX48KeDMjxBfHU9UX/AJhentkIfSSTt7gc/WubvviT4p12JrLQYY9D03p5VgNhx/tSfeJ+mM+lc7b6JaafF9p1SVWP9zPGf60HVrvUZPsulQ+VGON+MYH8hXTGUYr90vmfP16VevJSzGo7vaEdX92y+Yo0iytHNxq9150jHcVLH5j7/wARrf03Wby1Uf2LaixTp5yIIWI/3gN5/E1SsdFhtSJZiZ7g8l35wfaup8Pa0mg6ib02EF44UiMTdEP94e9YSrXdrntUMpdOlzqkl2jo5P1k7pfI0/CnhjVPGNxLLf6mVtoCDNLIxJ55wASefc8V0+qXvgrwhaNb6VZ2+qanjAklxKqH1J6Z9l/SvPta1i717U5L+8ZfNfAwgwqgdAPaqFZ+2UV7q17nZ/ZVStJOvNqK+wtvm93+A64uGlkluJmGWJdzgADueOgrC8FvNq3xY0SSDcWbUopPfYjBm/8AHVNUvEOsq4Nlbtkf8tHHf2rtPhjpf/COaHfeNbtdszo1npSsOWkPDyD2UZH/AH0K6sPD2cXOR85nuLWMrwweGV7O3z2+5In8RyRzeJ9Vkix5bXcpUjuN55rMoJJJJOSeporz5O7bPu6MPZ04w7JIKKKKRodN8PYBceO9LUjIV2f8kYj9QK8ve5N3Ya7fE5a4n3k/Vs/1r27wT4V1vSNcTVb6xa2tYYZMySuqkEqQOM5/SvCLH5vDOoL3DKf1Fd9KLjS17nw2aV4VswbpyTSpy272kep6yPK8HeDIB90aUsn4ucmufrtm8Oar4l8G+FLrSbdblINKjhkAlQFWHsSK5+88L67p4LXOk3aIOriIso/EZFYYiEvaN2PZyHF4dYKnTc1za6XV92ZNFHQ4IwaK5z6AKKKKACiinIjyyLHGrO7EBVUZJJ7CgTaSuxoBJAAJJ6V0stvpHgfTo9V8Up59/Ku+z0dTh39Gk/urnt/PkU3UdQ0/4Z2aTXUcV54qmXdb2jfMlkD0eT1b0H/6682it9Q8T6lLq+s3Ek7ytueSQ/NIfb0A6ew4FdtOjGnHnqHx+YZtWxtX6nl/zl/Wy8yxq2r678QNV+26nNtt0+WONBiKFf7qL+Xv6mluLuy8P2/kWyBpyOnf6sadq+rR6XCLW1CiXGAAOEH+NcxZ2s+qXojUksxy7nsO5rVJ1fenpE86bp5a1hsJ79d6OXbyRbtre81+9Lyu2wfeY9FHoK7C0s4bKAQwoFUdT3J9TRZ2kVlbLBCuFXv3J9TU9clatz6R0R9RlOVRwkfa1feqPd/ogooruNH8JeGPEfhi61S/fVNKW0+WWS3uAEc4/h3KTnpx7iop0/aO1zqzDHrBU1UcHK7tp+BwFze21mm6eVU9ieT+FcvqniOS5VobUGOI8Fv4m/wqr4gt7W11WSKzkmeIHI85gzD0BIAycYr1Gy8HeE/CFrYXWsw3Os6tPaxXQtHxHbxFhnDYyWwePQ9xzXbTo06a55M+QxubY/HVnhKMeXuk9fvOW8D+AG1pDretu1j4cgOZJ24a4I/gj9Seme3ua6jxDrZ1m6iWCEW2n2qCGztV+7FGOB+PrTNa1++12ZDdOqQRDbDbxLtjiXsFWsuueviPaaR2PcyXI1gv3tbWb/D+u4UUUVzH0YUUUUAcvNo+tanJ5uo37yv3M8rSNn8c/wA6g0qJlt9Vsm++Iyce65/+tXWoSyKSNpIBI9KzDpjx60L2Ir5cikSqa7FiHK6mfJVchp4d06mGTfR+kla/yuR+EvBEPiDT/treJrHS5llKLHcBgSAB824cDrj8K7uz8FfE7S087w34vt9SiXkRW2olx/3xINlcnYWS2Ft5KMWG4tk+9XY5ZIZBJE7I46MpwRVvGWdraHNDhPnopufLPqt1+BpX/jzXtLuFtPiF4Nhudxx9p8k20zepWRflb8MfWrtlYeHPFq7vCmrlbwjP9l6jiOY+yN91v85NTWXjrVI7Y2WqLFrGnuMSW16ofI+p5/PNYmv/AA+0zW7OXW/ArSJPAPMuNHkYmSPHVoj1YD06+nPFaJ0a2jWpw1KWaZO+eMrw+9fNdP61Ir2xutOuntry3kgnT7ySLg//AKveq9SeG/iTDqMEeh+OFe6tB8kGpDm4tT/tHq6+uefr0rQ13Q59Du0R3Se2mUSW11EcpMh6Mp/KuSth3T1WqPpspzynjv3cvdn27+n+RmKrOwVVLMxwAByTXQ6pqdt8MtNWR0jn8WXUeYYW+ZbBD/Gw/vnsP6dVN3a/D/w/H4gv4km1m7UjSrN/4B/z2ceg7evH1HltrFeeJdYn1DUZnmZ3LzyueXY9v89BW9CiqcfaTPIzjM6mMrLAYPW+jff/AIC6kunWFzrd7JqepySTGRy7PIctKxPJJro7lmgs5GhTLIh2qB7VKiLGgRAFUDAA7U6uarWc5Xex7+X5VTwWHdOD95rWXW//AAOh57DbXWpXZCqzyMcsx7e5rtNL02PTbbYvzSNy7+p/wq6FC5wAM+gp7I6WxuXVlgDbTKRhQfTPTNVVryqLlSsjmy3JaOXydapLml3elv8AgjaKrNqFmo5uoP8Av4KrTa7p0I5uAx9EBNYqnN7I9WpjsNTV51EvmjptK0lLv/Sb64FnpyH95O3Jb/ZQfxN9OnU1F418cx/YIdN0+L7Np1uMW1rnLMf78nqf8+9cTf8Ai6WVdlujDaNqvIckD2FZuk6Pq/irV0s9Pt5by8lPQdh6seij3PFd1HDtL3tD4/NM8pOV6L5pLZ9I+a7vz6dDR8F+HpvGPjC0085MUknm3Un9yIHLsT244HuRXoPivVU1nxNe3kQAgL7IQBgbFG1f0Gfxq0lrY+AdAn0HTrhLrWbwBdSvY/uoP+eMZ9PX1/RecrPF1U/cXQ7OGcunSUsXWWstr9t7/MKK6G38KSQ2C6nr19b6Lpx+7LdHDyf7idWNZtz418AaS3l2Ojalrkg/5a3M/wBmjJ9VCgnH1FZQw1Seux6WL4gwWGfLzcz8tfx2KFFX4PHfg2/mS31bwpd6Mr8C6tbppSvuUYDI+mTU2vaI2jXMRjnS6srmMTWt1H92WM9CPf2oq4edNXZeX55hcdP2cLqXZmVRRRWB7IUVT0+9+3pJKqMsQbahbqeOTVynKLi7Myo1oVqaqQ2YVmpdXOsa1baHo3lveXMgiWRzhVJ9/br+FVdTs9SNvOUvS0IUsI9vzY9M96wNF0/VL+/QaVFMbiNgwkjbZ5Z7MXyAv1JFdmHoQfvN3Pk88zjFU7UKcHBvr1fpY6G80a68NeObnRdXnjubqHA82KRiuSoYYzg9D3FdHYX9zpl9DeWcrRTxNuVh/L3HtVex+HTSXa6hrfjHS4bkv5jKkjXTluvzMOM575NW9Rs4LK48u3v4L1MZ3wqwA9vmApYpWkpRZrw3NyozoV4vV9VumZfxV0yxefTfFGmxrDFrCO1xbp0juEIDkezZz+Z71d+HPjjSbbSLjRPFgabTrQG8se7LIvJiHs/p0zn14xvFV0z+HIrVzmOKcvGO4LAA/wDoNcOiF3CKMknAFddKaqQuz5bM8I8Bi3Cm/NfPY2vEfiDUPGXiSbUbs5mncLHGD8sSZ+VF9h/ie9dTYWiWNmkCfwj5j6nua5rQrIJr0iNz9nDc+p6f1rrq5MXUu1FH03C2BUITxE1q3ZfLf8QooorjPrwrZ8PeJtQ8N3TS2bhopOJYJOUkHuPX3rG74rtND0iw8Oxx634l4cAPaad1klPZmHZfr/8AWOlJScrrQ4MwqUY0XCrHm5to9W/669Dq/FcXhj/hDU1XVPC+nR6jdx/uYXgTzA57lgAcDqfy6181+IIrO3ukgtIgjKMyEEnk9q7Txx48uNV1CS4ndWuMbYoVOVhX0+v8682dnldpGyzE5Jr0YOU5cz2/M+AxsaGFofVopOpJ3l15e0U/zPSPhj4M07W9L1XWNX0261CG2kigtbaCRk8+Vj8y5HPA2n8a9H1C+0nwrppsL/UNP8LWzjLaZpS+ddy/9dHHI+p/OvLNK+J3iGw8Hw+FdEt4LIhm3XVuCJnDHJ5J4P8AtDsBjGKq2NnoWmSfavECz6peyHd9mEpRSTz8xHzt+a89zWk3G9m/kceFp1nBypQWn2n0+/T9TpZfHnw+tGKW/hvVr9enmXN2ISfwTNIfid4a06B7rQPC8serHiJryfzoof8AaA6lvrWhpXjuayQJp3g3w9Y2/q9qS7fXByT9TVDxLqia/PDcDRtKtbmPpJbW4Qk+rHqcdhWDqUY7LU9elgc3xKfPN8r31f4Lqc+dmuXv9teOtYvJXk+5awjMzj0GfljX6A/Qda7fw/4rSwuIbbwn4L06waQhEluczXLk9Pm4P68VyFvYRQyGViZZz1lfr+HpXXaXe2vh7SpL2J1l1m5UxwBeRaoeC5/2z2HYc98Vm8S5Oy2PQhw/ToxU5x5pPRLz8+lur/Mr/EXxlqOp6DqGk6qljdCOQCOaOLDRyKwyUOfYj3FV/Dk7aj8F4/OJZ9O1doYSecRugcj/AL6JNcJ4qvstHZqc4+d/r2/z713+mwHSfg9o9q42y6pfS35B67VAjX88A1d26DcjiVOnHOqdLDq3LZO3dLUyKKKK84/QBFVUUKoCqOgAwBS1mPr+mqM+eW9lQ/4VXPiAzfLZ2M8x9SMD+taKjUfQ82ea4KmrKafktfyNusi/v0sYxa2Aj+0M3EarnGep471AbfWtQ4nlW0hPVU6n/P1rRsdLttPBMS5kPWRuSatKNPd38jmnUxGN0pQ5F/NLR28lv99hLZdSSRftDQSRnrgFWH9DV6iqGqanHp1sWbBlbhE9T6/Ss9akrJHe3TwVFzqTfKu7uYfiq8Dyx2iHOz5m+vb/AD71l6dEU1Sz8xSoaRSMjrzWjoennUrqS9u8ugbof4m/wqPxG7Q6yjrxtRSuO2K9GDS/crsfBYynVrf8KlXROSsvL/hka2nx/Z/Ed/Gesi+YPfJ/+vW5WXkXX2XVLcZZV2yKOpU9R9Qea1AcjI6VwVndpn2uVxVOEoLZvmXmpa/8AKpXGqW1qcTeYv8A2zNXaCM9azi1fU7q0aso/upJPzV/1MuHxtHpshlsoGaf+GRkGV/3c5wffGRWfc6pr+uzO4WRfMOWkYnLfVjXQiNAchVB+lPrdVoxVoxPHnlOJrzcq1bR/wAqS/HVmBY+GYoz5l4/nP8A3R93/wCvW5FDFCm2KNUX0UYp9FZTqzm7tno4TLsNhI2pQ+fX7yE20YZnjVY5GGC6qM4pIbOCBi0cY3nq55Y/ianoqeZ2tc2+r0ubm5VdBRRRSNwqtf3kdhaPPIen3R6n0qaWVIImkkYKijJJrh9Y1R9SueMiFPuL/U+9b0KLqS12PFzrNYYGjaL997L9Sz4e0e88YeK7TTYSTPeTAM+M7F6s30Cgn8K9R8X6hb3etC1sONO0+JLO1UdNiDGfxOf0qDwppf8Awg3gxtVuF2a9rcWy2U/et7U9X9i3GPbHvWPW+LqL+GjxuF8DJyljanXRfq/0+8KKKK4T7MjEEQ6RIPooqQDFICCMg5HrUM17bW4/fTxp7Fufyp+82Yt0aS5naK+SJ6KxLjxNap8tvG879sDA/wAapOdb1fK7Dbwn/gPH8zWyw8t5aHmVs7oJ8mHTqS7RX6mjqevW9kCkREs/oDwPqa5e6S7uYf7QuW4dtqk9/p7VLa6aG11bGRtwVyGI745NbnieDGmRGNcLG44HYYrqhyUpKMd31PmMTLFZlQq4itpGnoorv1v6Iv6LEItItwO67j9TWN4rtzvguQOMbG/mP61p6NextpNtvYDnyyewI6D8qt6jZrf2MkB4JGVPoe1c6k4Vrs9+rh4Y3KlRpbqKa9UrmRp8yWVpHdwZNnJxNH1MTeo9v/rVvo6SIrowZCMgjoa4nTb59Ku5Le5QmFjtlQjp71ps0+j4ubJvtGnSHOzOdv8AhWlajeX5ef8AwTz8rzVUaKuvdWkl1i+6X8r69mdLRVCx1izvwBHIFk/uPwf/AK9X645RcXZn1dDEUq8OelJNeQUUUUjYKKKKACiimSSxwoXldUUd2OKErkykoq8nZD6guruCyhMs7hV7DufpWNf+J4YwUtF8xv77cKP8a50te6veIgEtxcSMFSNFLFiegAH8q66WFlLWWiPmsy4loUE4Yf3pd+i/zLGq6zLqMm0ZSAfdT19zXc+AvBVvBaJ4t8URbdKiObO0bhr6QdOP7g7+v0zV/Qfh7p/hWGPVvGoWa7ID22iI2Wb0MxHQf7P59xUmt65ea9e/abtgAo2xRIMJEvZVHYV0Va0aMeWO54GX5Xic1rfWMQ3y9X38l/Vhmsatda5qk1/dtmSQ8KOiL2UewqhRRXmttu7P0KnTjTgoQVkgooopGgjKGGGAI9CMioDYWZOTaQE/9cxViimm1sZzpU5/HFP1RHHBFF/q40T/AHVAqSigkAZJwKV2xqMYLRWRyN0/9n+K/ObhCwJPsRz/ADNdPdQJeWkkLY2yLgH+Rrn9caHVLqC1sI5Lm9LbFWFSxbP8IA6n6VWXUbvT92n36XMEsBK9CskZH8LKev0Nd7pSqRjJaNHxVLMaGCxFfDz96Em3p57r+upDZTDTrmfT75T5EnyuP7p7MKuT/wBsWCD7LcNPa9UdQG496xL25kup98kplIGAxGDipbC6v45RFZPMXY8RoC2T9K6HTvroeHTx0IXp3koq9mnaSXZ9GiG4kuby4Mk295Tx92rFteXmlPtAIV+sUg4I+lddD4N+I+pQq0ei6gEccb4xCf8Ax7FXLf4MeIgRLr1/pmjRHlmurpWf8Aucn8RV20tLY5XO1TmoSk5d+v5u5wFzLbznzIYmgkJ5UHK/h6VPa65f2oCiYuo/hk5r1az0fwH4YjZEtJfEt442yTXOYYFHfYvXPuc+xqvceF/hzq5LRSatoMx/hBFzCPpn5z+dZupRfutnfDA5pTX1inCUb9tPw/4Bw0Pi08Ca1B9SjY/Q1bXxVYkfNHOP+Ag/1rdk+EdlPk6Z440aUdvtitbk/h81QH4L62T+713w3IPVb84/Val4ejLb8zojnebUdJX+cTKPimwHRZj9FH+NV5fFkIH7q2dj/tECt9fgxqi83HiXwzAvctfnP/oNWYvhXoNsc6n46swB1WytXmJ/HI/lU/V6C3/Mv+283q6QX3R/4BxFx4nvZeIhHEPYZP61not/q92sMSXF3cOcJGil2PsAK9Wg0L4caTgix1bW5Rz/AKTMIYj9Anzfgc1ojxnc2Nu1toOn2GiW7DBFlAA7D/ac8k+9P2tGn8Illmb493rN2/vO34f8A5TSfhFqYiS98T3sGgWJ5xOd87j/AGYxz+eD7V1NrquieEoGt/B+nGO4I2yareYe4f129kH0/KsG4uZ7udprmaSaVvvPIxYn8TUVc1TFylpHQ97AcMYeg1Ou+d/h/wAEknnluZnmnleWVzlndiSx9yajoorlPpoxUVZBRRRQMKKKKAMhPEVkeJFmib0ZKU+IrEkBDLIx4Cqhya0opYrmFZI2DxtyD2qzBdXFr/x7zyxf9c3K/wAq2vTT1T+88lU8fKN4Vovz5f8AJlaz0/xTrJC6R4X1CUN0lmiMaf8AfTYH61tx/C+9wJvGfiax0qDqbS3cSzEemBx+PzVUk1fU5l2y6jdyL/dadiP51T5JyTk1oq1OHwxOCrk2MxTticQ+XslY6yLWvDvhO1e08F6X5dwylZNUuxumYd9uen6D2ry/xfDJLJHfMS7sSJHJySeuT+tdDJLHDGXkdUQdSxwKbp2g6z47d7HQ7Ldag4mvp8pDHj37n2GT7VVKpVqVFLoc+Z4PLsFgZ0E7Se3Vto82AJ6V7V4D+KGn2fhyPw/qUzaHdRAJFqltaq4dewkXGc/7Q69Tjv5g0c3hfX7i3nEU7QO0bNG25XAP3lPofWtjT7S31cLqGoAzksQtuCVRVHYkck/Qj8eg7J1FH4tj5XB4GVdqNJ/vb/C1okurb0+Vj0qZ7DUpSB8TbCeVjwLi4eNfzJwKy9Z8L6vpEYurmJZrWT7t3A/mRN/wIdPxxWQ83g+zhH9oeFLEQ9MxXdwkn4Eu2T+Bqtpniv8A4RzVxN4MttXutElGL3Tb9BJE/qAVz26NgH1yMisPZU6qvG57TzPH5ZUUMRGLXZWv+H6ktFbdnq/gLxJO1tFLeeHL9mwi3pD25P8Ad3dV+pwBVXWdDv8AQbv7PfQ7SwyjqcpIPVT3FcdShOnqz6jAZxhca+Wm7S7PczqKKKyPUsFFFFAwooooAKKKKACiiigAooooAKKKKAPP7LU7rTpCYmwCeUPT8q6GHxHIYleawl2kcMnINcrN/rW+proIv+QNbfT+tevVpQk9Ufl+XY/FUVKFOo0ktt/zNBNdkm4g026kP04rSs7HWNRwz3Gm6XAf+WlxN5jY9lQE/mKp6B95v9w1p+lcc+WGqifT4SWKxtO86zXpZfoa1npPg3S2FxqEl/4mvF5VJB9ntgf93O4/jwfSrWr+MdT1S2Wyj8qx05BtSztE8uML6HHUe3T2rnx1/Cisp4ico9kephslwlCftLc0u8tX/kZusafbXlqXmYRNGMiQ9vr7VzFje3mkESBGa3k6BgQre4rqta/5BFx/u1zuqf8AIC076V04fWPK9Vc+d4gXscV7al7slG9111tqaOivHqd3Le3WySZD8kLDKoPXB4NdrbeJtds9vkaveoqjCr5zFR+BOK8/8K/8fU3+7/WurrGu3Go4p7HrZFSpYjBqpVinJt3bV2zqZvEmmeJIvsnjLSIL5WGFvoEEdzF7hh1+nT60yO4TwibbQtbvDq/gjUiRp2pf8tLJ/wCmO69McgdVrme9X/H3/JJ/DX/X7N/I1vhqkql4y1PH4hy+jg1HE4dcsr2026u47XNHuNC1aWxuCG28pIvSRD0YfWs6uw+JH/Iw2v8A14xf1rj646sVGbSPrMtrzxGEp1Z7tahRRRWZ2hRRRQAUUUUAFFFFABRRRQAUUUUAf//Z", + fit: "cover", + inset: "none", +}; + +export const openClawPresentation: HarnessPresentation = { + id: "openclaw", + name: "OpenClaw", + description: "Agent runtime with local session import support.", + icon: openClawIcon, + documentation_url: "https://docs.selftune.dev/guides/platform-hooks", +}; diff --git a/packages/harnesses/opencode/package.json b/packages/harnesses/opencode/package.json index 4d996952..cbbc7e52 100644 --- a/packages/harnesses/opencode/package.json +++ b/packages/harnesses/opencode/package.json @@ -17,7 +17,7 @@ "@selftune/harness-core": "workspace:*", "@selftune/observability": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/packages/harnesses/opencode/src/descriptor.ts b/packages/harnesses/opencode/src/descriptor.ts index bdf24169..78b5b655 100644 --- a/packages/harnesses/opencode/src/descriptor.ts +++ b/packages/harnesses/opencode/src/descriptor.ts @@ -3,20 +3,11 @@ import { join } from "node:path"; import type { HarnessPackageContribution, - HarnessPresentation, HarnessRuntimeContribution, } from "@selftune/harness-core/descriptor"; -import { svgHarnessIcon } from "@selftune/harness-core/descriptor"; -export const openCodePresentation: HarnessPresentation = { - id: "opencode", - name: "OpenCode", - description: "Open-source coding agent with plugin and session import support.", - icon: svgHarnessIcon( - "\n", - ), - documentation_url: "https://docs.selftune.dev/guides/platform-hooks", -}; +export { openCodePresentation } from "./presentation.js"; +import { openCodePresentation } from "./presentation.js"; export const openCodeRuntime: HarnessRuntimeContribution = { id: "opencode", diff --git a/packages/harnesses/opencode/src/presentation.ts b/packages/harnesses/opencode/src/presentation.ts new file mode 100644 index 00000000..972d29d8 --- /dev/null +++ b/packages/harnesses/opencode/src/presentation.ts @@ -0,0 +1,12 @@ +import type { HarnessPresentation } from "@selftune/harness-core/descriptor"; +import { svgHarnessIcon } from "@selftune/harness-core/descriptor"; + +export const openCodePresentation: HarnessPresentation = { + id: "opencode", + name: "OpenCode", + description: "Open-source coding agent with plugin and session import support.", + icon: svgHarnessIcon( + "\n", + ), + documentation_url: "https://docs.selftune.dev/guides/platform-hooks", +}; diff --git a/packages/harnesses/opencode/src/source-sync.ts b/packages/harnesses/opencode/src/source-sync.ts index 686b475c..18ad3323 100644 --- a/packages/harnesses/opencode/src/source-sync.ts +++ b/packages/harnesses/opencode/src/source-sync.ts @@ -172,6 +172,7 @@ const ingestSession = Effect.fn("OpenCode.syncSource.ingestSession")(function* ( .importTrace( LocalTraceImportRequest.make({ source_kind: "opencode", + source_session_ids: [session.session_id], source_revision: revision, normalizer_version: NORMALIZER_VERSION, batch: buildLocalTelemetryBatchFromOpenCode(session), diff --git a/packages/harnesses/pi/package.json b/packages/harnesses/pi/package.json index b65e9925..6ab34cea 100644 --- a/packages/harnesses/pi/package.json +++ b/packages/harnesses/pi/package.json @@ -17,7 +17,7 @@ "@selftune/harness-core": "workspace:*", "@selftune/observability": "workspace:*", "@selftune/runtime": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/packages/harnesses/pi/src/descriptor.ts b/packages/harnesses/pi/src/descriptor.ts index dd57624d..d0cd1e61 100644 --- a/packages/harnesses/pi/src/descriptor.ts +++ b/packages/harnesses/pi/src/descriptor.ts @@ -3,23 +3,13 @@ import { join } from "node:path"; import type { HarnessPackageContribution, - HarnessPresentation, HarnessRuntimeContribution, } from "@selftune/harness-core/descriptor"; -import { svgHarnessIcon } from "@selftune/harness-core/descriptor"; const PI_HOOK_NAMES = ["tool_call", "tool_result", "message", "session_shutdown"] as const; -export const piPresentation: HarnessPresentation = { - id: "pi", - name: "Pi", - description: "Pi coding agent with extension hooks and session import.", - icon: svgHarnessIcon( - 'π\n', - { fit: "contain", inset: "none" }, - ), - documentation_url: "https://docs.selftune.dev/guides/platform-hooks", -}; +export { piPresentation } from "./presentation.js"; +import { piPresentation } from "./presentation.js"; export const piRuntime: HarnessRuntimeContribution = { id: "pi", diff --git a/packages/harnesses/pi/src/presentation.ts b/packages/harnesses/pi/src/presentation.ts new file mode 100644 index 00000000..be61fc39 --- /dev/null +++ b/packages/harnesses/pi/src/presentation.ts @@ -0,0 +1,13 @@ +import type { HarnessPresentation } from "@selftune/harness-core/descriptor"; +import { svgHarnessIcon } from "@selftune/harness-core/descriptor"; + +export const piPresentation: HarnessPresentation = { + id: "pi", + name: "Pi", + description: "Pi coding agent with extension hooks and session import.", + icon: svgHarnessIcon( + 'π\n', + { fit: "contain", inset: "none" }, + ), + documentation_url: "https://docs.selftune.dev/guides/platform-hooks", +}; diff --git a/packages/harnesses/pi/src/source-sync.ts b/packages/harnesses/pi/src/source-sync.ts index b5838a2f..35299f74 100644 --- a/packages/harnesses/pi/src/source-sync.ts +++ b/packages/harnesses/pi/src/source-sync.ts @@ -15,6 +15,7 @@ import { PI_INGEST_MARKER } from "@selftune/runtime/constants"; import { NORMALIZER_VERSION } from "@selftune/runtime/normalization"; import { fingerprintIngestionFile, + fileIngestionRevision, isFileIngestionCurrent, loadFileIngestionMarker, saveFileIngestionMarker, @@ -55,7 +56,8 @@ const ingestParsedSession = Effect.fn("Pi.syncSource.ingestParsedSession")(funct const importer = yield* LocalTraceImporter; const importRequest = LocalTraceImportRequest.make({ source_kind: "pi", - source_revision: `${PI_SOURCE_PROJECTION_VERSION}:${fingerprint.size}:${fingerprint.mtime_ms}`, + source_session_ids: [session.session_id], + source_revision: `${PI_SOURCE_PROJECTION_VERSION}:${fileIngestionRevision(fingerprint)}`, normalizer_version: NORMALIZER_VERSION, batch: buildLocalTelemetryBatchFromPiSession(session), }); @@ -102,6 +104,14 @@ const makeSyncPiSource = (markerPath: string) => `found ${sessions.length} sessions, ${pending.length} pending`, ); + if (pending.length === 0) + return { + available: true, + scanned: sessions.length, + synced: 0, + skipped: 0, + authoritativeFiles: sessions.map(({ filePath }) => filePath), + }; const skillNames = yield* Effect.try({ try: () => findPiSkillNames(), catch: (cause) => sourceFailure("discover Pi skills", cause), diff --git a/packages/harnesses/registry/src/presentation.ts b/packages/harnesses/registry/src/presentation.ts new file mode 100644 index 00000000..a31afdcf --- /dev/null +++ b/packages/harnesses/registry/src/presentation.ts @@ -0,0 +1,15 @@ +import { claudeCodePresentation } from "../../claude-code/src/presentation.ts"; +import { codexPresentation } from "../../codex/src/presentation.ts"; +import { clinePresentation } from "../../cline/src/presentation.ts"; +import { openCodePresentation } from "../../opencode/src/presentation.ts"; +import { openClawPresentation } from "../../openclaw/src/presentation.ts"; +import { piPresentation } from "../../pi/src/presentation.ts"; + +export const harnessPresentations = [ + claudeCodePresentation, + codexPresentation, + clinePresentation, + openCodePresentation, + openClawPresentation, + piPresentation, +]; diff --git a/packages/library/package.json b/packages/library/package.json index e78a2697..c5bdc8b5 100644 --- a/packages/library/package.json +++ b/packages/library/package.json @@ -33,7 +33,7 @@ "@selftune/control-plane": "workspace:*", "@selftune/local-store": "workspace:*", "@selftune/telemetry-contract": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/packages/library/src/hash.ts b/packages/library/src/hash.ts index 34f5b131..d4394fef 100644 --- a/packages/library/src/hash.ts +++ b/packages/library/src/hash.ts @@ -15,6 +15,19 @@ function isPackageMetadataPath(relativePath: string): boolean { ); } +export function computePortableSkillVersionHash( + files: ReadonlyArray<{ path: string; content: Uint8Array }>, +): string { + const manifest = files + .filter((file) => !isPackageMetadataPath(file.path)) + .map((file) => ({ + path: file.path, + hash: createHash("sha256").update(file.content).digest("hex"), + size: file.content.byteLength, + })); + return createHash("sha256").update(canonicalizeSkillPackageManifest(manifest)).digest("hex"); +} + function buildSkillPackageManifest( rootDir: string, base = "", diff --git a/packages/library/src/remote/effect-sync.ts b/packages/library/src/remote/effect-sync.ts index 610674dd..a6a8957a 100644 --- a/packages/library/src/remote/effect-sync.ts +++ b/packages/library/src/remote/effect-sync.ts @@ -96,7 +96,7 @@ export const syncRemoteObjectsEffect = Effect.fn("selftune.library.remote.syncOb }); return true; }), - { concurrency: "unbounded" }, + { concurrency: 4 }, ); const uploaded = uploads.reduce((total, didUpload) => total + (didUpload ? 1 : 0), 0); const unchanged = uploads.length - uploaded; diff --git a/packages/library/src/remote/sync.ts b/packages/library/src/remote/sync.ts index efe19dde..18f1220f 100644 --- a/packages/library/src/remote/sync.ts +++ b/packages/library/src/remote/sync.ts @@ -78,22 +78,40 @@ export async function syncRemoteObjects(options: { now?: Date; onSnapshot?: (snapshot: RemoteSnapshot) => Promise; }): Promise<{ snapshot: RemoteSnapshot; uploaded: number; unchanged: number }> { - const uploads = await Promise.all( - options.objects.map(async (object) => { - if (await options.handle.hasObject(object.artifact.objectHash)) return false; - await options.handle.putObject(object.artifact.objectHash, object.bytes); - return true; - }), - ); + const uploads: boolean[] = []; + for (let start = 0; start < options.objects.length; start += 4) { + uploads.push( + ...(await Promise.all( + options.objects.slice(start, start + 4).map(async (object) => { + if (await options.handle.hasObject(object.artifact.objectHash)) return false; + await options.handle.putObject(object.artifact.objectHash, object.bytes); + return true; + }), + )), + ); + } const uploaded = uploads.filter(Boolean).length; const unchanged = uploads.length - uploaded; + const snapshot = await commitRemoteArtifacts({ + handle: options.handle, + artifacts: options.objects.map((object) => object.artifact), + now: options.now, + onSnapshot: options.onSnapshot, + }); + return { snapshot, uploaded, unchanged }; +} +export async function commitRemoteArtifacts(options: { + handle: RemoteLibraryHandle; + artifacts: ReadonlyArray; + now?: Date; + onSnapshot?: (snapshot: RemoteSnapshot) => Promise; +}): Promise { for (let attempt = 0; attempt < 3; attempt += 1) { const head = await options.handle.head(); const merged = new Map(); for (const artifact of head?.artifacts ?? []) merged.set(artifact.artifactId, artifact); - for (const object of options.objects) { - const artifact = object.artifact; + for (const artifact of options.artifacts) { const existing = merged.get(artifact.artifactId); if (existing && existing.objectHash !== artifact.objectHash) { throw new LibraryError( @@ -116,7 +134,7 @@ export async function syncRemoteObjects(options: { ) === JSON.stringify(artifacts.map(artifactIdentity)); if (head && unchangedSnapshot) { await options.onSnapshot?.(head); - return { snapshot: head, uploaded, unchanged }; + return head; } const snapshot = buildRemoteSnapshot({ @@ -127,7 +145,7 @@ export async function syncRemoteObjects(options: { try { const committed = await options.handle.commitSnapshot(snapshot); await options.onSnapshot?.(committed); - return { snapshot: committed, uploaded, unchanged }; + return committed; } catch (error) { if (!(error instanceof RemoteConflict) || attempt === 2) throw error; } diff --git a/packages/library/src/skills-sh-catalog.ts b/packages/library/src/skills-sh-catalog.ts index 177af695..779e80d0 100644 --- a/packages/library/src/skills-sh-catalog.ts +++ b/packages/library/src/skills-sh-catalog.ts @@ -32,22 +32,22 @@ export class SkillsShCatalogEntry extends Schema.Class( installs: Schema.Number, }) {} -export class SkillsShCatalogInputError extends Schema.TaggedErrorClass()( +export class SkillsShCatalogInputError extends Schema.TaggedError()( "SkillsShCatalogInputError", { message: Schema.String }, ) {} -export class SkillsShCatalogTransportError extends Schema.TaggedErrorClass()( +export class SkillsShCatalogTransportError extends Schema.TaggedError()( "SkillsShCatalogTransportError", { message: Schema.String }, ) {} -export class SkillsShCatalogHttpError extends Schema.TaggedErrorClass()( +export class SkillsShCatalogHttpError extends Schema.TaggedError()( "SkillsShCatalogHttpError", { status: Schema.Number, message: Schema.String }, ) {} -export class SkillsShCatalogDecodeError extends Schema.TaggedErrorClass()( +export class SkillsShCatalogDecodeError extends Schema.TaggedError()( "SkillsShCatalogDecodeError", { message: Schema.String }, ) {} diff --git a/packages/library/src/skills-sh-materializer.ts b/packages/library/src/skills-sh-materializer.ts index 02259895..a7f8f2cd 100644 --- a/packages/library/src/skills-sh-materializer.ts +++ b/packages/library/src/skills-sh-materializer.ts @@ -31,32 +31,32 @@ const SkillsShWireDownload = Schema.Struct({ files: Schema.NullOr(Schema.Array(SkillsShWireFile)), }); -export class SkillsShCatalogFetchError extends Schema.TaggedErrorClass()( +export class SkillsShCatalogFetchError extends Schema.TaggedError()( "SkillsShCatalogFetchError", { message: Schema.String }, ) {} -export class SkillsShCatalogDownloadHttpError extends Schema.TaggedErrorClass()( +export class SkillsShCatalogDownloadHttpError extends Schema.TaggedError()( "SkillsShCatalogDownloadHttpError", { status: Schema.Number, message: Schema.String }, ) {} -export class SkillsShCatalogDownloadDecodeError extends Schema.TaggedErrorClass()( +export class SkillsShCatalogDownloadDecodeError extends Schema.TaggedError()( "SkillsShCatalogDownloadDecodeError", { message: Schema.String }, ) {} -export class SkillsShCatalogIntegrityError extends Schema.TaggedErrorClass()( +export class SkillsShCatalogIntegrityError extends Schema.TaggedError()( "SkillsShCatalogIntegrityError", { message: Schema.String }, ) {} -export class SkillsShCatalogPathError extends Schema.TaggedErrorClass()( +export class SkillsShCatalogPathError extends Schema.TaggedError()( "SkillsShCatalogPathError", { path: Schema.String, message: Schema.String }, ) {} -export class SkillsShCatalogStorageError extends Schema.TaggedErrorClass()( +export class SkillsShCatalogStorageError extends Schema.TaggedError()( "SkillsShCatalogStorageError", { path: Schema.String, message: Schema.String }, ) {} diff --git a/packages/local-store/package.json b/packages/local-store/package.json index 24c7ef55..22b79a62 100644 --- a/packages/local-store/package.json +++ b/packages/local-store/package.json @@ -21,7 +21,7 @@ "dependencies": { "@selftune/config": "workspace:*", "drizzle-orm": "^0.45.0", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/packages/local-store/src/analytical-import-checkpoints.ts b/packages/local-store/src/analytical-import-checkpoints.ts index 5a4d2464..4fa74047 100644 --- a/packages/local-store/src/analytical-import-checkpoints.ts +++ b/packages/local-store/src/analytical-import-checkpoints.ts @@ -17,7 +17,7 @@ export class AnalyticalImportCheckpoint extends Schema.Class()( +export class AnalyticalImportCheckpointFailure extends Schema.TaggedError()( "AnalyticalImportCheckpointFailure", { operation: Schema.String, message: Schema.String }, ) {} diff --git a/packages/local-store/src/correction-signal-study-drafts.ts b/packages/local-store/src/correction-signal-study-drafts.ts index 95433d3f..be91ce3d 100644 --- a/packages/local-store/src/correction-signal-study-drafts.ts +++ b/packages/local-store/src/correction-signal-study-drafts.ts @@ -91,12 +91,12 @@ export class ListCorrectionStudyDrafts extends Schema.Class()( +export class CorrectionSignalStudyDraftFailure extends Schema.TaggedError()( "CorrectionSignalStudyDraftFailure", { operation: Schema.String, message: Schema.String }, ) {} -export class CorrectionSignalStudyDraftConflict extends Schema.TaggedErrorClass()( +export class CorrectionSignalStudyDraftConflict extends Schema.TaggedError()( "CorrectionSignalStudyDraftConflict", { operation: Schema.String, message: Schema.String }, ) {} diff --git a/packages/local-store/src/correction-studies.ts b/packages/local-store/src/correction-studies.ts index 700bc2b0..9740b65c 100644 --- a/packages/local-store/src/correction-studies.ts +++ b/packages/local-store/src/correction-studies.ts @@ -379,12 +379,12 @@ export class CorrectionStudy extends Schema.Class("CorrectionSt promoted_case: Schema.NullOr(PromotedStudyCase), }) {} -export class CorrectionStudyPersistenceFailure extends Schema.TaggedErrorClass()( +export class CorrectionStudyPersistenceFailure extends Schema.TaggedError()( "CorrectionStudyPersistenceFailure", { operation: Schema.String, message: Schema.String }, ) {} -export class CorrectionStudyPersistenceConflict extends Schema.TaggedErrorClass()( +export class CorrectionStudyPersistenceConflict extends Schema.TaggedError()( "CorrectionStudyPersistenceConflict", { operation: Schema.String, message: Schema.String }, ) {} diff --git a/packages/local-store/src/drizzle-schema.ts b/packages/local-store/src/drizzle-schema.ts index 52b26d63..807e65b1 100644 --- a/packages/local-store/src/drizzle-schema.ts +++ b/packages/local-store/src/drizzle-schema.ts @@ -8,6 +8,7 @@ import { sql } from "drizzle-orm"; import { index, integer, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; +export { skill_local_revisions } from "./skill-revision-schema.js"; export { correction_episodes, @@ -22,24 +23,28 @@ export { correction_candidate_evaluations, } from "./correction-study-schema.js"; -export const sessions = sqliteTable("sessions", { - session_id: text().primaryKey(), - started_at: text(), - ended_at: text(), - platform: text(), - model: text(), - completion_status: text(), - source_session_kind: text(), - agent_cli: text(), - workspace_path: text(), - repo_remote: text(), - branch: text(), - schema_version: text(), - normalized_at: text(), - normalizer_version: text(), - capture_mode: text(), - raw_source_ref: text(), -}); +export const sessions = sqliteTable( + "sessions", + { + session_id: text().primaryKey(), + started_at: text(), + ended_at: text(), + platform: text(), + model: text(), + completion_status: text(), + source_session_kind: text(), + agent_cli: text(), + workspace_path: text(), + repo_remote: text(), + branch: text(), + schema_version: text(), + normalized_at: text(), + normalizer_version: text(), + capture_mode: text(), + raw_source_ref: text(), + }, + (table) => [index("idx_sessions_workspace_path").on(table.workspace_path)], +); export const prompts = sqliteTable( "prompts", @@ -256,7 +261,10 @@ export const session_telemetry = sqliteTable( session_type: text(), agent_summary: text(), }, - (table) => [index("idx_session_tel_ts").on(table.timestamp)], + (table) => [ + index("idx_session_tel_ts").on(table.timestamp), + index("idx_session_tel_cwd").on(table.cwd), + ], ); export const skill_usage = sqliteTable( diff --git a/packages/local-store/src/drizzle/0019_narrow_magma.sql b/packages/local-store/src/drizzle/0019_narrow_magma.sql new file mode 100644 index 00000000..463ef26d --- /dev/null +++ b/packages/local-store/src/drizzle/0019_narrow_magma.sql @@ -0,0 +1,11 @@ +CREATE TABLE `skill_local_revisions` ( + `package_path` text NOT NULL, + `revision` integer NOT NULL, + `content_hash` text NOT NULL, + `captured_at` text NOT NULL, + `reason` text NOT NULL, + `restored_from` integer, + `snapshot_json` text NOT NULL +); +--> statement-breakpoint +CREATE UNIQUE INDEX `idx_skill_local_revisions_path_version` ON `skill_local_revisions` (`package_path`,`revision`); \ No newline at end of file diff --git a/packages/local-store/src/drizzle/0020_numerous_apocalypse.sql b/packages/local-store/src/drizzle/0020_numerous_apocalypse.sql new file mode 100644 index 00000000..82201ca3 --- /dev/null +++ b/packages/local-store/src/drizzle/0020_numerous_apocalypse.sql @@ -0,0 +1,2 @@ +CREATE INDEX `idx_session_tel_cwd` ON `session_telemetry` (`cwd`);--> statement-breakpoint +CREATE INDEX `idx_sessions_workspace_path` ON `sessions` (`workspace_path`); \ No newline at end of file diff --git a/packages/local-store/src/drizzle/meta/0019_snapshot.json b/packages/local-store/src/drizzle/meta/0019_snapshot.json new file mode 100644 index 00000000..a877275f --- /dev/null +++ b/packages/local-store/src/drizzle/meta/0019_snapshot.json @@ -0,0 +1,5353 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "40238ed5-e582-452a-940b-800bb59392db", + "prevId": "fc124acb-f223-475a-b1a7-5dc5cbb4ab22", + "tables": { + "_meta": { + "name": "_meta", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "analytical_import_checkpoints": { + "name": "analytical_import_checkpoints", + "columns": { + "source_kind": { + "name": "source_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_identity": { + "name": "source_identity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_fingerprint": { + "name": "source_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "normalizer_version": { + "name": "normalizer_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "imported_at": { + "name": "imported_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "analytical_import_checkpoints_source_unique": { + "name": "analytical_import_checkpoints_source_unique", + "columns": ["source_kind", "source_identity"], + "isUnique": true + }, + "idx_analytical_import_checkpoints_imported": { + "name": "idx_analytical_import_checkpoints_imported", + "columns": ["imported_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "canonical_eval_sets": { + "name": "canonical_eval_sets", + "columns": { + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "stored_at": { + "name": "stored_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "eval_set_json": { + "name": "eval_set_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_canonical_eval_sets_stored_at": { + "name": "idx_canonical_eval_sets_stored_at", + "columns": ["stored_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "canonical_upload_staging": { + "name": "canonical_upload_staging", + "columns": { + "local_seq": { + "name": "local_seq", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "record_kind": { + "name": "record_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_id": { + "name": "record_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_json": { + "name": "record_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prompt_id": { + "name": "prompt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalized_at": { + "name": "normalized_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "staged_at": { + "name": "staged_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_sha256": { + "name": "content_sha256", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_staging_sha256": { + "name": "idx_staging_sha256", + "columns": ["content_sha256"], + "isUnique": false + }, + "idx_staging_dedup": { + "name": "idx_staging_dedup", + "columns": ["record_kind", "record_id"], + "isUnique": true + }, + "idx_staging_session": { + "name": "idx_staging_session", + "columns": ["session_id"], + "isUnique": false + }, + "idx_staging_kind": { + "name": "idx_staging_kind", + "columns": ["record_kind"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "commit_tracking": { + "name": "commit_tracking", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "commit_sha": { + "name": "commit_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "commit_title": { + "name": "commit_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "repo_remote": { + "name": "repo_remote", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(datetime('now'))" + } + }, + "indexes": { + "idx_commit_dedup": { + "name": "idx_commit_dedup", + "columns": ["session_id", "commit_sha"], + "isUnique": true + }, + "idx_commit_ts": { + "name": "idx_commit_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_commit_session": { + "name": "idx_commit_session", + "columns": ["session_id"], + "isUnique": false + }, + "idx_commit_sha": { + "name": "idx_commit_sha", + "columns": ["commit_sha"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_candidate_evaluations": { + "name": "correction_candidate_evaluations", + "columns": { + "evaluation_id": { + "name": "evaluation_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "current_revision": { + "name": "current_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "candidate_revision": { + "name": "candidate_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "blind_manifest_json": { + "name": "blind_manifest_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blind_result_json": { + "name": "blind_result_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verifier_provenance": { + "name": "verifier_provenance", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "runtime_provenance": { + "name": "runtime_provenance", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cost_estimate": { + "name": "cost_estimate", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_actual": { + "name": "cost_actual", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "applies_change": { + "name": "applies_change", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recorded_at": { + "name": "recorded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "correction_candidate_evaluations_candidate_unique": { + "name": "correction_candidate_evaluations_candidate_unique", + "columns": ["evaluation_id", "candidate_id"], + "isUnique": true + }, + "idx_correction_candidate_evaluations_candidate": { + "name": "idx_correction_candidate_evaluations_candidate", + "columns": ["candidate_id", "recorded_at"], + "isUnique": false + } + }, + "foreignKeys": { + "correction_candidate_evaluations_candidate_id_correction_signal_candidates_candidate_id_fk": { + "name": "correction_candidate_evaluations_candidate_id_correction_signal_candidates_candidate_id_fk", + "tableFrom": "correction_candidate_evaluations", + "tableTo": "correction_signal_candidates", + "columnsFrom": ["candidate_id"], + "columnsTo": ["candidate_id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_episodes": { + "name": "correction_episodes", + "columns": { + "episode_id": { + "name": "episode_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "capture_key": { + "name": "capture_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_path": { + "name": "skill_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "harness": { + "name": "harness", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_session_id": { + "name": "source_session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pre_revision": { + "name": "pre_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "post_revision": { + "name": "post_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manifest_json": { + "name": "manifest_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "correction_intent_json": { + "name": "correction_intent_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trace_payload_json": { + "name": "trace_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "captured_at": { + "name": "captured_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "correction_episodes_capture_key_unique": { + "name": "correction_episodes_capture_key_unique", + "columns": ["capture_key"], + "isUnique": true + }, + "idx_correction_episodes_skill": { + "name": "idx_correction_episodes_skill", + "columns": ["skill_id", "updated_at"], + "isUnique": false + }, + "idx_correction_episodes_status": { + "name": "idx_correction_episodes_status", + "columns": ["status", "updated_at"], + "isUnique": false + }, + "idx_correction_episodes_source_session": { + "name": "idx_correction_episodes_source_session", + "columns": ["source_session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_evidence_ledger_entries": { + "name": "correction_evidence_ledger_entries", + "columns": { + "evidence_id": { + "name": "evidence_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "episode_id": { + "name": "episode_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_key": { + "name": "evidence_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "manifest_json": { + "name": "manifest_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verifier_payload_json": { + "name": "verifier_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trial_payload_json": { + "name": "trial_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recorded_at": { + "name": "recorded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "correction_evidence_ledger_episode_key_unique": { + "name": "correction_evidence_ledger_episode_key_unique", + "columns": ["episode_id", "evidence_key"], + "isUnique": true + }, + "idx_correction_evidence_ledger_episode": { + "name": "idx_correction_evidence_ledger_episode", + "columns": ["episode_id", "recorded_at"], + "isUnique": false + }, + "idx_correction_evidence_ledger_status": { + "name": "idx_correction_evidence_ledger_status", + "columns": ["status", "recorded_at"], + "isUnique": false + } + }, + "foreignKeys": { + "correction_evidence_ledger_entries_episode_id_correction_episodes_episode_id_fk": { + "name": "correction_evidence_ledger_entries_episode_id_correction_episodes_episode_id_fk", + "tableFrom": "correction_evidence_ledger_entries", + "tableTo": "correction_episodes", + "columnsFrom": ["episode_id"], + "columnsTo": ["episode_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_learning_policies": { + "name": "correction_learning_policies", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "capture_enabled": { + "name": "capture_enabled", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "proactive_generation_enabled": { + "name": "proactive_generation_enabled", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "managed_execution_enabled": { + "name": "managed_execution_enabled", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kill_switch_enabled": { + "name": "kill_switch_enabled", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "workspace_budget": { + "name": "workspace_budget", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "max_concurrency": { + "name": "max_concurrency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "retention_e0_days": { + "name": "retention_e0_days", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_raw_source_material": { + "name": "correction_raw_source_material", + "columns": { + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_correction_raw_source_material_expiry": { + "name": "idx_correction_raw_source_material_expiry", + "columns": ["evidence_level", "expires_at"], + "isUnique": false + }, + "idx_correction_raw_source_material_candidate": { + "name": "idx_correction_raw_source_material_candidate", + "columns": ["candidate_id"], + "isUnique": false + } + }, + "foreignKeys": { + "correction_raw_source_material_candidate_id_correction_signal_candidates_candidate_id_fk": { + "name": "correction_raw_source_material_candidate_id_correction_signal_candidates_candidate_id_fk", + "tableFrom": "correction_raw_source_material", + "tableTo": "correction_signal_candidates", + "columnsFrom": ["candidate_id"], + "columnsTo": ["candidate_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_review_decisions": { + "name": "correction_review_decisions", + "columns": { + "decision_id": { + "name": "decision_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "replacement_candidate_id": { + "name": "replacement_candidate_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manifest_digest": { + "name": "manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "decided_at": { + "name": "decided_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_correction_review_decisions_candidate": { + "name": "idx_correction_review_decisions_candidate", + "columns": ["candidate_id", "decided_at"], + "isUnique": false + }, + "idx_correction_review_decisions_replacement": { + "name": "idx_correction_review_decisions_replacement", + "columns": ["replacement_candidate_id"], + "isUnique": false + } + }, + "foreignKeys": { + "correction_review_decisions_candidate_id_correction_signal_candidates_candidate_id_fk": { + "name": "correction_review_decisions_candidate_id_correction_signal_candidates_candidate_id_fk", + "tableFrom": "correction_review_decisions", + "tableTo": "correction_signal_candidates", + "columnsFrom": ["candidate_id"], + "columnsTo": ["candidate_id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "correction_review_decisions_replacement_candidate_id_correction_signal_candidates_candidate_id_fk": { + "name": "correction_review_decisions_replacement_candidate_id_correction_signal_candidates_candidate_id_fk", + "tableFrom": "correction_review_decisions", + "tableTo": "correction_signal_candidates", + "columnsFrom": ["replacement_candidate_id"], + "columnsTo": ["candidate_id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_signal_candidates": { + "name": "correction_signal_candidates", + "columns": { + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_session_id": { + "name": "source_session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lifecycle": { + "name": "lifecycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "manifest_digest": { + "name": "manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signal_payload_digest": { + "name": "signal_payload_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signal_payload_json": { + "name": "signal_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "correction_signal_candidates_idempotency_unique": { + "name": "correction_signal_candidates_idempotency_unique", + "columns": ["idempotency_key"], + "isUnique": true + }, + "idx_correction_signal_candidates_skill": { + "name": "idx_correction_signal_candidates_skill", + "columns": ["skill_id", "updated_at"], + "isUnique": false + }, + "idx_correction_signal_candidates_lifecycle": { + "name": "idx_correction_signal_candidates_lifecycle", + "columns": ["lifecycle", "updated_at"], + "isUnique": false + }, + "idx_correction_signal_candidates_session": { + "name": "idx_correction_signal_candidates_session", + "columns": ["source_session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_study_drafts": { + "name": "correction_study_drafts", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_revision": { + "name": "source_revision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lifecycle": { + "name": "lifecycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "manifest_digest": { + "name": "manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "study_payload_digest": { + "name": "study_payload_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "study_payload_json": { + "name": "study_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "correction_study_drafts_idempotency_unique": { + "name": "correction_study_drafts_idempotency_unique", + "columns": ["idempotency_key"], + "isUnique": true + }, + "correction_study_drafts_candidate_unique": { + "name": "correction_study_drafts_candidate_unique", + "columns": ["candidate_id"], + "isUnique": true + }, + "idx_correction_study_drafts_skill": { + "name": "idx_correction_study_drafts_skill", + "columns": ["skill_id", "updated_at"], + "isUnique": false + }, + "idx_correction_study_drafts_lifecycle": { + "name": "idx_correction_study_drafts_lifecycle", + "columns": ["lifecycle", "updated_at"], + "isUnique": false + } + }, + "foreignKeys": { + "correction_study_drafts_candidate_id_correction_signal_candidates_candidate_id_fk": { + "name": "correction_study_drafts_candidate_id_correction_signal_candidates_candidate_id_fk", + "tableFrom": "correction_study_drafts", + "tableTo": "correction_signal_candidates", + "columnsFrom": ["candidate_id"], + "columnsTo": ["candidate_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "creator_contribution_staging": { + "name": "creator_contribution_staging", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "creator_id": { + "name": "creator_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "staged_at": { + "name": "staged_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_creator_contrib_dedup": { + "name": "idx_creator_contrib_dedup", + "columns": ["dedupe_key"], + "isUnique": true + }, + "idx_creator_contrib_skill": { + "name": "idx_creator_contrib_skill", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_creator_contrib_status": { + "name": "idx_creator_contrib_status", + "columns": ["status"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "cron_runs": { + "name": "cron_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "job_name": { + "name": "job_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "elapsed_ms": { + "name": "elapsed_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metrics_json": { + "name": "metrics_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "cron_runs_job_started_unique": { + "name": "cron_runs_job_started_unique", + "columns": ["job_name", "started_at"], + "isUnique": true + }, + "idx_cron_runs_job_ts": { + "name": "idx_cron_runs_job_ts", + "columns": ["job_name", "started_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "evaluation_submission_drafts": { + "name": "evaluation_submission_drafts", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "pattern_id": { + "name": "pattern_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cohort_fingerprint": { + "name": "cohort_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_revision": { + "name": "skill_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lifecycle": { + "name": "lifecycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cloud_run_id": { + "name": "cloud_run_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_evaluation_submission_drafts_cohort": { + "name": "idx_evaluation_submission_drafts_cohort", + "columns": ["pattern_id", "cohort_fingerprint", "skill_revision"], + "isUnique": false + }, + "idx_evaluation_submission_drafts_status": { + "name": "idx_evaluation_submission_drafts_status", + "columns": ["lifecycle", "updated_at"], + "isUnique": false + }, + "idx_evaluation_submission_drafts_skill": { + "name": "idx_evaluation_submission_drafts_skill", + "columns": ["skill_name", "skill_revision", "updated_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "evolution_audit": { + "name": "evolution_audit", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "proposal_id": { + "name": "proposal_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "details": { + "name": "details", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "eval_snapshot_json": { + "name": "eval_snapshot_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "iterations_used": { + "name": "iterations_used", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "validation_mode": { + "name": "validation_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "validation_agent": { + "name": "validation_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "validation_fixture_id": { + "name": "validation_fixture_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "validation_evidence_ref": { + "name": "validation_evidence_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_evo_audit_dedup": { + "name": "idx_evo_audit_dedup", + "columns": ["proposal_id", "action", "timestamp"], + "isUnique": true + }, + "idx_evo_audit_action": { + "name": "idx_evo_audit_action", + "columns": ["action"], + "isUnique": false + }, + "idx_evo_audit_ts": { + "name": "idx_evo_audit_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_evo_audit_proposal": { + "name": "idx_evo_audit_proposal", + "columns": ["proposal_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "evolution_evidence": { + "name": "evolution_evidence", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "proposal_id": { + "name": "proposal_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_path": { + "name": "skill_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target": { + "name": "target", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stage": { + "name": "stage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rationale": { + "name": "rationale", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "confidence": { + "name": "confidence", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "details": { + "name": "details", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "original_text": { + "name": "original_text", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proposed_text": { + "name": "proposed_text", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "eval_set_json": { + "name": "eval_set_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "validation_json": { + "name": "validation_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_evo_evidence_dedup": { + "name": "idx_evo_evidence_dedup", + "columns": ["proposal_id", "stage", "timestamp"], + "isUnique": true + }, + "idx_evo_evidence_ts": { + "name": "idx_evo_evidence_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_evo_evidence_skill": { + "name": "idx_evo_evidence_skill", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_evo_evidence_proposal": { + "name": "idx_evo_evidence_proposal", + "columns": ["proposal_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "execution_facts": { + "name": "execution_facts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "execution_fact_id": { + "name": "execution_fact_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prompt_id": { + "name": "prompt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tool_calls_json": { + "name": "tool_calls_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "total_tool_calls": { + "name": "total_tool_calls", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assistant_turns": { + "name": "assistant_turns", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errors_encountered": { + "name": "errors_encountered", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "input_tokens": { + "name": "input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "output_tokens": { + "name": "output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completion_status": { + "name": "completion_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalized_at": { + "name": "normalized_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalizer_version": { + "name": "normalizer_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capture_mode": { + "name": "capture_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_source_ref": { + "name": "raw_source_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "files_changed": { + "name": "files_changed", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_added": { + "name": "lines_added", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_removed": { + "name": "lines_removed", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_modified": { + "name": "lines_modified", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cached_input_tokens": { + "name": "cached_input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reasoning_output_tokens": { + "name": "reasoning_output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_usd": { + "name": "cost_usd", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "artifact_count": { + "name": "artifact_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_type": { + "name": "session_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_exec_facts_canonical_id": { + "name": "idx_exec_facts_canonical_id", + "columns": ["execution_fact_id"], + "isUnique": true + }, + "idx_exec_facts_session": { + "name": "idx_exec_facts_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": { + "execution_facts_session_id_sessions_session_id_fk": { + "name": "execution_facts_session_id_sessions_session_id_fk", + "tableFrom": "execution_facts", + "tableTo": "sessions", + "columnsFrom": ["session_id"], + "columnsTo": ["session_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "grading_baselines": { + "name": "grading_baselines", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "proposal_id": { + "name": "proposal_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "measured_at": { + "name": "measured_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pass_rate": { + "name": "pass_rate", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mean_score": { + "name": "mean_score", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sample_size": { + "name": "sample_size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "grading_results_json": { + "name": "grading_results_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_grading_bl_skill_proposal": { + "name": "idx_grading_bl_skill_proposal", + "columns": ["skill_name", "proposal_id", "measured_at"], + "isUnique": false + }, + "idx_grading_bl_ts": { + "name": "idx_grading_bl_ts", + "columns": ["measured_at"], + "isUnique": false + }, + "idx_grading_bl_proposal": { + "name": "idx_grading_bl_proposal", + "columns": ["proposal_id"], + "isUnique": false + }, + "idx_grading_bl_skill": { + "name": "idx_grading_bl_skill", + "columns": ["skill_name"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "grading_results": { + "name": "grading_results", + "columns": { + "grading_id": { + "name": "grading_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "transcript_path": { + "name": "transcript_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "graded_at": { + "name": "graded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pass_rate": { + "name": "pass_rate", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mean_score": { + "name": "mean_score", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "score_std_dev": { + "name": "score_std_dev", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "passed_count": { + "name": "passed_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "total_count": { + "name": "total_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expectations_json": { + "name": "expectations_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claims_json": { + "name": "claims_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "eval_feedback_json": { + "name": "eval_feedback_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "failure_feedback_json": { + "name": "failure_feedback_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "execution_metrics_json": { + "name": "execution_metrics_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_grading_dedup": { + "name": "idx_grading_dedup", + "columns": ["session_id", "skill_name", "graded_at"], + "isUnique": true + }, + "idx_grading_ts": { + "name": "idx_grading_ts", + "columns": ["graded_at"], + "isUnique": false + }, + "idx_grading_skill": { + "name": "idx_grading_skill", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_grading_session": { + "name": "idx_grading_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "improvement_signals": { + "name": "improvement_signals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signal_type": { + "name": "signal_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mentioned_skill": { + "name": "mentioned_skill", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consumed": { + "name": "consumed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "consumed_at": { + "name": "consumed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consumed_by_run": { + "name": "consumed_by_run", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_signals_dedup": { + "name": "idx_signals_dedup", + "columns": ["session_id", "query", "signal_type", "timestamp"], + "isUnique": true + }, + "idx_signals_ts": { + "name": "idx_signals_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_signals_consumed": { + "name": "idx_signals_consumed", + "columns": ["consumed"], + "isUnique": false + }, + "idx_signals_session": { + "name": "idx_signals_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "orchestrate_runs": { + "name": "orchestrate_runs", + "columns": { + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "elapsed_ms": { + "name": "elapsed_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dry_run": { + "name": "dry_run", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "approval_mode": { + "name": "approval_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total_skills": { + "name": "total_skills", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evaluated": { + "name": "evaluated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evolved": { + "name": "evolved", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "deployed": { + "name": "deployed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "watched": { + "name": "watched", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skipped": { + "name": "skipped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_actions_json": { + "name": "skill_actions_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_orchestrate_runs_ts": { + "name": "idx_orchestrate_runs_ts", + "columns": ["timestamp"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "package_candidates": { + "name": "package_candidates", + "columns": { + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_path": { + "name": "skill_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "package_fingerprint": { + "name": "package_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parent_candidate_id": { + "name": "parent_candidate_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "candidate_generation": { + "name": "candidate_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "evaluation_count": { + "name": "evaluation_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "first_evaluated_at": { + "name": "first_evaluated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_evaluated_at": { + "name": "last_evaluated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "latest_status": { + "name": "latest_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "latest_evaluation_source": { + "name": "latest_evaluation_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "latest_acceptance_decision": { + "name": "latest_acceptance_decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "artifact_path": { + "name": "artifact_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary_json": { + "name": "summary_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "package_candidates_skill_fingerprint_unique": { + "name": "package_candidates_skill_fingerprint_unique", + "columns": ["skill_name", "package_fingerprint"], + "isUnique": true + }, + "idx_package_candidates_parent": { + "name": "idx_package_candidates_parent", + "columns": ["parent_candidate_id"], + "isUnique": false + }, + "idx_package_candidates_skill_ts": { + "name": "idx_package_candidates_skill_ts", + "columns": ["skill_name", "last_evaluated_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "package_evaluation_reports": { + "name": "package_evaluation_reports", + "columns": { + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "stored_at": { + "name": "stored_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "summary_json": { + "name": "summary_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_package_evaluation_reports_stored_at": { + "name": "idx_package_evaluation_reports_stored_at", + "columns": ["stored_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "package_search_runs": { + "name": "package_search_runs", + "columns": { + "search_id": { + "name": "search_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parent_candidate_id": { + "name": "parent_candidate_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "winner_candidate_id": { + "name": "winner_candidate_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "winner_rationale": { + "name": "winner_rationale", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "candidates_evaluated": { + "name": "candidates_evaluated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provenance_json": { + "name": "provenance_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "completed_at": { + "name": "completed_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_pkg_search_ts": { + "name": "idx_pkg_search_ts", + "columns": ["started_at"], + "isUnique": false + }, + "idx_pkg_search_skill": { + "name": "idx_pkg_search_skill", + "columns": ["skill_name"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "promoted_study_case_retirements": { + "name": "promoted_study_case_retirements", + "columns": { + "retirement_id": { + "name": "retirement_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "case_id": { + "name": "case_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prior_manifest_digest": { + "name": "prior_manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "retired_at": { + "name": "retired_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "promoted_study_case_retirements_case_unique": { + "name": "promoted_study_case_retirements_case_unique", + "columns": ["case_id"], + "isUnique": true + }, + "idx_promoted_study_case_retirements_case": { + "name": "idx_promoted_study_case_retirements_case", + "columns": ["case_id", "retired_at"], + "isUnique": false + } + }, + "foreignKeys": { + "promoted_study_case_retirements_case_id_promoted_study_cases_case_id_fk": { + "name": "promoted_study_case_retirements_case_id_promoted_study_cases_case_id_fk", + "tableFrom": "promoted_study_case_retirements", + "tableTo": "promoted_study_cases", + "columnsFrom": ["case_id"], + "columnsTo": ["case_id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "promoted_study_cases": { + "name": "promoted_study_cases", + "columns": { + "case_id": { + "name": "case_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "episode_id": { + "name": "episode_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_id": { + "name": "evidence_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pre_revision": { + "name": "pre_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "post_revision": { + "name": "post_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manifest_json": { + "name": "manifest_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verifier_payload_json": { + "name": "verifier_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trial_payload_json": { + "name": "trial_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "promoted_at": { + "name": "promoted_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "promoted_study_cases_episode_unique": { + "name": "promoted_study_cases_episode_unique", + "columns": ["episode_id"], + "isUnique": true + }, + "idx_promoted_study_cases_skill": { + "name": "idx_promoted_study_cases_skill", + "columns": ["skill_id", "promoted_at"], + "isUnique": false + }, + "idx_promoted_study_cases_evidence": { + "name": "idx_promoted_study_cases_evidence", + "columns": ["evidence_id"], + "isUnique": false + } + }, + "foreignKeys": { + "promoted_study_cases_episode_id_correction_episodes_episode_id_fk": { + "name": "promoted_study_cases_episode_id_correction_episodes_episode_id_fk", + "tableFrom": "promoted_study_cases", + "tableTo": "correction_episodes", + "columnsFrom": ["episode_id"], + "columnsTo": ["episode_id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "promoted_study_cases_evidence_id_correction_evidence_ledger_entries_evidence_id_fk": { + "name": "promoted_study_cases_evidence_id_correction_evidence_ledger_entries_evidence_id_fk", + "tableFrom": "promoted_study_cases", + "tableTo": "correction_evidence_ledger_entries", + "columnsFrom": ["evidence_id"], + "columnsTo": ["evidence_id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "prompts": { + "name": "prompts", + "columns": { + "prompt_id": { + "name": "prompt_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prompt_kind": { + "name": "prompt_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_actionable": { + "name": "is_actionable", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prompt_index": { + "name": "prompt_index", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prompt_text": { + "name": "prompt_text", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalized_at": { + "name": "normalized_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalizer_version": { + "name": "normalizer_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capture_mode": { + "name": "capture_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_source_ref": { + "name": "raw_source_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_prompts_occurred": { + "name": "idx_prompts_occurred", + "columns": ["occurred_at"], + "isUnique": false + }, + "idx_prompts_session": { + "name": "idx_prompts_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": { + "prompts_session_id_sessions_session_id_fk": { + "name": "prompts_session_id_sessions_session_id_fk", + "tableFrom": "prompts", + "tableTo": "sessions", + "columnsFrom": ["session_id"], + "columnsTo": ["session_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "queries": { + "name": "queries", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_queries_dedup": { + "name": "idx_queries_dedup", + "columns": ["session_id", "query", "timestamp"], + "isUnique": true + }, + "idx_queries_ts": { + "name": "idx_queries_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_queries_session": { + "name": "idx_queries_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "replay_entry_results": { + "name": "replay_entry_results", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "proposal_id": { + "name": "proposal_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "validation_mode": { + "name": "validation_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phase": { + "name": "phase", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "should_trigger": { + "name": "should_trigger", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "triggered": { + "name": "triggered", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "passed": { + "name": "passed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence": { + "name": "evidence", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_replay_entry_proposal_phase": { + "name": "idx_replay_entry_proposal_phase", + "columns": ["proposal_id", "phase"], + "isUnique": false + }, + "idx_replay_entry_passed": { + "name": "idx_replay_entry_passed", + "columns": ["passed"], + "isUnique": false + }, + "idx_replay_entry_skill": { + "name": "idx_replay_entry_skill", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_replay_entry_proposal": { + "name": "idx_replay_entry_proposal", + "columns": ["proposal_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "session_telemetry": { + "name": "session_telemetry", + "columns": { + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cwd": { + "name": "cwd", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "transcript_path": { + "name": "transcript_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tool_calls_json": { + "name": "tool_calls_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "total_tool_calls": { + "name": "total_tool_calls", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bash_commands_json": { + "name": "bash_commands_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skills_triggered_json": { + "name": "skills_triggered_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skills_invoked_json": { + "name": "skills_invoked_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assistant_turns": { + "name": "assistant_turns", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errors_encountered": { + "name": "errors_encountered", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "transcript_chars": { + "name": "transcript_chars", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_user_query": { + "name": "last_user_query", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "input_tokens": { + "name": "input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "output_tokens": { + "name": "output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "files_changed": { + "name": "files_changed", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_added": { + "name": "lines_added", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_removed": { + "name": "lines_removed", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_modified": { + "name": "lines_modified", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cached_input_tokens": { + "name": "cached_input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reasoning_output_tokens": { + "name": "reasoning_output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_usd": { + "name": "cost_usd", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "artifact_count": { + "name": "artifact_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_type": { + "name": "session_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_summary": { + "name": "agent_summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_session_tel_ts": { + "name": "idx_session_tel_ts", + "columns": ["timestamp"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completion_status": { + "name": "completion_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_session_kind": { + "name": "source_session_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_cli": { + "name": "agent_cli", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "repo_remote": { + "name": "repo_remote", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalized_at": { + "name": "normalized_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalizer_version": { + "name": "normalizer_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capture_mode": { + "name": "capture_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_source_ref": { + "name": "raw_source_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_classification_corrections": { + "name": "skill_classification_corrections", + "columns": { + "correction_id": { + "name": "correction_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "inferred_category": { + "name": "inferred_category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "algorithm_version": { + "name": "algorithm_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "corrected_at": { + "name": "corrected_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_classification_corrections_algorithm": { + "name": "idx_skill_classification_corrections_algorithm", + "columns": ["algorithm_version", "corrected_at"], + "isUnique": false + }, + "idx_skill_classification_corrections_skill": { + "name": "idx_skill_classification_corrections_skill", + "columns": ["skill_id", "corrected_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_classification_overrides": { + "name": "skill_classification_overrides", + "columns": { + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "inferred_category": { + "name": "inferred_category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "algorithm_version": { + "name": "algorithm_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_classification_overrides_updated": { + "name": "idx_skill_classification_overrides_updated", + "columns": ["updated_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_install_commit_locks": { + "name": "skill_install_commit_locks", + "columns": { + "lock_name": { + "name": "lock_name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "owner_token": { + "name": "owner_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_install_operation_steps": { + "name": "skill_install_operation_steps", + "columns": { + "operation_id": { + "name": "operation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sequence": { + "name": "sequence", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "receipt_id": { + "name": "receipt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_path": { + "name": "target_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "staging_path": { + "name": "staging_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rollback_path": { + "name": "rollback_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "snapshot_path": { + "name": "snapshot_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expected_sha256": { + "name": "expected_sha256", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "retain_rollback_after_commit": { + "name": "retain_rollback_after_commit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "restore_backup_path": { + "name": "restore_backup_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "strategy": { + "name": "strategy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_path": { + "name": "source_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "operations_json": { + "name": "operations_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expected_before_json": { + "name": "expected_before_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completed_at": { + "name": "completed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "skill_install_operation_steps_identity_unique": { + "name": "skill_install_operation_steps_identity_unique", + "columns": ["operation_id", "sequence"], + "isUnique": true + }, + "idx_skill_install_operation_steps_state": { + "name": "idx_skill_install_operation_steps_state", + "columns": ["operation_id", "state"], + "isUnique": false + } + }, + "foreignKeys": { + "skill_install_operation_steps_operation_id_skill_install_operations_operation_id_fk": { + "name": "skill_install_operation_steps_operation_id_skill_install_operations_operation_id_fk", + "tableFrom": "skill_install_operation_steps", + "tableTo": "skill_install_operations", + "columnsFrom": ["operation_id"], + "columnsTo": ["operation_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_install_operations": { + "name": "skill_install_operations", + "columns": { + "operation_id": { + "name": "operation_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "preview_fingerprint": { + "name": "preview_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fence_id": { + "name": "fence_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fence_generation": { + "name": "fence_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "request_json": { + "name": "request_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "request_sha256": { + "name": "request_sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "recovery_token": { + "name": "recovery_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "recovery_generation": { + "name": "recovery_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "recovery_started_at": { + "name": "recovery_started_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "completed_at": { + "name": "completed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_install_operations_state": { + "name": "idx_skill_install_operations_state", + "columns": ["state", "created_at"], + "isUnique": false + }, + "idx_skill_install_operations_preview": { + "name": "idx_skill_install_operations_preview", + "columns": ["preview_fingerprint", "kind"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_install_receipt_files": { + "name": "skill_install_receipt_files", + "columns": { + "receipt_id": { + "name": "receipt_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "relative_path": { + "name": "relative_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "byte_length": { + "name": "byte_length", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "durable_snapshot_ref": { + "name": "durable_snapshot_ref", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "skill_install_receipt_files_identity_unique": { + "name": "skill_install_receipt_files_identity_unique", + "columns": ["receipt_id", "relative_path"], + "isUnique": true + }, + "idx_skill_install_receipt_files_receipt": { + "name": "idx_skill_install_receipt_files_receipt", + "columns": ["receipt_id"], + "isUnique": false + } + }, + "foreignKeys": { + "skill_install_receipt_files_receipt_id_skill_install_receipts_receipt_id_fk": { + "name": "skill_install_receipt_files_receipt_id_skill_install_receipts_receipt_id_fk", + "tableFrom": "skill_install_receipt_files", + "tableTo": "skill_install_receipts", + "columnsFrom": ["receipt_id"], + "columnsTo": ["receipt_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_install_receipts": { + "name": "skill_install_receipts", + "columns": { + "receipt_id": { + "name": "receipt_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subject_kind": { + "name": "subject_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_set_id": { + "name": "skill_set_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_set_version": { + "name": "skill_set_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_set_package_sha256": { + "name": "skill_set_package_sha256", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logical_skill_id": { + "name": "logical_skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logical_version": { + "name": "logical_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "distribution_id": { + "name": "distribution_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "share_id": { + "name": "share_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "handoff_id": { + "name": "handoff_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sealed_package_sha256": { + "name": "sealed_package_sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sealed_object_id": { + "name": "sealed_object_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "signature_algorithm": { + "name": "signature_algorithm", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signature_key_id": { + "name": "signature_key_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signature_value": { + "name": "signature_value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "license_spdx_expression": { + "name": "license_spdx_expression", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "license_file_json": { + "name": "license_file_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "license_notices_json": { + "name": "license_notices_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "agent": { + "name": "agent", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_root": { + "name": "project_root", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "registry_root": { + "name": "registry_root", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_path": { + "name": "target_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_path_key": { + "name": "target_path_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "strategy": { + "name": "strategy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conflict_decision": { + "name": "conflict_decision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "backup_path": { + "name": "backup_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consent_id": { + "name": "consent_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recipient_principal_id": { + "name": "recipient_principal_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "consent_recorded_at": { + "name": "consent_recorded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "consent_action": { + "name": "consent_action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "disclosure_sha256": { + "name": "disclosure_sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contributor_signals": { + "name": "contributor_signals", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contributor_signal_owner_id": { + "name": "contributor_signal_owner_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "contributor_signal_fields_json": { + "name": "contributor_signal_fields_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lifecycle_reporting": { + "name": "lifecycle_reporting", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lifecycle_fields_json": { + "name": "lifecycle_fields_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_kind": { + "name": "source_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_identity": { + "name": "source_identity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "preview_fingerprint": { + "name": "preview_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "operation_id": { + "name": "operation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_receipt_id": { + "name": "previous_receipt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "superseded_by_receipt_id": { + "name": "superseded_by_receipt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "removed_at": { + "name": "removed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_install_receipts_target": { + "name": "idx_skill_install_receipts_target", + "columns": ["target_path", "state"], + "isUnique": false + }, + "idx_skill_install_receipts_distribution": { + "name": "idx_skill_install_receipts_distribution", + "columns": ["distribution_id", "share_id", "handoff_id"], + "isUnique": false + }, + "idx_skill_install_receipts_lineage": { + "name": "idx_skill_install_receipts_lineage", + "columns": ["previous_receipt_id"], + "isUnique": false + }, + "skill_install_receipts_operation_target_unique": { + "name": "skill_install_receipts_operation_target_unique", + "columns": ["operation_id", "target_path"], + "isUnique": true + }, + "skill_install_receipts_active_target_unique": { + "name": "skill_install_receipts_active_target_unique", + "columns": ["target_path_key"], + "isUnique": true, + "where": "\"skill_install_receipts\".\"state\" = 'active'" + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_invocations": { + "name": "skill_invocations", + "columns": { + "skill_invocation_id": { + "name": "skill_invocation_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invocation_mode": { + "name": "invocation_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "triggered": { + "name": "triggered", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "confidence": { + "name": "confidence", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "matched_prompt_id": { + "name": "matched_prompt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_type": { + "name": "agent_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_path": { + "name": "skill_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_version_hash": { + "name": "skill_version_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_scope": { + "name": "skill_scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalized_at": { + "name": "normalized_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalizer_version": { + "name": "normalizer_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capture_mode": { + "name": "capture_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_source_ref": { + "name": "raw_source_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_inv_dedup": { + "name": "idx_skill_inv_dedup", + "columns": ["session_id", "skill_name", "query", "occurred_at", "triggered"], + "isUnique": false + }, + "idx_skill_inv_version": { + "name": "idx_skill_inv_version", + "columns": ["skill_name", "skill_version_hash", "occurred_at"], + "isUnique": false + }, + "idx_skill_inv_scope": { + "name": "idx_skill_inv_scope", + "columns": ["skill_name", "skill_scope", "occurred_at"], + "isUnique": false + }, + "idx_skill_inv_query_triggered": { + "name": "idx_skill_inv_query_triggered", + "columns": ["query", "triggered"], + "isUnique": false + }, + "idx_skill_inv_ts": { + "name": "idx_skill_inv_ts", + "columns": ["occurred_at"], + "isUnique": false + }, + "idx_skill_inv_name": { + "name": "idx_skill_inv_name", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_skill_inv_session": { + "name": "idx_skill_inv_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": { + "skill_invocations_session_id_sessions_session_id_fk": { + "name": "skill_invocations_session_id_sessions_session_id_fk", + "tableFrom": "skill_invocations", + "tableTo": "sessions", + "columnsFrom": ["session_id"], + "columnsTo": ["session_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_local_revisions": { + "name": "skill_local_revisions", + "columns": { + "package_path": { + "name": "package_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "captured_at": { + "name": "captured_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "restored_from": { + "name": "restored_from", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "snapshot_json": { + "name": "snapshot_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_local_revisions_path_version": { + "name": "idx_skill_local_revisions_path_version", + "columns": ["package_path", "revision"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_set_outcomes": { + "name": "skill_set_outcomes", + "columns": { + "outcome_id": { + "name": "outcome_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "review_id": { + "name": "review_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "receipt_id": { + "name": "receipt_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "set_id": { + "name": "set_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "algorithm_version": { + "name": "algorithm_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_root": { + "name": "project_root", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "measured_at": { + "name": "measured_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "minimum_sessions": { + "name": "minimum_sessions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "before_session_count": { + "name": "before_session_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "after_session_count": { + "name": "after_session_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metrics_json": { + "name": "metrics_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "skill_set_outcomes_review_receipt_unique": { + "name": "skill_set_outcomes_review_receipt_unique", + "columns": ["review_id", "receipt_id"], + "isUnique": true + }, + "idx_skill_set_outcomes_algorithm": { + "name": "idx_skill_set_outcomes_algorithm", + "columns": ["algorithm_version", "measured_at"], + "isUnique": false + }, + "idx_skill_set_outcomes_set": { + "name": "idx_skill_set_outcomes_set", + "columns": ["set_id", "activated_at"], + "isUnique": false + }, + "idx_skill_set_outcomes_status": { + "name": "idx_skill_set_outcomes_status", + "columns": ["status", "measured_at"], + "isUnique": false + } + }, + "foreignKeys": { + "skill_set_outcomes_review_id_skill_set_suggestion_reviews_review_id_fk": { + "name": "skill_set_outcomes_review_id_skill_set_suggestion_reviews_review_id_fk", + "tableFrom": "skill_set_outcomes", + "tableTo": "skill_set_suggestion_reviews", + "columnsFrom": ["review_id"], + "columnsTo": ["review_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_set_suggestion_reviews": { + "name": "skill_set_suggestion_reviews", + "columns": { + "review_id": { + "name": "review_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "snapshot_id": { + "name": "snapshot_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_fingerprint": { + "name": "evidence_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason_code": { + "name": "reason_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resulting_set_id": { + "name": "resulting_set_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resulting_set_revision_hash": { + "name": "resulting_set_revision_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "result_json": { + "name": "result_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "edit_distance": { + "name": "edit_distance", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "algorithm_version": { + "name": "algorithm_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "skill_set_suggestion_review_decision_unique": { + "name": "skill_set_suggestion_review_decision_unique", + "columns": ["snapshot_id", "decision"], + "isUnique": true + }, + "idx_skill_set_suggestion_reviews_reviewed": { + "name": "idx_skill_set_suggestion_reviews_reviewed", + "columns": ["reviewed_at"], + "isUnique": false + }, + "idx_skill_set_suggestion_reviews_suggestion": { + "name": "idx_skill_set_suggestion_reviews_suggestion", + "columns": ["suggestion_id"], + "isUnique": false + }, + "idx_skill_set_suggestion_reviews_snapshot": { + "name": "idx_skill_set_suggestion_reviews_snapshot", + "columns": ["snapshot_id"], + "isUnique": false + } + }, + "foreignKeys": { + "skill_set_suggestion_reviews_snapshot_id_skill_set_suggestion_snapshots_snapshot_id_fk": { + "name": "skill_set_suggestion_reviews_snapshot_id_skill_set_suggestion_snapshots_snapshot_id_fk", + "tableFrom": "skill_set_suggestion_reviews", + "tableTo": "skill_set_suggestion_snapshots", + "columnsFrom": ["snapshot_id"], + "columnsTo": ["snapshot_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_set_suggestion_snapshots": { + "name": "skill_set_suggestion_snapshots", + "columns": { + "snapshot_id": { + "name": "snapshot_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_fingerprint": { + "name": "evidence_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pattern": { + "name": "pattern", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "algorithm_version": { + "name": "algorithm_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_version": { + "name": "evidence_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "suggestion_json": { + "name": "suggestion_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "generated_at": { + "name": "generated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "skill_set_suggestion_snapshot_evidence_unique": { + "name": "skill_set_suggestion_snapshot_evidence_unique", + "columns": ["suggestion_id", "evidence_fingerprint"], + "isUnique": true + }, + "idx_skill_set_suggestion_snapshots_last_seen": { + "name": "idx_skill_set_suggestion_snapshots_last_seen", + "columns": ["last_seen_at"], + "isUnique": false + }, + "idx_skill_set_suggestion_snapshots_suggestion": { + "name": "idx_skill_set_suggestion_snapshots_suggestion", + "columns": ["suggestion_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_usage": { + "name": "skill_usage", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_path": { + "name": "skill_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_scope": { + "name": "skill_scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "triggered": { + "name": "triggered", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_usage_dedup": { + "name": "idx_skill_usage_dedup", + "columns": ["session_id", "skill_name", "query", "timestamp", "triggered"], + "isUnique": true + }, + "idx_skill_usage_scope": { + "name": "idx_skill_usage_scope", + "columns": ["skill_name", "skill_scope", "timestamp"], + "isUnique": false + }, + "idx_skill_usage_query_triggered": { + "name": "idx_skill_usage_query_triggered", + "columns": ["query", "triggered"], + "isUnique": false + }, + "idx_skill_usage_ts": { + "name": "idx_skill_usage_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_skill_usage_name": { + "name": "idx_skill_usage_name", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_skill_usage_session": { + "name": "idx_skill_usage_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "unit_test_files": { + "name": "unit_test_files", + "columns": { + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "stored_at": { + "name": "stored_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tests_json": { + "name": "tests_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_unit_test_files_stored_at": { + "name": "idx_unit_test_files_stored_at", + "columns": ["stored_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "unit_test_run_results": { + "name": "unit_test_run_results", + "columns": { + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "run_at": { + "name": "run_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total": { + "name": "total", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "passed": { + "name": "passed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "failed": { + "name": "failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pass_rate": { + "name": "pass_rate", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "result_json": { + "name": "result_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_unit_test_run_results_run_at": { + "name": "idx_unit_test_run_results_run_at", + "columns": ["run_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "upload_queue": { + "name": "upload_queue", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "payload_type": { + "name": "payload_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "staging_max_seq": { + "name": "staging_max_seq", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_upload_queue_type_status": { + "name": "idx_upload_queue_type_status", + "columns": ["payload_type", "status"], + "isUnique": false + }, + "idx_upload_queue_status": { + "name": "idx_upload_queue_status", + "columns": ["status"], + "isUnique": false + }, + "idx_upload_queue_retry": { + "name": "idx_upload_queue_retry", + "columns": ["status", "next_attempt_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "upload_watermarks": { + "name": "upload_watermarks", + "columns": { + "payload_type": { + "name": "payload_type", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "last_uploaded_id": { + "name": "last_uploaded_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} diff --git a/packages/local-store/src/drizzle/meta/0020_snapshot.json b/packages/local-store/src/drizzle/meta/0020_snapshot.json new file mode 100644 index 00000000..1264fa9f --- /dev/null +++ b/packages/local-store/src/drizzle/meta/0020_snapshot.json @@ -0,0 +1,5364 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "8ff1cee7-25ee-4d49-a308-7de9dc456c8a", + "prevId": "40238ed5-e582-452a-940b-800bb59392db", + "tables": { + "_meta": { + "name": "_meta", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "analytical_import_checkpoints": { + "name": "analytical_import_checkpoints", + "columns": { + "source_kind": { + "name": "source_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_identity": { + "name": "source_identity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_fingerprint": { + "name": "source_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "normalizer_version": { + "name": "normalizer_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "imported_at": { + "name": "imported_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "analytical_import_checkpoints_source_unique": { + "name": "analytical_import_checkpoints_source_unique", + "columns": ["source_kind", "source_identity"], + "isUnique": true + }, + "idx_analytical_import_checkpoints_imported": { + "name": "idx_analytical_import_checkpoints_imported", + "columns": ["imported_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "canonical_eval_sets": { + "name": "canonical_eval_sets", + "columns": { + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "stored_at": { + "name": "stored_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "eval_set_json": { + "name": "eval_set_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_canonical_eval_sets_stored_at": { + "name": "idx_canonical_eval_sets_stored_at", + "columns": ["stored_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "canonical_upload_staging": { + "name": "canonical_upload_staging", + "columns": { + "local_seq": { + "name": "local_seq", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "record_kind": { + "name": "record_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_id": { + "name": "record_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_json": { + "name": "record_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prompt_id": { + "name": "prompt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalized_at": { + "name": "normalized_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "staged_at": { + "name": "staged_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_sha256": { + "name": "content_sha256", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_staging_sha256": { + "name": "idx_staging_sha256", + "columns": ["content_sha256"], + "isUnique": false + }, + "idx_staging_dedup": { + "name": "idx_staging_dedup", + "columns": ["record_kind", "record_id"], + "isUnique": true + }, + "idx_staging_session": { + "name": "idx_staging_session", + "columns": ["session_id"], + "isUnique": false + }, + "idx_staging_kind": { + "name": "idx_staging_kind", + "columns": ["record_kind"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "commit_tracking": { + "name": "commit_tracking", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "commit_sha": { + "name": "commit_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "commit_title": { + "name": "commit_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "repo_remote": { + "name": "repo_remote", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(datetime('now'))" + } + }, + "indexes": { + "idx_commit_dedup": { + "name": "idx_commit_dedup", + "columns": ["session_id", "commit_sha"], + "isUnique": true + }, + "idx_commit_ts": { + "name": "idx_commit_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_commit_session": { + "name": "idx_commit_session", + "columns": ["session_id"], + "isUnique": false + }, + "idx_commit_sha": { + "name": "idx_commit_sha", + "columns": ["commit_sha"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_candidate_evaluations": { + "name": "correction_candidate_evaluations", + "columns": { + "evaluation_id": { + "name": "evaluation_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "current_revision": { + "name": "current_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "candidate_revision": { + "name": "candidate_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "blind_manifest_json": { + "name": "blind_manifest_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blind_result_json": { + "name": "blind_result_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verifier_provenance": { + "name": "verifier_provenance", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "runtime_provenance": { + "name": "runtime_provenance", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cost_estimate": { + "name": "cost_estimate", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_actual": { + "name": "cost_actual", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "applies_change": { + "name": "applies_change", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recorded_at": { + "name": "recorded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "correction_candidate_evaluations_candidate_unique": { + "name": "correction_candidate_evaluations_candidate_unique", + "columns": ["evaluation_id", "candidate_id"], + "isUnique": true + }, + "idx_correction_candidate_evaluations_candidate": { + "name": "idx_correction_candidate_evaluations_candidate", + "columns": ["candidate_id", "recorded_at"], + "isUnique": false + } + }, + "foreignKeys": { + "correction_candidate_evaluations_candidate_id_correction_signal_candidates_candidate_id_fk": { + "name": "correction_candidate_evaluations_candidate_id_correction_signal_candidates_candidate_id_fk", + "tableFrom": "correction_candidate_evaluations", + "tableTo": "correction_signal_candidates", + "columnsFrom": ["candidate_id"], + "columnsTo": ["candidate_id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_episodes": { + "name": "correction_episodes", + "columns": { + "episode_id": { + "name": "episode_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "capture_key": { + "name": "capture_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_path": { + "name": "skill_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "harness": { + "name": "harness", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_session_id": { + "name": "source_session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pre_revision": { + "name": "pre_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "post_revision": { + "name": "post_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manifest_json": { + "name": "manifest_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "correction_intent_json": { + "name": "correction_intent_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trace_payload_json": { + "name": "trace_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "captured_at": { + "name": "captured_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "correction_episodes_capture_key_unique": { + "name": "correction_episodes_capture_key_unique", + "columns": ["capture_key"], + "isUnique": true + }, + "idx_correction_episodes_skill": { + "name": "idx_correction_episodes_skill", + "columns": ["skill_id", "updated_at"], + "isUnique": false + }, + "idx_correction_episodes_status": { + "name": "idx_correction_episodes_status", + "columns": ["status", "updated_at"], + "isUnique": false + }, + "idx_correction_episodes_source_session": { + "name": "idx_correction_episodes_source_session", + "columns": ["source_session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_evidence_ledger_entries": { + "name": "correction_evidence_ledger_entries", + "columns": { + "evidence_id": { + "name": "evidence_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "episode_id": { + "name": "episode_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_key": { + "name": "evidence_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "manifest_json": { + "name": "manifest_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verifier_payload_json": { + "name": "verifier_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trial_payload_json": { + "name": "trial_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recorded_at": { + "name": "recorded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "correction_evidence_ledger_episode_key_unique": { + "name": "correction_evidence_ledger_episode_key_unique", + "columns": ["episode_id", "evidence_key"], + "isUnique": true + }, + "idx_correction_evidence_ledger_episode": { + "name": "idx_correction_evidence_ledger_episode", + "columns": ["episode_id", "recorded_at"], + "isUnique": false + }, + "idx_correction_evidence_ledger_status": { + "name": "idx_correction_evidence_ledger_status", + "columns": ["status", "recorded_at"], + "isUnique": false + } + }, + "foreignKeys": { + "correction_evidence_ledger_entries_episode_id_correction_episodes_episode_id_fk": { + "name": "correction_evidence_ledger_entries_episode_id_correction_episodes_episode_id_fk", + "tableFrom": "correction_evidence_ledger_entries", + "tableTo": "correction_episodes", + "columnsFrom": ["episode_id"], + "columnsTo": ["episode_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_learning_policies": { + "name": "correction_learning_policies", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "capture_enabled": { + "name": "capture_enabled", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "proactive_generation_enabled": { + "name": "proactive_generation_enabled", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "managed_execution_enabled": { + "name": "managed_execution_enabled", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kill_switch_enabled": { + "name": "kill_switch_enabled", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "workspace_budget": { + "name": "workspace_budget", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "max_concurrency": { + "name": "max_concurrency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "retention_e0_days": { + "name": "retention_e0_days", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_raw_source_material": { + "name": "correction_raw_source_material", + "columns": { + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_correction_raw_source_material_expiry": { + "name": "idx_correction_raw_source_material_expiry", + "columns": ["evidence_level", "expires_at"], + "isUnique": false + }, + "idx_correction_raw_source_material_candidate": { + "name": "idx_correction_raw_source_material_candidate", + "columns": ["candidate_id"], + "isUnique": false + } + }, + "foreignKeys": { + "correction_raw_source_material_candidate_id_correction_signal_candidates_candidate_id_fk": { + "name": "correction_raw_source_material_candidate_id_correction_signal_candidates_candidate_id_fk", + "tableFrom": "correction_raw_source_material", + "tableTo": "correction_signal_candidates", + "columnsFrom": ["candidate_id"], + "columnsTo": ["candidate_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_review_decisions": { + "name": "correction_review_decisions", + "columns": { + "decision_id": { + "name": "decision_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "replacement_candidate_id": { + "name": "replacement_candidate_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manifest_digest": { + "name": "manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "decided_at": { + "name": "decided_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_correction_review_decisions_candidate": { + "name": "idx_correction_review_decisions_candidate", + "columns": ["candidate_id", "decided_at"], + "isUnique": false + }, + "idx_correction_review_decisions_replacement": { + "name": "idx_correction_review_decisions_replacement", + "columns": ["replacement_candidate_id"], + "isUnique": false + } + }, + "foreignKeys": { + "correction_review_decisions_candidate_id_correction_signal_candidates_candidate_id_fk": { + "name": "correction_review_decisions_candidate_id_correction_signal_candidates_candidate_id_fk", + "tableFrom": "correction_review_decisions", + "tableTo": "correction_signal_candidates", + "columnsFrom": ["candidate_id"], + "columnsTo": ["candidate_id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "correction_review_decisions_replacement_candidate_id_correction_signal_candidates_candidate_id_fk": { + "name": "correction_review_decisions_replacement_candidate_id_correction_signal_candidates_candidate_id_fk", + "tableFrom": "correction_review_decisions", + "tableTo": "correction_signal_candidates", + "columnsFrom": ["replacement_candidate_id"], + "columnsTo": ["candidate_id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_signal_candidates": { + "name": "correction_signal_candidates", + "columns": { + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_session_id": { + "name": "source_session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lifecycle": { + "name": "lifecycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "manifest_digest": { + "name": "manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signal_payload_digest": { + "name": "signal_payload_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signal_payload_json": { + "name": "signal_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "correction_signal_candidates_idempotency_unique": { + "name": "correction_signal_candidates_idempotency_unique", + "columns": ["idempotency_key"], + "isUnique": true + }, + "idx_correction_signal_candidates_skill": { + "name": "idx_correction_signal_candidates_skill", + "columns": ["skill_id", "updated_at"], + "isUnique": false + }, + "idx_correction_signal_candidates_lifecycle": { + "name": "idx_correction_signal_candidates_lifecycle", + "columns": ["lifecycle", "updated_at"], + "isUnique": false + }, + "idx_correction_signal_candidates_session": { + "name": "idx_correction_signal_candidates_session", + "columns": ["source_session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "correction_study_drafts": { + "name": "correction_study_drafts", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_revision": { + "name": "source_revision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lifecycle": { + "name": "lifecycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "manifest_digest": { + "name": "manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "study_payload_digest": { + "name": "study_payload_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "study_payload_json": { + "name": "study_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "correction_study_drafts_idempotency_unique": { + "name": "correction_study_drafts_idempotency_unique", + "columns": ["idempotency_key"], + "isUnique": true + }, + "correction_study_drafts_candidate_unique": { + "name": "correction_study_drafts_candidate_unique", + "columns": ["candidate_id"], + "isUnique": true + }, + "idx_correction_study_drafts_skill": { + "name": "idx_correction_study_drafts_skill", + "columns": ["skill_id", "updated_at"], + "isUnique": false + }, + "idx_correction_study_drafts_lifecycle": { + "name": "idx_correction_study_drafts_lifecycle", + "columns": ["lifecycle", "updated_at"], + "isUnique": false + } + }, + "foreignKeys": { + "correction_study_drafts_candidate_id_correction_signal_candidates_candidate_id_fk": { + "name": "correction_study_drafts_candidate_id_correction_signal_candidates_candidate_id_fk", + "tableFrom": "correction_study_drafts", + "tableTo": "correction_signal_candidates", + "columnsFrom": ["candidate_id"], + "columnsTo": ["candidate_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "creator_contribution_staging": { + "name": "creator_contribution_staging", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "creator_id": { + "name": "creator_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "staged_at": { + "name": "staged_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_creator_contrib_dedup": { + "name": "idx_creator_contrib_dedup", + "columns": ["dedupe_key"], + "isUnique": true + }, + "idx_creator_contrib_skill": { + "name": "idx_creator_contrib_skill", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_creator_contrib_status": { + "name": "idx_creator_contrib_status", + "columns": ["status"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "cron_runs": { + "name": "cron_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "job_name": { + "name": "job_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "elapsed_ms": { + "name": "elapsed_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metrics_json": { + "name": "metrics_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "cron_runs_job_started_unique": { + "name": "cron_runs_job_started_unique", + "columns": ["job_name", "started_at"], + "isUnique": true + }, + "idx_cron_runs_job_ts": { + "name": "idx_cron_runs_job_ts", + "columns": ["job_name", "started_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "evaluation_submission_drafts": { + "name": "evaluation_submission_drafts", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "pattern_id": { + "name": "pattern_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cohort_fingerprint": { + "name": "cohort_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_revision": { + "name": "skill_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lifecycle": { + "name": "lifecycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cloud_run_id": { + "name": "cloud_run_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_evaluation_submission_drafts_cohort": { + "name": "idx_evaluation_submission_drafts_cohort", + "columns": ["pattern_id", "cohort_fingerprint", "skill_revision"], + "isUnique": false + }, + "idx_evaluation_submission_drafts_status": { + "name": "idx_evaluation_submission_drafts_status", + "columns": ["lifecycle", "updated_at"], + "isUnique": false + }, + "idx_evaluation_submission_drafts_skill": { + "name": "idx_evaluation_submission_drafts_skill", + "columns": ["skill_name", "skill_revision", "updated_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "evolution_audit": { + "name": "evolution_audit", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "proposal_id": { + "name": "proposal_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "details": { + "name": "details", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "eval_snapshot_json": { + "name": "eval_snapshot_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "iterations_used": { + "name": "iterations_used", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "validation_mode": { + "name": "validation_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "validation_agent": { + "name": "validation_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "validation_fixture_id": { + "name": "validation_fixture_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "validation_evidence_ref": { + "name": "validation_evidence_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_evo_audit_dedup": { + "name": "idx_evo_audit_dedup", + "columns": ["proposal_id", "action", "timestamp"], + "isUnique": true + }, + "idx_evo_audit_action": { + "name": "idx_evo_audit_action", + "columns": ["action"], + "isUnique": false + }, + "idx_evo_audit_ts": { + "name": "idx_evo_audit_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_evo_audit_proposal": { + "name": "idx_evo_audit_proposal", + "columns": ["proposal_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "evolution_evidence": { + "name": "evolution_evidence", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "proposal_id": { + "name": "proposal_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_path": { + "name": "skill_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target": { + "name": "target", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stage": { + "name": "stage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rationale": { + "name": "rationale", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "confidence": { + "name": "confidence", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "details": { + "name": "details", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "original_text": { + "name": "original_text", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proposed_text": { + "name": "proposed_text", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "eval_set_json": { + "name": "eval_set_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "validation_json": { + "name": "validation_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_evo_evidence_dedup": { + "name": "idx_evo_evidence_dedup", + "columns": ["proposal_id", "stage", "timestamp"], + "isUnique": true + }, + "idx_evo_evidence_ts": { + "name": "idx_evo_evidence_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_evo_evidence_skill": { + "name": "idx_evo_evidence_skill", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_evo_evidence_proposal": { + "name": "idx_evo_evidence_proposal", + "columns": ["proposal_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "execution_facts": { + "name": "execution_facts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "execution_fact_id": { + "name": "execution_fact_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prompt_id": { + "name": "prompt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tool_calls_json": { + "name": "tool_calls_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "total_tool_calls": { + "name": "total_tool_calls", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assistant_turns": { + "name": "assistant_turns", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errors_encountered": { + "name": "errors_encountered", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "input_tokens": { + "name": "input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "output_tokens": { + "name": "output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completion_status": { + "name": "completion_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalized_at": { + "name": "normalized_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalizer_version": { + "name": "normalizer_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capture_mode": { + "name": "capture_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_source_ref": { + "name": "raw_source_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "files_changed": { + "name": "files_changed", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_added": { + "name": "lines_added", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_removed": { + "name": "lines_removed", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_modified": { + "name": "lines_modified", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cached_input_tokens": { + "name": "cached_input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reasoning_output_tokens": { + "name": "reasoning_output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_usd": { + "name": "cost_usd", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "artifact_count": { + "name": "artifact_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_type": { + "name": "session_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_exec_facts_canonical_id": { + "name": "idx_exec_facts_canonical_id", + "columns": ["execution_fact_id"], + "isUnique": true + }, + "idx_exec_facts_session": { + "name": "idx_exec_facts_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": { + "execution_facts_session_id_sessions_session_id_fk": { + "name": "execution_facts_session_id_sessions_session_id_fk", + "tableFrom": "execution_facts", + "tableTo": "sessions", + "columnsFrom": ["session_id"], + "columnsTo": ["session_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "grading_baselines": { + "name": "grading_baselines", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "proposal_id": { + "name": "proposal_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "measured_at": { + "name": "measured_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pass_rate": { + "name": "pass_rate", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mean_score": { + "name": "mean_score", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sample_size": { + "name": "sample_size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "grading_results_json": { + "name": "grading_results_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_grading_bl_skill_proposal": { + "name": "idx_grading_bl_skill_proposal", + "columns": ["skill_name", "proposal_id", "measured_at"], + "isUnique": false + }, + "idx_grading_bl_ts": { + "name": "idx_grading_bl_ts", + "columns": ["measured_at"], + "isUnique": false + }, + "idx_grading_bl_proposal": { + "name": "idx_grading_bl_proposal", + "columns": ["proposal_id"], + "isUnique": false + }, + "idx_grading_bl_skill": { + "name": "idx_grading_bl_skill", + "columns": ["skill_name"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "grading_results": { + "name": "grading_results", + "columns": { + "grading_id": { + "name": "grading_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "transcript_path": { + "name": "transcript_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "graded_at": { + "name": "graded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pass_rate": { + "name": "pass_rate", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mean_score": { + "name": "mean_score", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "score_std_dev": { + "name": "score_std_dev", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "passed_count": { + "name": "passed_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "total_count": { + "name": "total_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expectations_json": { + "name": "expectations_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claims_json": { + "name": "claims_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "eval_feedback_json": { + "name": "eval_feedback_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "failure_feedback_json": { + "name": "failure_feedback_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "execution_metrics_json": { + "name": "execution_metrics_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_grading_dedup": { + "name": "idx_grading_dedup", + "columns": ["session_id", "skill_name", "graded_at"], + "isUnique": true + }, + "idx_grading_ts": { + "name": "idx_grading_ts", + "columns": ["graded_at"], + "isUnique": false + }, + "idx_grading_skill": { + "name": "idx_grading_skill", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_grading_session": { + "name": "idx_grading_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "improvement_signals": { + "name": "improvement_signals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signal_type": { + "name": "signal_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mentioned_skill": { + "name": "mentioned_skill", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consumed": { + "name": "consumed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "consumed_at": { + "name": "consumed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consumed_by_run": { + "name": "consumed_by_run", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_signals_dedup": { + "name": "idx_signals_dedup", + "columns": ["session_id", "query", "signal_type", "timestamp"], + "isUnique": true + }, + "idx_signals_ts": { + "name": "idx_signals_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_signals_consumed": { + "name": "idx_signals_consumed", + "columns": ["consumed"], + "isUnique": false + }, + "idx_signals_session": { + "name": "idx_signals_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "orchestrate_runs": { + "name": "orchestrate_runs", + "columns": { + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "elapsed_ms": { + "name": "elapsed_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dry_run": { + "name": "dry_run", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "approval_mode": { + "name": "approval_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total_skills": { + "name": "total_skills", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evaluated": { + "name": "evaluated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evolved": { + "name": "evolved", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "deployed": { + "name": "deployed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "watched": { + "name": "watched", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skipped": { + "name": "skipped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_actions_json": { + "name": "skill_actions_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_orchestrate_runs_ts": { + "name": "idx_orchestrate_runs_ts", + "columns": ["timestamp"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "package_candidates": { + "name": "package_candidates", + "columns": { + "candidate_id": { + "name": "candidate_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_path": { + "name": "skill_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "package_fingerprint": { + "name": "package_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parent_candidate_id": { + "name": "parent_candidate_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "candidate_generation": { + "name": "candidate_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "evaluation_count": { + "name": "evaluation_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "first_evaluated_at": { + "name": "first_evaluated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_evaluated_at": { + "name": "last_evaluated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "latest_status": { + "name": "latest_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "latest_evaluation_source": { + "name": "latest_evaluation_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "latest_acceptance_decision": { + "name": "latest_acceptance_decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "artifact_path": { + "name": "artifact_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary_json": { + "name": "summary_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "package_candidates_skill_fingerprint_unique": { + "name": "package_candidates_skill_fingerprint_unique", + "columns": ["skill_name", "package_fingerprint"], + "isUnique": true + }, + "idx_package_candidates_parent": { + "name": "idx_package_candidates_parent", + "columns": ["parent_candidate_id"], + "isUnique": false + }, + "idx_package_candidates_skill_ts": { + "name": "idx_package_candidates_skill_ts", + "columns": ["skill_name", "last_evaluated_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "package_evaluation_reports": { + "name": "package_evaluation_reports", + "columns": { + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "stored_at": { + "name": "stored_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "summary_json": { + "name": "summary_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_package_evaluation_reports_stored_at": { + "name": "idx_package_evaluation_reports_stored_at", + "columns": ["stored_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "package_search_runs": { + "name": "package_search_runs", + "columns": { + "search_id": { + "name": "search_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parent_candidate_id": { + "name": "parent_candidate_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "winner_candidate_id": { + "name": "winner_candidate_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "winner_rationale": { + "name": "winner_rationale", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "candidates_evaluated": { + "name": "candidates_evaluated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provenance_json": { + "name": "provenance_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "completed_at": { + "name": "completed_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_pkg_search_ts": { + "name": "idx_pkg_search_ts", + "columns": ["started_at"], + "isUnique": false + }, + "idx_pkg_search_skill": { + "name": "idx_pkg_search_skill", + "columns": ["skill_name"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "promoted_study_case_retirements": { + "name": "promoted_study_case_retirements", + "columns": { + "retirement_id": { + "name": "retirement_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "case_id": { + "name": "case_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prior_manifest_digest": { + "name": "prior_manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "retired_at": { + "name": "retired_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "promoted_study_case_retirements_case_unique": { + "name": "promoted_study_case_retirements_case_unique", + "columns": ["case_id"], + "isUnique": true + }, + "idx_promoted_study_case_retirements_case": { + "name": "idx_promoted_study_case_retirements_case", + "columns": ["case_id", "retired_at"], + "isUnique": false + } + }, + "foreignKeys": { + "promoted_study_case_retirements_case_id_promoted_study_cases_case_id_fk": { + "name": "promoted_study_case_retirements_case_id_promoted_study_cases_case_id_fk", + "tableFrom": "promoted_study_case_retirements", + "tableTo": "promoted_study_cases", + "columnsFrom": ["case_id"], + "columnsTo": ["case_id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "promoted_study_cases": { + "name": "promoted_study_cases", + "columns": { + "case_id": { + "name": "case_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "episode_id": { + "name": "episode_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_id": { + "name": "evidence_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pre_revision": { + "name": "pre_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "post_revision": { + "name": "post_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manifest_json": { + "name": "manifest_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verifier_payload_json": { + "name": "verifier_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trial_payload_json": { + "name": "trial_payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_level": { + "name": "evidence_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "promoted_at": { + "name": "promoted_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "promoted_study_cases_episode_unique": { + "name": "promoted_study_cases_episode_unique", + "columns": ["episode_id"], + "isUnique": true + }, + "idx_promoted_study_cases_skill": { + "name": "idx_promoted_study_cases_skill", + "columns": ["skill_id", "promoted_at"], + "isUnique": false + }, + "idx_promoted_study_cases_evidence": { + "name": "idx_promoted_study_cases_evidence", + "columns": ["evidence_id"], + "isUnique": false + } + }, + "foreignKeys": { + "promoted_study_cases_episode_id_correction_episodes_episode_id_fk": { + "name": "promoted_study_cases_episode_id_correction_episodes_episode_id_fk", + "tableFrom": "promoted_study_cases", + "tableTo": "correction_episodes", + "columnsFrom": ["episode_id"], + "columnsTo": ["episode_id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "promoted_study_cases_evidence_id_correction_evidence_ledger_entries_evidence_id_fk": { + "name": "promoted_study_cases_evidence_id_correction_evidence_ledger_entries_evidence_id_fk", + "tableFrom": "promoted_study_cases", + "tableTo": "correction_evidence_ledger_entries", + "columnsFrom": ["evidence_id"], + "columnsTo": ["evidence_id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "prompts": { + "name": "prompts", + "columns": { + "prompt_id": { + "name": "prompt_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prompt_kind": { + "name": "prompt_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_actionable": { + "name": "is_actionable", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prompt_index": { + "name": "prompt_index", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "prompt_text": { + "name": "prompt_text", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalized_at": { + "name": "normalized_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalizer_version": { + "name": "normalizer_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capture_mode": { + "name": "capture_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_source_ref": { + "name": "raw_source_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_prompts_occurred": { + "name": "idx_prompts_occurred", + "columns": ["occurred_at"], + "isUnique": false + }, + "idx_prompts_session": { + "name": "idx_prompts_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": { + "prompts_session_id_sessions_session_id_fk": { + "name": "prompts_session_id_sessions_session_id_fk", + "tableFrom": "prompts", + "tableTo": "sessions", + "columnsFrom": ["session_id"], + "columnsTo": ["session_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "queries": { + "name": "queries", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_queries_dedup": { + "name": "idx_queries_dedup", + "columns": ["session_id", "query", "timestamp"], + "isUnique": true + }, + "idx_queries_ts": { + "name": "idx_queries_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_queries_session": { + "name": "idx_queries_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "replay_entry_results": { + "name": "replay_entry_results", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "proposal_id": { + "name": "proposal_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "validation_mode": { + "name": "validation_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phase": { + "name": "phase", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "should_trigger": { + "name": "should_trigger", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "triggered": { + "name": "triggered", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "passed": { + "name": "passed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence": { + "name": "evidence", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_replay_entry_proposal_phase": { + "name": "idx_replay_entry_proposal_phase", + "columns": ["proposal_id", "phase"], + "isUnique": false + }, + "idx_replay_entry_passed": { + "name": "idx_replay_entry_passed", + "columns": ["passed"], + "isUnique": false + }, + "idx_replay_entry_skill": { + "name": "idx_replay_entry_skill", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_replay_entry_proposal": { + "name": "idx_replay_entry_proposal", + "columns": ["proposal_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "session_telemetry": { + "name": "session_telemetry", + "columns": { + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cwd": { + "name": "cwd", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "transcript_path": { + "name": "transcript_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tool_calls_json": { + "name": "tool_calls_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "total_tool_calls": { + "name": "total_tool_calls", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bash_commands_json": { + "name": "bash_commands_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skills_triggered_json": { + "name": "skills_triggered_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skills_invoked_json": { + "name": "skills_invoked_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assistant_turns": { + "name": "assistant_turns", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errors_encountered": { + "name": "errors_encountered", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "transcript_chars": { + "name": "transcript_chars", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_user_query": { + "name": "last_user_query", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "input_tokens": { + "name": "input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "output_tokens": { + "name": "output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "files_changed": { + "name": "files_changed", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_added": { + "name": "lines_added", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_removed": { + "name": "lines_removed", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines_modified": { + "name": "lines_modified", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cached_input_tokens": { + "name": "cached_input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reasoning_output_tokens": { + "name": "reasoning_output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cost_usd": { + "name": "cost_usd", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "artifact_count": { + "name": "artifact_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_type": { + "name": "session_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_summary": { + "name": "agent_summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_session_tel_ts": { + "name": "idx_session_tel_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_session_tel_cwd": { + "name": "idx_session_tel_cwd", + "columns": ["cwd"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completion_status": { + "name": "completion_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_session_kind": { + "name": "source_session_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_cli": { + "name": "agent_cli", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "repo_remote": { + "name": "repo_remote", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalized_at": { + "name": "normalized_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalizer_version": { + "name": "normalizer_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capture_mode": { + "name": "capture_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_source_ref": { + "name": "raw_source_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_sessions_workspace_path": { + "name": "idx_sessions_workspace_path", + "columns": ["workspace_path"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_classification_corrections": { + "name": "skill_classification_corrections", + "columns": { + "correction_id": { + "name": "correction_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "inferred_category": { + "name": "inferred_category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "algorithm_version": { + "name": "algorithm_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "corrected_at": { + "name": "corrected_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_classification_corrections_algorithm": { + "name": "idx_skill_classification_corrections_algorithm", + "columns": ["algorithm_version", "corrected_at"], + "isUnique": false + }, + "idx_skill_classification_corrections_skill": { + "name": "idx_skill_classification_corrections_skill", + "columns": ["skill_id", "corrected_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_classification_overrides": { + "name": "skill_classification_overrides", + "columns": { + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "inferred_category": { + "name": "inferred_category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "algorithm_version": { + "name": "algorithm_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_classification_overrides_updated": { + "name": "idx_skill_classification_overrides_updated", + "columns": ["updated_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_install_commit_locks": { + "name": "skill_install_commit_locks", + "columns": { + "lock_name": { + "name": "lock_name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "owner_token": { + "name": "owner_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_install_operation_steps": { + "name": "skill_install_operation_steps", + "columns": { + "operation_id": { + "name": "operation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sequence": { + "name": "sequence", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "receipt_id": { + "name": "receipt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_path": { + "name": "target_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "staging_path": { + "name": "staging_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rollback_path": { + "name": "rollback_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "snapshot_path": { + "name": "snapshot_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expected_sha256": { + "name": "expected_sha256", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "retain_rollback_after_commit": { + "name": "retain_rollback_after_commit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "restore_backup_path": { + "name": "restore_backup_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "strategy": { + "name": "strategy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_path": { + "name": "source_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "operations_json": { + "name": "operations_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expected_before_json": { + "name": "expected_before_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completed_at": { + "name": "completed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "skill_install_operation_steps_identity_unique": { + "name": "skill_install_operation_steps_identity_unique", + "columns": ["operation_id", "sequence"], + "isUnique": true + }, + "idx_skill_install_operation_steps_state": { + "name": "idx_skill_install_operation_steps_state", + "columns": ["operation_id", "state"], + "isUnique": false + } + }, + "foreignKeys": { + "skill_install_operation_steps_operation_id_skill_install_operations_operation_id_fk": { + "name": "skill_install_operation_steps_operation_id_skill_install_operations_operation_id_fk", + "tableFrom": "skill_install_operation_steps", + "tableTo": "skill_install_operations", + "columnsFrom": ["operation_id"], + "columnsTo": ["operation_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_install_operations": { + "name": "skill_install_operations", + "columns": { + "operation_id": { + "name": "operation_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "preview_fingerprint": { + "name": "preview_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fence_id": { + "name": "fence_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fence_generation": { + "name": "fence_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "request_json": { + "name": "request_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "request_sha256": { + "name": "request_sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "recovery_token": { + "name": "recovery_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "recovery_generation": { + "name": "recovery_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "recovery_started_at": { + "name": "recovery_started_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "completed_at": { + "name": "completed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_install_operations_state": { + "name": "idx_skill_install_operations_state", + "columns": ["state", "created_at"], + "isUnique": false + }, + "idx_skill_install_operations_preview": { + "name": "idx_skill_install_operations_preview", + "columns": ["preview_fingerprint", "kind"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_install_receipt_files": { + "name": "skill_install_receipt_files", + "columns": { + "receipt_id": { + "name": "receipt_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "relative_path": { + "name": "relative_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "byte_length": { + "name": "byte_length", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "durable_snapshot_ref": { + "name": "durable_snapshot_ref", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "skill_install_receipt_files_identity_unique": { + "name": "skill_install_receipt_files_identity_unique", + "columns": ["receipt_id", "relative_path"], + "isUnique": true + }, + "idx_skill_install_receipt_files_receipt": { + "name": "idx_skill_install_receipt_files_receipt", + "columns": ["receipt_id"], + "isUnique": false + } + }, + "foreignKeys": { + "skill_install_receipt_files_receipt_id_skill_install_receipts_receipt_id_fk": { + "name": "skill_install_receipt_files_receipt_id_skill_install_receipts_receipt_id_fk", + "tableFrom": "skill_install_receipt_files", + "tableTo": "skill_install_receipts", + "columnsFrom": ["receipt_id"], + "columnsTo": ["receipt_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_install_receipts": { + "name": "skill_install_receipts", + "columns": { + "receipt_id": { + "name": "receipt_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subject_kind": { + "name": "subject_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_set_id": { + "name": "skill_set_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_set_version": { + "name": "skill_set_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_set_package_sha256": { + "name": "skill_set_package_sha256", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logical_skill_id": { + "name": "logical_skill_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logical_version": { + "name": "logical_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "distribution_id": { + "name": "distribution_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "share_id": { + "name": "share_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "handoff_id": { + "name": "handoff_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sealed_package_sha256": { + "name": "sealed_package_sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sealed_object_id": { + "name": "sealed_object_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "signature_algorithm": { + "name": "signature_algorithm", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signature_key_id": { + "name": "signature_key_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signature_value": { + "name": "signature_value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "license_spdx_expression": { + "name": "license_spdx_expression", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "license_file_json": { + "name": "license_file_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "license_notices_json": { + "name": "license_notices_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "agent": { + "name": "agent", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_root": { + "name": "project_root", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "registry_root": { + "name": "registry_root", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_path": { + "name": "target_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_path_key": { + "name": "target_path_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "strategy": { + "name": "strategy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conflict_decision": { + "name": "conflict_decision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "backup_path": { + "name": "backup_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consent_id": { + "name": "consent_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recipient_principal_id": { + "name": "recipient_principal_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "consent_recorded_at": { + "name": "consent_recorded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "consent_action": { + "name": "consent_action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "disclosure_sha256": { + "name": "disclosure_sha256", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contributor_signals": { + "name": "contributor_signals", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contributor_signal_owner_id": { + "name": "contributor_signal_owner_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "contributor_signal_fields_json": { + "name": "contributor_signal_fields_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lifecycle_reporting": { + "name": "lifecycle_reporting", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lifecycle_fields_json": { + "name": "lifecycle_fields_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_kind": { + "name": "source_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_identity": { + "name": "source_identity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "preview_fingerprint": { + "name": "preview_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "operation_id": { + "name": "operation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_receipt_id": { + "name": "previous_receipt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "superseded_by_receipt_id": { + "name": "superseded_by_receipt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "removed_at": { + "name": "removed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_install_receipts_target": { + "name": "idx_skill_install_receipts_target", + "columns": ["target_path", "state"], + "isUnique": false + }, + "idx_skill_install_receipts_distribution": { + "name": "idx_skill_install_receipts_distribution", + "columns": ["distribution_id", "share_id", "handoff_id"], + "isUnique": false + }, + "idx_skill_install_receipts_lineage": { + "name": "idx_skill_install_receipts_lineage", + "columns": ["previous_receipt_id"], + "isUnique": false + }, + "skill_install_receipts_operation_target_unique": { + "name": "skill_install_receipts_operation_target_unique", + "columns": ["operation_id", "target_path"], + "isUnique": true + }, + "skill_install_receipts_active_target_unique": { + "name": "skill_install_receipts_active_target_unique", + "columns": ["target_path_key"], + "isUnique": true, + "where": "\"skill_install_receipts\".\"state\" = 'active'" + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_invocations": { + "name": "skill_invocations", + "columns": { + "skill_invocation_id": { + "name": "skill_invocation_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invocation_mode": { + "name": "invocation_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "triggered": { + "name": "triggered", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "confidence": { + "name": "confidence", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "matched_prompt_id": { + "name": "matched_prompt_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_type": { + "name": "agent_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_path": { + "name": "skill_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_version_hash": { + "name": "skill_version_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_scope": { + "name": "skill_scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schema_version": { + "name": "schema_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalized_at": { + "name": "normalized_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "normalizer_version": { + "name": "normalizer_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capture_mode": { + "name": "capture_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_source_ref": { + "name": "raw_source_ref", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_inv_dedup": { + "name": "idx_skill_inv_dedup", + "columns": ["session_id", "skill_name", "query", "occurred_at", "triggered"], + "isUnique": false + }, + "idx_skill_inv_version": { + "name": "idx_skill_inv_version", + "columns": ["skill_name", "skill_version_hash", "occurred_at"], + "isUnique": false + }, + "idx_skill_inv_scope": { + "name": "idx_skill_inv_scope", + "columns": ["skill_name", "skill_scope", "occurred_at"], + "isUnique": false + }, + "idx_skill_inv_query_triggered": { + "name": "idx_skill_inv_query_triggered", + "columns": ["query", "triggered"], + "isUnique": false + }, + "idx_skill_inv_ts": { + "name": "idx_skill_inv_ts", + "columns": ["occurred_at"], + "isUnique": false + }, + "idx_skill_inv_name": { + "name": "idx_skill_inv_name", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_skill_inv_session": { + "name": "idx_skill_inv_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": { + "skill_invocations_session_id_sessions_session_id_fk": { + "name": "skill_invocations_session_id_sessions_session_id_fk", + "tableFrom": "skill_invocations", + "tableTo": "sessions", + "columnsFrom": ["session_id"], + "columnsTo": ["session_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_local_revisions": { + "name": "skill_local_revisions", + "columns": { + "package_path": { + "name": "package_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "captured_at": { + "name": "captured_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "restored_from": { + "name": "restored_from", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "snapshot_json": { + "name": "snapshot_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_local_revisions_path_version": { + "name": "idx_skill_local_revisions_path_version", + "columns": ["package_path", "revision"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_set_outcomes": { + "name": "skill_set_outcomes", + "columns": { + "outcome_id": { + "name": "outcome_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "review_id": { + "name": "review_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "receipt_id": { + "name": "receipt_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "set_id": { + "name": "set_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "algorithm_version": { + "name": "algorithm_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_root": { + "name": "project_root", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "measured_at": { + "name": "measured_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "minimum_sessions": { + "name": "minimum_sessions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "before_session_count": { + "name": "before_session_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "after_session_count": { + "name": "after_session_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metrics_json": { + "name": "metrics_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "skill_set_outcomes_review_receipt_unique": { + "name": "skill_set_outcomes_review_receipt_unique", + "columns": ["review_id", "receipt_id"], + "isUnique": true + }, + "idx_skill_set_outcomes_algorithm": { + "name": "idx_skill_set_outcomes_algorithm", + "columns": ["algorithm_version", "measured_at"], + "isUnique": false + }, + "idx_skill_set_outcomes_set": { + "name": "idx_skill_set_outcomes_set", + "columns": ["set_id", "activated_at"], + "isUnique": false + }, + "idx_skill_set_outcomes_status": { + "name": "idx_skill_set_outcomes_status", + "columns": ["status", "measured_at"], + "isUnique": false + } + }, + "foreignKeys": { + "skill_set_outcomes_review_id_skill_set_suggestion_reviews_review_id_fk": { + "name": "skill_set_outcomes_review_id_skill_set_suggestion_reviews_review_id_fk", + "tableFrom": "skill_set_outcomes", + "tableTo": "skill_set_suggestion_reviews", + "columnsFrom": ["review_id"], + "columnsTo": ["review_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_set_suggestion_reviews": { + "name": "skill_set_suggestion_reviews", + "columns": { + "review_id": { + "name": "review_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "snapshot_id": { + "name": "snapshot_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_fingerprint": { + "name": "evidence_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason_code": { + "name": "reason_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resulting_set_id": { + "name": "resulting_set_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resulting_set_revision_hash": { + "name": "resulting_set_revision_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "result_json": { + "name": "result_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "edit_distance": { + "name": "edit_distance", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "algorithm_version": { + "name": "algorithm_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "skill_set_suggestion_review_decision_unique": { + "name": "skill_set_suggestion_review_decision_unique", + "columns": ["snapshot_id", "decision"], + "isUnique": true + }, + "idx_skill_set_suggestion_reviews_reviewed": { + "name": "idx_skill_set_suggestion_reviews_reviewed", + "columns": ["reviewed_at"], + "isUnique": false + }, + "idx_skill_set_suggestion_reviews_suggestion": { + "name": "idx_skill_set_suggestion_reviews_suggestion", + "columns": ["suggestion_id"], + "isUnique": false + }, + "idx_skill_set_suggestion_reviews_snapshot": { + "name": "idx_skill_set_suggestion_reviews_snapshot", + "columns": ["snapshot_id"], + "isUnique": false + } + }, + "foreignKeys": { + "skill_set_suggestion_reviews_snapshot_id_skill_set_suggestion_snapshots_snapshot_id_fk": { + "name": "skill_set_suggestion_reviews_snapshot_id_skill_set_suggestion_snapshots_snapshot_id_fk", + "tableFrom": "skill_set_suggestion_reviews", + "tableTo": "skill_set_suggestion_snapshots", + "columnsFrom": ["snapshot_id"], + "columnsTo": ["snapshot_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_set_suggestion_snapshots": { + "name": "skill_set_suggestion_snapshots", + "columns": { + "snapshot_id": { + "name": "snapshot_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_fingerprint": { + "name": "evidence_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pattern": { + "name": "pattern", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "algorithm_version": { + "name": "algorithm_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "evidence_version": { + "name": "evidence_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "suggestion_json": { + "name": "suggestion_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "generated_at": { + "name": "generated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "skill_set_suggestion_snapshot_evidence_unique": { + "name": "skill_set_suggestion_snapshot_evidence_unique", + "columns": ["suggestion_id", "evidence_fingerprint"], + "isUnique": true + }, + "idx_skill_set_suggestion_snapshots_last_seen": { + "name": "idx_skill_set_suggestion_snapshots_last_seen", + "columns": ["last_seen_at"], + "isUnique": false + }, + "idx_skill_set_suggestion_snapshots_suggestion": { + "name": "idx_skill_set_suggestion_snapshots_suggestion", + "columns": ["suggestion_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "skill_usage": { + "name": "skill_usage", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "skill_path": { + "name": "skill_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skill_scope": { + "name": "skill_scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "triggered": { + "name": "triggered", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_skill_usage_dedup": { + "name": "idx_skill_usage_dedup", + "columns": ["session_id", "skill_name", "query", "timestamp", "triggered"], + "isUnique": true + }, + "idx_skill_usage_scope": { + "name": "idx_skill_usage_scope", + "columns": ["skill_name", "skill_scope", "timestamp"], + "isUnique": false + }, + "idx_skill_usage_query_triggered": { + "name": "idx_skill_usage_query_triggered", + "columns": ["query", "triggered"], + "isUnique": false + }, + "idx_skill_usage_ts": { + "name": "idx_skill_usage_ts", + "columns": ["timestamp"], + "isUnique": false + }, + "idx_skill_usage_name": { + "name": "idx_skill_usage_name", + "columns": ["skill_name"], + "isUnique": false + }, + "idx_skill_usage_session": { + "name": "idx_skill_usage_session", + "columns": ["session_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "unit_test_files": { + "name": "unit_test_files", + "columns": { + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "stored_at": { + "name": "stored_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tests_json": { + "name": "tests_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_unit_test_files_stored_at": { + "name": "idx_unit_test_files_stored_at", + "columns": ["stored_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "unit_test_run_results": { + "name": "unit_test_run_results", + "columns": { + "skill_name": { + "name": "skill_name", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "run_at": { + "name": "run_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total": { + "name": "total", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "passed": { + "name": "passed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "failed": { + "name": "failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pass_rate": { + "name": "pass_rate", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "result_json": { + "name": "result_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "idx_unit_test_run_results_run_at": { + "name": "idx_unit_test_run_results_run_at", + "columns": ["run_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "upload_queue": { + "name": "upload_queue", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "payload_type": { + "name": "payload_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "staging_max_seq": { + "name": "staging_max_seq", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_upload_queue_type_status": { + "name": "idx_upload_queue_type_status", + "columns": ["payload_type", "status"], + "isUnique": false + }, + "idx_upload_queue_status": { + "name": "idx_upload_queue_status", + "columns": ["status"], + "isUnique": false + }, + "idx_upload_queue_retry": { + "name": "idx_upload_queue_retry", + "columns": ["status", "next_attempt_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "upload_watermarks": { + "name": "upload_watermarks", + "columns": { + "payload_type": { + "name": "payload_type", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "last_uploaded_id": { + "name": "last_uploaded_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} diff --git a/packages/local-store/src/drizzle/meta/_journal.json b/packages/local-store/src/drizzle/meta/_journal.json index 2d0d27d2..a0602b60 100644 --- a/packages/local-store/src/drizzle/meta/_journal.json +++ b/packages/local-store/src/drizzle/meta/_journal.json @@ -134,6 +134,20 @@ "when": 1786088000000, "tag": "0018_drop_legacy_evaluation_draft_identity", "breakpoints": true + }, + { + "idx": 19, + "version": "6", + "when": 1788856253727, + "tag": "0019_narrow_magma", + "breakpoints": true + }, + { + "idx": 20, + "version": "6", + "when": 1792529694837, + "tag": "0020_numerous_apocalypse", + "breakpoints": true } ] } diff --git a/packages/local-store/src/embedded-migrations.gen.ts b/packages/local-store/src/embedded-migrations.gen.ts index 43e17b70..52f16170 100644 --- a/packages/local-store/src/embedded-migrations.gen.ts +++ b/packages/local-store/src/embedded-migrations.gen.ts @@ -2,7 +2,7 @@ export default { "meta/_journal.json": - '{\n "version": "7",\n "dialect": "sqlite",\n "entries": [\n {\n "idx": 0,\n "version": "6",\n "when": 1784164687605,\n "tag": "0000_local_runtime_baseline",\n "breakpoints": true\n },\n {\n "idx": 1,\n "version": "6",\n "when": 1784187325823,\n "tag": "0001_fast_zombie",\n "breakpoints": true\n },\n {\n "idx": 2,\n "version": "6",\n "when": 1784191026725,\n "tag": "0002_great_bloodstrike",\n "breakpoints": true\n },\n {\n "idx": 3,\n "version": "6",\n "when": 1784193433052,\n "tag": "0003_silky_luckman",\n "breakpoints": true\n },\n {\n "idx": 4,\n "version": "6",\n "when": 1784283479072,\n "tag": "0004_volatile_cerebro",\n "breakpoints": true\n },\n {\n "idx": 5,\n "version": "6",\n "when": 1784373361781,\n "tag": "0005_naive_malcolm_colcord",\n "breakpoints": true\n },\n {\n "idx": 6,\n "version": "6",\n "when": 1784617671302,\n "tag": "0006_robust_wolfsbane",\n "breakpoints": true\n },\n {\n "idx": 7,\n "version": "6",\n "when": 1784808146888,\n "tag": "0007_yellow_phil_sheldon",\n "breakpoints": true\n },\n {\n "idx": 8,\n "version": "6",\n "when": 1784809896448,\n "tag": "0008_lame_purple_man",\n "breakpoints": true\n },\n {\n "idx": 9,\n "version": "6",\n "when": 1784813701790,\n "tag": "0009_naive_prima",\n "breakpoints": true\n },\n {\n "idx": 10,\n "version": "6",\n "when": 1784827767707,\n "tag": "0010_sleepy_captain_universe",\n "breakpoints": true\n },\n {\n "idx": 11,\n "version": "6",\n "when": 1784837254256,\n "tag": "0011_third_hannibal_king",\n "breakpoints": true\n },\n {\n "idx": 12,\n "version": "6",\n "when": 1784918687054,\n "tag": "0012_dizzy_madrox",\n "breakpoints": true\n },\n {\n "idx": 13,\n "version": "6",\n "when": 1785267461030,\n "tag": "0013_unique_micromax",\n "breakpoints": true\n },\n {\n "idx": 14,\n "version": "6",\n "when": 1785355200000,\n "tag": "0014_forward_correction_study_preview",\n "breakpoints": true\n },\n {\n "idx": 15,\n "version": "6",\n "when": 1785358800000,\n "tag": "0015_e0_signal_study_drafts",\n "breakpoints": true\n },\n {\n "idx": 16,\n "version": "6",\n "when": 1785362400000,\n "tag": "0016_regular_doctor_strange",\n "breakpoints": true\n },\n {\n "idx": 17,\n "version": "6",\n "when": 1785366000000,\n "tag": "0017_promoted_case_retirements",\n "breakpoints": true\n },\n {\n "idx": 18,\n "version": "6",\n "when": 1786088000000,\n "tag": "0018_drop_legacy_evaluation_draft_identity",\n "breakpoints": true\n }\n ]\n}\n', + '{\n "version": "7",\n "dialect": "sqlite",\n "entries": [\n {\n "idx": 0,\n "version": "6",\n "when": 1784164687605,\n "tag": "0000_local_runtime_baseline",\n "breakpoints": true\n },\n {\n "idx": 1,\n "version": "6",\n "when": 1784187325823,\n "tag": "0001_fast_zombie",\n "breakpoints": true\n },\n {\n "idx": 2,\n "version": "6",\n "when": 1784191026725,\n "tag": "0002_great_bloodstrike",\n "breakpoints": true\n },\n {\n "idx": 3,\n "version": "6",\n "when": 1784193433052,\n "tag": "0003_silky_luckman",\n "breakpoints": true\n },\n {\n "idx": 4,\n "version": "6",\n "when": 1784283479072,\n "tag": "0004_volatile_cerebro",\n "breakpoints": true\n },\n {\n "idx": 5,\n "version": "6",\n "when": 1784373361781,\n "tag": "0005_naive_malcolm_colcord",\n "breakpoints": true\n },\n {\n "idx": 6,\n "version": "6",\n "when": 1784617671302,\n "tag": "0006_robust_wolfsbane",\n "breakpoints": true\n },\n {\n "idx": 7,\n "version": "6",\n "when": 1784808146888,\n "tag": "0007_yellow_phil_sheldon",\n "breakpoints": true\n },\n {\n "idx": 8,\n "version": "6",\n "when": 1784809896448,\n "tag": "0008_lame_purple_man",\n "breakpoints": true\n },\n {\n "idx": 9,\n "version": "6",\n "when": 1784813701790,\n "tag": "0009_naive_prima",\n "breakpoints": true\n },\n {\n "idx": 10,\n "version": "6",\n "when": 1784827767707,\n "tag": "0010_sleepy_captain_universe",\n "breakpoints": true\n },\n {\n "idx": 11,\n "version": "6",\n "when": 1784837254256,\n "tag": "0011_third_hannibal_king",\n "breakpoints": true\n },\n {\n "idx": 12,\n "version": "6",\n "when": 1784918687054,\n "tag": "0012_dizzy_madrox",\n "breakpoints": true\n },\n {\n "idx": 13,\n "version": "6",\n "when": 1785267461030,\n "tag": "0013_unique_micromax",\n "breakpoints": true\n },\n {\n "idx": 14,\n "version": "6",\n "when": 1785355200000,\n "tag": "0014_forward_correction_study_preview",\n "breakpoints": true\n },\n {\n "idx": 15,\n "version": "6",\n "when": 1785358800000,\n "tag": "0015_e0_signal_study_drafts",\n "breakpoints": true\n },\n {\n "idx": 16,\n "version": "6",\n "when": 1785362400000,\n "tag": "0016_regular_doctor_strange",\n "breakpoints": true\n },\n {\n "idx": 17,\n "version": "6",\n "when": 1785366000000,\n "tag": "0017_promoted_case_retirements",\n "breakpoints": true\n },\n {\n "idx": 18,\n "version": "6",\n "when": 1786088000000,\n "tag": "0018_drop_legacy_evaluation_draft_identity",\n "breakpoints": true\n },\n {\n "idx": 19,\n "version": "6",\n "when": 1788856253727,\n "tag": "0019_narrow_magma",\n "breakpoints": true\n },\n {\n "idx": 20,\n "version": "6",\n "when": 1792529694837,\n "tag": "0020_numerous_apocalypse",\n "breakpoints": true\n }\n ]\n}\n', "0000_local_runtime_baseline.sql": "CREATE TABLE `_meta` (\n\t`key` text PRIMARY KEY NOT NULL,\n\t`value` text\n);\n--> statement-breakpoint\nCREATE TABLE `canonical_eval_sets` (\n\t`skill_name` text PRIMARY KEY NOT NULL,\n\t`stored_at` text NOT NULL,\n\t`eval_set_json` text NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `idx_canonical_eval_sets_stored_at` ON `canonical_eval_sets` (`stored_at`);--> statement-breakpoint\nCREATE TABLE `canonical_upload_staging` (\n\t`local_seq` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`record_kind` text NOT NULL,\n\t`record_id` text NOT NULL,\n\t`record_json` text NOT NULL,\n\t`session_id` text,\n\t`prompt_id` text,\n\t`normalized_at` text,\n\t`staged_at` text NOT NULL,\n\t`content_sha256` text\n);\n--> statement-breakpoint\nCREATE INDEX `idx_staging_sha256` ON `canonical_upload_staging` (`content_sha256`);--> statement-breakpoint\nCREATE UNIQUE INDEX `idx_staging_dedup` ON `canonical_upload_staging` (`record_kind`,`record_id`);--> statement-breakpoint\nCREATE INDEX `idx_staging_session` ON `canonical_upload_staging` (`session_id`);--> statement-breakpoint\nCREATE INDEX `idx_staging_kind` ON `canonical_upload_staging` (`record_kind`);--> statement-breakpoint\nCREATE TABLE `commit_tracking` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`session_id` text NOT NULL,\n\t`commit_sha` text NOT NULL,\n\t`commit_title` text,\n\t`branch` text,\n\t`repo_remote` text,\n\t`timestamp` text NOT NULL,\n\t`created_at` text DEFAULT (datetime('now')) NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `idx_commit_dedup` ON `commit_tracking` (`session_id`,`commit_sha`);--> statement-breakpoint\nCREATE INDEX `idx_commit_ts` ON `commit_tracking` (`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_commit_session` ON `commit_tracking` (`session_id`);--> statement-breakpoint\nCREATE INDEX `idx_commit_sha` ON `commit_tracking` (`commit_sha`);--> statement-breakpoint\nCREATE TABLE `creator_contribution_staging` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`dedupe_key` text NOT NULL,\n\t`skill_name` text NOT NULL,\n\t`creator_id` text NOT NULL,\n\t`payload_json` text NOT NULL,\n\t`status` text DEFAULT 'pending' NOT NULL,\n\t`staged_at` text NOT NULL,\n\t`updated_at` text NOT NULL,\n\t`last_error` text\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `idx_creator_contrib_dedup` ON `creator_contribution_staging` (`dedupe_key`);--> statement-breakpoint\nCREATE INDEX `idx_creator_contrib_skill` ON `creator_contribution_staging` (`skill_name`);--> statement-breakpoint\nCREATE INDEX `idx_creator_contrib_status` ON `creator_contribution_staging` (`status`);--> statement-breakpoint\nCREATE TABLE `cron_runs` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`job_name` text NOT NULL,\n\t`started_at` text NOT NULL,\n\t`elapsed_ms` integer NOT NULL,\n\t`status` text NOT NULL,\n\t`metrics_json` text,\n\t`error` text\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `cron_runs_job_started_unique` ON `cron_runs` (`job_name`,`started_at`);--> statement-breakpoint\nCREATE INDEX `idx_cron_runs_job_ts` ON `cron_runs` (`job_name`,`started_at`);--> statement-breakpoint\nCREATE TABLE `evolution_audit` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`timestamp` text NOT NULL,\n\t`proposal_id` text NOT NULL,\n\t`skill_name` text,\n\t`action` text NOT NULL,\n\t`details` text,\n\t`eval_snapshot_json` text,\n\t`iterations_used` integer,\n\t`validation_mode` text,\n\t`validation_agent` text,\n\t`validation_fixture_id` text,\n\t`validation_evidence_ref` text\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `idx_evo_audit_dedup` ON `evolution_audit` (`proposal_id`,`action`,`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_evo_audit_action` ON `evolution_audit` (`action`);--> statement-breakpoint\nCREATE INDEX `idx_evo_audit_ts` ON `evolution_audit` (`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_evo_audit_proposal` ON `evolution_audit` (`proposal_id`);--> statement-breakpoint\nCREATE TABLE `evolution_evidence` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`timestamp` text NOT NULL,\n\t`proposal_id` text NOT NULL,\n\t`skill_name` text NOT NULL,\n\t`skill_path` text,\n\t`target` text,\n\t`stage` text,\n\t`rationale` text,\n\t`confidence` real,\n\t`details` text,\n\t`original_text` text,\n\t`proposed_text` text,\n\t`eval_set_json` text,\n\t`validation_json` text\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `idx_evo_evidence_dedup` ON `evolution_evidence` (`proposal_id`,`stage`,`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_evo_evidence_ts` ON `evolution_evidence` (`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_evo_evidence_skill` ON `evolution_evidence` (`skill_name`);--> statement-breakpoint\nCREATE INDEX `idx_evo_evidence_proposal` ON `evolution_evidence` (`proposal_id`);--> statement-breakpoint\nCREATE TABLE `execution_facts` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`session_id` text NOT NULL,\n\t`occurred_at` text,\n\t`prompt_id` text,\n\t`tool_calls_json` text,\n\t`total_tool_calls` integer,\n\t`assistant_turns` integer,\n\t`errors_encountered` integer,\n\t`input_tokens` integer,\n\t`output_tokens` integer,\n\t`duration_ms` integer,\n\t`completion_status` text,\n\t`schema_version` text,\n\t`platform` text,\n\t`normalized_at` text,\n\t`normalizer_version` text,\n\t`capture_mode` text,\n\t`raw_source_ref` text,\n\t`files_changed` integer,\n\t`lines_added` integer,\n\t`lines_removed` integer,\n\t`lines_modified` integer,\n\t`cached_input_tokens` integer,\n\t`reasoning_output_tokens` integer,\n\t`cost_usd` real,\n\t`artifact_count` integer,\n\t`session_type` text,\n\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`session_id`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE INDEX `idx_exec_facts_session` ON `execution_facts` (`session_id`);--> statement-breakpoint\nCREATE TABLE `grading_baselines` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`skill_name` text NOT NULL,\n\t`proposal_id` text,\n\t`measured_at` text NOT NULL,\n\t`pass_rate` real NOT NULL,\n\t`mean_score` real,\n\t`sample_size` integer NOT NULL,\n\t`grading_results_json` text\n);\n--> statement-breakpoint\nCREATE INDEX `idx_grading_bl_skill_proposal` ON `grading_baselines` (`skill_name`,`proposal_id`,`measured_at`);--> statement-breakpoint\nCREATE INDEX `idx_grading_bl_ts` ON `grading_baselines` (`measured_at`);--> statement-breakpoint\nCREATE INDEX `idx_grading_bl_proposal` ON `grading_baselines` (`proposal_id`);--> statement-breakpoint\nCREATE INDEX `idx_grading_bl_skill` ON `grading_baselines` (`skill_name`);--> statement-breakpoint\nCREATE TABLE `grading_results` (\n\t`grading_id` text PRIMARY KEY NOT NULL,\n\t`session_id` text NOT NULL,\n\t`skill_name` text NOT NULL,\n\t`transcript_path` text,\n\t`graded_at` text NOT NULL,\n\t`pass_rate` real,\n\t`mean_score` real,\n\t`score_std_dev` real,\n\t`passed_count` integer,\n\t`failed_count` integer,\n\t`total_count` integer,\n\t`expectations_json` text,\n\t`claims_json` text,\n\t`eval_feedback_json` text,\n\t`failure_feedback_json` text,\n\t`execution_metrics_json` text\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `idx_grading_dedup` ON `grading_results` (`session_id`,`skill_name`,`graded_at`);--> statement-breakpoint\nCREATE INDEX `idx_grading_ts` ON `grading_results` (`graded_at`);--> statement-breakpoint\nCREATE INDEX `idx_grading_skill` ON `grading_results` (`skill_name`);--> statement-breakpoint\nCREATE INDEX `idx_grading_session` ON `grading_results` (`session_id`);--> statement-breakpoint\nCREATE TABLE `improvement_signals` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`timestamp` text NOT NULL,\n\t`session_id` text NOT NULL,\n\t`query` text NOT NULL,\n\t`signal_type` text NOT NULL,\n\t`mentioned_skill` text,\n\t`consumed` integer DEFAULT 0 NOT NULL,\n\t`consumed_at` text,\n\t`consumed_by_run` text\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `idx_signals_dedup` ON `improvement_signals` (`session_id`,`query`,`signal_type`,`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_signals_ts` ON `improvement_signals` (`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_signals_consumed` ON `improvement_signals` (`consumed`);--> statement-breakpoint\nCREATE INDEX `idx_signals_session` ON `improvement_signals` (`session_id`);--> statement-breakpoint\nCREATE TABLE `orchestrate_runs` (\n\t`run_id` text PRIMARY KEY NOT NULL,\n\t`timestamp` text NOT NULL,\n\t`elapsed_ms` integer NOT NULL,\n\t`dry_run` integer NOT NULL,\n\t`approval_mode` text NOT NULL,\n\t`total_skills` integer NOT NULL,\n\t`evaluated` integer NOT NULL,\n\t`evolved` integer NOT NULL,\n\t`deployed` integer NOT NULL,\n\t`watched` integer NOT NULL,\n\t`skipped` integer NOT NULL,\n\t`skill_actions_json` text NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `idx_orchestrate_runs_ts` ON `orchestrate_runs` (`timestamp`);--> statement-breakpoint\nCREATE TABLE `package_candidates` (\n\t`candidate_id` text PRIMARY KEY NOT NULL,\n\t`skill_name` text NOT NULL,\n\t`skill_path` text NOT NULL,\n\t`package_fingerprint` text NOT NULL,\n\t`parent_candidate_id` text,\n\t`candidate_generation` integer DEFAULT 0 NOT NULL,\n\t`evaluation_count` integer DEFAULT 0 NOT NULL,\n\t`first_evaluated_at` text NOT NULL,\n\t`last_evaluated_at` text NOT NULL,\n\t`latest_status` text NOT NULL,\n\t`latest_evaluation_source` text,\n\t`latest_acceptance_decision` text,\n\t`artifact_path` text,\n\t`summary_json` text NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `package_candidates_skill_fingerprint_unique` ON `package_candidates` (`skill_name`,`package_fingerprint`);--> statement-breakpoint\nCREATE INDEX `idx_package_candidates_parent` ON `package_candidates` (`parent_candidate_id`);--> statement-breakpoint\nCREATE INDEX `idx_package_candidates_skill_ts` ON `package_candidates` (`skill_name`,`last_evaluated_at`);--> statement-breakpoint\nCREATE TABLE `package_evaluation_reports` (\n\t`skill_name` text PRIMARY KEY NOT NULL,\n\t`stored_at` text NOT NULL,\n\t`summary_json` text NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `idx_package_evaluation_reports_stored_at` ON `package_evaluation_reports` (`stored_at`);--> statement-breakpoint\nCREATE TABLE `package_search_runs` (\n\t`search_id` text PRIMARY KEY NOT NULL,\n\t`skill_name` text NOT NULL,\n\t`parent_candidate_id` text,\n\t`winner_candidate_id` text,\n\t`winner_rationale` text,\n\t`candidates_evaluated` integer NOT NULL,\n\t`provenance_json` text NOT NULL,\n\t`started_at` text NOT NULL,\n\t`completed_at` text NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `idx_pkg_search_ts` ON `package_search_runs` (`started_at`);--> statement-breakpoint\nCREATE INDEX `idx_pkg_search_skill` ON `package_search_runs` (`skill_name`);--> statement-breakpoint\nCREATE TABLE `prompts` (\n\t`prompt_id` text PRIMARY KEY NOT NULL,\n\t`session_id` text NOT NULL,\n\t`occurred_at` text,\n\t`prompt_kind` text,\n\t`is_actionable` integer,\n\t`prompt_index` integer,\n\t`prompt_text` text,\n\t`schema_version` text,\n\t`platform` text,\n\t`normalized_at` text,\n\t`normalizer_version` text,\n\t`capture_mode` text,\n\t`raw_source_ref` text,\n\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`session_id`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE INDEX `idx_prompts_occurred` ON `prompts` (`occurred_at`);--> statement-breakpoint\nCREATE INDEX `idx_prompts_session` ON `prompts` (`session_id`);--> statement-breakpoint\nCREATE TABLE `queries` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`timestamp` text NOT NULL,\n\t`session_id` text NOT NULL,\n\t`query` text NOT NULL,\n\t`source` text\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `idx_queries_dedup` ON `queries` (`session_id`,`query`,`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_queries_ts` ON `queries` (`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_queries_session` ON `queries` (`session_id`);--> statement-breakpoint\nCREATE TABLE `replay_entry_results` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`proposal_id` text NOT NULL,\n\t`skill_name` text NOT NULL,\n\t`validation_mode` text NOT NULL,\n\t`phase` text NOT NULL,\n\t`query` text NOT NULL,\n\t`should_trigger` integer NOT NULL,\n\t`triggered` integer NOT NULL,\n\t`passed` integer NOT NULL,\n\t`evidence` text\n);\n--> statement-breakpoint\nCREATE INDEX `idx_replay_entry_proposal_phase` ON `replay_entry_results` (`proposal_id`,`phase`);--> statement-breakpoint\nCREATE INDEX `idx_replay_entry_passed` ON `replay_entry_results` (`passed`);--> statement-breakpoint\nCREATE INDEX `idx_replay_entry_skill` ON `replay_entry_results` (`skill_name`);--> statement-breakpoint\nCREATE INDEX `idx_replay_entry_proposal` ON `replay_entry_results` (`proposal_id`);--> statement-breakpoint\nCREATE TABLE `session_telemetry` (\n\t`session_id` text PRIMARY KEY NOT NULL,\n\t`timestamp` text NOT NULL,\n\t`cwd` text,\n\t`transcript_path` text,\n\t`tool_calls_json` text,\n\t`total_tool_calls` integer,\n\t`bash_commands_json` text,\n\t`skills_triggered_json` text,\n\t`skills_invoked_json` text,\n\t`assistant_turns` integer,\n\t`errors_encountered` integer,\n\t`transcript_chars` integer,\n\t`last_user_query` text,\n\t`source` text,\n\t`input_tokens` integer,\n\t`output_tokens` integer,\n\t`files_changed` integer,\n\t`lines_added` integer,\n\t`lines_removed` integer,\n\t`lines_modified` integer,\n\t`cached_input_tokens` integer,\n\t`reasoning_output_tokens` integer,\n\t`cost_usd` real,\n\t`artifact_count` integer,\n\t`session_type` text,\n\t`agent_summary` text\n);\n--> statement-breakpoint\nCREATE INDEX `idx_session_tel_ts` ON `session_telemetry` (`timestamp`);--> statement-breakpoint\nCREATE TABLE `sessions` (\n\t`session_id` text PRIMARY KEY NOT NULL,\n\t`started_at` text,\n\t`ended_at` text,\n\t`platform` text,\n\t`model` text,\n\t`completion_status` text,\n\t`source_session_kind` text,\n\t`agent_cli` text,\n\t`workspace_path` text,\n\t`repo_remote` text,\n\t`branch` text,\n\t`schema_version` text,\n\t`normalized_at` text,\n\t`normalizer_version` text,\n\t`capture_mode` text,\n\t`raw_source_ref` text\n);\n--> statement-breakpoint\nCREATE TABLE `skill_invocations` (\n\t`skill_invocation_id` text PRIMARY KEY NOT NULL,\n\t`session_id` text NOT NULL,\n\t`occurred_at` text,\n\t`skill_name` text NOT NULL,\n\t`invocation_mode` text,\n\t`triggered` integer,\n\t`confidence` real,\n\t`tool_name` text,\n\t`matched_prompt_id` text,\n\t`agent_type` text,\n\t`query` text,\n\t`skill_path` text,\n\t`skill_version_hash` text,\n\t`skill_scope` text,\n\t`source` text,\n\t`schema_version` text,\n\t`platform` text,\n\t`normalized_at` text,\n\t`normalizer_version` text,\n\t`capture_mode` text,\n\t`raw_source_ref` text,\n\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`session_id`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE INDEX `idx_skill_inv_dedup` ON `skill_invocations` (`session_id`,`skill_name`,`query`,`occurred_at`,`triggered`);--> statement-breakpoint\nCREATE INDEX `idx_skill_inv_version` ON `skill_invocations` (`skill_name`,`skill_version_hash`,`occurred_at`);--> statement-breakpoint\nCREATE INDEX `idx_skill_inv_scope` ON `skill_invocations` (`skill_name`,`skill_scope`,`occurred_at`);--> statement-breakpoint\nCREATE INDEX `idx_skill_inv_query_triggered` ON `skill_invocations` (`query`,`triggered`);--> statement-breakpoint\nCREATE INDEX `idx_skill_inv_ts` ON `skill_invocations` (`occurred_at`);--> statement-breakpoint\nCREATE INDEX `idx_skill_inv_name` ON `skill_invocations` (`skill_name`);--> statement-breakpoint\nCREATE INDEX `idx_skill_inv_session` ON `skill_invocations` (`session_id`);--> statement-breakpoint\nCREATE TABLE `skill_usage` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`timestamp` text NOT NULL,\n\t`session_id` text NOT NULL,\n\t`skill_name` text NOT NULL,\n\t`skill_path` text,\n\t`skill_scope` text,\n\t`query` text,\n\t`triggered` integer,\n\t`source` text\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `idx_skill_usage_dedup` ON `skill_usage` (`session_id`,`skill_name`,`query`,`timestamp`,`triggered`);--> statement-breakpoint\nCREATE INDEX `idx_skill_usage_scope` ON `skill_usage` (`skill_name`,`skill_scope`,`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_skill_usage_query_triggered` ON `skill_usage` (`query`,`triggered`);--> statement-breakpoint\nCREATE INDEX `idx_skill_usage_ts` ON `skill_usage` (`timestamp`);--> statement-breakpoint\nCREATE INDEX `idx_skill_usage_name` ON `skill_usage` (`skill_name`);--> statement-breakpoint\nCREATE INDEX `idx_skill_usage_session` ON `skill_usage` (`session_id`);--> statement-breakpoint\nCREATE TABLE `unit_test_files` (\n\t`skill_name` text PRIMARY KEY NOT NULL,\n\t`stored_at` text NOT NULL,\n\t`tests_json` text NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `idx_unit_test_files_stored_at` ON `unit_test_files` (`stored_at`);--> statement-breakpoint\nCREATE TABLE `unit_test_run_results` (\n\t`skill_name` text PRIMARY KEY NOT NULL,\n\t`run_at` text NOT NULL,\n\t`total` integer NOT NULL,\n\t`passed` integer NOT NULL,\n\t`failed` integer NOT NULL,\n\t`pass_rate` real NOT NULL,\n\t`result_json` text NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `idx_unit_test_run_results_run_at` ON `unit_test_run_results` (`run_at`);--> statement-breakpoint\nCREATE TABLE `upload_queue` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`payload_type` text NOT NULL,\n\t`payload_json` text NOT NULL,\n\t`status` text DEFAULT 'pending' NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`created_at` text NOT NULL,\n\t`updated_at` text NOT NULL,\n\t`last_error` text\n);\n--> statement-breakpoint\nCREATE INDEX `idx_upload_queue_type_status` ON `upload_queue` (`payload_type`,`status`);--> statement-breakpoint\nCREATE INDEX `idx_upload_queue_status` ON `upload_queue` (`status`);--> statement-breakpoint\nCREATE TABLE `upload_watermarks` (\n\t`payload_type` text PRIMARY KEY NOT NULL,\n\t`last_uploaded_id` integer NOT NULL,\n\t`updated_at` text NOT NULL\n);\n", "0001_fast_zombie.sql": @@ -40,4 +40,8 @@ export default { "CREATE TABLE `promoted_study_case_retirements` (\n\t`retirement_id` text PRIMARY KEY NOT NULL,\n\t`case_id` text NOT NULL,\n\t`actor` text NOT NULL,\n\t`reason` text NOT NULL,\n\t`prior_manifest_digest` text NOT NULL,\n\t`retired_at` text NOT NULL,\n\tFOREIGN KEY (`case_id`) REFERENCES `promoted_study_cases`(`case_id`) ON UPDATE no action ON DELETE restrict\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `promoted_study_case_retirements_case_unique` ON `promoted_study_case_retirements` (`case_id`);--> statement-breakpoint\nCREATE INDEX `idx_promoted_study_case_retirements_case` ON `promoted_study_case_retirements` (`case_id`,`retired_at`);\n--> statement-breakpoint\nCREATE TABLE `correction_candidate_evaluations` (\n\t`evaluation_id` text PRIMARY KEY NOT NULL, `candidate_id` text NOT NULL, `current_revision` text NOT NULL, `candidate_revision` text NOT NULL,\n\t`evidence_level` text NOT NULL, `status` text NOT NULL, `reason` text, `blind_manifest_json` text NOT NULL, `blind_result_json` text NOT NULL,\n\t`verifier_provenance` text NOT NULL, `runtime_provenance` text NOT NULL, `cost_estimate` text, `cost_actual` text, `applies_change` text NOT NULL, `recorded_at` text NOT NULL,\n\tFOREIGN KEY (`candidate_id`) REFERENCES `correction_signal_candidates`(`candidate_id`) ON UPDATE no action ON DELETE restrict\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `correction_candidate_evaluations_candidate_unique` ON `correction_candidate_evaluations` (`evaluation_id`,`candidate_id`);--> statement-breakpoint\nCREATE INDEX `idx_correction_candidate_evaluations_candidate` ON `correction_candidate_evaluations` (`candidate_id`,`recorded_at`);\n", "0018_drop_legacy_evaluation_draft_identity.sql": "DROP INDEX IF EXISTS `evaluation_submission_drafts_identity_unique`;\n", + "0019_narrow_magma.sql": + "CREATE TABLE `skill_local_revisions` (\n\t`package_path` text NOT NULL,\n\t`revision` integer NOT NULL,\n\t`content_hash` text NOT NULL,\n\t`captured_at` text NOT NULL,\n\t`reason` text NOT NULL,\n\t`restored_from` integer,\n\t`snapshot_json` text NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `idx_skill_local_revisions_path_version` ON `skill_local_revisions` (`package_path`,`revision`);", + "0020_numerous_apocalypse.sql": + "CREATE INDEX `idx_session_tel_cwd` ON `session_telemetry` (`cwd`);--> statement-breakpoint\nCREATE INDEX `idx_sessions_workspace_path` ON `sessions` (`workspace_path`);", } as const; diff --git a/packages/local-store/src/evaluation-submission-drafts.ts b/packages/local-store/src/evaluation-submission-drafts.ts index f7a19105..25714090 100644 --- a/packages/local-store/src/evaluation-submission-drafts.ts +++ b/packages/local-store/src/evaluation-submission-drafts.ts @@ -68,7 +68,7 @@ export class MarkEvaluationSubmissionDraftStale extends Schema.Class()( +export class EvaluationSubmissionDraftFailure extends Schema.TaggedError()( "EvaluationSubmissionDraftFailure", { operation: Schema.String, message: Schema.String }, ) {} diff --git a/packages/local-store/src/index.ts b/packages/local-store/src/index.ts index 167d474b..d765e0cf 100644 --- a/packages/local-store/src/index.ts +++ b/packages/local-store/src/index.ts @@ -5,3 +5,4 @@ export * from "./correction-studies.js"; export * from "./correction-signal-study-drafts.js"; export * from "./correction-review-controls.js"; export { SELFTUNE_CONFIG_DIR } from "./paths.js"; +export * from "./skill-revisions.js"; diff --git a/packages/local-store/src/skill-revision-schema.ts b/packages/local-store/src/skill-revision-schema.ts new file mode 100644 index 00000000..45c19cf1 --- /dev/null +++ b/packages/local-store/src/skill-revision-schema.ts @@ -0,0 +1,17 @@ +import { integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; + +export const skill_local_revisions = sqliteTable( + "skill_local_revisions", + { + package_path: text().notNull(), + revision: integer().notNull(), + content_hash: text().notNull(), + captured_at: text().notNull(), + reason: text().notNull(), + restored_from: integer(), + snapshot_json: text().notNull(), + }, + (table) => [ + uniqueIndex("idx_skill_local_revisions_path_version").on(table.package_path, table.revision), + ], +); diff --git a/packages/local-store/src/skill-revisions.ts b/packages/local-store/src/skill-revisions.ts new file mode 100644 index 00000000..5e8012a7 --- /dev/null +++ b/packages/local-store/src/skill-revisions.ts @@ -0,0 +1,57 @@ +import type { Database } from "bun:sqlite"; +import type { skill_local_revisions } from "./drizzle-schema.js"; + +export type StoredSkillRevision = typeof skill_local_revisions.$inferSelect; +export type SkillRevisionSummary = Omit; + +export function listSkillRevisions( + db: Database, + path: string, + before = Number.MAX_SAFE_INTEGER, +): SkillRevisionSummary[] { + return db + .query( + `SELECT package_path, revision, content_hash, captured_at, reason, restored_from + FROM skill_local_revisions WHERE package_path = ? AND revision < ? ORDER BY revision DESC LIMIT 50`, + ) + .all(path, before); +} + +export function getSkillRevision( + db: Database, + path: string, + revision: number, +): StoredSkillRevision | null { + return db + .query( + "SELECT * FROM skill_local_revisions WHERE package_path = ? AND revision = ?", + ) + .get(path, revision); +} + +export function recordSkillRevision( + db: Database, + input: Omit, +): SkillRevisionSummary { + return db + .transaction(() => { + const latest = listSkillRevisions(db, input.package_path)[0]; + if (latest?.content_hash === input.content_hash && input.restored_from === null) + return latest; + const revision = (latest?.revision ?? 0) + 1; + db.query(`INSERT INTO skill_local_revisions + (package_path, revision, content_hash, captured_at, reason, restored_from, snapshot_json) + VALUES (?, ?, ?, ?, ?, ?, ?)`).run( + input.package_path, + revision, + input.content_hash, + input.captured_at, + input.reason, + input.restored_from, + input.snapshot_json, + ); + const { snapshot_json: _snapshot, ...summary } = input; + return { ...summary, revision }; + }) + .immediate(); +} diff --git a/packages/observability/package.json b/packages/observability/package.json index 55e75d46..9c9bb2b2 100644 --- a/packages/observability/package.json +++ b/packages/observability/package.json @@ -12,6 +12,9 @@ "./otlp": "./src/otlp.ts", "./duckdb-store": "./src/duckdb-store.ts", "./duckdb-node-api": "./src/duckdb-node-api.ts", + "./storage-capacity": "./src/storage-capacity.ts", + "./source-reconstruction": "./src/source-reconstruction.ts", + "./source-identity": "./src/source-identity.ts", "./duckdb-module-resolution": "./src/duckdb-module-resolution.ts", "./evidence-cohort": "./src/evidence-cohort.ts", "./historical-backfill": "./src/historical-backfill.ts", @@ -25,7 +28,7 @@ "@duckdb/node-api": "1.4.5-r.1", "@opentelemetry/otlp-transformer": "0.206.0", "@selftune/config": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/packages/observability/src/duckdb-node-api.ts b/packages/observability/src/duckdb-node-api.ts index cdd883de..c396e217 100644 --- a/packages/observability/src/duckdb-node-api.ts +++ b/packages/observability/src/duckdb-node-api.ts @@ -3,6 +3,7 @@ import { constants } from "node:fs"; import { copyFile, lstat, mkdir, rename } from "node:fs/promises"; import { basename, dirname, join } from "node:path"; import { pathToFileURL } from "node:url"; +import * as Schema from "effect/Schema"; import { makeDuckDbAnalyticalStoreLive, @@ -11,6 +12,12 @@ import { type DuckDbInstanceFactory, } from "./duckdb-store.js"; import { resolvePackagedDuckDbModule } from "./duckdb-module-resolution.js"; +import { + ANALYTICAL_RECOVERY_RESERVE_BYTES, + availableStorageBytes, + inspectAnalyticalStorageFiles, + requireStorageCapacity, +} from "./storage-capacity.js"; const packagedDuckDbModule = resolvePackagedDuckDbModule({ desktopResourceDirectory: process.env.SELFTUNE_DESKTOP_RESOURCE_DIR, @@ -30,11 +37,13 @@ const { DuckDBInstance, DuckDBTimestampValue } = duckDbModule as typeof import(" export const DUCKDB_LOCAL_MEMORY_LIMIT = "512MB"; interface DuckDbWalRecoveryFileStat { + readonly size: bigint; readonly isFile: () => boolean; readonly isSymbolicLink: () => boolean; } export interface DuckDbWalRecoveryDependencies { + readonly availableBytes: (directory: string) => Promise; readonly copyFile: (source: string, destination: string, mode?: number) => Promise; readonly lstat: (path: string) => Promise; readonly mkdir: ( @@ -110,6 +119,12 @@ export async function openDuckDbWithWalRecovery( } assertRegularNonSymlinkFile(walPath, walStat); + const reserve = ANALYTICAL_RECOVERY_RESERVE_BYTES + walStat.size; + requireStorageCapacity( + await dependencies.availableBytes(dirname(databasePath)), + databaseStat.size + reserve, + ); + const backupRoot = join(dirname(databasePath), "backups"); await dependencies.mkdir(backupRoot, { recursive: true, mode: 0o700 }); const backupDirectory = join( @@ -123,6 +138,8 @@ export async function openDuckDbWithWalRecovery( constants.COPYFILE_EXCL, ); + requireStorageCapacity(await dependencies.availableBytes(dirname(databasePath)), reserve); + try { await dependencies.rename(walPath, join(backupDirectory, basename(walPath))); } catch (cause) { @@ -139,8 +156,9 @@ export async function openDuckDbWithWalRecovery( const liveWalRecoveryDependencies = ( open: (databasePath: string) => Promise, ): DuckDbWalRecoveryDependencies => ({ + availableBytes: availableStorageBytes, copyFile, - lstat, + lstat: (path) => lstat(path, { bigint: true }), mkdir, now: () => new Date(), open, @@ -175,7 +193,9 @@ function appendScalar( * behind the analytical-store contract so callers cannot acquire arbitrary * DuckDB connections or couple operational code to the driver. */ -const duckDbNodeApiFactory: DuckDbInstanceFactory = { +const makeDuckDbNodeApiFactory = ( + readAvailableBytes: (directory: string) => Promise, +): DuckDbInstanceFactory => ({ open: async (databasePath) => { const instance = await openDuckDbWithWalRecovery( databasePath, @@ -206,15 +226,120 @@ const duckDbNodeApiFactory: DuckDbInstanceFactory = { } }, closeSync: () => nativeConnection.closeSync(), - run: (sql, parameters) => nativeConnection.run(sql, parameters), + run: async (sql, parameters) => { + if (databasePath !== ":memory:" && sql === "BEGIN TRANSACTION") { + requireStorageCapacity( + await readAvailableBytes(dirname(databasePath)), + ANALYTICAL_RECOVERY_RESERVE_BYTES, + ); + } + return nativeConnection.run(sql, parameters); + }, }; return connection; }, }; }, -}; +}); -export const makeDuckDbNodeApiAnalyticalStoreLive = (databasePath?: string) => - makeDuckDbAnalyticalStoreLive(duckDbNodeApiFactory, databasePath); +export const makeDuckDbNodeApiAnalyticalStoreLive = ( + databasePath?: string, + readAvailableBytes: (directory: string) => Promise = availableStorageBytes, +) => makeDuckDbAnalyticalStoreLive(makeDuckDbNodeApiFactory(readAvailableBytes), databasePath); export const DuckDbAnalyticalStoreLive = makeDuckDbNodeApiAnalyticalStoreLive(); + +const StorageCatalogTable = Schema.Struct({ + table_name: Schema.String, + estimated_rows: Schema.String, + index_count: Schema.String, +}); +const StorageBlocks = Schema.Struct({ + block_size: Schema.String, + total_blocks: Schema.String, + used_blocks: Schema.String, + free_blocks: Schema.String, + wal_size: Schema.String, +}); +const EngineVersion = Schema.Struct({ engine_version: Schema.String }); +const MigrationLedgerPresence = Schema.Struct({ present: Schema.Boolean }); +const StoredSchemaVersion = Schema.Struct({ version: Schema.String }); + +/** Explicit diagnostics, outside the mutating live-store acquisition/migration path. */ +export async function inspectAnalyticalStorage(databasePath: string) { + const files = await inspectAnalyticalStorageFiles(databasePath); + if (files.database.state !== "present") { + return { files, catalog: { state: "unavailable", reason: files.database.state } }; + } + const instance = await DuckDBInstance.create(databasePath, { + access_mode: "READ_ONLY", + memory_limit: "128MB", + max_temp_directory_size: "0B", + threads: "1", + }); + try { + const connection = await instance.connect(); + try { + const version = await connection.run("SELECT version() AS engine_version"); + const engine = Schema.decodeUnknownSync(Schema.Array(EngineVersion))( + await version.getRowObjects(), + ); + const sizes = await connection.run(`SELECT + CAST(block_size AS VARCHAR) AS block_size, + CAST(total_blocks AS VARCHAR) AS total_blocks, + CAST(used_blocks AS VARCHAR) AS used_blocks, + CAST(free_blocks AS VARCHAR) AS free_blocks, + wal_size + FROM pragma_database_size()`); + const blocks = Schema.decodeUnknownSync(Schema.Array(StorageBlocks))( + await sizes.getRowObjects(), + ); + const tables = await connection.run(`SELECT table_name, + CAST(estimated_size AS VARCHAR) AS estimated_rows, + CAST(index_count AS VARCHAR) AS index_count + FROM duckdb_tables() + WHERE schema_name = 'main' AND starts_with(table_name, 'observability_') + ORDER BY table_name LIMIT 64`); + const catalog = Schema.decodeUnknownSync(Schema.Array(StorageCatalogTable))( + await tables.getRowObjects(), + ); + const ledgerPresence = await connection.run(`SELECT EXISTS ( + SELECT 1 FROM duckdb_tables() + WHERE schema_name = 'main' AND table_name = 'observability_schema_migrations' + ) AS present`); + const [ledger] = Schema.decodeUnknownSync(Schema.Array(MigrationLedgerPresence))( + await ledgerPresence.getRowObjects(), + ); + const schemaVersion = ledger?.present + ? Schema.decodeUnknownSync(Schema.Array(StoredSchemaVersion))( + await ( + await connection.run(`SELECT CAST(version AS VARCHAR) AS version + FROM main.observability_schema_migrations ORDER BY version DESC LIMIT 1`) + ).getRowObjects(), + )[0]?.version + : undefined; + return { + files, + catalog: { + state: "available", + engine, + stored_schema: + schemaVersion === undefined + ? { + state: "unavailable", + reason: ledger?.present ? "empty_ledger" : "missing_ledger", + } + : { state: "available", version: schemaVersion }, + blocks, + tables: catalog, + row_counts: "estimates_not_exact", + table_limit: 64, + }, + }; + } finally { + connection.closeSync(); + } + } finally { + instance.closeSync(); + } +} diff --git a/packages/observability/src/duckdb-store.ts b/packages/observability/src/duckdb-store.ts index 6e76f6a8..88b66ae1 100644 --- a/packages/observability/src/duckdb-store.ts +++ b/packages/observability/src/duckdb-store.ts @@ -9,6 +9,19 @@ import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; import { EvidenceCohortCandidate, EvidenceCohortPattern } from "./evidence-cohort.js"; +import { + durableSummaryMigration, + retainBatchSummaries, + sourceReconstructionMigration, + sourceIdentityMigration, +} from "./durable-summary-sql.js"; +import { SourceIdentities, sourceIdentityKey } from "./source-identity.js"; +import { + SourceReconstruction, + sourceDigest, + type SourceTaskResolution, +} from "./source-reconstruction.js"; +import { createHash } from "node:crypto"; const TraceId = Schema.String.check( Schema.isLengthBetween(32, 32), @@ -240,6 +253,8 @@ export class DuckDbAnalyticalBatch extends Schema.Class( batch_id: BoundedText, source_revision: BoundedText, normalizer_version: BoundedText, + reconstruction: Schema.optionalKey(SourceReconstruction), + source_identities: Schema.optionalKey(SourceIdentities), spans: Schema.Array(DuckDbTraceSpan).check(Schema.isMaxLength(256)), links: Schema.Array(DuckDbTraceSkillLink).check(Schema.isMaxLength(256)), resources: Schema.optionalKey(Schema.Array(DuckDbTraceResource).check(Schema.isMaxLength(64))), @@ -324,7 +339,7 @@ export class DuckDbAnalyticalStoreHealth extends Schema.Class()( +export class DuckDbAnalyticalStoreFailure extends Schema.TaggedError()( "DuckDbAnalyticalStoreFailure", { operation: Schema.String, message: Schema.String }, ) {} @@ -375,6 +390,9 @@ export interface DuckDbInstanceFactory { } export interface DuckDbAnalyticalStoreService { + readonly resolveSourceTask: ( + input: SourceTaskRequest, + ) => Effect.Effect; /** * Verifies the durable analytical receipt for one normalized source revision. * This is intentionally a domain operation rather than exposing DuckDB query @@ -406,6 +424,40 @@ export interface DuckDbAnalyticalStoreService { readonly health: () => Effect.Effect; } +export interface SourceTaskRequest { + readonly trace_id: string; + readonly span_id: string; + readonly skill_invocation_id: string; + readonly skill_revision: string; + readonly source_revision: string; + readonly pin_id: string; + readonly replay: (input: { + readonly signal: AbortSignal; + readonly batch_id: string; + readonly source_revision: string; + readonly normalizer_version: string; + readonly reconstruction: SourceReconstruction; + }) => Promise< + | { + readonly state: "reconstructed"; + readonly task: string; + readonly batch: typeof DuckDbAnalyticalBatch.Encoded; + } + | Extract + >; +} + +/** Schema order makes the fingerprint independent of caller object construction order. */ +export function analyticalBatchDigest(input: typeof DuckDbAnalyticalBatch.Encoded): string { + const decoded = Schema.decodeUnknownSync(DuckDbAnalyticalBatch)(input); + const { + reconstruction: _proof, + source_identities: _identity, + ...facts + } = Schema.encodeSync(DuckDbAnalyticalBatch)(decoded); + return createHash("sha256").update(JSON.stringify(facts)).digest("hex"); +} + export class DuckDbAnalyticalStore extends Context.Service< DuckDbAnalyticalStore, DuckDbAnalyticalStoreService @@ -967,15 +1019,24 @@ const migrate = Effect.fn("DuckDbAnalyticalStore.migrate")(function* ( const migrationVersion = Schema.is(Schema.Union([Schema.Number, Schema.BigInt]))(existingVersion) ? Number(existingVersion) : 0; - if (migrationVersion > 9) { + if (migrationVersion > 12) { return yield* Effect.fail( DuckDbAnalyticalStoreFailure.make({ operation: "migrate DuckDB analytical store", - message: `DuckDB schema version ${migrationVersion} is newer than supported version 9.`, + message: `DuckDB schema version ${migrationVersion} is newer than supported version 12.`, }), ); } - if (migrationVersion >= 9) return; + if (migrationVersion >= 12) return; + if (migrationVersion >= 9) { + if (migrationVersion === 9) + for (const statement of durableSummaryMigration) yield* runStatement(connection, statement); + if (migrationVersion < 11) + for (const statement of sourceReconstructionMigration) + yield* runStatement(connection, statement); + for (const statement of sourceIdentityMigration) yield* runStatement(connection, statement); + return; + } const hadMigration = migrationVersion > 0; for (const statement of schemaStatements) yield* runStatement(connection, statement); if (!hadMigration) { @@ -989,6 +1050,10 @@ const migrate = Effect.fn("DuckDbAnalyticalStore.migrate")(function* ( for (const statement of v7MigrationStatements) yield* runStatement(connection, statement); for (const statement of v8MigrationStatements) yield* runStatement(connection, statement); for (const statement of v9MigrationStatements) yield* runStatement(connection, statement); + for (const statement of durableSummaryMigration) yield* runStatement(connection, statement); + for (const statement of sourceReconstructionMigration) + yield* runStatement(connection, statement); + for (const statement of sourceIdentityMigration) yield* runStatement(connection, statement); return; } if (migrationVersion < 4) { @@ -1001,6 +1066,9 @@ const migrate = Effect.fn("DuckDbAnalyticalStore.migrate")(function* ( for (const statement of v7MigrationStatements) yield* runStatement(connection, statement); for (const statement of v8MigrationStatements) yield* runStatement(connection, statement); for (const statement of v9MigrationStatements) yield* runStatement(connection, statement); + for (const statement of durableSummaryMigration) yield* runStatement(connection, statement); + for (const statement of sourceReconstructionMigration) yield* runStatement(connection, statement); + for (const statement of sourceIdentityMigration) yield* runStatement(connection, statement); }); const decodeBatch = (input: typeof DuckDbAnalyticalBatch.Encoded) => @@ -1061,11 +1129,74 @@ const batchDisposition = Effect.fn("DuckDbAnalyticalStore.batchDisposition")(fun : "revised"; }); +const sourceKeys = (batch: DuckDbAnalyticalBatch) => + JSON.stringify([...new Set((batch.source_identities ?? []).map(sourceIdentityKey))]); + +const sourceExpired = Effect.fn("DuckDbAnalyticalStore.sourceExpired")(function* ( + connection: DuckDbConnection, + batchId: string, + incomingKeys = "[]", +) { + const result = yield* runStatement( + connection, + `SELECT 1 AS expired FROM observability_expired_sources + WHERE source_key IN ( + SELECT source_key FROM observability_batch_sources WHERE batch_id = $batch_id + UNION ALL SELECT json_extract_string(value, '$') FROM json_each($source_keys) + ) + UNION ALL SELECT 1 FROM observability_source_reconstruction + WHERE batch_id = $batch_id AND detail_state = 'expired' + LIMIT 1`, + { batch_id: batchId, source_keys: incomingKeys }, + ); + return (yield* readRows(result, "check source expiration")).length > 0; +}); + +const assertSourceActive = Effect.fn("DuckDbAnalyticalStore.assertSourceActive")(function* ( + connection: DuckDbConnection, + batch: DuckDbAnalyticalBatch, +) { + if (yield* sourceExpired(connection, batch.batch_id, sourceKeys(batch))) + return yield* DuckDbAnalyticalStoreFailure.make({ + operation: "ingest analytical source", + message: "Source detail is expired; force sync cannot resurrect expired evidence.", + }); + if (!batch.source_identities) return; + const result = yield* runStatement( + connection, + `SELECT 1 FROM observability_batch_sources WHERE batch_id = $batch_id + AND (source_key NOT IN (SELECT json_extract_string(value, '$') FROM json_each($source_keys)) + OR (SELECT COUNT(*) FROM observability_batch_sources WHERE batch_id = $batch_id) + != (SELECT COUNT(*) FROM json_each($source_keys))) LIMIT 1`, + { batch_id: batch.batch_id, source_keys: sourceKeys(batch) }, + ); + if ((yield* readRows(result, "verify immutable batch source identities")).length > 0) + return yield* DuckDbAnalyticalStoreFailure.make({ + operation: "ingest analytical source", + message: "A qualified batch cannot change its logical source identities.", + }); +}); + +const retainSourceIdentities = Effect.fn("DuckDbAnalyticalStore.retainSourceIdentities")(function* ( + connection: DuckDbConnection, + batch: DuckDbAnalyticalBatch, +) { + if (!batch.source_identities) return; + yield* runStatement( + connection, + `INSERT INTO observability_batch_sources + SELECT $batch_id, json_extract_string(value, '$') FROM json_each($source_keys) + ON CONFLICT DO NOTHING`, + { batch_id: batch.batch_id, source_keys: sourceKeys(batch) }, + ); +}); + const hasExactBatchReceipt = Effect.fn("DuckDbAnalyticalStore.hasExactBatchReceipt")(function* ( connection: DuckDbConnection, input: typeof DuckDbAnalyticalBatch.Encoded, ) { const batch = yield* decodeBatch(input); + yield* assertSourceActive(connection, batch); const result = yield* runStatement( connection, `SELECT 1 AS receipt_exists @@ -1073,11 +1204,18 @@ const hasExactBatchReceipt = Effect.fn("DuckDbAnalyticalStore.hasExactBatchRecei WHERE batch_id = $batch_id AND source_revision = $source_revision AND normalizer_version = $normalizer_version + AND NOT EXISTS ( + SELECT 1 FROM json_each($source_keys) AS incoming + WHERE NOT EXISTS (SELECT 1 FROM observability_batch_sources AS known + WHERE known.batch_id = $batch_id + AND known.source_key = json_extract_string(incoming.value, '$')) + ) LIMIT 1`, { batch_id: batch.batch_id, source_revision: batch.source_revision, normalizer_version: batch.normalizer_version, + source_keys: sourceKeys(batch), }, ); const rows = yield* readRows(result, "verify analytical batch receipt"); @@ -1092,6 +1230,8 @@ const ingestBatch = Effect.fn("DuckDbAnalyticalStore.ingest")(function* ( yield* runStatement(connection, "BEGIN TRANSACTION"); const rollback = () => runStatement(connection, "ROLLBACK").pipe(Effect.ignore); const outcome = yield* Effect.gen(function* () { + yield* assertSourceActive(connection, batch); + yield* retainSourceIdentities(connection, batch); const disposition = yield* batchDisposition(connection, batch); if (disposition === "exact") { yield* runStatement(connection, "COMMIT"); @@ -1105,8 +1245,25 @@ const ingestBatch = Effect.fn("DuckDbAnalyticalStore.ingest")(function* ( }); } + const stateResult = yield* runStatement( + connection, + "SELECT detail_state FROM observability_source_reconstruction WHERE batch_id = $batch_id", + { batch_id: batch.batch_id }, + ); + const stateRows = yield* readRows(stateResult, "read source detail state"); + const detailState = stateRows[0]?.detail_state; if (disposition === "revised") { + yield* runStatement( + connection, + `CREATE OR REPLACE TEMP TABLE observability_revised_metric_keys AS + SELECT DISTINCT trace_id, metric_name + FROM observability_retained_metric_candidates WHERE batch_id = $batch_id`, + { batch_id: batch.batch_id }, + ); for (const table of [ + "observability_summary_receipts", + "observability_span_summaries", + "observability_metric_contributions", "observability_span_links", "observability_logs", "observability_historical_log_skill_links", @@ -1279,6 +1436,9 @@ const ingestBatch = Effect.fn("DuckDbAnalyticalStore.ingest")(function* ( ]), ); const latestPoints = latestMetricPointsInBatch(batch.metric_points ?? []); + for (const statement of retainBatchSummaries) { + yield* runStatement(connection, statement, { batch_id: batch.batch_id }); + } yield* runStatement(connection, "DELETE FROM observability_historical_metric_rollup_staging"); yield* appendRows( connection, @@ -1323,9 +1483,18 @@ const ingestBatch = Effect.fn("DuckDbAnalyticalStore.ingest")(function* ( )`, ); if (disposition === "revised") { - // A revision may remove the current newest point. Rebuild only on this - // rare replacement path so an older surviving batch can become current. - yield* runStatement(connection, "DELETE FROM observability_historical_metric_rollups"); + // Include both removed and newly introduced keys; never rebuild unrelated history. + yield* runStatement( + connection, + `INSERT INTO observability_revised_metric_keys + SELECT trace_id, metric_name FROM observability_historical_metric_rollup_staging`, + ); + yield* runStatement( + connection, + `DELETE FROM observability_historical_metric_rollups AS rollup + WHERE EXISTS (SELECT 1 FROM observability_revised_metric_keys AS affected + WHERE affected.trace_id = rollup.trace_id AND affected.metric_name = rollup.metric_name)`, + ); yield* runStatement( connection, `INSERT INTO observability_historical_metric_rollups ( @@ -1339,10 +1508,13 @@ const ingestBatch = Effect.fn("DuckDbAnalyticalStore.ingest")(function* ( PARTITION BY trace_id, metric_name ORDER BY observed_at DESC, metric_id DESC ) AS point_rank - FROM observability_historical_metric_points + FROM observability_retained_metric_candidates AS point + WHERE EXISTS (SELECT 1 FROM observability_revised_metric_keys AS affected + WHERE affected.trace_id = point.trace_id AND affected.metric_name = point.metric_name) ) AS latest WHERE point_rank = 1`, ); + yield* runStatement(connection, "DROP TABLE observability_revised_metric_keys"); } yield* runStatement(connection, "DELETE FROM observability_historical_metric_rollup_staging"); yield* appendRows( @@ -1370,6 +1542,43 @@ const ingestBatch = Effect.fn("DuckDbAnalyticalStore.ingest")(function* ( batch.batch_id, ]), ); + if (batch.reconstruction) { + yield* runStatement( + connection, + `INSERT INTO observability_source_reconstruction + VALUES ($batch_id, $source_revision, $normalizer_version, $content_sha256, $descriptor_json, $detail_state) + ON CONFLICT (batch_id) DO UPDATE SET + source_revision = excluded.source_revision, normalizer_version = excluded.normalizer_version, + content_sha256 = excluded.content_sha256, descriptor_json = excluded.descriptor_json`, + { + batch_id: batch.batch_id, + source_revision: batch.source_revision, + normalizer_version: batch.normalizer_version, + content_sha256: analyticalBatchDigest(batch), + descriptor_json: JSON.stringify(batch.reconstruction), + detail_state: "resident", + }, + ); + } else if (detailState !== "evicted") { + yield* runStatement( + connection, + "DELETE FROM observability_source_reconstruction WHERE batch_id = $batch_id", + { batch_id: batch.batch_id }, + ); + } + if (detailState === "evicted") { + // Preserve an explicit detail absence across revised imports. No scheduler sets this state. + for (const table of [ + "observability_spans", + "observability_metrics", + "observability_logs", + "observability_historical_metric_points", + ]) { + yield* runStatement(connection, `DELETE FROM ${table} WHERE batch_id = $batch_id`, { + batch_id: batch.batch_id, + }); + } + } yield* runStatement(connection, "COMMIT"); if (disposition === "revised") { // Revised batches delete and reinsert the same indexed identities. Persist that uncommon @@ -1389,6 +1598,139 @@ const ingestBatch = Effect.fn("DuckDbAnalyticalStore.ingest")(function* ( return outcome; }); +const ReconstructionRow = Schema.Struct({ + batch_id: BoundedText, + source_revision: BoundedText, + normalizer_version: BoundedText, + content_sha256: Schema.String, + descriptor_json: Schema.String, + detail_state: Schema.Literals(["resident", "evicted", "expired"]), + pinned: Schema.Boolean, +}); +const SourceTaskIdentity = Schema.Struct({ + trace_id: TraceId, + span_id: SpanId, + skill_invocation_id: BoundedText, + skill_revision: BoundedText, + source_revision: BoundedText, + pin_id: BoundedText, +}); + +const resolveSourceTask = Effect.fn("DuckDbAnalyticalStore.resolveSourceTask")(function* ( + connection: DuckDbConnection, + input: SourceTaskRequest, +): Effect.fn.Return { + const request = yield* Schema.decodeUnknownEffect(SourceTaskIdentity)(input).pipe( + Effect.mapError((error) => + DuckDbAnalyticalStoreFailure.make({ + operation: "decode source task request", + message: error.message, + }), + ), + ); + const result = yield* runStatement( + connection, + `SELECT pin.batch_id, pin.source_revision, + pin.normalizer_version, pin.content_sha256, pin.descriptor_json, + COALESCE(current.detail_state, 'resident') AS detail_state, true AS pinned + FROM observability_source_evidence_pins AS pin + LEFT JOIN observability_source_reconstruction AS current ON current.batch_id = pin.batch_id + WHERE pin.pin_id = $pin_id + UNION ALL + SELECT proof.batch_id, proof.source_revision, proof.normalizer_version, + proof.content_sha256, proof.descriptor_json, proof.detail_state, false AS pinned + FROM observability_source_reconstruction AS proof + JOIN observability_span_summaries AS span ON span.batch_id = proof.batch_id + WHERE span.trace_id = $trace_id AND span.span_id = $span_id + AND NOT EXISTS (SELECT 1 FROM observability_source_evidence_pins WHERE pin_id = $pin_id) + LIMIT 1`, + { pin_id: request.pin_id, trace_id: request.trace_id, span_id: request.span_id }, + ); + const rows = yield* readRows(result, "read exact reconstruction descriptor"); + const [row] = yield* Schema.decodeUnknownEffect(Schema.Array(ReconstructionRow))(rows).pipe( + Effect.mapError((error) => + DuckDbAnalyticalStoreFailure.make({ + operation: "decode reconstruction descriptor", + message: error.message, + }), + ), + ); + if (!row) return { state: "unavailable", reason: "missing" }; + if (row.detail_state === "expired" || (yield* sourceExpired(connection, row.batch_id))) + return { state: "unavailable", reason: "expired" }; + if (row.source_revision !== request.source_revision) + return { state: "unavailable", reason: "projection_changed" }; + const reconstruction = yield* Schema.decodeUnknownEffect( + Schema.fromJsonString(SourceReconstruction), + )(row.descriptor_json).pipe( + Effect.mapError((error) => + DuckDbAnalyticalStoreFailure.make({ + operation: "decode source provenance", + message: error.message, + }), + ), + ); + const binding = reconstruction.bindings.find( + (item) => item.skill_invocation_id === request.skill_invocation_id, + ); + if (!binding?.skill_revision || binding.skill_revision !== request.skill_revision) + return { state: "unavailable", reason: "unverified_skill_revision" }; + const replayed = yield* Effect.tryPromise({ + try: (signal) => input.replay({ ...row, reconstruction, signal }), + catch: (cause) => + DuckDbAnalyticalStoreFailure.make({ + operation: "reconstruct bounded source task", + message: cause instanceof Error ? cause.message : String(cause), + }), + }); + if (replayed.state === "unavailable") return replayed; + if (sourceDigest(Buffer.from(replayed.task)) !== reconstruction.snapshot.task_sha256) + return { state: "unavailable", reason: "projection_changed" }; + const batch = yield* decodeBatch(replayed.batch); + if ( + batch.batch_id !== row.batch_id || + batch.source_revision !== row.source_revision || + batch.normalizer_version !== row.normalizer_version || + analyticalBatchDigest(batch) !== row.content_sha256 || + !batch.links.some( + (link) => + link.trace_id === request.trace_id && + link.span_id === request.span_id && + link.skill_invocation_id === request.skill_invocation_id && + link.skill_name === binding.skill_name, + ) + ) + return { state: "unavailable", reason: "projection_changed" }; + if (Buffer.byteLength(replayed.task, "utf8") > 8192) + return { state: "unavailable", reason: "over_budget" }; + if (!replayed.task.trim()) return { state: "unavailable", reason: "missing" }; + // Pin the exact recipe, not a copied transcript. Saved evaluation artifacts still own their evidence bytes. + if (!row.pinned) + yield* Effect.uninterruptible( + Effect.gen(function* () { + yield* runStatement(connection, "BEGIN TRANSACTION"); + yield* Effect.gen(function* () { + yield* runStatement( + connection, + `INSERT INTO observability_source_evidence_pins + VALUES ($pin_id, $batch_id, $source_revision, $normalizer_version, $content_sha256, $descriptor_json) + ON CONFLICT (pin_id) DO NOTHING`, + { + pin_id: request.pin_id, + batch_id: row.batch_id, + source_revision: row.source_revision, + normalizer_version: row.normalizer_version, + content_sha256: row.content_sha256, + descriptor_json: row.descriptor_json, + }, + ); + yield* runStatement(connection, "COMMIT"); + }).pipe(Effect.onError(() => runStatement(connection, "ROLLBACK").pipe(Effect.ignore))); + }), + ); + return { state: "available", task: replayed.task, source: "verified_original" }; +}); + class SkillSignalRow extends Schema.Class("SkillSignalRow")({ skill_name: BoundedText, invocation_count: MetricCount, @@ -1409,7 +1751,7 @@ const querySkillSignals = Effect.fn("DuckDbAnalyticalStore.querySkillSignals")(f `WITH linked_facts AS ( SELECT DISTINCT link.skill_name, link.skill_invocation_id, link.trace_id, link.span_id FROM observability_trace_skill_links AS link - INNER JOIN observability_spans AS span + INNER JOIN observability_discovery_spans AS span ON span.trace_id = link.trace_id AND span.span_id = link.span_id ), invocation_totals AS ( SELECT @@ -1428,7 +1770,7 @@ const querySkillSignals = Effect.fn("DuckDbAnalyticalStore.querySkillSignals")(f MAX(CASE WHEN metric_name = 'output_tokens' THEN value ELSE 0 END) AS output_tokens, MAX(CASE WHEN metric_name = 'error_count' THEN value ELSE 0 END) AS error_count, MAX(CASE WHEN metric_name = 'tool_call_count' THEN value ELSE 0 END) AS tool_call_count - FROM observability_metrics + FROM observability_discovery_metrics WHERE metric_name IN ('input_tokens', 'output_tokens', 'error_count', 'tool_call_count') GROUP BY trace_id, span_id ), span_totals AS ( @@ -1442,7 +1784,7 @@ const querySkillSignals = Effect.fn("DuckDbAnalyticalStore.querySkillSignals")(f CAST(COALESCE(SUM(metric.error_count), 0) AS DOUBLE) AS error_count, CAST(COALESCE(SUM(metric.tool_call_count), 0) AS DOUBLE) AS tool_call_count FROM skill_spans AS link - INNER JOIN observability_spans AS span + INNER JOIN observability_discovery_spans AS span ON span.trace_id = link.trace_id AND span.span_id = link.span_id LEFT JOIN metric_rollup AS metric ON metric.trace_id = link.trace_id AND metric.span_id = link.span_id @@ -1499,7 +1841,7 @@ const queryEvidenceCohortCandidates = Effect.fn( MAX(CASE WHEN metric_name = 'output_tokens' THEN value ELSE 0 END) AS output_tokens, MAX(CASE WHEN metric_name = 'error_count' THEN value ELSE 0 END) AS error_count, MAX(CASE WHEN metric_name = 'tool_call_count' THEN value ELSE 0 END) AS tool_call_count - FROM observability_metrics + FROM observability_discovery_metrics WHERE metric_name IN ('input_tokens', 'output_tokens', 'error_count', 'tool_call_count') GROUP BY trace_id, span_id ) @@ -1516,7 +1858,7 @@ const queryEvidenceCohortCandidates = Effect.fn( CAST(COALESCE(metric.error_count, 0) AS DOUBLE) AS error_count, CAST(COALESCE(metric.tool_call_count, 0) AS DOUBLE) AS tool_call_count FROM observability_trace_skill_links AS link - INNER JOIN observability_spans AS span + INNER JOIN observability_discovery_spans AS span ON span.trace_id = link.trace_id AND span.span_id = link.span_id INNER JOIN observability_ingested_batches AS batch ON batch.batch_id = span.batch_id LEFT JOIN metric_rollup AS metric @@ -1526,7 +1868,11 @@ const queryEvidenceCohortCandidates = Effect.fn( ORDER BY span.trace_id, span.span_id, link.skill_invocation_id`, { skill_id: query.pattern.skill_id.trim().toLowerCase() }, ); - const rows = yield* readRows(result, "read DuckDB evidence cohort candidates"); + const rows = (yield* readRows(result, "read DuckDB evidence cohort candidates")).map((row) => { + const normalized = { ...row }; + if (normalized.model === null) delete normalized.model; + return normalized; + }); return yield* Schema.decodeUnknownEffect(Schema.Array(EvidenceCohortCandidate))(rows).pipe( Effect.map((decoded) => decoded.map((candidate) => EvidenceCohortCandidate.make(candidate))), Effect.catchTag("SchemaError", (error) => @@ -1567,7 +1913,7 @@ const queryHistoricalSkillTaskReferences = Effect.fn( span.evidence_quality, span.model FROM observability_trace_skill_links AS link - INNER JOIN observability_spans AS span + INNER JOIN observability_discovery_spans AS span ON span.trace_id = link.trace_id AND span.span_id = link.span_id INNER JOIN observability_ingested_batches AS batch ON batch.batch_id = span.batch_id WHERE LOWER(TRIM(link.skill_name)) = $skill_id @@ -1712,7 +2058,7 @@ const health = Effect.fn("DuckDbAnalyticalStore.health")(function* ( ); return DuckDbAnalyticalStoreHealth.make({ database_path: databasePath, - schema_version: 9, + schema_version: 12, ...row, }); }); @@ -1781,6 +2127,8 @@ export function makeDuckDbAnalyticalStoreLive( hasExactBatchReceipt: (input) => semaphore.withPermit(hasExactBatchReceipt(connection, input)), ingest: (input) => semaphore.withPermit(ingestBatch(connection, input)), + resolveSourceTask: (input) => + semaphore.withPermit(resolveSourceTask(connection, input)), querySkillSignals: () => semaphore.withPermit(querySkillSignals(connection)), queryEvidenceCohortCandidates: (input) => semaphore.withPermit(queryEvidenceCohortCandidates(connection, input)), diff --git a/packages/observability/src/durable-summary-sql.ts b/packages/observability/src/durable-summary-sql.ts new file mode 100644 index 00000000..16c87084 --- /dev/null +++ b/packages/observability/src/durable-summary-sql.ts @@ -0,0 +1,104 @@ +/** Compact analytical facts, not transcript copies. Legacy detail remains readable. */ +export const durableSummaryMigration: ReadonlyArray = [ + `CREATE TABLE IF NOT EXISTS observability_summary_receipts ( + batch_id VARCHAR PRIMARY KEY, source_revision VARCHAR NOT NULL, + normalizer_version VARCHAR NOT NULL + )`, + `CREATE TABLE IF NOT EXISTS observability_span_summaries ( + trace_id VARCHAR NOT NULL, span_id VARCHAR NOT NULL, batch_id VARCHAR NOT NULL, + source_id VARCHAR NOT NULL, trace_boundary VARCHAR NOT NULL, + capture_mode VARCHAR NOT NULL, source_authority VARCHAR NOT NULL, + evidence_quality VARCHAR, model VARCHAR, duration_ms BIGINT NOT NULL, + input_tokens BIGINT NOT NULL, output_tokens BIGINT NOT NULL, + error_count BIGINT NOT NULL, tool_call_count BIGINT NOT NULL, + PRIMARY KEY (trace_id, span_id) + )`, + `CREATE TABLE IF NOT EXISTS observability_metric_contributions ( + batch_id VARCHAR NOT NULL, trace_id VARCHAR NOT NULL, metric_name VARCHAR NOT NULL, + metric_id VARCHAR NOT NULL, source_id VARCHAR NOT NULL, observed_at TIMESTAMP NOT NULL, + value DOUBLE NOT NULL, unit VARCHAR NOT NULL, temporality VARCHAR NOT NULL, + evidence_quality VARCHAR NOT NULL, source_reference VARCHAR NOT NULL, + PRIMARY KEY (batch_id, trace_id, metric_name) + )`, + `CREATE VIEW IF NOT EXISTS observability_discovery_spans AS + SELECT trace_id, span_id, batch_id, source_id, trace_boundary, capture_mode, + source_authority, evidence_quality, model, duration_ms + FROM observability_span_summaries + UNION ALL + SELECT trace_id, span_id, batch_id, source_id, trace_boundary, capture_mode, + source_authority, evidence_quality, model, duration_ms + FROM observability_spans AS span + WHERE NOT EXISTS (SELECT 1 FROM observability_summary_receipts AS receipt + WHERE receipt.batch_id = span.batch_id)`, + `CREATE VIEW IF NOT EXISTS observability_discovery_metrics AS + SELECT trace_id, span_id, 'input_tokens' AS metric_name, input_tokens AS value FROM observability_span_summaries + UNION ALL SELECT trace_id, span_id, 'output_tokens', output_tokens FROM observability_span_summaries + UNION ALL SELECT trace_id, span_id, 'error_count', error_count FROM observability_span_summaries + UNION ALL SELECT trace_id, span_id, 'tool_call_count', tool_call_count FROM observability_span_summaries + UNION ALL SELECT trace_id, span_id, metric_name, value FROM observability_metrics AS metric + WHERE NOT EXISTS (SELECT 1 FROM observability_summary_receipts AS receipt + WHERE receipt.batch_id = metric.batch_id)`, + `CREATE VIEW IF NOT EXISTS observability_retained_metric_candidates AS + SELECT batch_id, trace_id, metric_name, metric_id, source_id, observed_at, + value, unit, temporality, evidence_quality, source_reference + FROM observability_metric_contributions + UNION ALL + SELECT batch_id, trace_id, metric_name, metric_id, source_id, observed_at, + value, unit, temporality, evidence_quality, source_reference + FROM observability_historical_metric_points AS point + WHERE NOT EXISTS (SELECT 1 FROM observability_summary_receipts AS receipt + WHERE receipt.batch_id = point.batch_id)`, + "INSERT OR IGNORE INTO observability_schema_migrations (version) VALUES (10)", +]; + +/** Called inside ingestion's transaction, restricted to its bounded batch. */ +export const retainBatchSummaries: ReadonlyArray = [ + `INSERT INTO observability_span_summaries + SELECT span.trace_id, span.span_id, span.batch_id, span.source_id, + span.trace_boundary, span.capture_mode, span.source_authority, + span.evidence_quality, span.model, span.duration_ms, + CAST(COALESCE(MAX(CASE WHEN metric.metric_name = 'input_tokens' THEN metric.value END), 0) AS BIGINT), + CAST(COALESCE(MAX(CASE WHEN metric.metric_name = 'output_tokens' THEN metric.value END), 0) AS BIGINT), + CAST(COALESCE(MAX(CASE WHEN metric.metric_name = 'error_count' THEN metric.value END), 0) AS BIGINT), + CAST(COALESCE(MAX(CASE WHEN metric.metric_name = 'tool_call_count' THEN metric.value END), 0) AS BIGINT) + FROM observability_spans AS span + LEFT JOIN observability_metrics AS metric + ON metric.trace_id = span.trace_id AND metric.span_id = span.span_id + WHERE span.batch_id = $batch_id + GROUP BY ALL`, + `INSERT INTO observability_metric_contributions + SELECT batch_id, trace_id, metric_name, metric_id, source_id, observed_at, + value, unit, temporality, evidence_quality, source_reference + FROM observability_historical_metric_points WHERE batch_id = $batch_id + QUALIFY ROW_NUMBER() OVER (PARTITION BY trace_id, metric_name + ORDER BY observed_at DESC, metric_id DESC) = 1`, + `INSERT INTO observability_summary_receipts + SELECT batch_id, source_revision, normalizer_version FROM observability_ingested_batches + WHERE batch_id = $batch_id`, +]; + +export const sourceReconstructionMigration: ReadonlyArray = [ + `CREATE TABLE IF NOT EXISTS observability_source_reconstruction ( + batch_id VARCHAR PRIMARY KEY, source_revision VARCHAR NOT NULL, + normalizer_version VARCHAR NOT NULL, content_sha256 VARCHAR NOT NULL, + descriptor_json VARCHAR NOT NULL, + detail_state VARCHAR NOT NULL CHECK (detail_state IN ('resident', 'evicted', 'expired')) + )`, + `CREATE TABLE IF NOT EXISTS observability_source_evidence_pins ( + pin_id VARCHAR PRIMARY KEY, batch_id VARCHAR NOT NULL, source_revision VARCHAR NOT NULL, + normalizer_version VARCHAR NOT NULL, content_sha256 VARCHAR NOT NULL, descriptor_json VARCHAR NOT NULL + )`, + "INSERT OR IGNORE INTO observability_schema_migrations (version) VALUES (11)", +]; + +/** No policy or corpus backfill: identities become qualified during bounded imports. */ +export const sourceIdentityMigration: ReadonlyArray = [ + `CREATE TABLE IF NOT EXISTS observability_batch_sources ( + batch_id VARCHAR NOT NULL, source_key VARCHAR NOT NULL, + PRIMARY KEY (batch_id, source_key) + )`, + `CREATE TABLE IF NOT EXISTS observability_expired_sources ( + source_key VARCHAR PRIMARY KEY + )`, + "INSERT OR IGNORE INTO observability_schema_migrations (version) VALUES (12)", +]; diff --git a/packages/observability/src/evidence-cohort.ts b/packages/observability/src/evidence-cohort.ts index 271ccdda..0b53e5c1 100644 --- a/packages/observability/src/evidence-cohort.ts +++ b/packages/observability/src/evidence-cohort.ts @@ -31,7 +31,7 @@ const RequestLimit = Schema.Number.check( Schema.isLessThanOrEqualTo(32_768), ); -export class EvidenceCohortFailure extends Schema.TaggedErrorClass()( +export class EvidenceCohortFailure extends Schema.TaggedError()( "EvidenceCohortFailure", { reason: Schema.Literals([ diff --git a/packages/observability/src/historical-backfill.ts b/packages/observability/src/historical-backfill.ts index 73ffd04f..1c729e3d 100644 --- a/packages/observability/src/historical-backfill.ts +++ b/packages/observability/src/historical-backfill.ts @@ -6,6 +6,7 @@ import * as Predicate from "effect/Predicate"; import { flow } from "effect/Function"; import { LocalTraceImportRequest } from "./local-trace-importer.js"; +import { SourceSessionIds } from "./source-identity.js"; import { LocalTelemetryBatch, LocalTelemetryLogRecord, @@ -134,7 +135,7 @@ export class HistoricalBackfillNormalizationResult extends Schema.Class()( +export class HistoricalBackfillNormalizationFailure extends Schema.TaggedError()( "HistoricalBackfillNormalizationFailure", { operation: Schema.String, message: Schema.String }, ) {} @@ -169,11 +170,11 @@ interface HistoricalSourceRevision { readonly platform: SupportedPlatform; readonly current: readonly HistoricalFact[]; } -const decodeHashValue = Schema.decodeUnknownSync(Schema.Json); +const decodeHashValue = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Json)); const hash = (domain: string, value: string | HistoricalSourceRevision) => createHash("sha256") .update(domain) - .update(canonicalJson(decodeHashValue(value))) + .update(canonicalJson(decodeHashValue(JSON.stringify(value)))) .digest("hex"); const traceId = (sessionId: string) => hash("historical-backfill:trace:v1", sessionId).slice(0, 32); const id = (domain: string, sourceId: string, length: number) => @@ -456,6 +457,9 @@ const chunk = ( }; const normalize = (input: HistoricalBackfillInput): HistoricalBackfillNormalizationResult => { + const sessionIdsByTrace = new Map( + input.sessions.map((session) => [traceId(session.session_id), session.session_id]), + ); const prompts = Map.groupBy(input.prompts, (item) => item.session_id); const invocations = Map.groupBy(input.skill_invocations, (item) => item.session_id); const executions = Map.groupBy(input.execution_facts, (item) => item.session_id); @@ -498,6 +502,15 @@ const normalize = (input: HistoricalBackfillInput): HistoricalBackfillNormalizat imports.push( LocalTraceImportRequest.make({ source_kind: platform, + source_session_ids: Schema.decodeUnknownSync(SourceSessionIds)([ + ...new Set( + current.map((fact) => + sessionIdsByTrace.get( + fact.kind === "span" ? fact.span.trace_id : (fact.log.trace_id ?? ""), + ), + ), + ), + ]), source_revision, normalizer_version: HISTORICAL_BACKFILL_NORMALIZER_VERSION, batch: LocalTelemetryBatch.make({ diff --git a/packages/observability/src/local-trace-importer.ts b/packages/observability/src/local-trace-importer.ts index c1e6b8a7..7b17910f 100644 --- a/packages/observability/src/local-trace-importer.ts +++ b/packages/observability/src/local-trace-importer.ts @@ -3,6 +3,8 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { LocalTelemetryBatch } from "./trace-batch.js"; +import { SourceSnapshot } from "./source-reconstruction.js"; +import { SourceProvider, SourceSessionIds } from "./source-identity.js"; const BoundedText = Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(256)); const TraceId = Schema.String.check( @@ -16,13 +18,7 @@ const MetricCount = Schema.Number.check( ); /** Source identities supported by the local trace import pipeline. */ -export const LocalTraceSourceKind = Schema.Literals([ - "claude_code", - "codex", - "opencode", - "pi", - "otlp", -]); +export const LocalTraceSourceKind = SourceProvider; /** * A normalized source revision ready to be made durable in local analytics. @@ -35,6 +31,8 @@ export class LocalTraceImportRequest extends Schema.Class skill_failure_signals: Schema.Array(LocalSkillFailureSignal), }) {} -export class LocalTraceImportFailure extends Schema.TaggedErrorClass()( +export class LocalTraceImportFailure extends Schema.TaggedError()( "LocalTraceImportFailure", { operation: Schema.String, message: Schema.String }, ) {} diff --git a/packages/observability/src/otlp.ts b/packages/observability/src/otlp.ts index 42c21d2e..dc1e83c1 100644 --- a/packages/observability/src/otlp.ts +++ b/packages/observability/src/otlp.ts @@ -38,7 +38,7 @@ export class NormalizedOtlpExport extends Schema.Class( }) {} /** Typed failures at the OTLP transport and normalization boundary. */ -export class OtlpDecodeFailure extends Schema.TaggedErrorClass()( +export class OtlpDecodeFailure extends Schema.TaggedError()( "OtlpDecodeFailure", { reason: Schema.Literals([ diff --git a/packages/observability/src/source-identity.ts b/packages/observability/src/source-identity.ts new file mode 100644 index 00000000..c3dbfa43 --- /dev/null +++ b/packages/observability/src/source-identity.ts @@ -0,0 +1,22 @@ +import { createHash } from "node:crypto"; +import * as Schema from "effect/Schema"; + +export const SourceProvider = Schema.Literals(["claude_code", "codex", "opencode", "pi", "otlp"]); +export const SourceSessionIds = Schema.Array( + Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(256)), +).check(Schema.isMinLength(1), Schema.isMaxLength(256)); +export const SourceIdentity = Schema.Struct({ + provider: SourceProvider, + session_id: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(256)), +}); +export interface SourceIdentity extends Schema.Schema.Type {} +export const SourceIdentities = Schema.Array(SourceIdentity).check( + Schema.isMinLength(1), + Schema.isMaxLength(256), +); + +/** Logical source identity deliberately excludes path, revision, batch and normalizer. */ +export const sourceIdentityKey = (identity: SourceIdentity): string => + createHash("sha256") + .update(JSON.stringify(["selftune-source/v1", identity.provider, identity.session_id])) + .digest("hex"); diff --git a/packages/observability/src/source-reconstruction.ts b/packages/observability/src/source-reconstruction.ts new file mode 100644 index 00000000..38a544b3 --- /dev/null +++ b/packages/observability/src/source-reconstruction.ts @@ -0,0 +1,108 @@ +import { createHash } from "node:crypto"; +import { constants } from "node:fs"; +import { open } from "node:fs/promises"; +import * as Schema from "effect/Schema"; + +/** Per-demand I/O bound, not a retention policy. Larger sources remain unqualified. */ +export const MAX_RECONSTRUCTION_BYTES = 8 * 1024 * 1024; +export const CODEX_RECONSTRUCTION_PARSER = "codex-rollout/v1"; +const Text = Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(512)); +const FilePath = Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(4096)); +export const SourceSnapshot = Schema.Struct({ + parser: Schema.Literal(CODEX_RECONSTRUCTION_PARSER), + path: FilePath, + sha256: Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/)), + task_sha256: Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/)), + bytes: Schema.Number.check( + Schema.isInt(), + Schema.isGreaterThan(0), + Schema.isLessThanOrEqualTo(MAX_RECONSTRUCTION_BYTES), + ), + skill_names: Schema.Array(Text).check(Schema.isMaxLength(1024)), + workspace_skills: Schema.Array( + Schema.Struct({ + cwd: FilePath, + names: Schema.Array(Text).check(Schema.isMaxLength(1024)), + }), + ).check(Schema.isMaxLength(16)), +}).check( + Schema.makeFilter( + (snapshot) => + snapshot.workspace_skills.reduce( + (count, workspace) => count + workspace.names.length, + snapshot.skill_names.length, + ) <= 1024, + ), +); +export interface SourceSnapshot extends Schema.Schema.Type {} + +export const SourceReconstruction = Schema.Struct({ + snapshot: SourceSnapshot, + bindings: Schema.Array( + Schema.Struct({ + skill_invocation_id: Text, + skill_name: Text, + skill_revision: Schema.NullOr(Text), + }), + ).check(Schema.isMaxLength(256)), +}); +export interface SourceReconstruction extends Schema.Schema.Type {} + +export type SourceTaskResolution = + | { readonly state: "available"; readonly task: string; readonly source: "verified_original" } + | { + readonly state: "unavailable"; + readonly reason: + | "missing" + | "expired" + | "source_missing" + | "source_unavailable" + | "source_changed" + | "unverified_skill_revision" + | "normalizer_changed" + | "projection_changed" + | "over_budget"; + }; + +export const sourceDigest = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex"); + +/** Read one regular file from one descriptor; never follow a final symlink or read unboundedly. */ +export async function readBoundedSource(path: string): Promise< + | { readonly state: "available"; readonly bytes: Buffer } + | { + readonly state: "unavailable"; + readonly reason: "source_missing" | "source_unavailable" | "over_budget"; + } +> { + try { + const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const before = await file.stat(); + if (!before.isFile()) return { state: "unavailable", reason: "source_unavailable" }; + if (before.size === 0 || before.size > MAX_RECONSTRUCTION_BYTES) + return { state: "unavailable", reason: "over_budget" }; + const bytes = Buffer.alloc(before.size + 1); + let offset = 0; + while (offset < bytes.length) { + // oxlint-disable-next-line no-await-in-loop -- bounded reads from one verified file descriptor. + const read = await file.read(bytes, offset, bytes.length - offset, offset); + if (read.bytesRead === 0) break; + offset += read.bytesRead; + } + const after = await file.stat(); + if (offset !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs) + return { state: "unavailable", reason: "source_unavailable" }; + return { state: "available", bytes: bytes.subarray(0, offset) }; + } finally { + await file.close(); + } + } catch (error) { + return { + state: "unavailable", + reason: + error instanceof Error && "code" in error && error.code === "ENOENT" + ? "source_missing" + : "source_unavailable", + }; + } +} diff --git a/packages/observability/src/storage-capacity.ts b/packages/observability/src/storage-capacity.ts new file mode 100644 index 00000000..d0186b16 --- /dev/null +++ b/packages/observability/src/storage-capacity.ts @@ -0,0 +1,67 @@ +import { lstat, statfs } from "node:fs/promises"; +import { dirname } from "node:path"; + +export const ANALYTICAL_RECOVERY_RESERVE_BYTES = 512n * 1024n * 1024n; + +export class AnalyticalStoragePressureError extends Error { + readonly code = "ANALYTICAL_STORAGE_PRESSURE"; + + constructor( + readonly availableBytes: bigint, + readonly requiredBytes: bigint, + ) { + super( + `Analytical maintenance deferred: ${requiredBytes} free bytes required, ${availableBytes} available. Free space and retry; do not reset or delete the analytical database.`, + ); + this.name = "AnalyticalStoragePressureError"; + } +} + +export async function availableStorageBytes(directory: string): Promise { + const capacity = await statfs(directory, { bigint: true }); + return capacity.bavail * capacity.bsize; +} + +export function requireStorageCapacity(availableBytes: bigint, requiredBytes: bigint): void { + if (availableBytes < requiredBytes) { + throw new AnalyticalStoragePressureError(availableBytes, requiredBytes); + } +} + +type FileFootprint = + | { readonly state: "missing" } + | { readonly state: "unsafe_file_type" } + | { readonly state: "present"; readonly logical_bytes: string; readonly allocated_bytes: string }; + +async function fileFootprint(path: string): Promise { + try { + const metadata = await lstat(path, { bigint: true }); + if (!metadata.isFile() || metadata.isSymbolicLink()) return { state: "unsafe_file_type" }; + return { + state: "present", + logical_bytes: metadata.size.toString(), + allocated_bytes: (metadata.blocks * 512n).toString(), + }; + } catch (cause) { + // SAFETY-TYPEOF: Only a filesystem ENOENT proves absence; access/I/O failures remain failures. + if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") { + return { state: "missing" }; + } + throw cause; + } +} + +/** Filesystem metadata only: never opens DuckDB, follows file symlinks, or scans source logs. */ +export async function inspectAnalyticalStorageFiles(databasePath: string) { + const [database, wal, available] = await Promise.all([ + fileFootprint(databasePath), + fileFootprint(`${databasePath}.wal`), + availableStorageBytes(dirname(databasePath)), + ]); + return { + database, + wal, + available_bytes: available.toString(), + coverage: "database_and_wal_only", + }; +} diff --git a/packages/orchestration/package.json b/packages/orchestration/package.json index 6a0f2628..af808c7d 100644 --- a/packages/orchestration/package.json +++ b/packages/orchestration/package.json @@ -25,13 +25,13 @@ "@selftune/skill-intelligence": "workspace:*", "@selftune/source-management": "workspace:*", "@selftune/telemetry-contract": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { - "@effect/vitest": "4.0.0-beta.66", + "@effect/vitest": "4.0.0-rc.115", "@types/bun": "^1.3.11", "bun-types": "^1.3.11", "typescript": "^5.9.3", - "vitest": "^4.0.18" + "vitest": "5.0.1" } } diff --git a/packages/orchestration/src/canonical-export.ts b/packages/orchestration/src/canonical-export.ts index 7ea2846f..d3e5d598 100644 --- a/packages/orchestration/src/canonical-export.ts +++ b/packages/orchestration/src/canonical-export.ts @@ -107,7 +107,7 @@ export function cliMain(): void { buildPushPayloadV2( records, queryEvolutionEvidence(getDb()).flatMap((row) => { - const decoded = decodeEvolutionEvidenceRecord(row, { onExcessProperty: "preserve" }); + const decoded = decodeEvolutionEvidenceRecord(row); return Option.isSome(decoded) ? [decoded.value] : []; }), ), diff --git a/packages/orchestration/src/historical-backfill.ts b/packages/orchestration/src/historical-backfill.ts index e56c069d..91dd791c 100644 --- a/packages/orchestration/src/historical-backfill.ts +++ b/packages/orchestration/src/historical-backfill.ts @@ -35,7 +35,7 @@ const BoundaryRow = Schema.Struct({ const PageCursorRow = Schema.Struct({ cursor_key: Schema.Number }); const MaximumKeyRow = Schema.Struct({ key: Schema.Number }); -export class HistoricalBackfillFailure extends Schema.TaggedErrorClass()( +export class HistoricalBackfillFailure extends Schema.TaggedError()( "HistoricalBackfillFailure", { operation: Schema.String, message: Schema.String }, ) {} diff --git a/packages/orchestration/src/improve.ts b/packages/orchestration/src/improve.ts index 86d307bd..80977ff0 100644 --- a/packages/orchestration/src/improve.ts +++ b/packages/orchestration/src/improve.ts @@ -17,6 +17,8 @@ export interface ImproveDeps { readonly skill: string; readonly skillPath: string; readonly agent?: string; + readonly budgetRemainingUsd: number; + readonly estimatedCostUsd: number; }) => Promise<{ readonly handled: boolean; readonly result?: unknown }>; } @@ -57,6 +59,40 @@ function hasOption(args: readonly string[], flag: string): boolean { return args.includes(flag) || args.some((arg) => arg.startsWith(`${flag}=`)); } +function readRequiredUsdAmount(args: readonly string[], flag: string): number { + const values: string[] = []; + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + if (arg === flag) { + const next = args[index + 1]; + if (next === undefined) { + throw new CLIError(`${flag} requires a non-negative USD amount.`, "MISSING_FLAG"); + } + values.push(next); + index += 1; + } else if (arg.startsWith(`${flag}=`)) { + values.push(arg.slice(flag.length + 1)); + } + } + + if (values.length === 0 || values[0] === "") { + throw new CLIError(`${flag} requires a non-negative USD amount.`, "MISSING_FLAG"); + } + if (values.length > 1) { + throw new CLIError(`${flag} can only be provided once.`, "INVALID_FLAG"); + } + + const [rawValue] = values; + if (rawValue === undefined || !/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(rawValue)) { + throw new CLIError(`${flag} must be a finite, non-negative USD amount.`, "INVALID_FLAG"); + } + const value = Number(rawValue); + if (!Number.isFinite(value)) { + throw new CLIError(`${flag} must be a finite, non-negative USD amount.`, "INVALID_FLAG"); + } + return value; +} + function replaceOption(args: readonly string[], sourceFlag: string, targetFlag: string): string[] { const value = readOptionValue(args, sourceFlag); if (value == null) { @@ -138,14 +174,50 @@ export async function runImprove( ); } - if (effectiveScope === "auto" && hasOption(delegatedArgs, "--dry-run") && historicalImprove) { + const historicalBudgetFlags = ["--budget-remaining-usd", "--estimated-cost-usd"]; + const hasHistoricalBudgetInput = historicalBudgetFlags.some((flag) => + hasOption(delegatedArgs, flag), + ); + const isHistoricalReplayDryRun = + effectiveScope === "auto" && hasOption(delegatedArgs, "--dry-run"); + if (hasHistoricalBudgetInput && (!isHistoricalReplayDryRun || !historicalImprove)) { + throw new CLIError( + "Spend estimates are only used by the historical replay dry-run.", + "INVALID_FLAG", + "Pass both spend flags with --scope auto --dry-run, --skill, and --skill-path.", + ); + } + + if (isHistoricalReplayDryRun && historicalImprove) { const skill = readOptionValue(delegatedArgs, "--skill"); const skillPath = readOptionValue(delegatedArgs, "--skill-path"); + if (hasHistoricalBudgetInput && (!skill || !skillPath)) { + throw new CLIError( + "Caller spend inputs require both --skill and --skill-path.", + "MISSING_FLAG", + "Pass --skill and --skill-path with both spend flags.", + ); + } if (skill && skillPath) { + const budgetRemainingUsd = readRequiredUsdAmount(delegatedArgs, "--budget-remaining-usd"); + const estimatedCostUsd = readRequiredUsdAmount(delegatedArgs, "--estimated-cost-usd"); + if (estimatedCostUsd > budgetRemainingUsd) { + throw new CLIError( + `Historical replay was not started: estimated total run cost ($${estimatedCostUsd}) exceeds caller-reported remaining spend ($${budgetRemainingUsd}).`, + "GUARD_BLOCKED", + "Review the total-run estimate and the remaining amount, then rerun with current caller-provided values.", + ); + } + delegatedArgs = historicalBudgetFlags.reduce( + (args, flag) => stripOption(args, flag), + delegatedArgs, + ); const historical = await historicalImprove({ skill, skillPath, agent: readOptionValue(delegatedArgs, "--agent"), + budgetRemainingUsd, + estimatedCostUsd, }); if (historical.handled) { console.log(JSON.stringify(historical.result, null, 2)); diff --git a/packages/orchestration/src/orchestrate/signals.ts b/packages/orchestration/src/orchestrate/signals.ts index a2a52fa5..871a2caa 100644 --- a/packages/orchestration/src/orchestrate/signals.ts +++ b/packages/orchestration/src/orchestrate/signals.ts @@ -13,7 +13,7 @@ export function readPendingSignals( (() => { const db = getDb(); return queryImprovementSignals(db, false).flatMap((row) => { - const decoded = decodeImprovementSignalRecord(row, { onExcessProperty: "preserve" }); + const decoded = decodeImprovementSignalRecord(row); return Option.isSome(decoded) ? [decoded.value] : []; }); }); diff --git a/packages/orchestration/src/reconstruct-source-task.ts b/packages/orchestration/src/reconstruct-source-task.ts new file mode 100644 index 00000000..fa7197e5 --- /dev/null +++ b/packages/orchestration/src/reconstruct-source-task.ts @@ -0,0 +1,54 @@ +import { parseRolloutTextAsync } from "@selftune/harness-codex/ingestors/codex-rollout"; +import { buildLocalTelemetryBatchFromRollout } from "@selftune/harness-codex/ingestors/codex-trace-projection"; +import type { SourceTaskRequest } from "@selftune/observability/duckdb-store"; +import { + CODEX_RECONSTRUCTION_PARSER, + readBoundedSource, + sourceDigest, +} from "@selftune/observability/source-reconstruction"; +import { NORMALIZER_VERSION } from "@selftune/runtime/normalization"; + +/** Replays only captured parser inputs, never today's installed skill inventory. */ +export const reconstructSourceTask: SourceTaskRequest["replay"] = async (input) => { + const snapshot = input.reconstruction.snapshot; + if ( + input.normalizer_version !== NORMALIZER_VERSION || + snapshot.parser !== CODEX_RECONSTRUCTION_PARSER + ) + return { state: "unavailable", reason: "normalizer_changed" }; + const source = await readBoundedSource(snapshot.path); + if (source.state === "unavailable") return source; + if (source.bytes.length !== snapshot.bytes || sourceDigest(source.bytes) !== snapshot.sha256) + return { state: "unavailable", reason: "source_changed" }; + const parsed = await parseRolloutTextAsync( + snapshot.path, + source.bytes.toString("utf8"), + new Set(snapshot.skill_names), + (cwd) => + new Set(snapshot.workspace_skills.find((workspace) => workspace.cwd === cwd)?.names ?? []), + input.signal, + ); + if (!parsed) return { state: "unavailable", reason: "projection_changed" }; + const telemetry = buildLocalTelemetryBatchFromRollout(parsed); + if (!telemetry) return { state: "unavailable", reason: "projection_changed" }; + const { log_skill_links, ...sourceBatch } = telemetry; + if (log_skill_links !== undefined) return { state: "unavailable", reason: "projection_changed" }; + const links = []; + for (const link of telemetry.links ?? []) { + const binding = input.reconstruction.bindings.find( + (item) => item.skill_invocation_id === link.skill_invocation_id, + ); + if (!binding) return { state: "unavailable", reason: "projection_changed" }; + links.push({ ...link, skill_name: binding.skill_name }); + } + return { + state: "reconstructed", + task: parsed.query, + batch: { + ...sourceBatch, + links, + source_revision: input.source_revision, + normalizer_version: input.normalizer_version, + }, + }; +}; diff --git a/packages/orchestration/src/sync/local-trace-importer.ts b/packages/orchestration/src/sync/local-trace-importer.ts index 0e9fdd1e..bffa9438 100644 --- a/packages/orchestration/src/sync/local-trace-importer.ts +++ b/packages/orchestration/src/sync/local-trace-importer.ts @@ -26,6 +26,7 @@ import { LocalTraceImportRequest, LocalTraceImportResult, } from "@selftune/observability/local-trace-importer"; +import { SourceReconstruction } from "@selftune/observability/source-reconstruction"; const resolveSkillName = Effect.fn("LocalTraceImporter.resolveSkillName")(function* ( database: Database, @@ -34,7 +35,10 @@ const resolveSkillName = Effect.fn("LocalTraceImporter.resolveSkillName")(functi const invocation = yield* Effect.try({ try: () => getDrizzleDb(database) - .select({ skill_name: skill_invocations.skill_name }) + .select({ + skill_name: skill_invocations.skill_name, + skill_revision: skill_invocations.skill_version_hash, + }) .from(skill_invocations) .where(eq(skill_invocations.skill_invocation_id, skillInvocationId)) .get(), @@ -52,7 +56,7 @@ const resolveSkillName = Effect.fn("LocalTraceImporter.resolveSkillName")(functi }), ); } - return invocation.skill_name; + return invocation; }); const signalId = (sourceKind: string, traceId: string, skillInvocationId: string) => { @@ -137,6 +141,7 @@ const resolveBatch = Effect.fn("LocalTraceImporter.resolveBatch")(function* ( } } const logSkillLinks: DuckDbHistoricalLogSkillLink[] = []; + const bindings: SourceReconstruction["bindings"][number][] = []; const logLinkIds = new Set(); for (const sourceLink of request.batch.log_skill_links ?? []) { if (logLinkIds.has(sourceLink.link_id)) { @@ -157,7 +162,8 @@ const resolveBatch = Effect.fn("LocalTraceImporter.resolveBatch")(function* ( }), ); } - const skillName = yield* resolveSkillName(database, sourceLink.skill_invocation_id); + const skill = yield* resolveSkillName(database, sourceLink.skill_invocation_id); + const skillName = skill.skill_name; logSkillLinks.push( DuckDbHistoricalLogSkillLink.make({ ...sourceLink, @@ -196,7 +202,9 @@ const resolveBatch = Effect.fn("LocalTraceImporter.resolveBatch")(function* ( }), ); } - const skillName = yield* resolveSkillName(database, sourceLink.skill_invocation_id); + const skill = yield* resolveSkillName(database, sourceLink.skill_invocation_id); + const skillName = skill.skill_name; + bindings.push({ skill_invocation_id: sourceLink.skill_invocation_id, ...skill }); links.push(DuckDbTraceSkillLink.make({ ...sourceLink, skill_name: skillName })); if (span.error_count > 0) { skillFailureSignals.push( @@ -222,10 +230,22 @@ const resolveBatch = Effect.fn("LocalTraceImporter.resolveBatch")(function* ( normalizer_version: request.normalizer_version, links, }; + const identifiedInput = request.source_session_ids + ? { + ...analyticalInput, + source_identities: request.source_session_ids.map((session_id) => ({ + provider: request.source_kind, + session_id, + })), + } + : analyticalInput; + const sourceWithProof = request.source_snapshot + ? { ...identifiedInput, reconstruction: { snapshot: request.source_snapshot, bindings } } + : identifiedInput; const analyticalBatch = yield* Schema.decodeEffect(DuckDbAnalyticalBatch)( sourceLogLinks === undefined - ? analyticalInput - : { ...analyticalInput, log_skill_links: logSkillLinks }, + ? sourceWithProof + : { ...sourceWithProof, log_skill_links: logSkillLinks }, ).pipe( Effect.mapError((error) => LocalTraceImportFailure.make({ diff --git a/packages/orchestration/src/sync/services.ts b/packages/orchestration/src/sync/services.ts index fae90205..925d7f8e 100644 --- a/packages/orchestration/src/sync/services.ts +++ b/packages/orchestration/src/sync/services.ts @@ -10,7 +10,7 @@ import type { SyncResult, } from "./model.js"; -export class SyncInternalFailure extends Schema.TaggedErrorClass()( +export class SyncInternalFailure extends Schema.TaggedError()( "SyncInternalFailure", { operation: Schema.String, diff --git a/packages/orchestration/src/watch/services.ts b/packages/orchestration/src/watch/services.ts index 36dba6bb..e2e5f573 100644 --- a/packages/orchestration/src/watch/services.ts +++ b/packages/orchestration/src/watch/services.ts @@ -9,7 +9,7 @@ import type { SyncResult } from "@selftune/source-management/sync"; import type { WatchMemoryUpdate, WatchRollbackRequest, WatchRollbackResult } from "./model.js"; -export class WatchInternalFailure extends Schema.TaggedErrorClass()( +export class WatchInternalFailure extends Schema.TaggedError()( "WatchInternalFailure", { operation: Schema.String, diff --git a/packages/runtime/billing-plans.ts b/packages/runtime/billing-plans.ts new file mode 100644 index 00000000..8f96d63e --- /dev/null +++ b/packages/runtime/billing-plans.ts @@ -0,0 +1,39 @@ +import type { DesktopBillingPlan } from "./dashboard-contract"; +export const billingPlans: readonly DesktopBillingPlan[] = [ + { + id: "free", + name: "Community", + price: "$0", + period: null, + description: "Find, review, package, and install skills on your machine.", + features: [ + "Unlimited local skills and Skill Sets", + "Discovery across supported agents and projects", + "Local evaluation and reviewable proposals", + ], + highlighted: false, + }, + { + id: "pro", + name: "Pro", + price: "$19", + period: "/month", + description: "Share skills and Skill Sets through controlled links.", + features: [ + "Explicit skill and Skill Set sharing", + "Expiring and revocable share links", + "Linked-device and revision status", + ], + highlighted: true, + }, + { + id: "team", + name: "Team", + price: "$49", + period: "/month", + description: "Distribute reviewed Skill Sets across a workspace.", + features: ["Everything in Pro", "3 members included", "Workspace membership and access roles"], + highlighted: false, + seats: { minimum: 3, label: "members" }, + }, +]; diff --git a/packages/runtime/command-surface/improvement.ts b/packages/runtime/command-surface/improvement.ts index babfdfcf..36f146a6 100644 --- a/packages/runtime/command-surface/improvement.ts +++ b/packages/runtime/command-surface/improvement.ts @@ -121,6 +121,16 @@ export const IMPROVEMENT_COMMAND_SURFACES = { helpLabel: "--dry-run", description: "Validate candidate changes without deploying", }, + { + flag: "--budget-remaining-usd", + helpLabel: "--budget-remaining-usd ", + description: "Caller-reported remaining spend for historical replay preflight", + }, + { + flag: "--estimated-cost-usd", + helpLabel: "--estimated-cost-usd ", + description: "Caller estimate for the full historical replay run", + }, { flag: "--validation-mode", helpLabel: "--validation-mode", @@ -133,7 +143,7 @@ export const IMPROVEMENT_COMMAND_SURFACES = { }, ], quickReference: - "selftune improve --skill --skill-path [--scope auto|description|routing|body|package] [--dry-run] [--validation-mode auto|replay|judge]", + "selftune improve --skill --skill-path [--scope auto|description|routing|body|package] [--dry-run] [--budget-remaining-usd --estimated-cost-usd ] [--validation-mode auto|replay|judge]", extraHelpSections: [ `Scope mapping: auto -> historical DuckDB replay with \`--dry-run\` when eligible, @@ -143,7 +153,16 @@ export const IMPROVEMENT_COMMAND_SURFACES = { body -> \`selftune evolve body --target body\` package -> \`selftune search-run\` -With \`--scope auto --dry-run\`, SelfTune first looks for historical skill/task +With \`--scope auto --dry-run\`, pass both \`--budget-remaining-usd\` and +\`--estimated-cost-usd\` to allow an eligible historical replay attempt. The +preflight compares the total-run estimate with the caller-reported remaining +amount before candidate generation starts. The result reports this as an +estimate-only check; it does not read subscription usage, meter provider spend, +or cap actual spend. The caller must refresh the remaining amount before a +separate rerun. The replay request uses five search candidates, requires three +scored repetitions, and allows at most three attempts per arm. + +SelfTune first looks for historical skill/task provenance in local DuckDB. Invocation-local outcomes may form a contrastive cohort; otherwise exact explicit tasks form a neutral quality cohort and session errors are ignored. Candidate generation sees calibration only. Codex execution diff --git a/packages/runtime/contribute/sanitize.ts b/packages/runtime/contribute/sanitize.ts index 3f5d070c..43242fb2 100644 --- a/packages/runtime/contribute/sanitize.ts +++ b/packages/runtime/contribute/sanitize.ts @@ -19,7 +19,7 @@ import { SECRET_PATTERNS, } from "../constants.js"; import { ContributionBundle } from "../types.js"; -import { Schema } from "effect"; +import { preservingDecoder } from "../utils/preserving-schema.js"; // UUID v4 pattern for session ID redaction const UUID_PATTERN = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi; @@ -206,9 +206,7 @@ export function sanitizeBundle( } // Defense-in-depth: recursively redact any secrets that slipped through field-level sanitization - return Schema.decodeUnknownSync(ContributionBundle)(redactSecretsDeep(fieldSanitized), { - onExcessProperty: "preserve", - }); + return preservingDecoder(ContributionBundle)(redactSecretsDeep(fieldSanitized)); } // --------------------------------------------------------------------------- diff --git a/packages/runtime/credential-store.ts b/packages/runtime/credential-store.ts index a5b9fa75..03aa0829 100644 --- a/packages/runtime/credential-store.ts +++ b/packages/runtime/credential-store.ts @@ -30,7 +30,7 @@ export interface AsyncPlatformCredentialStore { ) => Promise; } -export class CredentialStoreFailure extends Schema.TaggedErrorClass()( +export class CredentialStoreFailure extends Schema.TaggedError()( "CredentialStoreFailure", { operation: Schema.String, diff --git a/packages/runtime/dashboard-contract/action-events.ts b/packages/runtime/dashboard-contract/action-events.ts index bf2a1ece..78a3a976 100644 --- a/packages/runtime/dashboard-contract/action-events.ts +++ b/packages/runtime/dashboard-contract/action-events.ts @@ -1,4 +1,5 @@ import * as Schema from "effect/Schema"; +import { preservingJsonDecoder } from "../utils/preserving-schema.js"; import { DashboardActionName } from "./action-name.js"; import type { DashboardActionEvent, DashboardActionResultSummary } from "../dashboard-contract.js"; import { @@ -114,6 +115,4 @@ const ActionEvent: Schema.Codec = Schema.Struct({ ), }); -const decodeActionLine = Schema.decodeUnknownSync(Schema.fromJsonString(ActionEvent)); -export const decodeDashboardActionLine = (line: string) => - decodeActionLine(line, { onExcessProperty: "preserve" }); +export const decodeDashboardActionLine = preservingJsonDecoder(ActionEvent); diff --git a/packages/runtime/dashboard-contract/local-management.ts b/packages/runtime/dashboard-contract/local-management.ts index 21cbf2e5..46e27418 100644 --- a/packages/runtime/dashboard-contract/local-management.ts +++ b/packages/runtime/dashboard-contract/local-management.ts @@ -1,5 +1,5 @@ import { Schema } from "effect"; -import { SyncPreferences } from "@selftune/control-plane"; +import { SyncPreferences } from "@selftune/control-plane/domain/remote-library"; export type PortfolioClassification = | "protected" @@ -226,6 +226,7 @@ export interface CompleteCloudAccountLinkResponse { settings: DesktopSettingsResponse; first_backup: | { status: "completed"; uploaded: number; unchanged: number } + | { status: "not_configured"; message: string } | { status: "failed"; message: string }; } diff --git a/packages/runtime/dashboard-contract/report-schemas.ts b/packages/runtime/dashboard-contract/report-schemas.ts index d3056f34..8d45a8b3 100644 --- a/packages/runtime/dashboard-contract/report-schemas.ts +++ b/packages/runtime/dashboard-contract/report-schemas.ts @@ -1,5 +1,5 @@ import * as Schema from "effect/Schema"; -import { CandidateSnapshot } from "@selftune/control-plane"; +import { CandidateSnapshot } from "@selftune/control-plane/domain/synthesis"; import type { SkillIntelligenceReport } from "@selftune/skill-intelligence"; import type { PortfolioAuditResult } from "./local-management.js"; import type { InsightsResponse } from "./requests.js"; diff --git a/packages/runtime/eval/baseline.ts b/packages/runtime/eval/baseline.ts index 7c2cd7fd..6bf130ff 100644 --- a/packages/runtime/eval/baseline.ts +++ b/packages/runtime/eval/baseline.ts @@ -10,6 +10,7 @@ import { parseArgs } from "node:util"; import * as Schema from "effect/Schema"; +import { preservingJsonDecoder } from "../utils/preserving-schema.js"; import { writeGradingBaseline } from "../localdb/direct-write.js"; import type { BaselineResult } from "../types.js"; @@ -202,9 +203,9 @@ Options: ); } try { - evalSet = Schema.decodeUnknownSync( - Schema.fromJsonString(Schema.mutable(Schema.Array(EvalEntry))), - )(readFileSync(evalSetPath, "utf8"), { onExcessProperty: "preserve" }); + evalSet = preservingJsonDecoder(Schema.mutable(Schema.Array(EvalEntry)))( + readFileSync(evalSetPath, "utf8"), + ); } catch { throw new CLIError( `Eval set at ${evalSetPath} is invalid.`, diff --git a/packages/runtime/eval/cli-contract.ts b/packages/runtime/eval/cli-contract.ts index c9f92c1f..764a7bcb 100644 --- a/packages/runtime/eval/cli-contract.ts +++ b/packages/runtime/eval/cli-contract.ts @@ -1,4 +1,5 @@ import type { ComposabilityInput } from "./composability-program.js"; +import type { PluginEvalInput } from "./plugin.js"; export interface EvalGenerateInput { readonly skill?: string; @@ -31,6 +32,7 @@ export interface EvalUnitTestInput { } export interface EvalRunInput { + readonly threshold?: string; readonly skillPath?: string; readonly evals?: string; readonly workspace?: string; @@ -57,6 +59,15 @@ export interface EvalFamilyOverlapInput { } export type EvalCommandRequest = + | { + readonly action: "report"; + readonly input: { + readonly input: string; + readonly threshold: string; + readonly json: boolean; + }; + } + | { readonly action: "plugin"; readonly input: PluginEvalInput } | { readonly action: "generate"; readonly input: EvalGenerateInput } | { readonly action: "unit-test"; readonly input: EvalUnitTestInput } | { readonly action: "run"; readonly input: EvalRunInput } diff --git a/packages/runtime/eval/history.ts b/packages/runtime/eval/history.ts new file mode 100644 index 00000000..895ea941 --- /dev/null +++ b/packages/runtime/eval/history.ts @@ -0,0 +1,63 @@ +import { createHash } from "node:crypto"; +import { + existsSync, + lstatSync, + mkdirSync, + readdirSync, + readFileSync, + writeFileSync, +} from "node:fs"; +import { join } from "node:path"; +import { Schema } from "effect"; +import { EvaluationHistory } from "@selftune/control-plane/domain/evaluation-report"; +import { SELFTUNE_CONFIG_DIR } from "../constants.js"; +import { summarizeEvalReport } from "./report.js"; + +export const MAX_EVALUATION_BYTES = 2 * 1024 * 1024; +const digest = (text: string) => createHash("sha256").update(text).digest("hex"); +const bucket = (skill: string, root: string) => join(root, "evaluation-history", digest(skill)); +const decode = Schema.decodeUnknownSync(Schema.fromJsonString(EvaluationHistory)); + +export function readEvaluationHistory( + skill: string, + root = SELFTUNE_CONFIG_DIR, +): EvaluationHistory { + const directory = bucket(skill, root); + if (!existsSync(directory)) return []; + if (lstatSync(directory).isSymbolicLink()) + throw new Error("Evaluation history cannot be a symlink"); + const files = readdirSync(directory); + if (files.length > 1000) + throw new Error("Evaluation history exceeds 1,000 records; archive older runs first"); + return files + .filter((name) => /^[a-f0-9]{64}\.json$/.test(name)) + .map((name) => { + const path = join(directory, name); + const stat = lstatSync(path); + if (!stat.isFile() || stat.size > MAX_EVALUATION_BYTES) + throw new Error("Invalid evaluation history record"); + return { path, modified: stat.mtimeMs }; + }) + .sort((a, b) => b.modified - a.modified) + .slice(0, 20) + .flatMap(({ path }) => decode(readFileSync(path, "utf8"))); +} + +export function saveEvaluationReport(skill: string, raw: string, root = SELFTUNE_CONFIG_DIR) { + if (!skill.trim() || skill.length > 256) throw new Error("A skill name is required"); + if (Buffer.byteLength(raw) > MAX_EVALUATION_BYTES) throw new Error("Report exceeds 2 MiB"); + const result = summarizeEvalReport(raw); + const id = digest(raw); + const directory = bucket(skill, root); + mkdirSync(directory, { recursive: true, mode: 0o700 }); + if (lstatSync(directory).isSymbolicLink()) + throw new Error("Evaluation history cannot be a symlink"); + const path = join(directory, `${id}.json`); + if (!existsSync(path)) { + writeFileSync(path, JSON.stringify([{ id, importedAt: new Date().toISOString(), result }]), { + mode: 0o600, + flag: "wx", + }); + } + return readEvaluationHistory(skill, root); +} diff --git a/packages/runtime/eval/output-quality.ts b/packages/runtime/eval/output-quality.ts index 5c4ab6d8..fe549f55 100644 --- a/packages/runtime/eval/output-quality.ts +++ b/packages/runtime/eval/output-quality.ts @@ -13,7 +13,14 @@ export const OutputEvalCase = Schema.Struct({ expected_output: Schema.String, files: Schema.optionalKey(Schema.Array(Schema.String)), assertions: Schema.optionalKey(Schema.Array(Schema.String)), - selftune_assertions: Schema.optionalKey(Schema.Array(SkillAssertion)), + selftune_assertions: Schema.optionalKey( + Schema.Array( + Schema.Struct({ + ...SkillAssertion.fields, + arm: Schema.optionalKey(Schema.Literals(["with-only", "both"])), + }), + ), + ), }); export type OutputEvalCase = typeof OutputEvalCase.Type; @@ -24,6 +31,7 @@ export const OutputEvalFile = Schema.Struct({ export type OutputEvalFile = typeof OutputEvalFile.Type; export interface OutputEvalRunInput { + readonly threshold?: number; readonly skillPath: string; readonly evalsPath?: string; readonly workspacePath?: string; @@ -85,7 +93,7 @@ interface ArmResult { readonly duration_ms: number; readonly total_tokens: number | null; readonly grading: { - readonly assertion_results: readonly GradingAssertionResult[]; + readonly assertion_results: readonly (GradingAssertionResult & { readonly scored: boolean })[]; readonly summary: { readonly passed: number; readonly failed: number; @@ -280,11 +288,19 @@ async function runArm( text: assertion.description ?? `${assertion.type}: ${assertion.value}`, passed: result.passed, evidence: result.actual ?? "No mechanical evidence was produced.", + scored: + assertion.arm === "both" || + (assertion.arm !== "with-only" && + !(assertion.type === "tool_called" && assertion.value === "Skill")), }; }); - const assertionResults = [...judged, ...mechanical]; - const passed = assertionResults.filter((result) => result.passed).length; - const total = assertionResults.length; + const assertionResults = [ + ...judged.map((result) => ({ ...result, scored: true })), + ...mechanical, + ]; + const scoredResults = assertionResults.filter((result) => result.scored); + const passed = scoredResults.filter((result) => result.passed).length; + const total = scoredResults.length; const grading = { assertion_results: assertionResults, summary: { passed, failed: total - passed, total, pass_rate: total === 0 ? 0 : passed / total }, @@ -405,6 +421,7 @@ export async function runOutputQualityEvaluation( result.baseline.grading.assertion_results.map((assertion) => [assertion.text, assertion]), ); return result.with_skill.grading.assertion_results.flatMap((withSkill) => { + if (!withSkill.scored) return []; const baseline = baselineByText.get(withSkill.text); return baseline ? [{ id: result.id, text: withSkill.text, withSkill, baseline }] : []; }); @@ -416,6 +433,10 @@ export async function runOutputQualityEvaluation( .filter((pair) => !pair.withSkill.passed && !pair.baseline.passed) .map((pair) => ({ eval_id: pair.id, assertion: pair.text })); const benchmark = { + agent, + model: input.model, + created_at: new Date().toISOString(), + threshold: input.threshold, iteration: iterationNumber, skill_name: contract.skill_name, baseline: baselineArm, @@ -433,6 +454,9 @@ export async function runOutputQualityEvaluation( id: result.id, with_skill_pass_rate: result.with_skill.pass_rate, baseline_pass_rate: result.baseline.pass_rate, + prompt: contract.evals.find((entry) => entry.id === result.id)?.prompt, + with_skill_assertions: result.with_skill.grading.assertion_results, + baseline_assertions: result.baseline.grading.assertion_results, blind_comparison: result.blind_comparison, })), }; diff --git a/packages/runtime/eval/plugin.ts b/packages/runtime/eval/plugin.ts new file mode 100644 index 00000000..c95603a6 --- /dev/null +++ b/packages/runtime/eval/plugin.ts @@ -0,0 +1,101 @@ +import { spawn } from "node:child_process"; +import * as Effect from "effect/Effect"; +import { CLIError } from "../utils/cli-error.js"; +import { parseScoreThreshold } from "./score-gate.js"; + +export interface PluginEvalInput { + readonly target: string; + readonly runs: string; + readonly threshold: string; + readonly concurrency: string; + readonly maxCostUsd?: string; + readonly model?: string; + readonly judgeModel?: string; + readonly case?: string; + readonly evalDir?: string; + readonly outputDir?: string; + readonly report?: string; + readonly ablation: "none" | "with-without"; + readonly trustPlugin: boolean; + readonly json: boolean; +} + +export function pluginEvalArguments(input: PluginEvalInput): string[] { + parseScoreThreshold(input.threshold); + for (const [name, raw, min, max, integer] of [ + ["runs", input.runs, 1, 100, true], + ["concurrency", input.concurrency, 1, 8, true], + ["max-cost-usd", input.maxCostUsd ?? "1", Number.MIN_VALUE, Infinity, false], + ] satisfies [string, string, number, number, boolean][]) { + const value = Number(raw); + if ( + !raw.trim() || + !Number.isFinite(value) || + value < min || + value > max || + (integer && !Number.isInteger(value)) + ) { + throw new CLIError( + `Invalid --${name}: ${raw}`, + "INVALID_ARGUMENT", + "selftune eval plugin --help", + ); + } + } + if (!input.target.trim() || input.target.startsWith("-")) { + throw new CLIError("Provide a plugin path or installed plugin name", "INVALID_ARGUMENT"); + } + const args = [ + "plugin", + "eval", + input.target, + "--no-publish", + "--no-scaffold", + "--mocks", + "record", + "--runs", + input.runs, + "--threshold", + input.threshold, + "--concurrency", + input.concurrency, + "--ablation", + input.ablation, + ]; + for (const [flag, value] of [ + ["--max-cost-usd", input.maxCostUsd], + ["--model", input.model], + ["--judge-model", input.judgeModel], + ["--case", input.case], + ["--eval-dir", input.evalDir], + ["--output-dir", input.outputDir], + ["--report", input.report], + ] satisfies [string, string | undefined][]) + if (value !== undefined) args.push(flag, value); + if (input.trustPlugin) args.push("--trust-plugin"); + if (input.json) args.push("--json"); + return args; +} + +export const runPluginEval = Effect.fn("selftune.eval.plugin")(function* (input: PluginEvalInput) { + const args = yield* Effect.try({ + try: () => pluginEvalArguments(input), + catch: (cause) => + cause instanceof CLIError ? cause : new CLIError(String(cause), "INVALID_ARGUMENT"), + }); + const exitCode = yield* Effect.tryPromise({ + try: (signal) => + new Promise((resolve, reject) => { + const child = spawn("claude", args, { stdio: "inherit", signal }); + child.once("error", reject); + child.once("close", (code) => resolve(code ?? 2)); + }), + catch: (cause) => + new CLIError( + `Claude plugin evaluation could not start: ${cause instanceof Error ? cause.message : String(cause)}`, + "OPERATION_FAILED", + "Requires Claude Code 2.1.269 or later: claude plugin eval --help", + ), + }); + process.exitCode = exitCode; +}); diff --git a/packages/runtime/eval/programs.ts b/packages/runtime/eval/programs.ts index 160c92de..1e94bc91 100644 --- a/packages/runtime/eval/programs.ts +++ b/packages/runtime/eval/programs.ts @@ -2,6 +2,8 @@ import * as Effect from "effect/Effect"; import { CLIError } from "../utils/cli-error.js"; import type { EvalCommandRequest } from "./cli-contract.js"; +import { saveEvaluationReport } from "./history.js"; +import { parseScoreThreshold, scoreGate } from "./score-gate.js"; function toEvalCliError(cause: unknown, action: EvalCommandRequest["action"]): CLIError { return cause instanceof CLIError @@ -17,6 +19,38 @@ export const runEvalProgram = Effect.fn("selftune.eval.run")(function* ( request: EvalCommandRequest, ) { switch (request.action) { + case "report": { + const reader = yield* Effect.promise(() => import("./report.js")); + const result = yield* Effect.try({ + try: () => + reader.readEvalReport(request.input.input, parseScoreThreshold(request.input.threshold)), + catch: (cause) => toEvalCliError(cause, request.action), + }); + console.log( + request.input.json + ? JSON.stringify(result, null, 2) + : [ + `Engine: ${result.engine} | threshold: ${result.threshold} | exit: ${result.exitCode}`, + "Case\tWith\tBaseline\tDelta\tErrors", + ...result.cases.map((entry) => + [ + entry.name, + entry.score.toFixed(2), + entry.baseline?.toFixed(2) ?? "—", + entry.delta?.toFixed(2) ?? "—", + entry.errors.join("; "), + ].join("\t"), + ), + ].join("\n"), + ); + process.exitCode = result.exitCode; + return; + } + case "plugin": { + const plugin = yield* Effect.promise(() => import("./plugin.js")); + yield* plugin.runPluginEval(request.input); + return; + } case "generate": { const generator = yield* Effect.promise(() => import("./hooks-to-evals.js")); yield* Effect.tryPromise({ @@ -34,6 +68,13 @@ export const runEvalProgram = Effect.fn("selftune.eval.run")(function* ( return; } case "run": { + const threshold = yield* Effect.try({ + try: () => + request.input.threshold === undefined + ? undefined + : parseScoreThreshold(request.input.threshold), + catch: (cause) => toEvalCliError(cause, request.action), + }); const runner = yield* Effect.promise(() => import("./output-quality.js")); if (!request.input.skillPath) { return yield* Effect.fail( @@ -54,6 +95,7 @@ export const runEvalProgram = Effect.fn("selftune.eval.run")(function* ( feedbackPath: request.input.feedback, agent: request.input.agent, model: request.input.model, + threshold, }), catch: (cause) => toEvalCliError(cause, request.action), }); @@ -62,6 +104,18 @@ export const runEvalProgram = Effect.fn("selftune.eval.run")(function* ( ? JSON.stringify(result, null, 2) : `Evaluation iteration written to ${result.iteration_dir}`, ); + yield* Effect.try({ + try: () => + saveEvaluationReport(result.benchmark.skill_name, JSON.stringify(result.benchmark)), + catch: (cause) => toEvalCliError(cause, request.action), + }); + if (threshold !== undefined) + process.exitCode = scoreGate( + result.benchmark.cases.map((entry) => entry.with_skill_pass_rate), + threshold, + ) + ? 0 + : 1; return; } case "import": { diff --git a/packages/runtime/eval/report.ts b/packages/runtime/eval/report.ts new file mode 100644 index 00000000..b898b1b0 --- /dev/null +++ b/packages/runtime/eval/report.ts @@ -0,0 +1,190 @@ +import { readFileSync, statSync } from "node:fs"; +import { Schema } from "effect"; +import { CLIError } from "../utils/cli-error.js"; +import { scoreGate } from "./score-gate.js"; +import type { EvaluationSummary } from "@selftune/control-plane/domain/evaluation-report"; +type Assertion = EvaluationSummary["cases"][number]["assertions"][number]; + +const Grader = Schema.Struct({ + name: Schema.String, + passed: Schema.Boolean, + scored: Schema.optionalKey(Schema.Boolean), + explanation: Schema.String, +}); +const PortableGrader = Schema.Struct({ + text: Schema.String, + passed: Schema.Boolean, + scored: Schema.optionalKey(Schema.Boolean), + evidence: Schema.String, +}); + +const Score = Schema.Number.check(Schema.isFinite(), Schema.isBetween({ minimum: 0, maximum: 1 })); +const NativeRun = Schema.Struct({ + score: Score, + error: Schema.Union([Schema.String, Schema.Null]), + skippedPaidGraders: Schema.Boolean, + graders: Schema.optionalKey(Schema.Array(Grader)), +}); +const NativeReport = Schema.Struct({ + schemaVersion: Schema.Literal(1), + claudeVersion: Schema.String, + partial: Schema.Boolean, + startedAt: Schema.optionalKey(Schema.String), + suite: Schema.Struct({ + ablation: Schema.Literals(["none", "with-without"]), + threshold: Schema.optionalKey(Score), + }), + cases: Schema.Array( + Schema.Struct({ + name: Schema.String, + model: Schema.optionalKey(Schema.String), + promptMarkdown: Schema.optionalKey(Schema.String), + runsPerCase: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)), + arms: Schema.Struct({ + with: Schema.Array(NativeRun), + without: Schema.optionalKey(Schema.Array(NativeRun)), + }), + }), + ), +}); +const SkillReport = Schema.Struct({ + skill_name: Schema.String, + agent: Schema.optionalKey(Schema.String), + model: Schema.optionalKey(Schema.String), + created_at: Schema.optionalKey(Schema.String), + threshold: Schema.optionalKey(Score), + baseline: Schema.Literals(["old_skill", "without_skill"]), + cases: Schema.Array( + Schema.Struct({ + id: Schema.Union([Schema.String, Schema.Number]), + with_skill_pass_rate: Score, + baseline_pass_rate: Score, + prompt: Schema.optionalKey(Schema.String), + with_skill_assertions: Schema.optionalKey(Schema.Array(PortableGrader)), + baseline_assertions: Schema.optionalKey(Schema.Array(PortableGrader)), + }), + ), +}); +const decodeReport = Schema.decodeUnknownSync( + Schema.fromJsonString(Schema.Union([NativeReport, SkillReport])), +); +const mean = (scores: readonly number[]) => + scores.length ? scores.reduce((a, b) => a + b, 0) / scores.length : 0; + +export function summarizeEvalReport(raw: string, thresholdOverride?: number): EvaluationSummary { + const report = decodeReport(raw); + const threshold = + thresholdOverride ?? + ("schemaVersion" in report ? report.suite.threshold : report.threshold) ?? + 1; + if ("schemaVersion" in report) { + const cases = report.cases.map((entry) => { + const without = entry.arms.without ?? []; + const withScore = mean(entry.arms.with.map((run) => run.score)); + const baseline = + report.suite.ablation === "with-without" ? mean(without.map((run) => run.score)) : null; + const runs = [...entry.arms.with, ...without]; + const errors = runs.flatMap((run) => (run.error === null ? [] : [run.error])); + const incomplete = + entry.arms.with.length !== entry.runsPerCase || + (baseline !== null && without.length !== entry.runsPerCase) || + runs.some((run) => run.skippedPaidGraders) || + errors.length > 0; + return { + name: entry.name, + score: withScore, + baseline, + delta: baseline === null ? null : withScore - baseline, + incomplete, + errors, + prompt: entry.promptMarkdown ?? null, + assertions: [ + ...entry.arms.with.flatMap((run) => + (run.graders ?? []).map((grader) => ({ + arm: "with", + name: grader.name, + passed: grader.passed, + scored: grader.scored ?? true, + evidence: grader.explanation, + })), + ), + ...without.flatMap((run) => + (run.graders ?? []).map((grader) => ({ + arm: "baseline", + name: grader.name, + passed: grader.passed, + scored: grader.scored ?? true, + evidence: grader.explanation, + })), + ), + ], + }; + }); + const incomplete = report.partial || cases.some((entry) => entry.incomplete); + return { + engine: "claude-plugin", + harness: "claude", + model: + [...new Set(report.cases.flatMap((entry) => (entry.model ? [entry.model] : [])))].join( + ", ", + ) || null, + recordedAt: report.startedAt ?? null, + threshold, + cases, + exitCode: incomplete + ? 2 + : scoreGate( + cases.map((entry) => entry.score), + threshold, + ) + ? 0 + : 1, + }; + } + const cases = report.cases.map((entry) => ({ + name: String(entry.id), + score: entry.with_skill_pass_rate, + baseline: entry.baseline_pass_rate, + delta: entry.with_skill_pass_rate - entry.baseline_pass_rate, + incomplete: false, + errors: [], + prompt: entry.prompt ?? null, + assertions: [ + ...(entry.with_skill_assertions ?? []).map((grader) => ({ + arm: "with", + name: grader.text, + passed: grader.passed, + scored: grader.scored ?? true, + evidence: grader.evidence, + })), + ...(entry.baseline_assertions ?? []).map((grader) => ({ + arm: "baseline", + name: grader.text, + passed: grader.passed, + scored: grader.scored ?? true, + evidence: grader.evidence, + })), + ], + })); + return { + engine: "selftune-skill", + harness: report.agent ?? null, + model: report.model ?? null, + recordedAt: report.created_at ?? null, + threshold, + cases, + exitCode: scoreGate( + cases.map((entry) => entry.score), + threshold, + ) + ? 0 + : 1, + }; +} + +export function readEvalReport(path: string, threshold: number) { + if (statSync(path).size > 32 * 1024 * 1024) { + throw new CLIError("Evaluation report exceeds the 32 MiB read limit", "INVALID_ARGUMENT"); + } + return summarizeEvalReport(readFileSync(path, "utf8"), threshold); +} diff --git a/packages/runtime/eval/score-gate.ts b/packages/runtime/eval/score-gate.ts new file mode 100644 index 00000000..305a10d5 --- /dev/null +++ b/packages/runtime/eval/score-gate.ts @@ -0,0 +1,13 @@ +import { CLIError } from "../utils/cli-error.js"; + +export function parseScoreThreshold(raw: string): number { + const value = Number(raw); + if (!raw.trim() || !Number.isFinite(value) || value < 0 || value > 1) { + throw new CLIError("--threshold must be between 0 and 1", "INVALID_ARGUMENT"); + } + return value; +} + +export function scoreGate(scores: readonly number[], threshold: number) { + return scores.length > 0 && scores.every((score) => Number.isFinite(score) && score >= threshold); +} diff --git a/packages/runtime/evolution/audit.ts b/packages/runtime/evolution/audit.ts index bbe0544b..177c37ba 100644 --- a/packages/runtime/evolution/audit.ts +++ b/packages/runtime/evolution/audit.ts @@ -14,7 +14,7 @@ import { decodeEvolutionAuditRecord } from "../utils/log-contracts.js"; function loadAuditEntries(skillName?: string): EvolutionAuditEntry[] { return queryEvolutionAudit(getDb(), skillName).flatMap((row) => { - const decoded = decodeEvolutionAuditRecord(row, { onExcessProperty: "preserve" }); + const decoded = decodeEvolutionAuditRecord(row); return Option.isSome(decoded) ? [decoded.value] : []; }); } diff --git a/packages/runtime/evolution/evidence.ts b/packages/runtime/evolution/evidence.ts index 40626de1..d9d61c44 100644 --- a/packages/runtime/evolution/evidence.ts +++ b/packages/runtime/evolution/evidence.ts @@ -26,7 +26,7 @@ export function appendEvidenceEntry(entry: EvolutionEvidenceEntry): void { export function readEvidenceTrail(skillName?: string): EvolutionEvidenceEntry[] { const db = getDb(); return queryEvolutionEvidence(db, skillName).flatMap((row) => { - const decoded = decodeEvolutionEvidenceRecord(row, { onExcessProperty: "preserve" }); + const decoded = decodeEvolutionEvidenceRecord(row); return Option.isSome(decoded) ? [decoded.value] : []; }); } diff --git a/packages/runtime/evolution/validate-host-replay.ts b/packages/runtime/evolution/validate-host-replay.ts index 331ddb6d..43ad6ca8 100644 --- a/packages/runtime/evolution/validate-host-replay.ts +++ b/packages/runtime/evolution/validate-host-replay.ts @@ -1,4 +1,5 @@ export type { + ReplayWorkspace, RuntimeReplayContentTarget, RuntimeReplayInvoker, RuntimeReplayInvokerInput, @@ -23,6 +24,7 @@ export { } from "./validate-host-replay/parsers.js"; export { buildRuntimeReplayValidationOptions, + evaluateRuntimeReplayObservation, runClaudeRuntimeReplayFixture, runHostReplayFixture, runHostRuntimeReplayFixture, diff --git a/packages/runtime/evolution/validate-host-replay/runner.ts b/packages/runtime/evolution/validate-host-replay/runner.ts index ff36402c..706c22a8 100644 --- a/packages/runtime/evolution/validate-host-replay/runner.ts +++ b/packages/runtime/evolution/validate-host-replay/runner.ts @@ -213,7 +213,7 @@ async function invokeOpenCodeRuntimeReplay( return observation; } -function evaluateRuntimeReplayObservation( +export function evaluateRuntimeReplayObservation( entry: EvalEntry, fixture: RoutingReplayFixture, observation: RuntimeReplayObservation, @@ -249,6 +249,15 @@ function evaluateRuntimeReplayObservation( const sessionPrefix = observation.sessionId ? `runtime replay session ${observation.sessionId}` : "runtime replay"; + if (unrelatedReadPaths.length > 0) { + return { + query: entry.query, + should_trigger: entry.should_trigger, + triggered: false, + passed: false, + evidence: `${sessionPrefix} read files outside staged skill set: ${unrelatedReadPaths.join(", ")}`, + }; + } if (observation.triggeredSkillNames.length > 1) { return { query: entry.query, @@ -285,15 +294,6 @@ function evaluateRuntimeReplayObservation( evidence: `${sessionPrefix} selected unrelated skill: ${unrelatedTriggered}`, }; } - if (unrelatedReadPaths.length > 0) { - return { - query: entry.query, - should_trigger: entry.should_trigger, - triggered: false, - passed: false, - evidence: `${sessionPrefix} read files outside staged skill set: ${unrelatedReadPaths.join(", ")}`, - }; - } if (targetRead) { return { query: entry.query, diff --git a/packages/runtime/grading/grade-session.ts b/packages/runtime/grading/grade-session.ts index 37bb49ba..43cebcb2 100644 --- a/packages/runtime/grading/grade-session.ts +++ b/packages/runtime/grading/grade-session.ts @@ -61,6 +61,9 @@ Grade each expectation and output ONLY valid JSON matching this schema: "expectations": [ {"text": "...", "passed": true/false, "evidence": "specific quote or metric", "score": 0.0-1.0} ], + "unobserved_expectations": [ + {"text": "exact expectation text", "reason": "specific missing evidence"} + ], "summary": {"passed": N, "failed": N, "total": N, "pass_rate": 0.0, "mean_score": 0.0}, "claims": [ {"claim": "...", "type": "factual|process|quality", "verified": true/false, "evidence": "..."} @@ -77,17 +80,20 @@ Grade each expectation and output ONLY valid JSON matching this schema: Score guide: - 1.0: Clear, specific evidence of full completion - 0.7-0.9: Strong evidence with minor gaps -- 0.4-0.6: Partial evidence or partial completion -- 0.1-0.3: Weak evidence, mostly not met -- 0.0: No evidence or clearly not met +- 0.4-0.6: Observed partial completion +- 0.1-0.3: Observed behavior mostly fails the requirement +- 0.0: Specific evidence establishes failure Rules: - PASS only when there is clear, specific evidence — not assumptions -- FAIL when evidence is absent or contradictory +- FAIL when specific evidence establishes that the requirement was not met +- Put expectations with insufficient evidence in unobserved_expectations instead of expectations; leave them unscored +- Treat excerpts as partial observations. Missing events or aggregate counts alone cannot establish completion, tool identity, read order, or absence of errors +- Copy each expectation's exact text into exactly one of the two arrays - Cite exact quotes or specific metric values - Extract 2-4 implicit claims from the transcript and verify them - Suggest eval improvements only for clear gaps -- Set score to reflect confidence level (0.0-1.0) +- Set score to reflect observed fulfillment (0.0-1.0), not confidence - For each FAILED expectation, provide a failure_feedback entry with the relevant query, specific reason for failure, and actionable improvement hint`; // --------------------------------------------------------------------------- @@ -567,6 +573,25 @@ function normalizeExpectations(expectations: GradingExpectation[]): GradingExpec })); } +function hasTranscriptEvidence(excerpt: string): boolean { + const normalized = excerpt.trim(); + return ( + normalized.length > 0 && + normalized !== "(no transcript)" && + normalized !== "(transcript not found)" + ); +} + +function requireObservedEvidence(output: Partial): void { + if (output.unobserved_expectations?.length) { + throw new CLIError( + `Grading incomplete: ${output.unobserved_expectations.length} expectation(s) have unobserved evidence. No quality score was saved.`, + "MISSING_DATA", + "Recover the source transcript and required artifacts, then rerun selftune grade", + ); + } +} + function assembleResultFromExpectations( expectations: GradingExpectation[], telemetry: PreGateContext["telemetry"] | null, @@ -619,6 +644,13 @@ export async function gradeSession({ agent, gradeViaAgentFn = gradeViaAgent, }: GradeSessionParams): Promise { + if (expectations.length === 0) { + throw new CLIError( + "Grading requires at least one expectation", + "MISSING_DATA", + "Provide expectations with selftune grade", + ); + } const preGateCtx: PreGateContext = { telemetry, skillName, @@ -634,6 +666,13 @@ export async function gradeSession({ ); allExpectations = preGateResult.resolved; } else { + if (!hasTranscriptEvidence(transcriptExcerpt)) { + throw new CLIError( + "Grading incomplete: source transcript evidence is unavailable. No quality score was saved.", + "MISSING_DATA", + "Recover the source transcript, then rerun selftune grade", + ); + } console.error( `[INFO] Pre-gates resolved ${preGateResult.resolved.length}/${expectations.length} expectations`, ); @@ -656,12 +695,21 @@ export async function gradeSession({ }); } + requireObservedEvidence(graderOutput); const llmExpectations = normalizeExpectations(graderOutput.expectations ?? []); if (llmExpectations.length !== preGateResult.remaining.length) { throw new Error( `Grader returned ${llmExpectations.length} expectations for ${preGateResult.remaining.length} unresolved expectations`, ); } + const unmatched = [...preGateResult.remaining]; + for (const expectation of llmExpectations) { + const index = unmatched.indexOf(expectation.text); + if (index === -1) { + throw new Error("Grader returned duplicate or unrelated expectations"); + } + unmatched.splice(index, 1); + } allExpectations = [...preGateResult.resolved, ...llmExpectations]; } @@ -686,6 +734,7 @@ export function assembleResult( skillName: string | null, transcriptPath: string | null, ): GradingResult { + requireObservedEvidence(graderOutput); const result = assembleResultFromExpectations( normalizeExpectations(graderOutput?.expectations ?? []), telemetry, diff --git a/packages/runtime/grading/pre-gates.ts b/packages/runtime/grading/pre-gates.ts index 4c433aa5..801b823a 100644 --- a/packages/runtime/grading/pre-gates.ts +++ b/packages/runtime/grading/pre-gates.ts @@ -1,22 +1,5 @@ -/** - * pre-gates.ts - * - * Deterministic pre-gate checks that resolve grading expectations without LLM. - * Each gate matches an expectation text pattern and resolves it using telemetry data. - */ - import type { GradingExpectation, SessionTelemetryRecord } from "../types.js"; -// --------------------------------------------------------------------------- -// Gate definitions -// --------------------------------------------------------------------------- - -export interface PreGate { - name: string; - pattern: RegExp; - check: (ctx: PreGateContext) => boolean; -} - export interface PreGateContext { telemetry: Partial; skillName: string; @@ -28,77 +11,26 @@ export interface PreGateResult { remaining: string[]; } -/** Default set of pre-gates. */ -export const DEFAULT_GATES: PreGate[] = [ - { - name: "skill_md_read", - pattern: /(read.*skill\.md|skill\.md.*read)/i, - check: (ctx) => { - // Check if skills_triggered contains the skill name - const triggered = ctx.telemetry.skills_triggered ?? []; - if (triggered.includes(ctx.skillName)) return true; - // Also check if transcript mentions reading SKILL.md - if (ctx.transcriptExcerpt && /Read.*SKILL\.md/i.test(ctx.transcriptExcerpt)) return true; - return false; - }, - }, - { - name: "expected_tools_called", - pattern: /tool[s]?\s+(were\s+)?called/i, - check: (ctx) => (ctx.telemetry.total_tool_calls ?? 0) > 0, - }, - { - name: "error_count", - pattern: /error[s]?\s*(count|encountered)/i, - check: (ctx) => (ctx.telemetry.errors_encountered ?? 0) <= 2, - }, - { - name: "session_completed", - pattern: /session\s*(completed|finished)/i, - check: (ctx) => (ctx.telemetry.assistant_turns ?? 0) > 0, - }, -]; - -// --------------------------------------------------------------------------- -// Pre-gate runner -// --------------------------------------------------------------------------- - -/** - * Run pre-gate checks against expectations. Returns resolved expectations - * (with source: "pre-gate" and score: 1.0 or 0.0) and remaining expectation - * texts that need LLM grading. - */ -export function runPreGates( - expectations: string[], - ctx: PreGateContext, - gates: PreGate[] = DEFAULT_GATES, -): PreGateResult { +/** Resolve only a recorded trigger, not file reads, ordering, completion, or quality. */ +export function runPreGates(expectations: string[], ctx: PreGateContext): PreGateResult { const resolved: GradingExpectation[] = []; const remaining: string[] = []; - + const triggerClaims = [ + "The skill was triggered during the session", + `The "${ctx.skillName}" skill was triggered during the session`, + ]; for (const text of expectations) { - let matched = false; - for (const gate of gates) { - if (gate.pattern.global || gate.pattern.sticky) { - gate.pattern.lastIndex = 0; - } - if (gate.pattern.test(text)) { - const passed = gate.check(ctx); - resolved.push({ - text, - passed, - evidence: `Pre-gate "${gate.name}": ${passed ? "PASS" : "FAIL"}`, - score: passed ? 1.0 : 0.0, - source: "pre-gate", - }); - matched = true; - break; // first matching gate wins - } - } - if (!matched) { + if (triggerClaims.includes(text) && ctx.telemetry.skills_triggered?.includes(ctx.skillName)) { + resolved.push({ + text, + passed: true, + evidence: `telemetry.skills_triggered includes ${JSON.stringify(ctx.skillName)}`, + score: 1, + source: "pre-gate", + }); + } else { remaining.push(text); } } - return { resolved, remaining }; } diff --git a/packages/runtime/installer/materializer.ts b/packages/runtime/installer/materializer.ts index 6ed8c479..5df01ba9 100644 --- a/packages/runtime/installer/materializer.ts +++ b/packages/runtime/installer/materializer.ts @@ -22,7 +22,7 @@ import type { const SHA256 = /^[a-f0-9]{64}$/; -export class InstallerMaterializationError extends Schema.TaggedErrorClass()( +export class InstallerMaterializationError extends Schema.TaggedError()( "InstallerMaterializationError", { code: Schema.String, diff --git a/packages/runtime/installer/types.ts b/packages/runtime/installer/types.ts index ce36ecc4..0c55da1b 100644 --- a/packages/runtime/installer/types.ts +++ b/packages/runtime/installer/types.ts @@ -425,7 +425,7 @@ export interface LocalInstallPlan { readonly journal: OperationJournalIntent | null; } -export class InstallerPlanningError extends Schema.TaggedErrorClass()( +export class InstallerPlanningError extends Schema.TaggedError()( "InstallerPlanningError", { code: Schema.String, diff --git a/packages/runtime/localdb/queries/dashboard.ts b/packages/runtime/localdb/queries/dashboard.ts index 2bd75bea..85d7ce40 100644 --- a/packages/runtime/localdb/queries/dashboard.ts +++ b/packages/runtime/localdb/queries/dashboard.ts @@ -14,17 +14,12 @@ import type { RecentActivityItem, SkillReportPaginatedPayload, SkillReportPayload, - SkillTestingReadiness, - SkillSummary, SkillUsageRecord, TelemetryRecord, } from "../../dashboard-contract.js"; -import { computeCreateDashboardReadiness, isCreateSkillDraft } from "../../create/readiness.js"; import { getPendingProposals } from "./evolution.js"; import { safeParseJsonArray } from "./json.js"; import { queryTrustedSkillObservationRows } from "./trust.js"; -import { listSkillTestingReadiness } from "../../testing-readiness.js"; -import { classifySkillPath } from "../../utils/skill-discovery.js"; function mapOverviewEvolutionEntry(row: { timestamp: string; @@ -592,145 +587,7 @@ function paginateSkillReportInvocations( return { items, next_cursor, has_more: hasMore }; } -export function getSkillsList( - db: Database, - testingReadinessRows?: SkillTestingReadiness[], -): SkillSummary[] { - const trustedRows = queryTrustedSkillObservationRows(db); - const bySkill = new Map< - string, - Array<{ - skill_name: string; - session_id: string; - occurred_at: string | null; - triggered: number; - matched_prompt_id: string | null; - confidence: number | null; - }> - >(); - - for (const row of trustedRows) { - const base = { - skill_name: row.skill_name, - session_id: row.session_id, - occurred_at: row.occurred_at, - triggered: row.triggered, - matched_prompt_id: row.matched_prompt_id, - confidence: row.confidence, - }; - const existing = bySkill.get(row.skill_name); - if (existing) existing.push(base); - else bySkill.set(row.skill_name, [base]); - } - - const evidenceSkills = new Set( - db - .query< - { - skill_name: string; - }, - SQLQueryBindings[] - >(`SELECT DISTINCT skill_name FROM evolution_evidence`) - .all() - .map((row) => row.skill_name), - ); - - const skillScopeRows = db - .query<{ skill_name: string; skill_scope: string | null }, SQLQueryBindings[]>( - `SELECT - si.skill_name, - COALESCE( - (SELECT s2.skill_scope FROM skill_invocations s2 - WHERE s2.skill_name = si.skill_name AND s2.skill_scope IS NOT NULL - ORDER BY s2.occurred_at DESC LIMIT 1), - (SELECT su.skill_scope FROM skill_usage su - WHERE su.skill_name = si.skill_name AND su.skill_scope IS NOT NULL - ORDER BY su.timestamp DESC LIMIT 1) - ) as skill_scope - FROM skill_invocations si - GROUP BY si.skill_name`, - ) - .all(); - const scopeBySkill = new Map(skillScopeRows.map((row) => [row.skill_name, row.skill_scope])); - const testingReadiness = testingReadinessRows ?? listSkillTestingReadiness(db); - const testingReadinessBySkill = new Map( - testingReadiness.map((row) => [row.skill_name, row] as const), - ); - const createReadinessBySkill = new Map( - testingReadiness - .flatMap((row) => { - if (!row.skill_path || !isCreateSkillDraft(row.skill_path)) return []; - try { - return [ - [ - row.skill_name, - computeCreateDashboardReadiness(row.skill_path, { - getTestingReadiness: () => row, - }), - ] as const, - ]; - } catch { - return []; - } - }) - .filter(Boolean), - ); - const knownSkills = new Set(bySkill.keys()); - for (const skillName of createReadinessBySkill.keys()) { - knownSkills.add(skillName); - } - - return [...knownSkills] - .map((skillName) => { - const rows = bySkill.get(skillName) ?? []; - const totalChecks = rows.length; - const triggeredCount = rows.filter((row) => row.triggered === 1).length; - const uniqueSessions = new Set(rows.map((row) => row.session_id)).size; - const lastSeen = - rows - .map((row) => row.occurred_at) - .filter((value): value is string => value != null) - .sort((a, b) => b.localeCompare(a))[0] ?? null; - const withConfidence = rows.filter((row) => row.confidence != null); - const routingConfidence = - withConfidence.length > 0 - ? withConfidence.reduce((sum, row) => sum + (row.confidence ?? 0), 0) / - withConfidence.length - : null; - const readiness = testingReadinessBySkill.get(skillName); - const createReadiness = createReadinessBySkill.get(skillName); - const fallbackScope = - readiness?.skill_path != null ? classifySkillPath(readiness.skill_path).skill_scope : null; - const createScope = - createReadiness?.skill_path != null - ? classifySkillPath(createReadiness.skill_path).skill_scope - : null; - - return { - skill_name: skillName, - skill_scope: - scopeBySkill.get(skillName) ?? - (createScope && createScope !== "unknown" ? createScope : null) ?? - (fallbackScope && fallbackScope !== "unknown" ? fallbackScope : null), - total_checks: totalChecks, - triggered_count: triggeredCount, - pass_rate: totalChecks > 0 ? triggeredCount / totalChecks : 0, - unique_sessions: uniqueSessions, - last_seen: lastSeen, - has_evidence: evidenceSkills.has(skillName), - routing_confidence: routingConfidence, - confidence_coverage: totalChecks > 0 ? withConfidence.length / totalChecks : 0, - testing_readiness: readiness, - create_readiness: createReadiness, - }; - }) - .sort( - (a, b) => - b.total_checks - a.total_checks || - (b.last_seen ?? "").localeCompare(a.last_seen ?? "") || - a.skill_name.localeCompare(b.skill_name), - ); -} +export { getSkillsList } from "./skills.js"; export function getAnalyticsPayload(db: Database): AnalyticsResponse { const trustedRows = queryTrustedSkillObservationRows(db); diff --git a/packages/runtime/localdb/queries/skills.ts b/packages/runtime/localdb/queries/skills.ts new file mode 100644 index 00000000..163e108b --- /dev/null +++ b/packages/runtime/localdb/queries/skills.ts @@ -0,0 +1,152 @@ +import type { Database, SQLQueryBindings } from "bun:sqlite"; +import type { SkillTestingReadiness, SkillSummary } from "../../dashboard-contract.js"; +import { computeCreateDashboardReadiness, isCreateSkillDraft } from "../../create/readiness.js"; +import { iterateTrustedSkillObservationRows } from "./trust.js"; +import { listSkillTestingReadiness } from "../../testing-readiness.js"; +import { classifySkillPath } from "../../utils/skill-discovery.js"; + +export function getSkillsList( + db: Database, + testingReadinessRows?: SkillTestingReadiness[], +): SkillSummary[] { + const bySkill = new Map< + string, + { + checks: number; + triggered: number; + sessions: Set; + lastSeen: string | null; + confidenceSum: number; + confidenceCount: number; + } + >(); + + for (const row of iterateTrustedSkillObservationRows(db)) { + let totals = bySkill.get(row.skill_name); + if (!totals) { + totals = { + checks: 0, + triggered: 0, + sessions: new Set(), + lastSeen: null, + confidenceSum: 0, + confidenceCount: 0, + }; + bySkill.set(row.skill_name, totals); + } + totals.checks++; + if (row.triggered === 1) totals.triggered++; + totals.sessions.add(row.session_id); + if ( + row.occurred_at != null && + (totals.lastSeen == null || row.occurred_at.localeCompare(totals.lastSeen) > 0) + ) { + totals.lastSeen = row.occurred_at; + } + if (row.confidence != null) { + totals.confidenceSum += row.confidence; + totals.confidenceCount++; + } + } + + const evidenceSkills = new Set( + db + .query< + { + skill_name: string; + }, + SQLQueryBindings[] + >(`SELECT DISTINCT skill_name FROM evolution_evidence`) + .all() + .map((row) => row.skill_name), + ); + + const skillScopeRows = db + .query<{ skill_name: string; skill_scope: string | null }, SQLQueryBindings[]>( + `SELECT + si.skill_name, + COALESCE( + (SELECT s2.skill_scope FROM skill_invocations s2 + WHERE s2.skill_name = si.skill_name AND s2.skill_scope IS NOT NULL + ORDER BY s2.occurred_at DESC LIMIT 1), + (SELECT su.skill_scope FROM skill_usage su + WHERE su.skill_name = si.skill_name AND su.skill_scope IS NOT NULL + ORDER BY su.timestamp DESC LIMIT 1) + ) as skill_scope + FROM skill_invocations si + GROUP BY si.skill_name`, + ) + .all(); + const scopeBySkill = new Map(skillScopeRows.map((row) => [row.skill_name, row.skill_scope])); + const testingReadiness = testingReadinessRows ?? listSkillTestingReadiness(db); + const testingReadinessBySkill = new Map( + testingReadiness.map((row) => [row.skill_name, row] as const), + ); + const createReadinessBySkill = new Map( + testingReadiness + .flatMap((row) => { + if (!row.skill_path || !isCreateSkillDraft(row.skill_path)) return []; + try { + return [ + [ + row.skill_name, + computeCreateDashboardReadiness(row.skill_path, { + getTestingReadiness: () => row, + }), + ] as const, + ]; + } catch { + return []; + } + }) + .filter(Boolean), + ); + const knownSkills = new Set(bySkill.keys()); + for (const skillName of createReadinessBySkill.keys()) { + knownSkills.add(skillName); + } + + return [...knownSkills] + .map((skillName) => { + const totals = bySkill.get(skillName); + const totalChecks = totals?.checks ?? 0; + const triggeredCount = totals?.triggered ?? 0; + const uniqueSessions = totals?.sessions.size ?? 0; + const lastSeen = totals?.lastSeen ?? null; + const confidenceCount = totals?.confidenceCount ?? 0; + const routingConfidence = + totals && confidenceCount > 0 ? totals.confidenceSum / confidenceCount : null; + const readiness = testingReadinessBySkill.get(skillName); + const createReadiness = createReadinessBySkill.get(skillName); + const fallbackScope = + readiness?.skill_path != null ? classifySkillPath(readiness.skill_path).skill_scope : null; + const createScope = + createReadiness?.skill_path != null + ? classifySkillPath(createReadiness.skill_path).skill_scope + : null; + + return { + skill_name: skillName, + skill_scope: + scopeBySkill.get(skillName) ?? + (createScope && createScope !== "unknown" ? createScope : null) ?? + (fallbackScope && fallbackScope !== "unknown" ? fallbackScope : null), + total_checks: totalChecks, + triggered_count: triggeredCount, + pass_rate: totalChecks > 0 ? triggeredCount / totalChecks : 0, + unique_sessions: uniqueSessions, + last_seen: lastSeen, + has_evidence: evidenceSkills.has(skillName), + routing_confidence: routingConfidence, + confidence_coverage: totalChecks > 0 ? confidenceCount / totalChecks : 0, + testing_readiness: readiness, + create_readiness: createReadiness, + }; + }) + .sort( + (a, b) => + b.total_checks - a.total_checks || + (b.last_seen ?? "").localeCompare(a.last_seen ?? "") || + a.skill_name.localeCompare(b.skill_name), + ); +} diff --git a/packages/runtime/localdb/queries/trust.ts b/packages/runtime/localdb/queries/trust.ts index 163e3e4a..0a820437 100644 --- a/packages/runtime/localdb/queries/trust.ts +++ b/packages/runtime/localdb/queries/trust.ts @@ -77,7 +77,7 @@ function fingerprint(value: string): string { return createHash("sha256").update(value).digest("hex"); } -export function* iterateTrustedSkillObservationRows( +function* readTrustedSkillObservationRows( db: Database, ): IterableIterator { const isSystemLike = (text: string | null | undefined): boolean => { @@ -247,6 +247,37 @@ export function* iterateTrustedSkillObservationRows( } } +const trustedSnapshots = new WeakMap< + Database, + { version: string; rows: readonly TrustedSkillObservationRow[] } +>(); + +function observationVersion(db: Database): string { + const row = db + .query<{ changes: number; data_version: number }, []>( + "SELECT total_changes() AS changes, data_version FROM pragma_data_version", + ) + .get(); + if (row === null) throw new Error("SQLite returned no observation version"); + return `${row.changes}:${row.data_version}`; +} + +/** One accepted snapshot per connection, never a TTL or a persisted evidence replacement. */ +export function* iterateTrustedSkillObservationRows( + db: Database, +): IterableIterator { + const version = observationVersion(db); + const cached = trustedSnapshots.get(db); + let rows = cached?.version === version ? cached.rows : undefined; + if (!rows) { + rows = [...readTrustedSkillObservationRows(db)]; + if (observationVersion(db) === version) trustedSnapshots.set(db, { version, rows }); + else trustedSnapshots.delete(db); + } + // Callers historically own mutable rows. Do not let one caller poison another summary. + for (const row of rows) yield { ...row }; +} + export function queryTrustedSkillObservationRows(db: Database): TrustedSkillObservationRow[] { return [...iterateTrustedSkillObservationRows(db)]; } @@ -304,8 +335,10 @@ export function getSkillTrustSummaries(db: Database): SkillTrustSummary[] { return summaries; } -export function getAttentionQueue(db: Database): AttentionItem[] { - const summaries = getSkillTrustSummaries(db); +export function getAttentionQueue( + db: Database, + summaries = getSkillTrustSummaries(db), +): AttentionItem[] { const pending = getPendingProposals(db); const pendingSkills = new Set(pending.map((proposal) => proposal.skill_name).filter(Boolean)); diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 892ebd66..3f9e0191 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -35,7 +35,7 @@ "@selftune/source-management": "workspace:*", "@selftune/telemetry-contract": "workspace:*", "drizzle-orm": "^0.45.0", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/packages/runtime/registry/client.ts b/packages/runtime/registry/client.ts index c5b0fe19..7ff662d0 100644 --- a/packages/runtime/registry/client.ts +++ b/packages/runtime/registry/client.ts @@ -25,12 +25,12 @@ export interface RegistryRequestOptions { readonly formData?: FormData; } -export class RegistryAuthenticationError extends Schema.TaggedErrorClass()( +export class RegistryAuthenticationError extends Schema.TaggedError()( "RegistryAuthenticationError", { message: Schema.String }, ) {} -export class RegistryConfigError extends Schema.TaggedErrorClass()( +export class RegistryConfigError extends Schema.TaggedError()( "RegistryConfigError", { path: Schema.String, @@ -38,12 +38,12 @@ export class RegistryConfigError extends Schema.TaggedErrorClass()( +export class RegistryTransportError extends Schema.TaggedError()( "RegistryTransportError", { message: Schema.String }, ) {} -export class RegistryHttpError extends Schema.TaggedErrorClass()( +export class RegistryHttpError extends Schema.TaggedError()( "RegistryHttpError", { status: Schema.Number, @@ -51,7 +51,7 @@ export class RegistryHttpError extends Schema.TaggedErrorClass()( +export class RegistryResponseDecodeError extends Schema.TaggedError()( "RegistryResponseDecodeError", { status: Schema.Number, @@ -59,22 +59,22 @@ export class RegistryResponseDecodeError extends Schema.TaggedErrorClass()( +export class RegistryResponseSizeError extends Schema.TaggedError()( "RegistryResponseSizeError", { message: Schema.String }, ) {} -export class RegistryDownloadSizeError extends Schema.TaggedErrorClass()( +export class RegistryDownloadSizeError extends Schema.TaggedError()( "RegistryDownloadSizeError", { message: Schema.String }, ) {} -export class RegistryDownloadUrlError extends Schema.TaggedErrorClass()( +export class RegistryDownloadUrlError extends Schema.TaggedError()( "RegistryDownloadUrlError", { message: Schema.String }, ) {} -export class RegistryApiUrlError extends Schema.TaggedErrorClass()( +export class RegistryApiUrlError extends Schema.TaggedError()( "RegistryApiUrlError", { message: Schema.String }, ) {} diff --git a/packages/runtime/registry/path-policy.ts b/packages/runtime/registry/path-policy.ts index 7939c71e..aa8ad4cb 100644 --- a/packages/runtime/registry/path-policy.ts +++ b/packages/runtime/registry/path-policy.ts @@ -6,7 +6,7 @@ const MAX_IDENTIFIER_LENGTH = 128; const SKILL_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; const VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9.+_-]*$/; -export class RegistryIdentifierValidationError extends Schema.TaggedErrorClass()( +export class RegistryIdentifierValidationError extends Schema.TaggedError()( "RegistryIdentifierValidationError", { identifierType: Schema.Literals(["skill-name", "version"]), @@ -15,7 +15,7 @@ export class RegistryIdentifierValidationError extends Schema.TaggedErrorClass()( +export class RegistryPathConfinementError extends Schema.TaggedError()( "RegistryPathConfinementError", { root: Schema.String, diff --git a/packages/runtime/registry/program-types.ts b/packages/runtime/registry/program-types.ts index e9d9892e..7649cad2 100644 --- a/packages/runtime/registry/program-types.ts +++ b/packages/runtime/registry/program-types.ts @@ -39,7 +39,7 @@ export interface FormattedRegistryResult { readonly exitCode: 0 | 1; } -export class RegistryOperationError extends Schema.TaggedErrorClass()( +export class RegistryOperationError extends Schema.TaggedError()( "RegistryOperationError", { operation: Schema.String, message: Schema.String }, ) {} diff --git a/packages/runtime/registry/registry-state.ts b/packages/runtime/registry/registry-state.ts index bb6ee1b8..aaf2ab2d 100644 --- a/packages/runtime/registry/registry-state.ts +++ b/packages/runtime/registry/registry-state.ts @@ -132,7 +132,7 @@ const RegistryState = Schema.Array( }), ); -export class RegistryStateValidationError extends Schema.TaggedErrorClass()( +export class RegistryStateValidationError extends Schema.TaggedError()( "RegistryStateValidationError", { message: Schema.String, diff --git a/packages/runtime/remote-library/restore.ts b/packages/runtime/remote-library/restore.ts index e85d6b4d..5da58c0a 100644 --- a/packages/runtime/remote-library/restore.ts +++ b/packages/runtime/remote-library/restore.ts @@ -50,7 +50,9 @@ export async function restoreRemoteLibrary(options: { staging, "library", "packages", - identity.revisionHash, + artifact.artifactId.startsWith("backup-skill-object/") + ? artifact.objectHash + : identity.revisionHash, identity.skillName, ); const authority = restorePackage(bytes, destination); diff --git a/packages/runtime/skill-package-inspector.ts b/packages/runtime/skill-package-inspector.ts new file mode 100644 index 00000000..0c22d684 --- /dev/null +++ b/packages/runtime/skill-package-inspector.ts @@ -0,0 +1,14 @@ +import { Schema } from "effect"; + +export const SkillPackageIndex = Schema.Struct({ + files: Schema.Array( + Schema.Struct({ path: Schema.String, size: Schema.Number, symlink: Schema.Boolean }), + ), + limited: Schema.Boolean, +}); +export const SkillPackageFile = Schema.Struct({ + path: Schema.String, + size: Schema.Number, + content: Schema.NullOr(Schema.String), + reason: Schema.NullOr(Schema.Literals(["binary", "too_large", "symlink"])), +}); diff --git a/packages/runtime/skill-revision-history.ts b/packages/runtime/skill-revision-history.ts new file mode 100644 index 00000000..c555e8e2 --- /dev/null +++ b/packages/runtime/skill-revision-history.ts @@ -0,0 +1,236 @@ +import { createHash, randomUUID } from "node:crypto"; +import { + chmodSync, + existsSync, + lstatSync, + mkdirSync, + readFileSync, + readdirSync, + realpathSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { dirname, join, relative, resolve } from "node:path"; +import type { Database } from "bun:sqlite"; +import { getSkillRevision, listSkillRevisions, recordSkillRevision } from "@selftune/local-store"; +import { Schema } from "effect"; + +const SnapshotFile = Schema.Struct({ + path: Schema.String, + content: Schema.String, + mode: Schema.Number, +}); +const Snapshot = Schema.Array(SnapshotFile); +type FileSnapshot = typeof Snapshot.Type; +const MAX_BYTES = 8 * 1024 * 1024; +const MAX_FILES = 512; + +function safeRelativePath(path: string): boolean { + return ( + path.length > 0 && + !path.startsWith("/") && + !path.includes("\\") && + path.split("/").every((part) => part !== ".." && part !== "." && part.length > 0) + ); +} + +function snapshotPackage(root: string): FileSnapshot { + const files: Array = []; + let bytes = 0; + const visit = (directory: string): void => { + for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => + a.name.localeCompare(b.name), + )) { + const path = join(directory, entry.name); + const relativePath = relative(root, path); + if (!safeRelativePath(relativePath)) throw new Error("Unsupported skill file path."); + if (entry.isSymbolicLink()) + throw new Error("Skill history does not follow links inside a skill package."); + if (entry.isDirectory()) { + visit(path); + continue; + } + if (!entry.isFile()) throw new Error("Skill history only supports regular files."); + const stat = lstatSync(path); + bytes += stat.size; + if (bytes > MAX_BYTES || files.length >= MAX_FILES) + throw new Error("Skill history supports packages up to 8 MiB and 512 files."); + const content = readFileSync(path); + bytes += content.length - stat.size; + if (bytes > MAX_BYTES) throw new Error("Skill changed beyond the 8 MiB history limit."); + files.push({ + path: relativePath, + content: content.toString("base64"), + mode: stat.mode & 0o777, + }); + } + }; + visit(root); + if (!files.some((file) => file.path === "SKILL.md")) + throw new Error("Skill package must contain SKILL.md."); + return files; +} + +function hashSnapshot(files: FileSnapshot): string { + return createHash("sha256").update(JSON.stringify(files)).digest("hex"); +} + +function packageMetadata(root: string): string { + const entries: string[] = []; + let bytes = 0; + const visit = (directory: string): void => { + for (const entry of readdirSync(directory, { withFileTypes: true }).toSorted((a, b) => + a.name.localeCompare(b.name), + )) { + const path = join(directory, entry.name); + if (entry.isSymbolicLink()) + throw new Error("Skill history does not follow links inside a skill package."); + if (entry.isDirectory()) { + visit(path); + continue; + } + if (!entry.isFile()) throw new Error("Skill history only supports regular files."); + const stat = lstatSync(path, { bigint: true }); + bytes += Number(stat.size); + if (bytes > MAX_BYTES || entries.length >= MAX_FILES) + throw new Error("Skill history supports packages up to 8 MiB and 512 files."); + entries.push( + JSON.stringify([ + relative(root, path), + String(stat.ino), + String(stat.size), + String(stat.mtimeNs), + String(stat.ctimeNs), + String(stat.mode), + ]), + ); + } + }; + visit(root); + return entries.join("\n"); +} + +export function createSkillRevisionHistory(db: Database, configRoot: string) { + const fingerprints = new Map(); + const canonicalPath = (path: string): string => { + const root = realpathSync(path); + const libraryPath = resolve(configRoot, "library"); + const library = existsSync(libraryPath) ? realpathSync(libraryPath) : libraryPath; + const withinLibrary = relative(library, root); + if ( + withinLibrary === "" || + (!withinLibrary.startsWith("..") && !withinLibrary.startsWith("/")) + ) { + throw new Error( + "Immutable Library packages cannot be restored in place. Install an editable copy first.", + ); + } + return root; + }; + const capture = (path: string, reason = "observed", restoredFrom: number | null = null) => { + const root = canonicalPath(path); + const files = snapshotPackage(root); + const contentHash = hashSnapshot(files); + if (hashSnapshot(snapshotPackage(root)) !== contentHash) + throw new Error("Skill changed during capture; retry after the edit finishes."); + return recordSkillRevision(db, { + package_path: root, + content_hash: contentHash, + captured_at: new Date().toISOString(), + reason, + restored_from: restoredFrom, + snapshot_json: JSON.stringify(files), + }); + }; + const read = (path: string, revision: number) => { + const stored = getSkillRevision(db, canonicalPath(path), revision); + if (!stored) throw new Error("Revision not found."); + const files = Schema.decodeUnknownSync(Schema.fromJsonString(Snapshot))(stored.snapshot_json); + if ( + files.some((file) => !safeRelativePath(file.path)) || + hashSnapshot(files) !== stored.content_hash + ) + throw new Error("Revision snapshot failed its integrity check."); + return files; + }; + return { + capture, + fingerprint: (path: string) => { + const root = canonicalPath(path); + const metadata = packageMetadata(root); + const cached = fingerprints.get(root); + if (cached?.metadata === metadata) return cached.hash; + const hash = hashSnapshot(snapshotPackage(root)); + if (packageMetadata(root) !== metadata) + throw new Error("Skill changed during capture; retry after the edit finishes."); + if (fingerprints.size >= 2048) fingerprints.clear(); + fingerprints.set(root, { metadata, hash }); + return hash; + }, + list: (path: string, before?: number) => listSkillRevisions(db, canonicalPath(path), before), + diff: (path: string, revision: number) => { + const after = read(path, revision); + const before = revision > 1 ? read(path, revision - 1) : []; + const previous = new Map(before.map((file) => [file.path, file])); + const current = new Map(after.map((file) => [file.path, file])); + return [...new Set([...previous.keys(), ...current.keys()])].sort().flatMap((filePath) => { + const left = previous.get(filePath); + const right = current.get(filePath); + if (left?.content === right?.content && left?.mode === right?.mode) return []; + const text = (file: typeof SnapshotFile.Type | undefined) => { + if (!file) return null; + const bytes = Buffer.from(file.content, "base64"); + const value = bytes.toString("utf8"); + return value.includes("\0") || !Buffer.from(value).equals(bytes) ? null : value; + }; + return [ + { + path: filePath, + change: !left ? "added" : !right ? "deleted" : "modified", + before: text(left), + after: text(right), + beforeMode: left?.mode ?? null, + afterMode: right?.mode ?? null, + }, + ]; + }); + }, + restore: (path: string, revision: number, expectedHash: string) => { + const root = canonicalPath(path); + const files = read(root, revision); + const current = capture(root, "before_restore"); + if (current.content_hash !== expectedHash) + throw new Error("Skill changed since review. Refresh history before restoring."); + const staging = join(dirname(root), `.selftune-restore-${randomUUID()}`); + const backup = `${staging}-previous`; + mkdirSync(staging, { mode: lstatSync(root).mode & 0o777 }); + let moved = false; + try { + for (const file of files) { + const target = join(staging, file.path); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, Buffer.from(file.content, "base64"), { mode: file.mode }); + chmodSync(target, file.mode); + } + if (hashSnapshot(snapshotPackage(root)) !== expectedHash) + throw new Error("Skill changed during restore preparation. Retry after editing stops."); + renameSync(root, backup); + moved = true; + renameSync(staging, root); + const result = capture(root, "restore", revision); + moved = false; + rmSync(backup, { recursive: true }); + return result; + } catch (error) { + if (moved) { + rmSync(root, { recursive: true, force: true }); + renameSync(backup, root); + } + throw error; + } finally { + rmSync(staging, { recursive: true, force: true }); + } + }, + }; +} diff --git a/packages/runtime/skill-sets/catalog-resolution.ts b/packages/runtime/skill-sets/catalog-resolution.ts index 20060161..ae3e81e5 100644 --- a/packages/runtime/skill-sets/catalog-resolution.ts +++ b/packages/runtime/skill-sets/catalog-resolution.ts @@ -30,7 +30,7 @@ export class CatalogSkillResolutionProgress extends Schema.Class()( +export class CatalogSkillResolverFailure extends Schema.TaggedError()( "CatalogSkillResolverFailure", { skill_name: Schema.String, @@ -52,7 +52,7 @@ export const CatalogSkillResolutionFailureDetail = Schema.Struct({ }); export type CatalogSkillResolutionFailureDetail = typeof CatalogSkillResolutionFailureDetail.Type; -export class CatalogSkillSetResolutionError extends Schema.TaggedErrorClass()( +export class CatalogSkillSetResolutionError extends Schema.TaggedError()( "CatalogSkillSetResolutionError", { code: Schema.Literal("CATALOG_SKILL_RESOLUTION_FAILED"), @@ -63,7 +63,7 @@ export class CatalogSkillSetResolutionError extends Schema.TaggedErrorClass()( +export class SkillSetCreationError extends Schema.TaggedError()( "SkillSetCreationError", { code: Schema.String, diff --git a/packages/runtime/team-contribution.ts b/packages/runtime/team-contribution.ts index 91b6beed..f1c1cf36 100644 --- a/packages/runtime/team-contribution.ts +++ b/packages/runtime/team-contribution.ts @@ -159,7 +159,9 @@ function stateStore(configRoot: string) { let queue: Promise = Promise.resolve(); const load = async (): Promise => { try { - const state = Schema.decodeUnknownSync(StoredState)(JSON.parse(await readFile(path, "utf8"))); + const state = Schema.decodeUnknownSync(StoredState, { onExcessProperty: "error" })( + JSON.parse(await readFile(path, "utf8")), + ); for (const [requestId, upload] of Object.entries(state.outbox)) { if ( upload.request.request_id !== requestId || diff --git a/packages/runtime/team-revalidation.ts b/packages/runtime/team-revalidation.ts index aad8da25..7a90dc5d 100644 --- a/packages/runtime/team-revalidation.ts +++ b/packages/runtime/team-revalidation.ts @@ -105,7 +105,7 @@ export interface TeamRevalidationHostedSummary { readonly supported_model_count: number; } -export class TeamSkillSetRevalidationError extends Schema.TaggedErrorClass()( +export class TeamSkillSetRevalidationError extends Schema.TaggedError()( "TeamSkillSetRevalidationError", { code: Schema.String, diff --git a/packages/runtime/testing-readiness.ts b/packages/runtime/testing-readiness.ts index 3cfd7852..4db26032 100644 --- a/packages/runtime/testing-readiness.ts +++ b/packages/runtime/testing-readiness.ts @@ -1,4 +1,6 @@ import type { Database } from "bun:sqlite"; +import { SELFTUNE_CONFIG_DIR } from "./constants.js"; +import { queryKnownWorkspacePaths } from "./localdb/queries.js"; import { existsSync, readdirSync, statSync } from "node:fs"; import { dirname, join } from "node:path"; @@ -7,6 +9,7 @@ import type { grading_baselines, package_evaluation_reports, evolution_audit, + evolution_evidence, skill_invocations, } from "@selftune/local-store/schema"; @@ -21,15 +24,16 @@ import type { } from "./dashboard-contract.js"; import type { CreatePackageEvaluationStatus, CreatePackageEvaluationSummary } from "./types.js"; import { computeCreatePackageFingerprint } from "./create/package-fingerprint.js"; -import { queryEvolutionEvidence } from "./localdb/queries/evolution.js"; +import { safeParseJsonObjectArray } from "./localdb/queries/json.js"; import { queryTrustedSkillObservationRows } from "./localdb/queries/trust.js"; import { MIN_LOG_READY_POSITIVES } from "./utils/eval-readiness.js"; import { extractPositiveEvalQueryText } from "./utils/query-filter.js"; import { findInstalledSkillNames, findInstalledSkillPath, - findRepositoryClaudeSkillDirs, - findRepositorySkillDirs, + findInstalledSkillPaths, + getDefaultSkillSearchDirs, + extendSkillSearchDirsForWorkspaces, } from "./utils/skill-discovery.js"; import { getCanonicalEvalSetPath, @@ -79,7 +83,7 @@ interface TrustedSkillObservationSummary { interface TestingReadinessContext { db: Database; knownSkills: Set; - searchDirs: string[]; + installedSkillPaths: Map; trustedRowsBySkill: Map; evalEvidenceBySkill: Map; fallbackSkillPathBySkill: Map; @@ -95,17 +99,14 @@ interface TestingReadinessContext { latestEvolutionBySkill: Map; } -function getSkillSearchDirs(): string[] { - const cwd = process.cwd(); - const homeDir = process.env.HOME ?? ""; - const codexHome = process.env.CODEX_HOME ?? `${homeDir}/.codex`; - return [ - ...findRepositorySkillDirs(cwd), - ...findRepositoryClaudeSkillDirs(cwd), - `${homeDir}/.agents/skills`, - `${homeDir}/.claude/skills`, - `${codexHome}/skills`, - ]; +function getSkillSearchDirs(db: Database): string[] { + return extendSkillSearchDirsForWorkspaces( + [ + ...getDefaultSkillSearchDirs(), + join(process.env.SELFTUNE_CONFIG_DIR || SELFTUNE_CONFIG_DIR, "library", "packages"), + ], + queryKnownWorkspacePaths(db), + ); } function scanSkillNamesFromDir( @@ -319,7 +320,7 @@ function summarizeDeploymentReadiness( export function listSkillTestingReadiness( db: Database, - searchDirs: string[] = getSkillSearchDirs(), + searchDirs: string[] = getSkillSearchDirs(db), ): SkillTestingReadiness[] { const context = buildTestingReadinessContext(db, searchDirs); @@ -339,12 +340,19 @@ export function listSkillTestingReadiness( export function getSkillTestingReadiness( db: Database, skillName: string, - searchDirs: string[] = getSkillSearchDirs(), + searchDirs: string[] = getSkillSearchDirs(db), ): SkillTestingReadiness | null { - return buildSkillTestingReadinessRow(skillName, buildTestingReadinessContext(db, searchDirs)); + return buildSkillTestingReadinessRow( + skillName, + buildTestingReadinessContext(db, searchDirs, skillName), + ); } -function buildTestingReadinessContext(db: Database, searchDirs: string[]): TestingReadinessContext { +function buildTestingReadinessContext( + db: Database, + searchDirs: string[], + skillName?: string, +): TestingReadinessContext { const trustedRows = queryTrustedSkillObservationRows(db); const trustedRowsBySkill = new Map(); @@ -384,15 +392,23 @@ function buildTestingReadinessContext(db: Database, searchDirs: string[]): Testi const storedUnitTestRunNames = listStoredSkillNames(db, "unit_test_run_results"); const storedPackageEvaluationNames = listStoredSkillNames(db, "package_evaluation_reports"); - const evidenceRows = queryEvolutionEvidence(db); + const evidenceRows = db.query< + Pick< + typeof evolution_evidence.$inferSelect, + "skill_name" | "skill_path" | "timestamp" | "eval_set_json" + >, + string[] + >( + skillName === undefined + ? "SELECT skill_name, skill_path, timestamp, eval_set_json FROM evolution_evidence ORDER BY timestamp DESC" + : "SELECT skill_name, skill_path, timestamp, eval_set_json FROM evolution_evidence WHERE skill_name = ? ORDER BY timestamp DESC", + ); const evalEvidenceBySkill = new Map(); const fallbackSkillPathBySkill = new Map(); - for (const row of evidenceRows) { - if (row.eval_set && row.eval_set.length > 0 && !evalEvidenceBySkill.has(row.skill_name)) { - evalEvidenceBySkill.set(row.skill_name, { - count: row.eval_set.length, - latestAt: row.timestamp, - }); + for (const row of evidenceRows.iterate(...(skillName === undefined ? [] : [skillName]))) { + if (!evalEvidenceBySkill.has(row.skill_name)) { + const count = safeParseJsonObjectArray(row.eval_set_json).length; + if (count > 0) evalEvidenceBySkill.set(row.skill_name, { count, latestAt: row.timestamp }); } if (row.skill_path && !fallbackSkillPathBySkill.has(row.skill_name)) { fallbackSkillPathBySkill.set(row.skill_name, row.skill_path); @@ -535,10 +551,18 @@ function buildTestingReadinessContext(db: Database, searchDirs: string[]): Testi ...fallbackSkillPathBySkill.keys(), ]); + const installedSkillPaths = new Map(); + if (skillName !== undefined) { + const path = findInstalledSkillPath(skillName, searchDirs); + if (path) installedSkillPaths.set(skillName.trim(), path); + } return { db, knownSkills, - searchDirs, + installedSkillPaths: + skillName === undefined + ? findInstalledSkillPaths(searchDirs, knownSkills) + : installedSkillPaths, trustedRowsBySkill, evalEvidenceBySkill, fallbackSkillPathBySkill, @@ -560,7 +584,7 @@ function buildSkillTestingReadinessRow( const trustedTriggerCount = trustedPositiveRows.length; const trustedSessionCount = new Set(trustedPositiveRows.map((row) => row.session_id)).size; - const installedSkillPath = findInstalledSkillPath(skillName, context.searchDirs) ?? null; + const installedSkillPath = context.installedSkillPaths.get(skillName.trim()) ?? null; if (!context.knownSkills.has(skillName) && installedSkillPath == null) { return null; } diff --git a/packages/runtime/testing-readiness/evidence-completeness.ts b/packages/runtime/testing-readiness/evidence-completeness.ts new file mode 100644 index 00000000..d06f5a23 --- /dev/null +++ b/packages/runtime/testing-readiness/evidence-completeness.ts @@ -0,0 +1,208 @@ +import { isAbsolute, resolve } from "node:path"; +import { Effect, Option, Schema } from "effect"; +import { flow } from "effect/Function"; +import { EvaluationHistory } from "@selftune/control-plane/domain/evaluation-report"; +import { + MAX_RECONSTRUCTION_BYTES, + readBoundedSource, + sourceDigest, + SourceReconstruction, +} from "@selftune/observability/source-reconstruction"; +import { GradingResult } from "../types.js"; +import { EvalEntry } from "../types/evaluation.js"; + +const ExplicitPath = Schema.String.check( + Schema.isNonEmpty(), + Schema.isMaxLength(4096), + Schema.makeFilter(isAbsolute), +); +export const EvidenceInspectionRequest = Schema.Struct({ + artifacts: Schema.Array( + Schema.Struct({ + kind: Schema.Literals(["grade", "routing_evals", "evaluation_history", "source_recipe"]), + path: ExplicitPath, + }), + ).check(Schema.isMinLength(1), Schema.isMaxLength(16)), + authorized_sources: Schema.Array(ExplicitPath).check(Schema.isMaxLength(16)), +}).check( + Schema.makeFilter( + (request) => + new Set(request.artifacts.map((artifact) => resolve(artifact.path))).size === + request.artifacts.length, + ), +); + +export class EvidenceInspectionFailure extends Schema.TaggedError()( + "EvidenceInspectionFailure", + { message: Schema.String }, +) {} + +type Category = "self_contained" | "source_dependent" | "missing" | "unsupported"; +const categoryFor = { + routing_inputs_embedded: "self_contained", + grade_original_unverified: "source_dependent", + recipe_original_verified: "source_dependent", + source_not_authorized: "source_dependent", + evaluation_summary_only: "source_dependent", + artifact_missing: "missing", + source_path_missing: "missing", + source_missing: "missing", + source_changed: "missing", + empty_inputs: "missing", + unsupported_contract: "unsupported", + artifact_unavailable: "unsupported", + source_unavailable: "unsupported", + artifact_over_budget: "unsupported", + source_over_budget: "unsupported", + source_reference_unsupported: "unsupported", +} satisfies Record; +type Reason = keyof typeof categoryFor; + +/** Content-completeness only. This contract never authorizes eviction or claims replay validity. */ +export interface EvidenceCompletenessReport { + readonly schema_version: "1.0.0"; + readonly scope: "explicit_artifact_content_only"; + readonly decision: "keep_all_sources"; + readonly artifacts_assessed: number; + readonly replay_qualified: 0; + readonly eviction_eligible: 0; + readonly counts: Readonly>; + readonly reasons: Readonly>; + readonly limits: { + readonly max_artifacts: 16; + readonly max_source_reads: 16; + readonly max_bytes_per_file: number; + }; +} + +const decode = (schema: Schema.Codec, raw: string) => + Schema.decodeUnknownOption(Schema.fromJsonString(schema), { onExcessProperty: "error" })(raw); +const RoutingEvals = Schema.Array(EvalEntry).check(Schema.isMaxLength(256)); + +const inspectSource = Effect.fn("EvidenceCompleteness.inspectSource")(function* ( + path: string, + authorized: ReadonlySet, + expected?: { readonly sha256: string; readonly bytes: number }, +): Effect.fn.Return { + if (!path.trim()) return "source_path_missing"; + if (!isAbsolute(path)) return "source_reference_unsupported"; + if (!authorized.has(resolve(path))) return "source_not_authorized"; + const result = yield* Effect.promise(() => readBoundedSource(path)); + if (result.state === "unavailable") { + switch (result.reason) { + case "source_missing": + return "source_missing"; + case "source_unavailable": + return "source_unavailable"; + case "over_budget": + return "source_over_budget"; + } + } + if (!expected) return "grade_original_unverified"; + if (result.bytes.length !== expected.bytes || sourceDigest(result.bytes) !== expected.sha256) + return "source_changed"; + return "recipe_original_verified"; +}); + +const inspectArtifact = Effect.fn("EvidenceCompleteness.inspectArtifact")(function* ( + artifact: (typeof EvidenceInspectionRequest.Type.artifacts)[number], + authorized: ReadonlySet, +): Effect.fn.Return { + const result = yield* Effect.promise(() => readBoundedSource(artifact.path)); + if (result.state === "unavailable") { + switch (result.reason) { + case "source_missing": + return "artifact_missing"; + case "source_unavailable": + return "artifact_unavailable"; + case "over_budget": + return "artifact_over_budget"; + } + } + const raw = result.bytes.toString("utf8"); + switch (artifact.kind) { + case "grade": { + const grade = decode(GradingResult, raw); + return Option.isSome(grade) + ? yield* inspectSource(grade.value.transcript_path, authorized) + : "unsupported_contract"; + } + case "routing_evals": { + const entries = decode(RoutingEvals, raw); + if (Option.isNone(entries)) return "unsupported_contract"; + return entries.value.length > 0 && + entries.value.every((entry) => entry.query.trim().length > 0) + ? "routing_inputs_embedded" + : "empty_inputs"; + } + case "evaluation_history": { + const history = decode(EvaluationHistory, raw); + if (Option.isNone(history)) return "unsupported_contract"; + return history.value.length > 0 ? "evaluation_summary_only" : "empty_inputs"; + } + case "source_recipe": { + const recipe = decode(SourceReconstruction, raw); + return Option.isSome(recipe) + ? yield* inspectSource(recipe.value.snapshot.path, authorized, recipe.value.snapshot) + : "unsupported_contract"; + } + } +}); + +const inspectRequest = Effect.fn("EvidenceCompleteness.inspect")(function* ( + request: typeof EvidenceInspectionRequest.Type, +): Effect.fn.Return { + const authorized = new Set(request.authorized_sources.map((path) => resolve(path))); + const counts = { self_contained: 0, source_dependent: 0, missing: 0, unsupported: 0 }; + const reasons: Record = { + routing_inputs_embedded: 0, + grade_original_unverified: 0, + recipe_original_verified: 0, + source_not_authorized: 0, + evaluation_summary_only: 0, + artifact_missing: 0, + source_path_missing: 0, + source_missing: 0, + source_changed: 0, + empty_inputs: 0, + unsupported_contract: 0, + artifact_unavailable: 0, + source_unavailable: 0, + artifact_over_budget: 0, + source_over_budget: 0, + source_reference_unsupported: 0, + }; + for (const artifact of request.artifacts) { + const reason = yield* inspectArtifact(artifact, authorized); + counts[categoryFor[reason]]++; + reasons[reason]++; + } + return { + schema_version: "1.0.0", + scope: "explicit_artifact_content_only", + decision: "keep_all_sources", + artifacts_assessed: request.artifacts.length, + counts, + reasons, + replay_qualified: 0, + eviction_eligible: 0, + limits: { + max_artifacts: 16, + max_source_reads: 16, + max_bytes_per_file: MAX_RECONSTRUCTION_BYTES, + }, + }; +}); + +/** Explicit files only; decode before I/O. Never opens a database or discovers dependencies. */ +export const inspectEvidenceCompleteness = flow( + Schema.decodeUnknownEffect(EvidenceInspectionRequest), + Effect.mapError( + () => + new EvidenceInspectionFailure({ + message: + "Invalid evidence inspection request; supply 1–16 distinct absolute artifact paths and at most 16 authorized source paths.", + }), + ), + Effect.flatMap(inspectRequest), +); diff --git a/packages/runtime/types/grading.ts b/packages/runtime/types/grading.ts index bc7de93f..e3e5f5ef 100644 --- a/packages/runtime/types/grading.ts +++ b/packages/runtime/types/grading.ts @@ -53,6 +53,9 @@ export type EvalFeedback = typeof EvalFeedback.Type; export const GraderOutput = Schema.Struct({ expectations: Schema.mutableKey(Schema.mutable(Schema.Array(GradingExpectation))), + unobserved_expectations: Schema.optionalKey( + Schema.Array(Schema.Struct({ text: Schema.String, reason: Schema.String })), + ), summary: Schema.mutableKey(GradingSummary), claims: Schema.mutableKey(Schema.mutable(Schema.Array(GradingClaim))), eval_feedback: Schema.mutableKey(EvalFeedback), diff --git a/packages/runtime/utils/frontmatter.ts b/packages/runtime/utils/frontmatter.ts index e28c9c6e..83938b20 100644 --- a/packages/runtime/utils/frontmatter.ts +++ b/packages/runtime/utils/frontmatter.ts @@ -102,7 +102,7 @@ export function parseFrontmatter(content: string): SkillFrontmatter { inMetadata = false; const afterKey = trimmed.slice("description:".length).trim(); - if (afterKey === ">" || afterKey === "|") { + if (/^[>|][+-]?$/.test(afterKey)) { // Folded/literal scalar: collect indented continuation lines const descParts: string[] = []; let j = i + 1; diff --git a/packages/runtime/utils/jsonl.ts b/packages/runtime/utils/jsonl.ts index bc086b95..d915a8b5 100644 --- a/packages/runtime/utils/jsonl.ts +++ b/packages/runtime/utils/jsonl.ts @@ -15,10 +15,10 @@ import { } from "node:fs"; import { dirname } from "node:path"; import * as Schema from "effect/Schema"; +import { preservingJsonDecoder } from "./preserving-schema.js"; export function jsonlDecoder(schema: Schema.Codec) { - const decode = Schema.decodeUnknownSync(Schema.fromJsonString(schema)); - return (line: string) => decode(line, { onExcessProperty: "preserve" }); + return preservingJsonDecoder(schema); } export const decodeJsonLine = jsonlDecoder(Schema.Json); @@ -119,6 +119,8 @@ export interface FileIngestionFingerprint { readonly size: number; readonly mtime_ms: number; readonly normalizer_version: string; + readonly ctime_ns?: string; + readonly file_identity?: string; } export type FileIngestionMarker = Map; @@ -127,6 +129,8 @@ const FileFingerprint = Schema.Struct({ size: Schema.Number.check(Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0)), mtime_ms: Schema.Number.check(Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0)), normalizer_version: Schema.String.check(Schema.isMinLength(1)), + ctime_ns: Schema.optionalKey(Schema.String), + file_identity: Schema.optionalKey(Schema.String), }); const SerializedFileIngestionMarker = Schema.Struct({ marker_version: Schema.Literal(2), @@ -156,11 +160,13 @@ export function fingerprintIngestionFile( path: string, normalizerVersion: string, ): FileIngestionFingerprint { - const stats = statSync(path); + const stats = statSync(path, { bigint: true }); return { - size: stats.size, - mtime_ms: stats.mtimeMs, + size: Number(stats.size), + mtime_ms: Number(stats.mtimeNs) / 1_000_000, normalizer_version: normalizerVersion, + ctime_ns: String(stats.ctimeNs), + file_identity: `${stats.dev}:${stats.ino}`, }; } @@ -173,10 +179,21 @@ export function isFileIngestionCurrent( return ( previous?.size === fingerprint.size && previous.mtime_ms === fingerprint.mtime_ms && + previous.ctime_ns === fingerprint.ctime_ns && + previous.file_identity === fingerprint.file_identity && previous.normalizer_version === fingerprint.normalizer_version ); } +export function fileIngestionRevision(fingerprint: FileIngestionFingerprint): string { + return [ + fingerprint.size, + fingerprint.mtime_ms, + fingerprint.ctime_ns, + fingerprint.file_identity, + ].join(":"); +} + /** Save deterministic, versioned file fingerprints for append-aware ingestion. */ export function saveFileIngestionMarker(path: string, marker: FileIngestionMarker): void { const dir = dirname(path); diff --git a/packages/runtime/utils/log-contracts.ts b/packages/runtime/utils/log-contracts.ts index 39666a87..eb806fac 100644 --- a/packages/runtime/utils/log-contracts.ts +++ b/packages/runtime/utils/log-contracts.ts @@ -1,4 +1,6 @@ import * as Schema from "effect/Schema"; +import * as Option from "effect/Option"; +import { preservingDecoder } from "./preserving-schema.js"; import { OrchestrateRunReport } from "@selftune/control-plane/orchestration"; import { isCanonicalRecord } from "@selftune/telemetry-contract"; import { EvalEntry } from "../types/evaluation.js"; @@ -180,11 +182,17 @@ export const decodeQueryLogLine = jsonlDecoder(QueryLog); export const decodeSkillUsageLine = jsonlDecoder(SkillUsageLog); export const decodeSessionTelemetryLine = jsonlDecoder(SessionTelemetryLog); export const decodeImprovementSignalLine = jsonlDecoder(ImprovementSignalLog); -export const decodeImprovementSignalRecord = Schema.decodeUnknownOption(ImprovementSignalLog); +export const decodeImprovementSignalRecord = Option.liftThrowable( + preservingDecoder(ImprovementSignalLog), +); export const decodeEvolutionAuditLine = jsonlDecoder(EvolutionAuditLog); export const decodeEvolutionEvidenceLine = jsonlDecoder(EvolutionEvidenceLog); -export const decodeEvolutionAuditRecord = Schema.decodeUnknownOption(EvolutionAuditLog); -export const decodeEvolutionEvidenceRecord = Schema.decodeUnknownOption(EvolutionEvidenceLog); +export const decodeEvolutionAuditRecord = Option.liftThrowable( + preservingDecoder(EvolutionAuditLog), +); +export const decodeEvolutionEvidenceRecord = Option.liftThrowable( + preservingDecoder(EvolutionEvidenceLog), +); export const decodeOrchestrateRunLine = jsonlDecoder(OrchestrateRunReport); export const decodeLogTimestampLine = Schema.decodeUnknownSync( Schema.fromJsonString(Schema.Struct({ timestamp: Schema.String })), diff --git a/packages/runtime/utils/preserving-schema.test.ts b/packages/runtime/utils/preserving-schema.test.ts new file mode 100644 index 00000000..3fa06113 --- /dev/null +++ b/packages/runtime/utils/preserving-schema.test.ts @@ -0,0 +1,18 @@ +import { expect, test } from "bun:test"; +import * as Schema from "effect/Schema"; +import { preservingJsonDecoder } from "./preserving-schema.js"; + +test("local identity records retain unknown fields at every nesting level", () => { + const decode = preservingJsonDecoder( + Schema.Struct({ nested: Schema.Struct({ known: Schema.String }) }), + ); + const record = { nested: { known: "yes", future: [1, 2] }, version: 2 }; + expect(decode(JSON.stringify(record))).toEqual(record); + expect(() => decode('{"nested":{"known":42}}')).toThrow(); + expect(() => decode("invalid JSON")).toThrow(); +}); + +test("codec transformations still decode when the input is not already a valid decoded value", () => { + const decode = preservingJsonDecoder(Schema.NumberFromString); + expect(decode('"42"')).toBe(42); +}); diff --git a/packages/runtime/utils/preserving-schema.ts b/packages/runtime/utils/preserving-schema.ts new file mode 100644 index 00000000..c9c07dee --- /dev/null +++ b/packages/runtime/utils/preserving-schema.ts @@ -0,0 +1,52 @@ +import * as Schema from "effect/Schema"; +import type * as Predicate from "effect/Predicate"; +const isRecord = Schema.is(Schema.Record(Schema.String, Schema.Unknown)); + +// SAFETY-UNKNOWN: Only used within the schema boundary; the merged result is validated below. +function restoreExtensions( + original: unknown, + decoded: unknown, + validate: Predicate.Predicate, +): unknown { + if (Array.isArray(decoded) && Array.isArray(original)) { + return decoded.map((value, index) => + restoreExtensions(original[index], value, (child) => + validate(decoded.map((entry, position) => (position === index ? child : entry))), + ), + ); + } + if (isRecord(original) && isRecord(decoded)) { + let result = { ...decoded }; + for (const [key, value] of Object.entries(original)) { + const child = Object.hasOwn(decoded, key) + ? restoreExtensions(value, decoded[key], (candidate) => + validate({ ...result, [key]: candidate }), + ) + : value; + const candidate = { ...result, [key]: child }; + if (validate(candidate)) result = candidate; + } + return result; + } + return decoded; +} + +/** Validate identity-shaped local records without stripping forward-compatible fields. */ +export function preservingDecoder(schema: Schema.Decoder) { + const isDecoded = Schema.is(Schema.toType(schema)); + const decode = Schema.decodeUnknownSync(schema); + // SAFETY-UNKNOWN: Schema.is validates the complete decoded value before returning it. + const decodePreserving = (value: unknown): A => { + if (isDecoded(value)) return value; + const decoded = decode(value); + const merged = restoreExtensions(value, decoded, isDecoded); + return isDecoded(merged) ? merged : decoded; + }; + return decodePreserving; +} + +export function preservingJsonDecoder(schema: Schema.Decoder) { + const parse = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); + const decode = preservingDecoder(schema); + return (text: string): A => decode(parse(text)); +} diff --git a/packages/runtime/utils/skill-discovery.ts b/packages/runtime/utils/skill-discovery.ts index 90ca72cb..38a2ce4d 100644 --- a/packages/runtime/utils/skill-discovery.ts +++ b/packages/runtime/utils/skill-discovery.ts @@ -241,6 +241,55 @@ export function findInstalledSkillPackages( ); } +/** Index a report's lookup paths once, preserving direct-before-nested and registry order. */ +export function findInstalledSkillPaths( + dirs: string[], + requestedNames: Iterable = [], +): Map { + const paths = new Map(); + const aliases = new Map>(); + for (const name of requestedNames) { + const trimmed = name.trim(); + const key = trimmed.toLowerCase(); + const names = aliases.get(key) ?? new Set(); + names.add(trimmed); + aliases.set(key, names); + } + const add = (name: string, path: string) => { + if (paths.has(name) || !existsSync(path)) return; + try { + paths.set(name, realpathSync(path)); + } catch { + paths.set(name, path); + } + }; + const addPackage = (parent: string, name: string) => { + add(name, join(parent, name, "SKILL.md")); + for (const alias of aliases.get(name.toLowerCase()) ?? []) { + add(alias, join(parent, alias, "SKILL.md")); + } + }; + for (const dir of dirs) { + if (!existsSync(dir)) continue; + try { + const entries = readdirSync(dir); + for (const entry of entries) addPackage(dir, entry); + for (const entry of entries) { + try { + for (const nested of readdirSync(join(dir, entry))) { + addPackage(join(dir, entry), nested); + } + } catch { + // Files, broken links, and unreadable directories cannot contain skills. + } + } + } catch { + // Ignore unreadable registries, matching individual skill lookup. + } + } + return paths; +} + export function findInstalledSkillPath(skillName: string, dirs: string[]): string | undefined { const trimmedName = skillName.trim(); if (!trimmedName) return undefined; diff --git a/packages/skill-intelligence/src/blind-benchmark.ts b/packages/skill-intelligence/src/blind-benchmark.ts index 8c807adf..fc454011 100644 --- a/packages/skill-intelligence/src/blind-benchmark.ts +++ b/packages/skill-intelligence/src/blind-benchmark.ts @@ -58,7 +58,7 @@ export const BlindBenchmarkAttempt = Schema.Union([ ]); export type BlindBenchmarkAttempt = typeof BlindBenchmarkAttempt.Type; -export class BlindBenchmarkExecutionFailure extends Schema.TaggedErrorClass()( +export class BlindBenchmarkExecutionFailure extends Schema.TaggedError()( "BlindBenchmarkExecutionFailure", { kind: Schema.Literals(["infrastructure", "cancelled", "budget_exhausted"]), diff --git a/packages/skill-intelligence/src/paired-replay.ts b/packages/skill-intelligence/src/paired-replay.ts index be49b037..0be0ea4a 100644 --- a/packages/skill-intelligence/src/paired-replay.ts +++ b/packages/skill-intelligence/src/paired-replay.ts @@ -73,7 +73,7 @@ export const ReplayArmAttempt = Schema.Union([ ]); export type ReplayArmAttempt = typeof ReplayArmAttempt.Type; -export class PairedReplayExecutionFailure extends Schema.TaggedErrorClass()( +export class PairedReplayExecutionFailure extends Schema.TaggedError()( "PairedReplayExecutionFailure", { kind: Schema.Literals(["infrastructure", "cancelled", "budget_exhausted"]), diff --git a/packages/source-management/package.json b/packages/source-management/package.json index e15ae895..72651a0e 100644 --- a/packages/source-management/package.json +++ b/packages/source-management/package.json @@ -17,7 +17,7 @@ }, "dependencies": { "@selftune/control-plane": "workspace:*", - "effect": "4.0.0-beta.66" + "effect": "4.0.0-rc.115" }, "devDependencies": { "@types/bun": "^1.3.11", diff --git a/packages/source-management/src/contracts.ts b/packages/source-management/src/contracts.ts index bd63c564..5d9f293d 100644 --- a/packages/source-management/src/contracts.ts +++ b/packages/source-management/src/contracts.ts @@ -89,7 +89,7 @@ export interface PreparedSkillSourceMergeAudit { >; } -export class SkillSourceUpdateFailure extends Schema.TaggedErrorClass()( +export class SkillSourceUpdateFailure extends Schema.TaggedError()( "SkillSourceUpdateFailure", { code: Schema.String, diff --git a/packages/source-management/src/sync.ts b/packages/source-management/src/sync.ts index 0c4737b0..aa43865e 100644 --- a/packages/source-management/src/sync.ts +++ b/packages/source-management/src/sync.ts @@ -45,7 +45,7 @@ export interface SourceSyncRequest { dryRun?: boolean; } -export class SourceSyncUnavailable extends Schema.TaggedErrorClass()( +export class SourceSyncUnavailable extends Schema.TaggedError()( "SourceSyncUnavailable", { operation: Schema.String, diff --git a/packages/ui/src/components/SkillPackageViewer.tsx b/packages/ui/src/components/SkillPackageViewer.tsx new file mode 100644 index 00000000..4f4100fc --- /dev/null +++ b/packages/ui/src/components/SkillPackageViewer.tsx @@ -0,0 +1,202 @@ +"use client"; + +import { useEffect, useMemo, useState, type CSSProperties } from "react"; +import { FileTree, useFileTree, useFileTreeSearch } from "@pierre/trees/react"; +import { SearchIcon } from "lucide-react"; +import { File } from "@pierre/diffs/react"; +import Markdown from "react-markdown"; +import { Button } from "../primitives/button"; +import { InputGroup, InputGroupAddon, InputGroupInput } from "../primitives/input-group"; +import { cn } from "../lib/utils"; + +export interface SkillPackageViewerProps { + readonly paths: readonly string[]; + readonly selectedPath: string | null; + readonly content: string | null; + readonly message?: string; + readonly loading?: boolean; + readonly onSelect: (path: string) => void; + readonly theme?: "light" | "dark"; + readonly flush?: boolean; +} + +export function SkillPackageViewer(props: SkillPackageViewerProps) { + return ; +} + +function SkillPackageViewerContent({ + paths, + selectedPath, + content, + message, + loading, + onSelect, + theme = "light", + flush = false, +}: SkillPackageViewerProps) { + const [source, setSource] = useState(false); + const { model } = useFileTree({ + paths: useMemo(() => [...paths], [paths]), + initialExpansion: "open", + initialSelectedPaths: selectedPath ? [selectedPath] : [], + search: false, + fileTreeSearchMode: "hide-non-matches", + onSelectionChange: (selection) => { + const path = selection[0]; + if (path && paths.includes(path)) onSelect(path); + }, + }); + const search = useFileTreeSearch(model); + useEffect(() => { + if (!selectedPath || model.getSelectedPaths().includes(selectedPath)) return; + for (const path of model.getSelectedPaths()) model.getItem(path)?.deselect(); + model.getItem(selectedPath)?.select(); + }, [model, selectedPath]); + const treeStyle: CSSProperties & { [key: `--${string}`]: string } = { + height: "100%", + colorScheme: theme, + "--trees-fg-override": "var(--foreground)", + "--trees-fg-muted-override": "var(--muted-foreground)", + "--trees-bg-override": "var(--card)", + "--trees-bg-muted-override": "var(--secondary)", + "--trees-border-color-override": "var(--border)", + "--trees-selected-bg-override": "var(--secondary)", + "--trees-selected-fg-override": "var(--foreground)", + "--trees-search-bg-override": "var(--card)", + "--trees-search-fg-override": "var(--foreground)", + }; + const markdown = /\.(md|markdown|mdx)$/i.test(selectedPath ?? ""); + const frontmatter = content?.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/); + const body = frontmatter ? (content?.slice(frontmatter[0].length) ?? "") : (content ?? ""); + return ( +

+ +
+
+ + {selectedPath ?? "Select a file"} + + {markdown ? ( + + ) : null} +
+
+ {loading ? ( +

+ Loading file… +

+ ) : message ? ( +

+ {message} +

+ ) : content !== null && selectedPath ? ( + markdown && !source ? ( +
+ {frontmatter ? ( +
+ Package metadata +
{frontmatter[1]}
+
+ ) : null} + ( + + [Image: {alt || "image"} — not loaded in preview] + + ), + a: ({ href, children }) => { + let filePath: string | null = null; + try { + const url = new URL(href ?? "", `https://package.invalid/${selectedPath}`); + if (url.origin === "https://package.invalid") + filePath = decodeURIComponent(url.pathname.slice(1)); + } catch { + /* Leave malformed links inert. */ + } + const target = filePath; + if (target && paths.includes(target)) + return ( + + ); + return ( +
+ {children} + + ); + }, + }} + > + {body} + +
+ ) : ( + + ) + ) : ( +

+ Select a file to inspect its contents. +

+ )} +
+
+
+ ); +} diff --git a/packages/ui/src/components/index.ts b/packages/ui/src/components/index.ts index 8972d6cc..be24b126 100644 --- a/packages/ui/src/components/index.ts +++ b/packages/ui/src/components/index.ts @@ -104,3 +104,4 @@ export type { SkillCardProps, SkillFilterTabsProps, } from "./SkillsLibrary"; +export { SkillPackageViewer, type SkillPackageViewerProps } from "./SkillPackageViewer"; diff --git a/packages/ui/src/primitives/alert.tsx b/packages/ui/src/primitives/alert.tsx new file mode 100644 index 00000000..b1d5cda9 --- /dev/null +++ b/packages/ui/src/primitives/alert.tsx @@ -0,0 +1,68 @@ +import * as React from "react"; +import { cva, type VariantProps } from "class-variance-authority"; +import { cn } from "../lib/utils"; + +const alertVariants = cva( + "group/alert relative grid w-full gap-0.5 rounded-lg border px-2.5 py-2 text-left text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4", + { + variants: { + variant: { + default: "bg-card text-card-foreground", + destructive: + "bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current", + }, + }, + defaultVariants: { + variant: "default", + }, + }, +); + +function Alert({ + className, + variant, + ...props +}: React.ComponentProps<"div"> & VariantProps) { + return ( +
+ ); +} + +function AlertTitle({ className, ...props }: React.ComponentProps<"div">) { + return ( +
svg]/alert:col-start-2 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground", + className, + )} + {...props} + /> + ); +} + +function AlertDescription({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function AlertAction({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +export { Alert, AlertTitle, AlertDescription, AlertAction }; diff --git a/packages/ui/src/primitives/index.ts b/packages/ui/src/primitives/index.ts index 73e8b0bf..3687ac7d 100644 --- a/packages/ui/src/primitives/index.ts +++ b/packages/ui/src/primitives/index.ts @@ -6,6 +6,7 @@ export { AccordionTrigger, } from "./accordion"; export { Badge, badgeVariants } from "./badge"; +export { Alert, AlertTitle, AlertDescription, AlertAction } from "./alert"; export { Button, buttonVariants } from "./button"; export { Card, diff --git a/scripts/benchmark-dashboard-http.ts b/scripts/benchmark-dashboard-http.ts new file mode 100644 index 00000000..4ce6f94a --- /dev/null +++ b/scripts/benchmark-dashboard-http.ts @@ -0,0 +1,77 @@ +const base = new URL(process.argv[2] ?? "http://invalid"); +const samples = Number(process.argv[3] ?? 100); +const skillName = process.argv[4] ?? "selftune"; +if ( + !["127.0.0.1", "localhost", "[::1]"].includes(base.hostname) || + !Number.isSafeInteger(samples) || + samples < 100 || + samples > 1000 +) { + throw new Error( + "Usage: bun scripts/benchmark-dashboard-http.ts [samples:100..1000] [skill-name]", + ); +} +const measure = async (path: string) => { + const start = performance.now(); + const response = await fetch(new URL(path, base)); + const bytes = (await response.arrayBuffer()).byteLength; + if (!response.ok) + throw new Error(`Benchmark route ${path.split("?")[0]} returned ${response.status}`); + return { ms: performance.now() - start, bytes }; +}; +const summarize = (name: string, timings: number[], bytes: number) => { + timings.sort((a, b) => a - b); + const at = (fraction: number) => + Math.round((timings[Math.ceil(timings.length * fraction) - 1] ?? 0) * 100) / 100; + console.log( + JSON.stringify({ + name, + samples: timings.length, + p50Ms: at(0.5), + p95Ms: at(0.95), + maxMs: at(1), + bytes, + }), + ); +}; +async function measureWithHealth(name: string, path: string) { + let workDone = false; + const pending = Promise.allSettled([measure(path)]).finally(() => { + workDone = true; + }); + const underLoad: number[] = []; + let overlapping = 0; + let healthBytes = 0; + for (let index = 0; index < samples; index++) { + await new Promise((resolve) => setTimeout(resolve, 15)); + if (!workDone) overlapping++; + const health = await measure("/api/health"); + underLoad.push(health.ms); + healthBytes = health.bytes; + } + const [report] = await pending; + if (!report || report.status === "rejected") + throw new Error("Background report benchmark failed"); + summarize(`health-during-${name}`, underLoad, healthBytes); + console.log(JSON.stringify({ name, ...report.value, healthSamplesWhilePending: overlapping })); +} +for (const [name, path] of [ + ["health", "/api/health"], + ["shell", "/api/v2/shell"], + ["analytics", "/api/v2/analytics"], + ["library-page", "/api/v2/library?view=index&limit=50"], + ["library-search", "/api/v2/library?view=index&limit=50&search=codex"], +] as const) { + const timings = []; + let bytes = 0; + if (name === "shell" || name === "analytics") await measureWithHealth(`${name}-first`, path); + else console.log(JSON.stringify({ name: `${name}-first`, ...(await measure(path)) })); + for (let index = 0; index < samples; index++) { + const sample = await measure(path); + timings.push(sample.ms); + bytes = sample.bytes; + } + summarize(name, timings, bytes); +} +await measureWithHealth("overview", "/api/v2/overview"); +await measureWithHealth("skill-report", `/api/v2/skills/${encodeURIComponent(skillName)}`); diff --git a/scripts/benchmark-dashboard.ts b/scripts/benchmark-dashboard.ts new file mode 100644 index 00000000..a8fce2b9 --- /dev/null +++ b/scripts/benchmark-dashboard.ts @@ -0,0 +1,38 @@ +import { Database } from "bun:sqlite"; +import { handleDashboardShell, handleOverview } from "../apps/local/src/routes/overview.js"; + +const databasePath = process.argv[2]; +if (!databasePath) throw new Error("Usage: bun scripts/benchmark-dashboard.ts "); + +// Read-only, local measurements; never print records, paths, or credentials. +const db = new Database(databasePath, { readonly: true }); +try { + for (const [name, handler] of [ + ["shell-cold", handleDashboardShell], + ["shell-warm", handleDashboardShell], + ["overview", handleOverview], + ] as const) { + const started = performance.now(); + const cpu = process.cpuUsage(); + const nextTimer = new Promise((resolve) => + setTimeout(() => resolve(performance.now() - started), 0), + ); + const response = handler(db, "benchmark"); + const bytes = (await response.arrayBuffer()).byteLength; + const elapsedMs = performance.now() - started; + const timerDelayMs = await nextTimer; + const usedCpu = process.cpuUsage(cpu); + console.log( + JSON.stringify({ + name, + elapsedMs: Math.round(elapsedMs * 100) / 100, + timerDelayMs: Math.round(timerDelayMs * 100) / 100, + bytes, + cpuMs: Math.round((usedCpu.user + usedCpu.system) / 1000), + rssMiB: Math.round(process.memoryUsage().rss / 1024 / 1024), + }), + ); + } +} finally { + db.close(); +} diff --git a/scripts/benchmark-library-transport.ts b/scripts/benchmark-library-transport.ts new file mode 100644 index 00000000..7ba97f59 --- /dev/null +++ b/scripts/benchmark-library-transport.ts @@ -0,0 +1,30 @@ +import { readFileSync } from "node:fs"; +import { isDeepStrictEqual } from "node:util"; +import * as Schema from "effect/Schema"; +import { LibrarySnapshot } from "@selftune/control-plane/domain"; +import { + compactLibrarySnapshot, + expandLibrarySnapshot, +} from "@selftune/control-plane/library-transport"; + +const path = process.argv[2]; +if (!path) throw new Error("Supply an explicit local library cache artifact path."); +const { data } = Schema.decodeUnknownSync( + Schema.fromJsonString(Schema.Struct({ data: LibrarySnapshot })), +)(readFileSync(path, "utf8")); +const started = performance.now(); +const compact = compactLibrarySnapshot(data); +const compactJson = JSON.stringify(compact); +const encodeMs = performance.now() - started; +const expanded = expandLibrarySnapshot(compact); +if (!isDeepStrictEqual(expanded, data)) + throw new Error("Library transport changed canonical data."); +console.log( + JSON.stringify({ + skills: data.skills.length, + originalBytes: Buffer.byteLength(JSON.stringify(data)), + compactBytes: Buffer.byteLength(compactJson), + encodeMs, + exactRoundTrip: true, + }), +); diff --git a/scripts/benchmark-local-reads.ts b/scripts/benchmark-local-reads.ts new file mode 100644 index 00000000..80fdf7ef --- /dev/null +++ b/scripts/benchmark-local-reads.ts @@ -0,0 +1,70 @@ +import { Database } from "bun:sqlite"; +import { + getAnalyticsPayload, + getOverviewPayload, +} from "../packages/runtime/localdb/queries/dashboard.js"; +import { queryTrustedSkillObservationRows } from "../packages/runtime/localdb/queries/trust.js"; +import { getSkillsList } from "../packages/runtime/localdb/queries/skills.js"; +import { listSkillTestingReadiness } from "../packages/runtime/testing-readiness.js"; +import { handleDashboardShell } from "../apps/local/src/routes/overview.js"; + +const databasePath = process.argv[2]; +const samples = Number(process.argv[3] ?? 5); +if (!databasePath || !Number.isSafeInteger(samples) || samples < 1 || samples > 1000) { + throw new Error("Usage: bun scripts/benchmark-local-reads.ts [samples:1..1000]"); +} +const db = new Database(databasePath, { readonly: true }); +const percentile = (values: readonly number[], fraction: number) => { + const sorted = values.toSorted((left, right) => left - right); + return Math.round((sorted[Math.ceil(sorted.length * fraction) - 1] ?? 0) * 100) / 100; +}; + +try { + type BenchmarkResult = + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | Response; + const operations: ReadonlyArray BenchmarkResult]> = [ + ["trusted", () => queryTrustedSkillObservationRows(db)], + ["skills", () => getSkillsList(db, [])], + ["readiness", () => listSkillTestingReadiness(db)], + ["analytics", () => getAnalyticsPayload(db)], + ["overview-payload", () => getOverviewPayload(db)], + ["shell", () => handleDashboardShell(db, "benchmark")], + ]; + for (const [name, run] of operations) { + const timings: number[] = []; + const cpuTimes: number[] = []; + let bytes = 0; + for (let iteration = 0; iteration < samples; iteration++) { + const started = performance.now(); + const cpu = process.cpuUsage(); + const result = run(); + bytes = + result instanceof Response + ? (await result.arrayBuffer()).byteLength + : Buffer.byteLength(JSON.stringify(result)); + timings.push(performance.now() - started); + const used = process.cpuUsage(cpu); + cpuTimes.push((used.user + used.system) / 1000); + await new Promise((resolve) => setImmediate(resolve)); + } + console.log( + JSON.stringify({ + name, + samples, + p50Ms: percentile(timings, 0.5), + p95Ms: percentile(timings, 0.95), + maxMs: percentile(timings, 1), + cpuP50Ms: percentile(cpuTimes, 0.5), + bytes, + rssMiB: Math.round(process.memoryUsage().rss / 1024 / 1024), + }), + ); + } +} finally { + db.close(); +} diff --git a/scripts/inspect-analytical-storage.ts b/scripts/inspect-analytical-storage.ts new file mode 100644 index 00000000..600a6f02 --- /dev/null +++ b/scripts/inspect-analytical-storage.ts @@ -0,0 +1,18 @@ +import { inspectAnalyticalStorage } from "@selftune/observability/duckdb-node-api"; + +const [path, ...extra] = process.argv.slice(2); +if (!path || extra.length > 0) { + process.stderr.write( + "Usage: bun scripts/inspect-analytical-storage.ts /explicit/path/observability.duckdb\n", + ); + process.exitCode = 2; +} else { + try { + process.stdout.write(`${JSON.stringify(await inspectAnalyticalStorage(path), null, 2)}\n`); + } catch { + process.stderr.write( + "Storage inspection unavailable. Close the database owner and retry; no migration, recovery, or repair was attempted.\n", + ); + process.exitCode = 1; + } +} diff --git a/scripts/inspect-evidence-artifacts.ts b/scripts/inspect-evidence-artifacts.ts new file mode 100644 index 00000000..f0578c54 --- /dev/null +++ b/scripts/inspect-evidence-artifacts.ts @@ -0,0 +1,24 @@ +import { Effect } from "effect"; +import { readBoundedSource } from "@selftune/observability/source-reconstruction"; +import { inspectEvidenceCompleteness } from "@selftune/runtime/testing-readiness/evidence-completeness"; + +const [path, ...extra] = process.argv.slice(2); +if (!path || extra.length > 0) { + process.stderr.write( + "Usage: bun scripts/inspect-evidence-artifacts.ts /explicit/inspection-manifest.json\n", + ); + process.exitCode = 2; +} else { + try { + const manifest = await readBoundedSource(path); + if (manifest.state !== "available") throw new Error("Unavailable manifest"); + const input: unknown = JSON.parse(manifest.bytes.toString("utf8")); + const report = await Effect.runPromise(inspectEvidenceCompleteness(input)); + process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); + } catch { + process.stderr.write( + "Evidence inspection unavailable or request invalid. Nothing was changed; no source, payload or path was included in this error.\n", + ); + process.exitCode = 1; + } +} diff --git a/scripts/pack-package.ts b/scripts/pack-package.ts index 7524a9af..a26b1ed4 100644 --- a/scripts/pack-package.ts +++ b/scripts/pack-package.ts @@ -3,13 +3,10 @@ import { join, resolve } from "node:path"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -class PackageBuildFailure extends Schema.TaggedErrorClass()( - "PackageBuildFailure", - { - operation: Schema.String, - message: Schema.String, - }, -) {} +class PackageBuildFailure extends Schema.TaggedError()("PackageBuildFailure", { + operation: Schema.String, + message: Schema.String, +}) {} const repositoryRoot = resolve(import.meta.dirname, ".."); type InterruptSignal = "SIGINT" | "SIGTERM"; diff --git a/scripts/prepare-effect.sh b/scripts/prepare-effect.sh index 66112d97..7e2960fd 100755 --- a/scripts/prepare-effect.sh +++ b/scripts/prepare-effect.sh @@ -3,15 +3,15 @@ set -eu repo_dir=".repos/effect" -repo_url="https://github.com/Effect-TS/effect-smol" -repo_ref="effect@4.0.0-beta.66" +repo_url="https://github.com/Effect-TS/effect" +repo_ref="effect@4.0.0-rc.115" if [ -d "$repo_dir/.git" ] && [ "$(git -C "$repo_dir" rev-parse HEAD)" = "$(git -C "$repo_dir" rev-list -n 1 "$repo_ref" 2>/dev/null || true)" ]; then exit 0 fi if [ -d "$repo_dir/.git" ]; then - git -C "$repo_dir" fetch --depth 1 origin "refs/tags/$repo_ref:refs/tags/$repo_ref" + git -C "$repo_dir" fetch --depth 1 "$repo_url" "refs/tags/$repo_ref:refs/tags/$repo_ref" git -C "$repo_dir" checkout --detach "$repo_ref" exit 0 fi diff --git a/scripts/qualify-analytical-copy.ts b/scripts/qualify-analytical-copy.ts new file mode 100644 index 00000000..4c7ab7cc --- /dev/null +++ b/scripts/qualify-analytical-copy.ts @@ -0,0 +1,263 @@ +import { DuckDBInstance } from "@duckdb/node-api"; +import { + existsSync, + linkSync, + mkdtempSync, + realpathSync, + rmSync, + statSync, + statfsSync, +} from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { parseArgs } from "node:util"; +import * as Schema from "effect/Schema"; + +const MiB = 1024 ** 2; +const literal = (value: string) => `'${value.replaceAll("'", "''")}'`; +const identifier = (value: string) => `"${value.replaceAll('"', '""')}"`; +const Tables = Schema.Array( + Schema.Struct({ schema_name: Schema.String, table_name: Schema.String }), +); +const Differences = Schema.Array(Schema.Struct({ differences: Schema.String })); +const Receipt = Schema.Struct({ + qualified: Schema.Literal(true), + tables: Schema.Number, + sourceBytes: Schema.Number, + destinationBytes: Schema.Number, + elapsedMs: Schema.Number, +}); +type CopyReceipt = typeof Receipt.Type; +interface CopyBudgets { + maxOutputMiB: number; + reserveMiB: number; + tempMiB: number; + memoryMiB: number; +} +const defaults: CopyBudgets = { + maxOutputMiB: 4096, + reserveMiB: 4096, + tempMiB: 2048, + memoryMiB: 1024, +}; + +function validateBudgets(budgets: CopyBudgets) { + for (const [key, minimum, maximum] of [ + ["maxOutputMiB", 16, 8192], + ["reserveMiB", 256, 16384], + ["tempMiB", 0, 4096], + ["memoryMiB", 64, 1024], + ] as const) { + const value = budgets[key]; + if (!Number.isSafeInteger(value) || value < minimum || value > maximum) + throw new Error(`${key} must be an integer in ${minimum}..${maximum}`); + } +} +const capacity = (directory: string) => { + const fs = statfsSync(directory); + return fs.bavail * fs.bsize; +}; + +/** Closed-writer snapshot only. Never replaces, migrates, or deletes the source. */ +export async function qualifyAnalyticalCopy( + sourcePath: string, + destinationPath: string, + options: Partial = {}, +): Promise { + const budgets = { ...defaults, ...options }; + validateBudgets(budgets); + const source = realpathSync(sourcePath); + const destination = resolve(destinationPath); + if (!statSync(source).isFile() || existsSync(`${source}.wal`)) + throw new Error("Provide a closed-writer snapshot without a WAL"); + if (existsSync(destination)) throw new Error("Destination must not exist"); + const parent = realpathSync(dirname(destination)); + if (capacity(parent) < (budgets.maxOutputMiB + budgets.tempMiB + budgets.reserveMiB) * MiB) + throw new Error("Insufficient free space for the explicit output, spill, and reserve budgets"); + const directory = mkdtempSync(join(parent, ".selftune-qualified-")); + const staged = join(directory, "database.duckdb"); + const child = Bun.spawn( + [ + process.execPath, + import.meta.filename, + "--worker", + source, + staged, + "--max-output-mib", + String(budgets.maxOutputMiB), + "--reserve-mib", + String(budgets.reserveMiB), + "--temp-mib", + String(budgets.tempMiB), + "--memory-mib", + String(budgets.memoryMiB), + ], + { stdout: "pipe", stderr: "pipe" }, + ); + let budgetFailure: string | null = null; + const deadline = Date.now() + 120_000; + const monitor = setInterval(() => { + try { + const size = + (existsSync(staged) ? statSync(staged).size : 0) + + (existsSync(`${staged}.wal`) ? statSync(`${staged}.wal`).size : 0); + if ( + size > budgets.maxOutputMiB * MiB || + capacity(parent) < budgets.reserveMiB * MiB || + Date.now() > deadline + ) { + budgetFailure = "Copy exceeded its output, free-space, or time budget"; + child.kill("SIGKILL"); + } + } catch { + budgetFailure = "Unable to verify the copy's resource budget"; + child.kill("SIGKILL"); + } + }, 100); + try { + const [stdout, stderr, code] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + if (budgetFailure || code !== 0) + throw new Error( + budgetFailure ?? `Copy qualification failed (${code}): ${stderr.slice(-1000)}`, + ); + const receipt = Schema.decodeUnknownSync(Schema.fromJsonString(Receipt))(stdout.trim()); + if (existsSync(`${staged}.wal`) || receipt.destinationBytes > budgets.maxOutputMiB * MiB) + throw new Error("Qualified copy still has a WAL or exceeds its output budget"); + // An exclusive hard link publishes only the verified file; races never overwrite a destination. + linkSync(staged, destination); + return receipt; + } finally { + clearInterval(monitor); + if (child.exitCode === null) child.kill("SIGKILL"); + await child.exited; + rmSync(directory, { recursive: true, force: true }); + } +} + +async function copyAndVerify(source: string, destination: string, budgets: CopyBudgets) { + const before = statSync(source, { bigint: true }); + const database = await DuckDBInstance.create(":memory:", { + memory_limit: `${budgets.memoryMiB}MB`, + threads: "1", + preserve_insertion_order: "false", + max_temp_directory_size: `${budgets.tempMiB}MB`, + temp_directory: join(dirname(destination), "spill"), + }); + const connection = await database.connect(); + const started = performance.now(); + try { + await connection.run(`ATTACH ${literal(source)} AS original (READ_ONLY)`); + // This maintenance tool qualifies SelfTune's table/view store, not arbitrary database extensions. + for (const query of ["SELECT * FROM duckdb_sequences()", "SELECT * FROM duckdb_functions()"]) + if ( + (await (await connection.run(`${query} WHERE database_name = 'original'`)).getRowObjects()) + .length + ) + throw new Error( + "Source has sequences or user functions outside this qualifier's supported catalog", + ); + await connection.run(`ATTACH ${literal(destination)} AS compacted`); + await connection.run("COPY FROM DATABASE original TO compacted"); + const tables = Schema.decodeUnknownSync(Tables)( + await ( + await connection.run( + "SELECT schema_name, table_name FROM duckdb_tables() WHERE database_name = 'original' ORDER BY ALL", + ) + ).getRowObjects(), + ); + if (!tables.length) throw new Error("The source has no tables to qualify"); + for (const table of tables) { + const name = `${identifier(table.schema_name)}.${identifier(table.table_name)}`; + const rows = Schema.decodeUnknownSync(Differences)( + await ( + await connection.run( + `SELECT CAST(COUNT(*) AS VARCHAR) AS differences FROM ( + (SELECT * FROM original.${name} EXCEPT ALL SELECT * FROM compacted.${name}) + UNION ALL (SELECT * FROM compacted.${name} EXCEPT ALL SELECT * FROM original.${name}) + ) AS differences`, + ) + ).getRowObjects(), + ); + if (rows[0]?.differences !== "0") throw new Error("Full-row parity failed"); + } + for (const catalog of [ + "SELECT schema_name FROM duckdb_schemas()", + "SELECT schema_name,table_name FROM duckdb_tables()", + "SELECT schema_name,table_name,column_name,data_type,is_nullable,column_default FROM duckdb_columns()", + "SELECT schema_name,table_name,constraint_type,constraint_text,constraint_column_names FROM duckdb_constraints()", + "SELECT schema_name,table_name,index_name,is_unique,is_primary,expressions FROM duckdb_indexes()", + "SELECT schema_name,view_name,sql FROM duckdb_views()", + ]) { + const original = await ( + await connection.run(`${catalog} WHERE database_name = 'original' ORDER BY ALL`) + ).getRowObjects(); + const compacted = await ( + await connection.run(`${catalog} WHERE database_name = 'compacted' ORDER BY ALL`) + ).getRowObjects(); + if (JSON.stringify(original) !== JSON.stringify(compacted)) + throw new Error("Catalog parity failed"); + } + await connection.run("CHECKPOINT compacted"); + const after = statSync(source, { bigint: true }); + if ( + before.dev !== after.dev || + before.ino !== after.ino || + before.size !== after.size || + before.mtimeNs !== after.mtimeNs || + before.ctimeNs !== after.ctimeNs || + existsSync(`${source}.wal`) + ) + throw new Error("Source identity or metadata changed while qualifying the copy"); + return { + qualified: true, + tables: tables.length, + sourceBytes: Number(before.size), + destinationBytes: statSync(destination).size, + elapsedMs: performance.now() - started, + } satisfies CopyReceipt; + } finally { + connection.closeSync(); + database.closeSync(); + } +} + +if (import.meta.main) { + const { values, positionals } = parseArgs({ + args: process.argv.slice(2), + allowPositionals: true, + options: { + help: { type: "boolean" }, + worker: { type: "boolean" }, + "max-output-mib": { type: "string", default: "4096" }, + "reserve-mib": { type: "string", default: "4096" }, + "temp-mib": { type: "string", default: "2048" }, + "memory-mib": { type: "string", default: "1024" }, + }, + }); + if (values.help) + console.log( + "Usage: bun scripts/qualify-analytical-copy.ts [--max-output-mib 4096 --reserve-mib 4096 --temp-mib 2048 --memory-mib 1024]\nCreates a verified copy only. Never installs it, replaces the source, or removes history.", + ); + else { + const [source, destination] = positionals; + if (!source || !destination || positionals.length !== 2) + throw new Error("Provide a closed snapshot and a new destination; see --help"); + const budgets = { + maxOutputMiB: Number(values["max-output-mib"]), + reserveMiB: Number(values["reserve-mib"]), + tempMiB: Number(values["temp-mib"]), + memoryMiB: Number(values["memory-mib"]), + }; + validateBudgets(budgets); + console.log( + JSON.stringify( + values.worker + ? await copyAndVerify(source, destination, budgets) + : await qualifyAnalyticalCopy(source, destination, budgets), + ), + ); + } +} diff --git a/scripts/sanitize-packed-package.test.ts b/scripts/sanitize-packed-package.test.ts index c4d00c7e..02b0c190 100644 --- a/scripts/sanitize-packed-package.test.ts +++ b/scripts/sanitize-packed-package.test.ts @@ -13,7 +13,7 @@ test("sanitizes the real archive without changing package contents or registry d join(packageRoot, "package.json"), JSON.stringify({ name: "selftune", - dependencies: { "@selftune/runtime": "1.0.0", effect: "4.0.0-beta.66" }, + dependencies: { "@selftune/runtime": "1.0.0", effect: "4.0.0-rc.115" }, bundledDependencies: ["@selftune/runtime"], }), ); @@ -31,7 +31,7 @@ test("sanitizes the real archive without changing package contents or registry d manifestAfter.push(manifest); expect(JSON.parse(manifest)).toEqual({ name: "selftune", - dependencies: { effect: "4.0.0-beta.66" }, + dependencies: { effect: "4.0.0-rc.115" }, bundledDependencies: ["@selftune/runtime"], }); expect(readFileSync(join(output, "package/payload.bin"))).toEqual(payload); diff --git a/scripts/smoke-packed-package.ts b/scripts/smoke-packed-package.ts index 0014f6ef..33e8ca59 100644 --- a/scripts/smoke-packed-package.ts +++ b/scripts/smoke-packed-package.ts @@ -14,13 +14,10 @@ import { basename, join, relative, resolve, sep } from "node:path"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -class PackageSmokeFailure extends Schema.TaggedErrorClass()( - "PackageSmokeFailure", - { - operation: Schema.String, - message: Schema.String, - }, -) {} +class PackageSmokeFailure extends Schema.TaggedError()("PackageSmokeFailure", { + operation: Schema.String, + message: Schema.String, +}) {} const PackageManifest = Schema.Struct({ name: Schema.String, diff --git a/skill/SKILL.md b/skill/SKILL.md index ee6b6309..4df54dbd 100644 --- a/skill/SKILL.md +++ b/skill/SKILL.md @@ -14,7 +14,7 @@ description: > they do not name SelfTune explicitly. metadata: author: selftune-dev - version: 0.4.12 + version: 0.5.1 category: developer-tools --- diff --git a/skill/references/cli-quick-reference.md b/skill/references/cli-quick-reference.md index 324ef1a3..14d8f4db 100644 --- a/skill/references/cli-quick-reference.md +++ b/skill/references/cli-quick-reference.md @@ -20,7 +20,7 @@ selftune grade baseline --skill --skill-path [--eval-set ] selftune evolve --skill --skill-path [--dry-run] [--validation-mode auto|replay|judge] selftune evolve body --skill --skill-path --target [--dry-run] selftune evolve rollback --skill --skill-path [--proposal-id ] -selftune improve --skill --skill-path [--scope auto|description|routing|body|package] [--dry-run] [--validation-mode auto|replay|judge] +selftune improve --skill --skill-path [--scope auto|description|routing|body|package] [--dry-run] [--budget-remaining-usd --estimated-cost-usd ] [--validation-mode auto|replay|judge] # Create group selftune verify --skill-path [--agent AGENT] [--eval-set PATH] [--no-auto-fix] [--json] diff --git a/skill/references/grading-methodology.md b/skill/references/grading-methodology.md index 6424c939..295ecefc 100644 --- a/skill/references/grading-methodology.md +++ b/skill/references/grading-methodology.md @@ -31,8 +31,9 @@ Always include at least one Process and one Quality expectation. - Evidence: a `Read` tool call with a path ending in `SKILL.md` appears before any `Write`, `Edit`, or significant `Bash` command. -2. **No more than 1 error encountered** (Quality) - - Evidence: `errors_encountered` field in session telemetry is 0 or 1. +2. **The requested outcome satisfies its acceptance criteria** (Quality) + - Evidence: inspect the resulting artifact, test result, or verified end state. + An error count is a diagnostic, not an outcome-quality verdict. 3. **Expected output type exists** (Quality) - Evidence: the file, command output, or artifact the user asked for is present. @@ -41,8 +42,9 @@ Always include at least one Process and one Quality expectation. - Evidence: no single bash command or tool call is repeated more than 3 times consecutively in the transcript. -5. **Skill steps followed in order** (Process) - - Evidence: the sequence of tool calls matches the step order in SKILL.md. +5. **Required skill dependencies were respected** (Process) + - Evidence: observed actions satisfy ordering requirements that affect correctness. + Independent steps need not follow an arbitrary written order. --- @@ -59,8 +61,13 @@ Always include at least one Process and one Quality expectation. - **A file existing is NOT evidence it has correct content.** Verify content claims separately from existence claims. -- **Absence of evidence IS evidence of absence** for process steps. If the transcript - does not show SKILL.md being read, the expectation fails. +- **Incomplete observation is unscored.** If a partial transcript cannot establish + a step or outcome, record it in `unobserved_expectations` with the missing evidence. + Grading stops with `MISSING_DATA` before saving a quality score when any expectation + is unobserved. Recover the source evidence and rerun. +- **Match the exact claim.** A trigger is not proof of a successful file read or + read order; an assistant turn is not proof of completion; a tool count does not + identify which tools ran. - **Cite specific evidence.** Never mark PASS without pointing to a transcript line, tool call, or telemetry field. diff --git a/skill/workflows/Evolve.md b/skill/workflows/Evolve.md index e2e79e6b..a9e31d59 100644 --- a/skill/workflows/Evolve.md +++ b/skill/workflows/Evolve.md @@ -136,8 +136,15 @@ Claude Code uses `.claude/skills`, Codex uses `.agents/skills`, and OpenCode uses `.opencode/skills`. Validation records whether the runtime selected the target skill, selected a competing skill, selected an unrelated skill, or made no routing decision at all. Reads outside the staged skill set are treated as -replay failures even on negative evals, because they indicate the runtime left -the controlled evaluation surface. +replay failures even when the target was selected or on negative evals, because +they indicate the runtime left the controlled evaluation surface. + +Historical routing verifier v2 qualifies this decision mapping by running +synthetic runtime observations through the same predicate used by live replay. +Its controls cover target selection, no selection, boundary cases, repeated or +multiple skill selections, misleading output text, and off-path reads. This +qualifies the deterministic predicate only; it does not qualify a host harness, +provider, or actual runtime journey. For hosts without runtime replay support today, replay is not available. In `auto` mode selftune falls back to `llm_judge`; in `replay` mode it exits with diff --git a/skill/workflows/Grade.md b/skill/workflows/Grade.md index 75cd86be..ae1cef95 100644 --- a/skill/workflows/Grade.md +++ b/skill/workflows/Grade.md @@ -98,7 +98,10 @@ Search both the telemetry record and the transcript for evidence per expectation. Mark as: - **PASS** if evidence exists and supports the expectation -- **FAIL** if evidence is absent or contradicts the expectation +- **FAIL** if specific evidence establishes that the requirement was not met +- **UNOBSERVED** if the source excerpt or artifact is insufficient to decide. + Return it in `unobserved_expectations` with its exact text and missing evidence, + instead of assigning a score. The CLI returns `MISSING_DATA` and saves no grade. Cite specific evidence: transcript line numbers, tool call names, bash output. diff --git a/skill/workflows/Improve.md b/skill/workflows/Improve.md index 85f6234d..13100b96 100644 --- a/skill/workflows/Improve.md +++ b/skill/workflows/Improve.md @@ -9,7 +9,7 @@ Use this when the user wants to make a skill better based on measured evidence. The lifecycle entrypoint is: ```bash -selftune improve --skill --skill-path [--scope auto|description|routing|body|package] [--agent AGENT] [--eval-set PATH] [--dry-run] [--validation-mode auto|replay|judge] +selftune improve --skill --skill-path [--scope auto|description|routing|body|package] [--agent AGENT] [--eval-set PATH] [--dry-run] [--budget-remaining-usd AMOUNT --estimated-cost-usd AMOUNT] [--validation-mode auto|replay|judge] ``` ## Options @@ -22,6 +22,8 @@ selftune improve --skill --skill-path [--scope auto|description|ro | `--agent` | Agent CLI to use; for body/routing this sets both teacher and student agents | | `--eval-set` | Override the eval set JSON path | | `--dry-run` | Validate candidate changes without deploying | +| `--budget-remaining-usd ` | Caller-reported remaining spend for historical replay preflight | +| `--estimated-cost-usd ` | Caller estimate for the full historical replay run | | `--validation-mode` | Validation strategy: `auto`, `replay`, or `judge` | | `--help` | Show command help | @@ -54,9 +56,19 @@ If those are missing, route to `Verify` first. Use: ```bash -selftune improve --skill --skill-path --scope auto --dry-run --agent codex +selftune improve --skill --skill-path --scope auto --dry-run --agent codex --budget-remaining-usd --estimated-cost-usd ``` +Both amounts are required when attempting historical replay. The estimate must +cover the whole run, including candidate generation and replay. SelfTune +compares it with the caller-reported remaining amount before starting that +work, and reports the result as an estimate-only preflight. It does not read +subscription usage, measure provider spend, or enforce an actual-dollar +ceiling. The remaining amount is not tracked or decremented across separate +invocations, so refresh it before rerunning. The request uses five search +candidates, requires three scored repetitions, and allows at most three +attempts per arm; these count bounds do not guarantee a dollar ceiling. + SelfTune first looks for invocation-local failed traces plus a successful counterexample for the same installed skill revision. Session-level error totals are never assigned to a skill. When causal outcomes are unavailable but exact diff --git a/skill/workflows/Ingest.md b/skill/workflows/Ingest.md index 6ca4c820..df629810 100644 --- a/skill/workflows/Ingest.md +++ b/skill/workflows/Ingest.md @@ -13,6 +13,16 @@ An explicit ingest command imports its selected source regardless of onboarding source-enable preferences. OpenClaw remains canonical-only, and Cline remains hook-only; neither uses this batch trace-import path. +Codex source sync records a bounded reconstruction recipe for eligible rollout +files (up to 8 MiB): source and task hashes, parser/normalizer identity, captured +skill-name inventory and canonical skill revision bindings. Unknown historical +skill revisions remain unknown. Historical candidate preparation can recover a +missing task only when those checks match; it never substitutes the current +skill package or changed source bytes. Larger/legacy sources remain readable +through their existing records but are not qualified for this fallback. +No automatic detail eviction is enabled, and `--force` cannot revive explicitly +expired evidence. + ## When to Use Each | Sub-command | Platform | Mode | When | diff --git a/tests/cli/eval-effect-cli.test.ts b/tests/cli/eval-effect-cli.test.ts index 9f9851f8..c632d94d 100644 --- a/tests/cli/eval-effect-cli.test.ts +++ b/tests/cli/eval-effect-cli.test.ts @@ -66,6 +66,28 @@ afterEach(() => { } }); +test("parses native plugin and read-only report commands without invoking models", async () => { + const plugin = await parseEval( + "plugin", + "--target", + "/tmp/example", + "--runs", + "1", + "--trust-plugin", + "--json", + ); + expect(plugin.action).toBe("plugin"); + if (plugin.action === "plugin") { + expect(plugin.input.target).toBe("/tmp/example"); + expect(plugin.input.trustPlugin).toBe(true); + expect(plugin.input.ablation).toBe("with-without"); + } + expect(await parseEval("report", "--input", "/tmp/report.json", "--threshold", "0.8")).toEqual({ + action: "report", + input: { input: "/tmp/report.json", threshold: "0.8", json: false }, + }); +}); + describe("full eval Effect command family", () => { test("owns every parent and leaf argument shape", () => { for (const args of [ diff --git a/tests/dashboard/dashboard-server.test.ts b/tests/dashboard/dashboard-server.test.ts index a8094194..31c47e60 100644 --- a/tests/dashboard/dashboard-server.test.ts +++ b/tests/dashboard/dashboard-server.test.ts @@ -1467,6 +1467,22 @@ describe("dashboard-server", () => { }); describe("GET /api/v2/library", () => { + it("serves bounded indexes and complete selected skills, guarding stale snapshots", async () => { + const server = await getServer(); + const base = `http://127.0.0.1:${server.port}/api/v2/library`; + const page = await fetch(`${base}?view=index&limit=1`); + expect(page.status).toBe(200); + const index = await page.json(); + expect(index).toMatchObject({ total: 1, nextOffset: null }); + expect(index.skills[0]).not.toHaveProperty("locations"); + const selected = await fetch(`${base}?skill_id=test-skill`); + expect(await selected.json()).toEqual(libraryFixture); + expect((await fetch(`${base}?snapshot=old&view=index`)).status).toBe(409); + expect((await fetch(`${base}?skill_id=missing`)).status).toBe(404); + for (const query of ["limit=101", "offset=-1", "limit=0", "offset=NaN"]) { + expect((await fetch(`${base}?view=index&${query}`)).status).toBe(400); + } + }); it("returns the canonical grouped Library contract", async () => { const server = await getServer(); const res = await fetch(`http://127.0.0.1:${server.port}/api/v2/library`); diff --git a/tests/dashboard/sync-destination.test.ts b/tests/dashboard/sync-destination.test.ts index 5e1898e7..c89985d8 100644 --- a/tests/dashboard/sync-destination.test.ts +++ b/tests/dashboard/sync-destination.test.ts @@ -51,17 +51,6 @@ describe("Sync & Backup destinations", () => { }); }); - it("keeps the Settings copy on the customer-facing mental model", () => { - const settingsSource = readFileSync( - new URL("../../apps/local-dashboard/src/pages/Settings.tsx", import.meta.url), - "utf8", - ); - expect(settingsSource).toContain("Your Library stays local"); - expect(settingsSource).toContain("Cloud receives only a privacy-safe inventory"); - expect(settingsSource).toContain("Raw transcripts are never synced."); - expect(settingsSource).not.toContain("Remote Library"); - }); - it("uses Sync & Backup in customer and agent-facing removal guidance", () => { const customerDocs = [ new URL("../../skill/workflows/Uninstall.md", import.meta.url), diff --git a/tests/eval/evidence-completeness.test.ts b/tests/eval/evidence-completeness.test.ts new file mode 100644 index 00000000..708f3fa6 --- /dev/null +++ b/tests/eval/evidence-completeness.test.ts @@ -0,0 +1,269 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { + mkdtempSync, + rmSync, + writeFileSync, + readFileSync, + symlinkSync, + openSync, + closeSync, + ftruncateSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { Effect } from "effect"; +import { _setTestDb, openDb } from "@selftune/local-store"; +import { + SourceReconstruction, + sourceDigest, + MAX_RECONSTRUCTION_BYTES, +} from "@selftune/observability/source-reconstruction"; +import { + inspectEvidenceCompleteness, + type EvidenceInspectionRequest, +} from "@selftune/runtime/testing-readiness/evidence-completeness"; +import { writeCanonicalEvalSet } from "@selftune/runtime/testing-readiness/artifacts"; +import { saveEvaluationReport } from "@selftune/runtime/eval/history"; +import { assembleResult } from "@selftune/runtime/grading/grade-session"; + +let directory: string; +let previousConfig: string | undefined; +const marker = "PRIVATE_CANARY_DO_NOT_PRINT"; +const sourceText = `${marker} original transcript`; +// SAFETY-UNKNOWN: Fixture serialization deliberately includes malformed records to exercise the production decoder. +const artifact = (name: string, contents: unknown) => { + const path = join(directory, name); + writeFileSync(path, JSON.stringify(contents)); + return path; +}; +const inspect = (input: typeof EvidenceInspectionRequest.Type) => + Effect.runPromise(inspectEvidenceCompleteness(input)); + +beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), "selftune-evidence-inspection-")); + previousConfig = process.env.SELFTUNE_CONFIG_DIR; + process.env.SELFTUNE_CONFIG_DIR = directory; + _setTestDb(openDb(":memory:")); +}); +afterEach(() => { + _setTestDb(null); + if (previousConfig === undefined) delete process.env.SELFTUNE_CONFIG_DIR; + else process.env.SELFTUNE_CONFIG_DIR = previousConfig; + rmSync(directory, { recursive: true }); +}); + +function sourceArtifacts() { + const source = join(directory, "original.jsonl"); + writeFileSync(source, sourceText); + const grade = artifact( + "grade.json", + assembleResult( + { + expectations: [{ text: marker, passed: true, evidence: marker }], + }, + null, + "fixture-session", + "fixture-skill", + source, + ), + ); + const recipe = artifact( + "recipe.json", + SourceReconstruction.make({ + snapshot: { + parser: "codex-rollout/v1", + path: source, + sha256: sourceDigest(Buffer.from(sourceText)), + task_sha256: sourceDigest(Buffer.from("fixture task")), + bytes: Buffer.byteLength(sourceText), + skill_names: [], + workspace_skills: [], + }, + bindings: [], + }), + ); + return { source, grade, recipe }; +} + +test("actual saved grade, routing eval and history formats produce counts-only qualification, not eviction permission", async () => { + const { source, grade, recipe } = sourceArtifacts(); + const evals = writeCanonicalEvalSet("fixture", [ + { query: marker, should_trigger: true }, + { query: "unrelated fixture", should_trigger: false }, + ]); + const raw = JSON.stringify({ + skill_name: "fixture", + baseline: "old_skill", + cases: [{ id: 1, with_skill_pass_rate: 1, baseline_pass_rate: 0, prompt: marker }], + }); + const history = saveEvaluationReport("fixture", raw, directory); + const historyPath = join( + directory, + "evaluation-history", + sourceDigest(Buffer.from("fixture")), + `${history[0].id}.json`, + ); + const unknown = artifact("unknown.json", { secret: marker }); + const paths = [source, grade, recipe, evals, historyPath, unknown]; + const before = paths.map((path) => sourceDigest(readFileSync(path))); + const report = await inspect({ + artifacts: [ + { kind: "grade", path: grade }, + { kind: "source_recipe", path: recipe }, + { kind: "routing_evals", path: evals }, + { kind: "evaluation_history", path: historyPath }, + { kind: "grade", path: unknown }, + { kind: "grade", path: join(directory, "missing.json") }, + ], + authorized_sources: [source], + }); + expect(report.counts).toEqual({ + self_contained: 1, + source_dependent: 3, + missing: 1, + unsupported: 1, + }); + expect(report.reasons.grade_original_unverified).toBe(1); + expect(report.reasons.recipe_original_verified).toBe(1); + expect(report.reasons.evaluation_summary_only).toBe(1); + expect(report).toMatchObject({ + decision: "keep_all_sources", + replay_qualified: 0, + eviction_eligible: 0, + }); + expect(Object.values(report.reasons).reduce((total, value) => total + value, 0)).toBe(6); + expect(JSON.stringify(report)).not.toContain(marker); + expect(JSON.stringify(report)).not.toContain(directory); + expect(paths.map((path) => sourceDigest(readFileSync(path)))).toEqual(before); +}); + +test("changed and missing originals never qualify a grade or recipe as self-contained", async () => { + const { source, grade, recipe } = sourceArtifacts(); + const input = { + artifacts: [ + { kind: "grade", path: grade }, + { kind: "source_recipe", path: recipe }, + ], + authorized_sources: [source], + } satisfies typeof EvidenceInspectionRequest.Type; + writeFileSync(source, sourceText.replace("original", "modified")); + const changed = await inspect(input); + expect(changed.reasons.source_changed).toBe(1); + // A path-only grade has no historical digest. Existence cannot establish identity. + expect(changed.reasons.grade_original_unverified).toBe(1); + expect(changed.counts.self_contained).toBe(0); + rmSync(source); + const missing = await inspect(input); + expect(missing.reasons.source_missing).toBe(2); + expect(missing.eviction_eligible).toBe(0); +}); + +test("embedded source paths are not read unless explicitly authorized", async () => { + const { source, grade, recipe } = sourceArtifacts(); + rmSync(source); + const report = await inspect({ + artifacts: [ + { kind: "grade", path: grade }, + { kind: "source_recipe", path: recipe }, + ], + authorized_sources: [], + }); + expect(report.reasons.source_not_authorized).toBe(2); + expect(report.reasons.source_missing).toBe(0); +}); + +test("empty, extended and oversized routing datasets fail closed", async () => { + const empty = artifact("empty.json", []); + const blank = artifact("blank.json", [{ query: " ", should_trigger: true }]); + const extended = artifact("extended.json", [ + { query: marker, should_trigger: true, files: ["unverified"] }, + ]); + const excessive = artifact( + "excessive.json", + Array.from({ length: 257 }, () => ({ query: marker, should_trigger: true })), + ); + const report = await inspect({ + artifacts: [empty, blank, extended, excessive].map((path) => ({ kind: "routing_evals", path })), + authorized_sources: [], + }); + expect(report.counts).toEqual({ + self_contained: 0, + source_dependent: 0, + missing: 2, + unsupported: 2, + }); +}); + +test("unsafe files and byte limits are unavailable, not successful empty inspections", async () => { + const { source, grade } = sourceArtifacts(); + const link = join(directory, "link.json"); + symlinkSync(grade, link); + const oversize = join(directory, "large.json"); + const fd = openSync(oversize, "w"); + try { + ftruncateSync(fd, MAX_RECONSTRUCTION_BYTES + 1); + } finally { + closeSync(fd); + } + const report = await inspect({ + artifacts: [link, oversize, directory].map((path) => ({ kind: "grade", path })), + authorized_sources: [source], + }); + expect(report.reasons.artifact_unavailable).toBe(2); + expect(report.reasons.artifact_over_budget).toBe(1); + expect(report.counts.self_contained).toBe(0); +}); + +test("invalid and excessive requests fail before inspection without leaking inputs", async () => { + for (const input of [ + { artifacts: [], authorized_sources: [] }, + { artifacts: [{ kind: "grade", path: marker }], authorized_sources: [] }, + { + artifacts: Array.from({ length: 17 }, (_, index) => ({ + kind: "grade", + path: join(directory, `${index}.json`), + })), + authorized_sources: [], + }, + { + artifacts: [ + { kind: "grade", path: directory }, + { kind: "grade", path: directory }, + ], + authorized_sources: [], + }, + ]) { + await expect(Effect.runPromise(inspectEvidenceCompleteness(input))).rejects.toMatchObject({ + _tag: "EvidenceInspectionFailure", + message: expect.not.stringContaining(marker), + }); + } +}); + +test("maintenance command emits only the report and redacts malformed input errors", async () => { + const path = writeCanonicalEvalSet("frozen", [{ query: marker, should_trigger: true }]); + const manifest = artifact("manifest.json", { + artifacts: [{ kind: "routing_evals", path }], + authorized_sources: [], + }); + const run = (input: string) => + Bun.spawnSync([ + process.execPath, + resolve(import.meta.dir, "../../scripts/inspect-evidence-artifacts.ts"), + input, + ]); + const result = run(manifest); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout.toString())).toMatchObject({ + counts: { self_contained: 1 }, + eviction_eligible: 0, + }); + expect(`${result.stdout}${result.stderr}`).not.toContain(marker); + expect(`${result.stdout}${result.stderr}`).not.toContain(directory); + writeFileSync(manifest, marker); + const invalid = run(manifest); + expect(invalid.exitCode).toBe(1); + expect(invalid.stdout.toString()).toBe(""); + expect(invalid.stderr.toString()).not.toContain(marker); + expect(invalid.stderr.toString()).not.toContain(directory); +}); diff --git a/tests/eval/output-quality.test.ts b/tests/eval/output-quality.test.ts index 7965d331..bb4ba5ae 100644 --- a/tests/eval/output-quality.test.ts +++ b/tests/eval/output-quality.test.ts @@ -48,6 +48,49 @@ function createSkill(): string { } describe("Agent Skills output-quality evaluation", () => { + test("skill-only indicators remain visible but cannot inflate the paired score", async () => { + const skillDir = createSkill(); + writeFileSync( + join(skillDir, "evals", "evals.json"), + JSON.stringify({ + skill_name: "example", + evals: [ + { + id: 1, + prompt: "Return SUCCESS", + expected_output: "SUCCESS", + selftune_assertions: [ + { type: "contains", value: "SUCCESS" }, + { type: "tool_called", value: "Skill" }, + { type: "contains", value: "marker", arm: "with-only" }, + ], + }, + ], + }), + ); + const result = await runOutputQualityEvaluation( + { skillPath: skillDir, agent: "test" }, + { + execute: async ({ system }) => ({ + output: system.includes("Follow this Agent Skill") ? "SUCCESS Skill marker" : "SUCCESS", + totalTokens: 1, + }), + grade: async () => [], + compare: async () => ({ winner: "tie", evidence: "Same outcome" }), + }, + ); + expect(result.benchmark.run_summary.delta.pass_rate).toBe(0); + expect(result.benchmark.cases[0]?.with_skill_pass_rate).toBe(1); + const grading = JSON.parse( + readFileSync(join(result.iteration_dir, "eval-1", "with_skill", "grading.json"), "utf8"), + ); + expect(grading.assertion_results.map((row: { scored: boolean }) => row.scored)).toEqual([ + true, + false, + false, + ]); + expect(grading.summary.total).toBe(1); + }); test.each( [ {}, diff --git a/tests/eval/plugin.test.ts b/tests/eval/plugin.test.ts new file mode 100644 index 00000000..c3bd7403 --- /dev/null +++ b/tests/eval/plugin.test.ts @@ -0,0 +1,46 @@ +import { expect, test } from "bun:test"; +import { pluginEvalArguments, type PluginEvalInput } from "../../packages/runtime/eval/plugin.js"; + +const input: PluginEvalInput = { + target: "/tmp/plugin with spaces", + runs: "3", + threshold: "1", + concurrency: "1", + ablation: "with-without", + trustPlugin: false, + json: false, +}; +test("native plugin evaluations remain local and do not imply trust or tool grants", () => { + const args = pluginEvalArguments(input); + expect(args.slice(0, 3)).toEqual(["plugin", "eval", input.target]); + expect(args).toContain("--no-publish"); + expect(args).toContain("--no-scaffold"); + expect(args).not.toContain("--trust-plugin"); + expect(args).not.toContain("--allow-real-servers"); + expect(args).not.toContain("--allow-tools"); +}); +test("explicit options are passed as arguments, never shell text", () => { + const args = pluginEvalArguments({ + ...input, + trustPlugin: true, + json: true, + case: "a; echo nope", + maxCostUsd: "0.25", + }); + expect(args).toContain("a; echo nope"); + expect(args).toContain("--trust-plugin"); + expect(args.at(-1)).toBe("--json"); +}); +test("invalid numeric limits and option-like targets fail before execution", () => { + for (const patch of [ + { runs: "0" }, + { runs: "2.5" }, + { threshold: "NaN" }, + { threshold: "1.1" }, + { concurrency: "9" }, + { maxCostUsd: "0" }, + { target: "--publish-report" }, + ]) { + expect(() => pluginEvalArguments({ ...input, ...patch })).toThrow(); + } +}); diff --git a/tests/eval/report.test.ts b/tests/eval/report.test.ts new file mode 100644 index 00000000..2684b64f --- /dev/null +++ b/tests/eval/report.test.ts @@ -0,0 +1,48 @@ +import { expect, test } from "bun:test"; +import { summarizeEvalReport } from "../../packages/runtime/eval/report.js"; + +const run = { score: 1, error: null, skippedPaidGraders: false }; +function native(error: string | null = null, partial = false) { + return { + schemaVersion: 1, + claudeVersion: "2.1.269", + partial, + suite: { ablation: "with-without" }, + cases: [{ name: "smoke", runsPerCase: 1, arms: { with: [{ ...run, error }], without: [run] } }], + }; +} +test("native scores preserve neutral delta and engine provenance", () => { + const result = summarizeEvalReport(JSON.stringify(native()), 1); + expect(result.engine).toBe("claude-plugin"); + expect(result.cases[0]?.delta).toBe(0); + expect(result.exitCode).toBe(0); +}); +test("saved native thresholds are used unless a report command overrides them", () => { + const report = JSON.stringify({ + ...native(), + suite: { ablation: "with-without", threshold: 0.8 }, + }); + expect(summarizeEvalReport(report).threshold).toBe(0.8); + expect(summarizeEvalReport(report, 0.9).threshold).toBe(0.9); +}); +test("runtime errors and partial runs are not labeled quality regressions", () => { + expect(summarizeEvalReport(JSON.stringify(native("rate limit")), 1).exitCode).toBe(2); + expect(summarizeEvalReport(JSON.stringify(native(null, true)), 1).exitCode).toBe(2); +}); +test("skill reports use the same per-case gate without equating engines", () => { + const result = summarizeEvalReport( + JSON.stringify({ + skill_name: "sample", + baseline: "old_skill", + cases: [{ id: 1, with_skill_pass_rate: 0.5, baseline_pass_rate: 0.75 }], + }), + 0.8, + ); + expect(result.engine).toBe("selftune-skill"); + expect(result.cases[0]?.delta).toBe(-0.25); + expect(result.exitCode).toBe(1); +}); +test("unknown versions and malformed scores fail closed", () => { + expect(() => summarizeEvalReport(JSON.stringify({ ...native(), schemaVersion: 2 }), 1)).toThrow(); + expect(() => summarizeEvalReport('{"cases":[]}', 1)).toThrow(); +}); diff --git a/tests/eval/score-gate.test.ts b/tests/eval/score-gate.test.ts new file mode 100644 index 00000000..ced7d8f4 --- /dev/null +++ b/tests/eval/score-gate.test.ts @@ -0,0 +1,14 @@ +import { expect, test } from "bun:test"; +import { parseScoreThreshold, scoreGate } from "../../packages/runtime/eval/score-gate.js"; + +test("score gates reject empty results, nonfinite scores, and any failing case", () => { + expect(scoreGate([], 0)).toBe(false); + expect(scoreGate([1, 0.79], 0.8)).toBe(false); + expect(scoreGate([1, 0.8], 0.8)).toBe(true); + expect(scoreGate([NaN], 0)).toBe(false); +}); +test("thresholds are validated before any paid execution", () => { + for (const raw of ["", "NaN", "Infinity", "-0.1", "1.1"]) + expect(() => parseScoreThreshold(raw)).toThrow(); + expect(parseScoreThreshold("0.8")).toBe(0.8); +}); diff --git a/tests/evolution/validate-host-replay.test.ts b/tests/evolution/validate-host-replay.test.ts index b78410f8..ba8884ed 100644 --- a/tests/evolution/validate-host-replay.test.ts +++ b/tests/evolution/validate-host-replay.test.ts @@ -6,6 +6,7 @@ import { dirname, join } from "node:path"; import { buildRoutingReplayFixture, + evaluateRuntimeReplayObservation, parseCodexRuntimeReplayOutput, parseOpenCodeRuntimeReplayOutput, runHostRuntimeReplayFixture, @@ -14,6 +15,10 @@ import { } from "../../packages/runtime/evolution/validate-host-replay.js"; import { setCurrentDashboardActionContext } from "../../packages/runtime/dashboard-action-events.js"; import type { EvalEntry, RoutingReplayFixture } from "../../packages/runtime/types.js"; +import type { + ReplayWorkspace, + RuntimeReplayObservation, +} from "../../packages/runtime/evolution/validate-host-replay.js"; import { readJsonl } from "../../packages/runtime/utils/jsonl.js"; function writeSkill( @@ -52,6 +57,53 @@ function makeFixture(targetPath: string, competingSkillPaths: string[] = []): Ro }; } +describe("evaluateRuntimeReplayObservation", () => { + test("uses selection and read-path events rather than output claims", () => { + const targetSkillPath = "/qualification/.agents/skills/deck-skill/SKILL.md"; + const competingSkillPaths = [ + "/qualification/.agents/skills/compare-a/SKILL.md", + "/qualification/.agents/skills/compare-b/SKILL.md", + ]; + const fixture = makeFixture(targetSkillPath, competingSkillPaths); + const workspace: ReplayWorkspace = { + rootDir: "/qualification", + skillRegistryDir: "/qualification/.agents/skills", + targetSkillPath, + competingSkillPaths, + allowedReadRoots: [ + "/qualification/.agents/skills/deck-skill", + "/qualification/.agents/skills/compare-a", + "/qualification/.agents/skills/compare-b", + ], + }; + const evaluate = ( + shouldTrigger: boolean, + triggeredSkillNames: string[], + readSkillPaths: string[] = [], + rawOutput = "", + ) => { + const entry: EvalEntry = { query: "qualification control", should_trigger: shouldTrigger }; + const observation: RuntimeReplayObservation = { + triggeredSkillNames, + readSkillPaths, + rawOutput, + }; + return evaluateRuntimeReplayObservation(entry, fixture, observation, workspace); + }; + + expect(evaluate(true, ["deck-skill"], [targetSkillPath]).passed).toBe(true); + expect(evaluate(true, ["deck-skill", "deck-skill"]).passed).toBe(false); + expect(evaluate(true, ["deck-skill", "compare-a"]).passed).toBe(false); + expect(evaluate(false, ["compare-a", "compare-b"]).passed).toBe(false); + expect(evaluate(true, []).passed).toBe(false); + expect(evaluate(false, []).passed).toBe(true); + expect(evaluate(true, ["deck-skill"], ["/qualification/unrelated/SKILL.md"]).passed).toBe( + false, + ); + expect(evaluate(true, [], [], "Selected the deck-skill skill.").passed).toBe(false); + }); +}); + describe("runHostReplayFixture", () => { test("builds an auto fixture from the target skill registry", () => { const rootDir = mkdtempSync(join(tmpdir(), "selftune-replay-")); diff --git a/tests/grading/grade-session-flow.test.ts b/tests/grading/grade-session-flow.test.ts index 584096e4..62a97fdd 100644 --- a/tests/grading/grade-session-flow.test.ts +++ b/tests/grading/grade-session-flow.test.ts @@ -1,6 +1,7 @@ import { describe, expect, mock, test } from "bun:test"; -import { gradeSession } from "../../packages/runtime/grading/grade-session.js"; +import { assembleResult, gradeSession } from "../../packages/runtime/grading/grade-session.js"; +import type { GraderOutput } from "../../packages/runtime/types/grading.js"; import type { SessionTelemetryRecord } from "../../packages/runtime/types.js"; function makeTelemetryRecord( @@ -24,6 +25,94 @@ function makeTelemetryRecord( } describe("gradeSession", () => { + const base = { + expectations: ["session completed successfully"], + telemetry: makeTelemetryRecord(), + sessionId: "sess-abc", + skillName: "pptx", + transcriptExcerpt: "[ASSISTANT] Starting work", + transcriptPath: "/tmp/transcript.jsonl", + agent: "codex", + }; + const incomplete: GraderOutput = { + expectations: [], + unobserved_expectations: [ + { text: "session completed successfully", reason: "Only the start of work is captured" }, + ], + summary: { passed: 0, failed: 0, total: 0, pass_rate: 0 }, + claims: [], + eval_feedback: { suggestions: [], overall: "Incomplete evidence" }, + }; + + test("blocks incomplete evidence instead of persisting a synthetic failure or pass", async () => { + const grader = mock(async () => incomplete); + await expect(gradeSession({ ...base, gradeViaAgentFn: grader })).rejects.toThrow( + "unobserved evidence", + ); + expect(grader).toHaveBeenCalledTimes(1); + expect(() => assembleResult(incomplete, base.telemetry, "sess", "pptx", "source")).toThrow( + "unobserved evidence", + ); + }); + + test.each(["", "(no transcript)", "(transcript not found)"])( + "missing transcript source %j blocks before a model call", + async (transcriptExcerpt) => { + const grader = mock(async () => incomplete); + await expect( + gradeSession({ ...base, transcriptExcerpt, gradeViaAgentFn: grader }), + ).rejects.toThrow("source transcript evidence is unavailable"); + expect(grader).not.toHaveBeenCalled(); + }, + ); + + test("rejects an empty rubric before a model call", async () => { + const grader = mock(async () => incomplete); + await expect( + gradeSession({ ...base, expectations: [], gradeViaAgentFn: grader }), + ).rejects.toThrow("at least one expectation"); + expect(grader).not.toHaveBeenCalled(); + }); + + test("rejects duplicate or substituted judgments even with a matching count", async () => { + const grader = mock(async () => ({ + ...incomplete, + unobserved_expectations: [], + expectations: [{ text: "a different task", passed: true, evidence: "irrelevant" }], + })); + await expect(gradeSession({ ...base, gradeViaAgentFn: grader })).rejects.toThrow( + "duplicate or unrelated expectations", + ); + }); + + test("keeps a real observed failure separate from incomplete evidence", async () => { + const grader = mock(async () => ({ + ...incomplete, + unobserved_expectations: [], + expectations: [ + { + text: base.expectations[0], + passed: false, + evidence: "Terminal task result reports exit 1 and unrecovered failure", + score: 0, + }, + ], + })); + const result = await gradeSession({ ...base, gradeViaAgentFn: grader }); + expect(result.summary).toMatchObject({ passed: 0, failed: 1, total: 1, pass_rate: 0 }); + }); + + test("observed trigger-only rubric still avoids a model call", async () => { + const grader = mock(async () => incomplete); + const result = await gradeSession({ + ...base, + expectations: ["The skill was triggered during the session"], + gradeViaAgentFn: grader, + }); + expect(grader).not.toHaveBeenCalled(); + expect(result.summary).toMatchObject({ passed: 1, failed: 0, total: 1, pass_rate: 1 }); + }); + test("throws when the grader returns the wrong number of expectation results", async () => { const mockGradeViaAgent = mock(async () => ({ expectations: [], diff --git a/tests/grading/grader-output-boundary.test.ts b/tests/grading/grader-output-boundary.test.ts index 1b359ddc..2ec601c0 100644 --- a/tests/grading/grader-output-boundary.test.ts +++ b/tests/grading/grader-output-boundary.test.ts @@ -23,6 +23,14 @@ const output: GraderOutput = { }; describe("grader output boundary", () => { + test("retains unobserved evidence instead of stripping it at the JSON boundary", () => { + const incomplete = { + ...output, + expectations: [], + unobserved_expectations: [{ text: "writes the campaign", reason: "Missing final artifact" }], + }; + expect(parseGraderOutput(JSON.stringify(incomplete))).toEqual(incomplete); + }); test("decodes complete output and preserves false values, evidence, and feedback", () => { expect(parseGraderOutput(JSON.stringify(output))).toEqual(output); expect(parseGraderOutput(`\x60\x60\x60json\n${JSON.stringify(output)}\n\x60\x60\x60`)).toEqual( diff --git a/tests/grading/pre-gates.test.ts b/tests/grading/pre-gates.test.ts index e12239f0..71feeff9 100644 --- a/tests/grading/pre-gates.test.ts +++ b/tests/grading/pre-gates.test.ts @@ -1,218 +1,64 @@ import { describe, expect, test } from "bun:test"; +import { runPreGates } from "../../packages/runtime/grading/pre-gates.js"; -import { - DEFAULT_GATES, - type PreGate, - type PreGateContext, - runPreGates, -} from "../../packages/runtime/grading/pre-gates.js"; - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -function findGate(name: string): PreGate { - const gate = DEFAULT_GATES.find((g) => g.name === name); - if (!gate) throw new Error(`Gate "${name}" not found in DEFAULT_GATES`); - return gate; -} - -function makeCtx(overrides: Partial = {}): PreGateContext { - return { +describe("evidence-bound pre-gates", () => { + const context = { + skillName: "slides", telemetry: { - timestamp: "2025-01-15T10:00:00Z", - session_id: "sess-1", - cwd: "/tmp", - transcript_path: "/tmp/t.jsonl", - tool_calls: { Read: 3, Bash: 2 }, - total_tool_calls: 5, - bash_commands: ["ls"], - skills_triggered: ["myskill"], - assistant_turns: 4, - errors_encountered: 1, - transcript_chars: 5000, - last_user_query: "test", + skills_triggered: ["slides"], + total_tool_calls: 1, + assistant_turns: 1, + errors_encountered: 0, }, - skillName: "myskill", - ...overrides, + transcriptExcerpt: "[TOOL] Read /skills/other/SKILL.md", }; -} - -// --------------------------------------------------------------------------- -// Individual gate pattern matching -// --------------------------------------------------------------------------- - -describe("pre-gate pattern matching", () => { - test("skill_md_read gate matches both orderings", () => { - const gate = findGate("skill_md_read"); - expect(gate.pattern.test("SKILL.md was read")).toBe(true); - expect(gate.pattern.test("The skill.md file was read")).toBe(true); - expect(gate.pattern.test("read the SKILL.md file")).toBe(true); - expect(gate.pattern.test("Read SKILL.md")).toBe(true); - }); - - test("skill_md_read gate does not match unrelated text", () => { - const gate = findGate("skill_md_read"); - expect(gate.pattern.test("Output is a .pptx")).toBe(false); - }); - - test("expected_tools_called gate matches tool-related text", () => { - const gate = findGate("expected_tools_called"); - expect(gate.pattern.test("tools were called")).toBe(true); - expect(gate.pattern.test("tool called")).toBe(true); - }); - - test("error_count gate matches error-related text", () => { - const gate = findGate("error_count"); - expect(gate.pattern.test("errors encountered")).toBe(true); - expect(gate.pattern.test("error count")).toBe(true); - }); - - test("session_completed gate matches session text", () => { - const gate = findGate("session_completed"); - expect(gate.pattern.test("session completed")).toBe(true); - expect(gate.pattern.test("session finished")).toBe(true); - }); -}); - -// --------------------------------------------------------------------------- -// Individual gate logic -// --------------------------------------------------------------------------- - -describe("pre-gate check logic", () => { - test("skill_md_read passes when skill is in skills_triggered", () => { - const gate = findGate("skill_md_read"); - const ctx = makeCtx(); - expect(gate.check(ctx)).toBe(true); - }); - - test("skill_md_read fails when skill not triggered and no transcript match", () => { - const gate = findGate("skill_md_read"); - const ctx = makeCtx({ - telemetry: { ...makeCtx().telemetry, skills_triggered: [] }, - skillName: "myskill", - }); - expect(gate.check(ctx)).toBe(false); - }); - - test("skill_md_read passes via transcript match", () => { - const gate = findGate("skill_md_read"); - const ctx = makeCtx({ - telemetry: { ...makeCtx().telemetry, skills_triggered: [] }, - transcriptExcerpt: "[TOOL] Read file SKILL.md", - }); - expect(gate.check(ctx)).toBe(true); - }); - - test("expected_tools_called passes when tool_calls > 0", () => { - const gate = findGate("expected_tools_called"); - expect(gate.check(makeCtx())).toBe(true); - }); - - test("expected_tools_called fails when total_tool_calls is 0", () => { - const gate = findGate("expected_tools_called"); - const ctx = makeCtx({ - telemetry: { ...makeCtx().telemetry, total_tool_calls: 0 }, - }); - expect(gate.check(ctx)).toBe(false); - }); - - test("error_count passes when errors <= 2", () => { - const gate = findGate("error_count"); - expect(gate.check(makeCtx())).toBe(true); // errors_encountered: 1 - }); - - test("error_count fails when errors > 2", () => { - const gate = findGate("error_count"); - const ctx = makeCtx({ - telemetry: { ...makeCtx().telemetry, errors_encountered: 5 }, - }); - expect(gate.check(ctx)).toBe(false); - }); - - test("session_completed passes when assistant_turns > 0", () => { - const gate = findGate("session_completed"); - expect(gate.check(makeCtx())).toBe(true); - }); - test("session_completed fails when assistant_turns is 0", () => { - const gate = findGate("session_completed"); - const ctx = makeCtx({ - telemetry: { ...makeCtx().telemetry, assistant_turns: 0 }, + test.each([ + "SKILL.md was read", + "SKILL.md was read before editing files", + "Expected tools were called", + "session completed successfully", + "No unhandled errors were encountered", + "No more than 1 error encountered", + ])("does not substitute proxy telemetry for %s", (expectation) => { + expect(runPreGates([expectation], context)).toEqual({ + resolved: [], + remaining: [expectation], }); - expect(gate.check(ctx)).toBe(false); }); -}); -// --------------------------------------------------------------------------- -// runPreGates orchestration -// --------------------------------------------------------------------------- + test("resolves only the exact observed target trigger claim", () => { + const text = "The skill was triggered during the session"; + const result = runPreGates([text], context); + expect(result.remaining).toEqual([]); + expect(result.resolved).toEqual([ + { + text, + passed: true, + score: 1, + source: "pre-gate", + evidence: 'telemetry.skills_triggered includes "slides"', + }, + ]); + }); + + test.each([{}, { skills_triggered: [] }, { skills_triggered: ["other"] }])( + "missing target observation stays unresolved: %j", + (telemetry) => { + const text = "The skill was triggered during the session"; + expect(runPreGates([text], { ...context, telemetry })).toEqual({ + resolved: [], + remaining: [text], + }); + }, + ); -describe("runPreGates", () => { - test("resolves matching expectations and returns remaining", () => { + test("does not drop modifiers, negation, or another skill's identity", () => { const expectations = [ - "SKILL.md was read correctly", - "Output is a valid .pptx file", - "session completed successfully", + 'The "other" skill was triggered during the session', + "The skill was not triggered during the session", + "The skill was triggered during the session before any edits", ]; - const result = runPreGates(expectations, makeCtx()); - - expect(result.resolved.length).toBe(2); // skill_md_read + session_completed - expect(result.remaining).toEqual(["Output is a valid .pptx file"]); - }); - - test("resolved expectations have source 'pre-gate'", () => { - const result = runPreGates(["SKILL.md was read"], makeCtx()); - expect(result.resolved[0].source).toBe("pre-gate"); - }); - - test("resolved expectations have score 1.0 for pass", () => { - const result = runPreGates(["SKILL.md was read"], makeCtx()); - expect(result.resolved[0].score).toBe(1.0); - expect(result.resolved[0].passed).toBe(true); - }); - - test("resolved expectations have score 0.0 for fail", () => { - const ctx = makeCtx({ - telemetry: { ...makeCtx().telemetry, skills_triggered: [] }, - }); - const result = runPreGates(["SKILL.md was read"], ctx); - expect(result.resolved[0].score).toBe(0.0); - expect(result.resolved[0].passed).toBe(false); - }); - - test("empty expectations returns empty results", () => { - const result = runPreGates([], makeCtx()); - expect(result.resolved).toEqual([]); - expect(result.remaining).toEqual([]); - }); - - test("no matching gates sends all to remaining", () => { - const result = runPreGates(["completely unrelated text"], makeCtx()); - expect(result.resolved).toEqual([]); - expect(result.remaining).toEqual(["completely unrelated text"]); - }); - - test("custom gates via DI override defaults", () => { - const customGate: PreGate = { - name: "custom", - pattern: /custom check/i, - check: () => true, - }; - const result = runPreGates(["custom check please"], makeCtx(), [customGate]); - expect(result.resolved.length).toBe(1); - expect(result.resolved[0].evidence).toContain("custom"); - }); - - test("global regex gate does not carry stale lastIndex across calls", () => { - const globalGate: PreGate = { - name: "global_test", - pattern: /foo/gi, - check: () => true, - }; - // Without lastIndex reset, the second "foo" would fail because - // the global regex advances lastIndex past the match on first call - const result = runPreGates(["foo", "foo"], makeCtx(), [globalGate]); - expect(result.resolved.length).toBe(2); + expect(runPreGates(expectations, context)).toEqual({ resolved: [], remaining: expectations }); }); }); diff --git a/tests/improve.test.ts b/tests/improve.test.ts index ed3b3e35..48dc136e 100644 --- a/tests/improve.test.ts +++ b/tests/improve.test.ts @@ -35,6 +35,9 @@ describe("selftune improve", () => { "--dry-run", "--agent", "codex", + "--budget-remaining-usd", + "20.00", + "--estimated-cost-usd=5", ], { historicalImprove: async (input) => { @@ -54,12 +57,105 @@ describe("selftune improve", () => { skill: "to-issues", skillPath: "/tmp/skills/to-issues/SKILL.md", agent: "codex", + budgetRemainingUsd: 20, + estimatedCostUsd: 5, }); expect(evolved).toBe(false); }); + test("requires explicit spend inputs before attempting historical replay", async () => { + let historicalCalled = false; + + await expect( + runImprove( + [ + "--skill", + "to-issues", + "--skill-path", + "/tmp/skills/to-issues/SKILL.md", + "--scope", + "auto", + "--dry-run", + ], + { + historicalImprove: async () => { + historicalCalled = true; + return { handled: true }; + }, + }, + ), + ).rejects.toMatchObject({ code: "MISSING_FLAG" }); + + expect(historicalCalled).toBe(false); + }); + + test("rejects invalid or non-finite caller spend inputs", async () => { + let historicalCalled = false; + for (const amount of ["-0.01", "NaN", "Infinity"]) { + await expect( + runImprove( + [ + "--skill", + "to-issues", + "--skill-path", + "/tmp/skills/to-issues/SKILL.md", + "--scope", + "auto", + "--dry-run", + "--budget-remaining-usd", + "20", + "--estimated-cost-usd", + amount, + ], + { + historicalImprove: async () => { + historicalCalled = true; + return { handled: true }; + }, + }, + ), + ).rejects.toMatchObject({ code: "INVALID_FLAG" }); + } + + expect(historicalCalled).toBe(false); + }); + + test("stops before historical candidate generation when the total-run estimate exceeds remaining spend", async () => { + let historicalCalled = false; + + await expect( + runImprove( + [ + "--skill", + "to-issues", + "--skill-path", + "/tmp/skills/to-issues/SKILL.md", + "--scope", + "auto", + "--dry-run", + "--budget-remaining-usd", + "2", + "--estimated-cost-usd", + "2.01", + ], + { + historicalImprove: async () => { + historicalCalled = true; + return { handled: true }; + }, + }, + ), + ).rejects.toMatchObject({ + code: "GUARD_BLOCKED", + message: expect.stringContaining("Historical replay was not started"), + }); + + expect(historicalCalled).toBe(false); + }); + test("falls back to description evolution when historical contrast is ineligible", async () => { let evolved = false; + let evolvedArgs: string[] = []; await runImprove( [ "--skill", @@ -69,16 +165,23 @@ describe("selftune improve", () => { "--scope", "auto", "--dry-run", + "--budget-remaining-usd", + "20", + "--estimated-cost-usd", + "5", ], { historicalImprove: async () => ({ handled: false }), evolveCliMain: async () => { evolved = true; + evolvedArgs = [...process.argv]; }, }, ); expect(evolved).toBe(true); + expect(evolvedArgs).not.toContain("--budget-remaining-usd"); + expect(evolvedArgs).not.toContain("--estimated-cost-usd"); }); test("delegates package scope into search-run and preserves package-evaluator flags", async () => { diff --git a/tests/ingestors/codex-source-sync-analytics.test.ts b/tests/ingestors/codex-source-sync-analytics.test.ts index b1c325b6..c6d8a03e 100644 --- a/tests/ingestors/codex-source-sync-analytics.test.ts +++ b/tests/ingestors/codex-source-sync-analytics.test.ts @@ -1,5 +1,13 @@ import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, + utimesSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -192,6 +200,22 @@ test("source sync commits a Codex rollout to SQLite and DuckDB before advancing authoritativeFiles: [rolloutPath], }); expect(progress).toContain("processed 1/1 Codex rollouts"); + const [reference] = await queryDuckDb((store) => + store.queryHistoricalSkillTaskReferences({ skill_id: "diagnose", limit: 1 }), + ); + if (!reference) throw new Error("fixture discovery reference missing"); + expect( + await queryDuckDb((store) => + store.resolveSourceTask({ + ...reference, + skill_revision: "not-captured", + pin_id: "sync-proof-test", + replay: async () => { + throw new Error("Unknown historical revision must not read source bytes"); + }, + }), + ), + ).toEqual({ state: "unavailable", reason: "unverified_skill_revision" }); expect(getDb().query("SELECT COUNT(*) AS count FROM sessions").get()).toEqual({ count: 1 }); expect(getDb().query("SELECT COUNT(*) AS count FROM skill_invocations").get()).toEqual({ @@ -232,3 +256,23 @@ test("source sync acknowledges a multi-turn Codex rollout only after its session }); expect(existsSync(markerPath)).toBe(true); }); + +test("same-size corrected source with restored mtime replaces analytical facts once", async () => { + const path = writeRollout(); + const fixedTime = 1_700_000_000; + utimesSync(path, fixedTime, fixedTime); + const layer = Layer.provide( + makeLocalTraceImporterLive(getDb()), + makeDuckDbNodeApiAnalyticalStoreLive(analyticalPath), + ); + expect((await runSync(layer)).synced).toBe(1); + writeFileSync( + path, + readFileSync(path, "utf8").replace('"input_tokens":120', '"input_tokens":121'), + ); + utimesSync(path, fixedTime, fixedTime); + expect((await runSync(layer)).synced).toBe(1); + const signals = await queryDuckDb((store) => store.querySkillSignals()); + expect(signals.find((item) => item.skill_name === "diagnose")?.input_tokens).toBe(121); + expect((await runSync(layer)).synced).toBe(0); +}); diff --git a/tests/ingestors/codex-version-evidence.test.ts b/tests/ingestors/codex-version-evidence.test.ts new file mode 100644 index 00000000..e8202aa3 --- /dev/null +++ b/tests/ingestors/codex-version-evidence.test.ts @@ -0,0 +1,90 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + parseRolloutFile, + buildCanonicalRecordsFromRollout, +} from "@selftune/harness-codex/ingestors/codex-rollout"; +import { createSkillReadEvidenceCollector } from "../../packages/harnesses/codex/src/ingestors/skill-read-evidence"; + +test("retains desktop output provenance and rejects multi-skill ambiguity", () => { + const collector = createSkillReadEvidenceCollector(); + collector.customCall("a", 'text(await tools.exec_command({cmd:"cat /a/sample/SKILL.md"}));'); + collector.output("a", "wrapped output", 6); + expect(collector.reads[0]?.version_scope).toBe("captured_tool_output"); + collector.customCall("b", "cat /a/sample/SKILL.md /b/other/SKILL.md"); + collector.output("b", "ambiguous", 8); + expect(collector.reads).toHaveLength(1); +}); + +test("retains historical read provenance without inventing a package revision", () => { + const root = mkdtempSync(join(tmpdir(), "codex-version-")); + try { + const path = join(root, "rollout.jsonl"); + writeFileSync( + path, + [ + { type: "session_meta", payload: { id: "evidence-test", cwd: "/project" } }, + { + type: "event_msg", + payload: { type: "user_message", message: "Use sample to review this project" }, + }, + { + type: "response_item", + payload: { + type: "function_call", + name: "exec_command", + call_id: "r1", + arguments: JSON.stringify({ cmd: "cat /project/skills/sample/SKILL.md" }), + }, + }, + { + type: "response_item", + payload: { + type: "function_call_output", + call_id: "r1", + output: "Historical instructions, not today's installed file.", + }, + }, + ] + .map((event) => JSON.stringify(event)) + .join("\n"), + ); + const parsed = parseRolloutFile(path, new Set(["sample"])); + expect(parsed).not.toBeNull(); + if (!parsed) throw new Error("Expected parsed fixture"); + const invocation = buildCanonicalRecordsFromRollout(parsed).find( + (r) => r.record_kind === "skill_invocation", + ); + expect(invocation?.skill_path).toBe("/project/skills/sample/SKILL.md"); + expect(invocation?.skill_version_hash).toBeUndefined(); + expect(invocation?.raw_source_ref.metadata?.package_version_status).toBe("unknown"); + expect(parsed.skill_reads?.[0]?.output_line).toBe(4); + expect(parsed.skill_reads?.[0]?.output_sha256).toHaveLength(64); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("does not associate compound command output or unmatched outputs with a skill", () => { + const collector = createSkillReadEvidenceCollector(); + collector.call( + "a", + "exec_command", + JSON.stringify({ cmd: "cat /a/sample/SKILL.md; echo other" }), + ); + collector.output("a", "mixed output", 1); + collector.output("missing", "unrelated", 2); + expect(collector.reads).toEqual([]); +}); + +test("retains distinct reads rather than choosing a single historical version", () => { + const collector = createSkillReadEvidenceCollector(); + for (const id of ["a", "b"]) { + collector.call(id, "Read", JSON.stringify({ file_path: "/a/sample/SKILL.md" })); + collector.output(id, id, 3); + } + expect(collector.reads).toHaveLength(2); + expect(collector.reads[0]?.output_sha256).not.toBe(collector.reads[1]?.output_sha256); +}); diff --git a/tests/library/remote-library-sync.test.ts b/tests/library/remote-library-sync.test.ts index 587ae0ad..1cb53a7c 100644 --- a/tests/library/remote-library-sync.test.ts +++ b/tests/library/remote-library-sync.test.ts @@ -4,6 +4,7 @@ import { mkdirSync, mkdtempSync, readdirSync, + readFileSync, rmSync, symlinkSync, utimesSync, @@ -43,6 +44,7 @@ import { import { listSynthesisReleases } from "../../packages/runtime/synthesis.js"; import { CLIError } from "../../packages/runtime/utils/cli-error.js"; import { computeSkillVersionHash } from "../../packages/runtime/utils/skill-discovery.js"; +import { syncPrivateLibrary } from "../../apps/local/src/private-library-sync.js"; function passingPackageEvaluation(skillName: string, skillPath: string) { return { @@ -107,6 +109,87 @@ function memoryHandle(): RemoteLibraryHandle { } describe("Remote Library sync lifecycle", () => { + test("private Cloud backup retries without duplicate uploads and restores exact skill files", async () => { + const root = mkdtempSync(join(tmpdir(), "private-library-roundtrip-")); + const handle = memoryHandle(); + try { + const packagePath = createSkill(join(root, "skills"), "marketing"); + const library = await loadLibraryCatalog({ + searchDirs: [join(root, "skills")], + skillSetConfigRoot: join(root, "config"), + quarantineRoot: join(root, "quarantine"), + usageRows: [], + workspacePaths: [], + }); + const first = await syncPrivateLibrary({ handle, library }); + expect(first.uploaded).toBe(1); + const second = await syncPrivateLibrary({ handle, library }); + expect(second.uploaded).toBe(0); + expect(second.snapshot.snapshotId).toBe(first.snapshot.snapshotId); + const targetRoot = join(root, "restored"); + const restored = await restoreRemoteLibrary({ handle, targetRoot }); + expect(restored.restored).toBe(1); + const revision = first.snapshot.artifacts[0]!.objectHash; + for (const file of ["SKILL.md", "workflow.md"]) { + expect( + readFileSync(join(targetRoot, "library", "packages", revision, "marketing", file)), + ).toEqual(readFileSync(join(packagePath, file))); + } + await expect(restoreRemoteLibrary({ handle, targetRoot })).rejects.toThrow( + "Restore target must be empty", + ); + writeFileSync( + join(packagePath, "workflow.md"), + "A revised workflow without changing SKILL.md.\n", + ); + const changedLibrary = await loadLibraryCatalog({ + searchDirs: [join(root, "skills")], + skillSetConfigRoot: join(root, "config"), + quarantineRoot: join(root, "quarantine"), + usageRows: [], + workspacePaths: [], + }); + await expect( + syncPrivateLibrary({ + handle: { + ...handle, + commitSnapshot: async () => { + throw new Error("simulated interrupted snapshot commit"); + }, + }, + library: changedLibrary, + }), + ).rejects.toThrow("simulated interrupted snapshot commit"); + const changed = await syncPrivateLibrary({ handle, library: changedLibrary }); + expect(changed.uploaded).toBe(0); + expect(changed.snapshot.artifacts).toHaveLength(2); + const revised = await restoreRemoteLibrary({ + handle, + targetRoot: join(root, "revised-restore"), + }); + expect(revised.restored).toBe(2); + const blocked = createSkill(join(root, "skills"), "blocked"); + writeFileSync(join(blocked, "private.key"), "test fixture, not a real key"); + createSkill(join(root, "skills"), "another-safe-skill"); + const mixed = await loadLibraryCatalog({ + searchDirs: [join(root, "skills")], + skillSetConfigRoot: join(root, "config"), + quarantineRoot: join(root, "quarantine"), + usageRows: [], + workspacePaths: [], + }); + await expect(syncPrivateLibrary({ handle, library: mixed })).rejects.toThrow( + "Backup incomplete: 1 package(s) need attention", + ); + expect((await handle.head())?.artifacts).toHaveLength(3); + expect( + (await handle.head())?.artifacts.some((item) => item.artifactId.includes("/blocked/")), + ).toBe(false); + } finally { + await handle.dispose(); + rmSync(root, { recursive: true, force: true }); + } + }); test("syncs privacy-safe learned state and merges it into another local database", async () => { const root = mkdtempSync(join(tmpdir(), "selftune-learned-state-sync-")); const handle = memoryHandle(); diff --git a/tests/library/synthesis.test.ts b/tests/library/synthesis.test.ts index 8f4b875c..90b5947a 100644 --- a/tests/library/synthesis.test.ts +++ b/tests/library/synthesis.test.ts @@ -238,6 +238,9 @@ describe("local synthesis lifecycle", () => { const evals = Schema.decodeUnknownSync( Schema.fromJsonString(Schema.Array(GeneratedEvalCase)), )(readFileSync(join(skillDir, "evals", "generated.json"), "utf8")); + expect(evals.every((item) => item.kind === "positive" || item.kind === "execution")).toBe( + true, + ); expect( evals .filter((item) => item.expectedSkillNames.length > 0) @@ -257,6 +260,7 @@ describe("local synthesis lifecycle", () => { ), )(readFileSync(join(skillDir, "evals", "release.json"), "utf8")); expect(releaseEvals.some((item) => item.selftune_provenance.held_out)).toBe(true); + expect(releaseEvals.every((item) => item.selftune_provenance.held_out)).toBe(true); expect( releaseEvals .flatMap((item) => item.selftune_provenance.source_session_ids) diff --git a/tests/localdb/drizzle-migrations.test.ts b/tests/localdb/drizzle-migrations.test.ts index f0389c85..a220524b 100644 --- a/tests/localdb/drizzle-migrations.test.ts +++ b/tests/localdb/drizzle-migrations.test.ts @@ -57,6 +57,25 @@ afterEach(() => { }); describe("Drizzle local database", () => { + it("discovers workspace paths from covering indexes instead of wide telemetry rows", () => { + const db = openDb(":memory:"); + try { + const plans = db + .query<{ detail: string }, []>(`EXPLAIN QUERY PLAN + SELECT cwd AS workspace_path FROM session_telemetry WHERE cwd IS NOT NULL AND trim(cwd) <> '' + UNION SELECT workspace_path FROM sessions WHERE workspace_path IS NOT NULL AND trim(workspace_path) <> '' + ORDER BY workspace_path`) + .all(); + expect(plans.some((row) => row.detail.includes("COVERING INDEX idx_session_tel_cwd"))).toBe( + true, + ); + expect( + plans.some((row) => row.detail.includes("COVERING INDEX idx_sessions_workspace_path")), + ).toBe(true); + } finally { + db.close(); + } + }); it("rejects malformed journal metadata before migrations can use it", () => { const journal = Schema.decodeUnknownSync(Schema.fromJsonString(MigrationJournal))( embeddedMigrations["meta/_journal.json"], @@ -205,7 +224,7 @@ describe("Drizzle local database", () => { const journal = Schema.decodeUnknownSync(Schema.fromJsonString(MigrationJournal))( embeddedMigrations["meta/_journal.json"], ); - const previousEntries = journal.entries.slice(0, -1); + const previousEntries = journal.entries.filter((entry) => entry.idx < 18); writeFileSync( join(previousMeta, "_journal.json"), JSON.stringify({ ...journal, entries: previousEntries }), @@ -310,7 +329,7 @@ describe("Drizzle local database", () => { "created_at", "updated_at", ]); - expect(latestMigration).toEqual({ created_at: 1786088000000 }); + expect(latestMigration).toEqual({ created_at: journal.entries.at(-1)?.when }); expect(legacyEvaluationDraftIdentityIndex).toBeNull(); expect(signalCandidateColumns.map((column) => column.name)).toEqual( expect.arrayContaining(["candidate_id", "idempotency_key", "manifest_digest"]), @@ -326,6 +345,9 @@ describe("Drizzle local database", () => { temporaryRoots.push(root); const path = join(root, "selftune.db"); const preview = new Database(path); + const baseline = embeddedMigrations["0000_local_runtime_baseline.sql"]; + if (!baseline) throw new Error("Expected the preview's baseline schema."); + preview.exec(baseline); const journal = Schema.decodeUnknownSync(Schema.fromJsonString(MigrationJournal))( embeddedMigrations["meta/_journal.json"], ); diff --git a/tests/localdb/read-queries.test.ts b/tests/localdb/read-queries.test.ts index 2dfc4189..21b286a1 100644 --- a/tests/localdb/read-queries.test.ts +++ b/tests/localdb/read-queries.test.ts @@ -836,6 +836,34 @@ describe("getSkillsList", () => { expect(browser?.has_evidence).toBe(false); }); + it("aggregates confidence including zero without duplicating sessions", () => { + seedSkillUsage(db, { + query: "first request", + confidence: 0, + timestamp: "2026-03-17T12:00:00Z", + }); + seedSkillUsage(db, { + query: "second request", + confidence: 0.8, + timestamp: "2026-03-17T10:00:00Z", + }); + seedSkillUsage(db, { + query: "third request", + confidence: null, + triggered: 0, + timestamp: "2026-03-17T11:00:00Z", + }); + const [skill] = getSkillsList(db, []); + expect(skill).toMatchObject({ + total_checks: 3, + triggered_count: 2, + unique_sessions: 1, + last_seen: "2026-03-17T12:00:00Z", + routing_confidence: 0.4, + confidence_coverage: 2 / 3, + }); + }); + it("includes draft packages with create readiness even before telemetry exists", () => { const root = mkdtempSync(join(tmpdir(), "selftune-draft-skill-")); tempDirs.push(root); diff --git a/tests/localdb/trust-query-contracts.test.ts b/tests/localdb/trust-query-contracts.test.ts index df36628f..4ea1ad8b 100644 --- a/tests/localdb/trust-query-contracts.test.ts +++ b/tests/localdb/trust-query-contracts.test.ts @@ -1,5 +1,9 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import type { Database } from "bun:sqlite"; +import { Database as SQLite } from "bun:sqlite"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { openDb } from "../../packages/runtime/localdb/db.js"; import { getRecentDecisions, @@ -15,6 +19,49 @@ afterEach(() => { }); describe("trust query JSON projections", () => { + test("reuses unchanged facts without exposing cached mutable rows", () => { + db.run("INSERT INTO sessions (session_id) VALUES ('cached')"); + db.run( + "INSERT INTO skill_invocations (skill_invocation_id, session_id, skill_name, query, triggered) VALUES ('cached', 'cached', 'test', 'hello', 1)", + ); + const first = queryTrustedSkillObservationRows(db); + const row = first[0]; + if (!row) throw new Error("Expected an observation"); + row.triggered = 0; + first.length = 0; + expect(queryTrustedSkillObservationRows(db)[0]?.triggered).toBe(1); + db.run("UPDATE skill_invocations SET triggered = 0 WHERE skill_invocation_id = 'cached'"); + expect(queryTrustedSkillObservationRows(db)[0]?.triggered).toBe(0); + }); + + test("invalidates after another connection edits prompt classification or observations", () => { + const root = mkdtempSync(join(tmpdir(), "selftune-trust-version-")); + const path = join(root, "test.db"); + const writer = openDb(path); + const reader = new SQLite(path, { readonly: true }); + try { + writer.run("INSERT INTO sessions (session_id) VALUES ('external')"); + writer.run( + "INSERT INTO prompts (prompt_id, session_id, prompt_text, prompt_kind) VALUES ('prompt', 'external', 'ordinary prompt', 'user')", + ); + writer.run( + "INSERT INTO skill_invocations (skill_invocation_id, session_id, skill_name, query, triggered, matched_prompt_id) VALUES ('external', 'external', 'test', 'hello', 1, 'prompt')", + ); + expect(queryTrustedSkillObservationRows(reader)).toHaveLength(1); + writer.run( + "UPDATE prompts SET prompt_text = 'internal' WHERE prompt_id = 'prompt'", + ); + expect(queryTrustedSkillObservationRows(reader)).toHaveLength(0); + writer.run("UPDATE prompts SET prompt_text = 'ordinary prompt' WHERE prompt_id = 'prompt'"); + expect(queryTrustedSkillObservationRows(reader)).toHaveLength(1); + writer.run("DELETE FROM skill_invocations"); + expect(queryTrustedSkillObservationRows(reader)).toHaveLength(0); + } finally { + reader.close(); + writer.close(); + rmSync(root, { recursive: true, force: true }); + } + }); test("classifies valid regression arrays without accepting malformed evidence as failures", () => { const insert = db.prepare( "INSERT INTO evolution_audit (timestamp, proposal_id, skill_name, action, eval_snapshot_json) VALUES (?, ?, 'marketing', 'validated', ?)", diff --git a/tests/observability/compact-fixture.ts b/tests/observability/compact-fixture.ts new file mode 100644 index 00000000..5dc70865 --- /dev/null +++ b/tests/observability/compact-fixture.ts @@ -0,0 +1,74 @@ +import { expect } from "bun:test"; +import { existsSync, readFileSync, statSync } from "node:fs"; +import { DuckDBInstance } from "@duckdb/node-api"; +import { sourceDigest } from "@selftune/observability/source-reconstruction"; +import * as Schema from "effect/Schema"; + +const TableNames = Schema.Array(Schema.Struct({ table_name: Schema.String })); +const literal = (value: string) => `'${value.replaceAll("'", "''")}'`; +const identifier = (value: string) => `"${value.replaceAll('"', '""')}"`; + +/** Test-only closed-writer copy; never swaps, deletes, or opens a live store. */ +export async function compactFixture(source: string, destination: string) { + expect(existsSync(destination)).toBe(false); + expect(existsSync(`${source}.wal`)).toBe(false); + expect(statSync(source).size).toBeLessThan(32 * 1024 * 1024); + const originalDigest = sourceDigest(readFileSync(source)); + const db = await DuckDBInstance.create(":memory:", { + memory_limit: "128MB", + threads: "1", + max_temp_directory_size: "0B", + }); + try { + const connection = await db.connect(); + try { + await connection.run(`ATTACH ${literal(source)} AS original (READ_ONLY)`); + await connection.run(`ATTACH ${literal(destination)} AS compacted`); + await connection.run("COPY FROM DATABASE original TO compacted"); + const tables = Schema.decodeUnknownSync(TableNames)( + await ( + await connection.run( + "SELECT table_name FROM duckdb_tables() WHERE database_name = 'original' ORDER BY table_name", + ) + ).getRowObjects(), + ); + expect(tables.length).toBeGreaterThan(0); + for (const { table_name } of tables) { + const table = identifier(table_name); + const original = await connection.run(`SELECT * FROM original.main.${table} ORDER BY ALL`); + const compacted = await connection.run( + `SELECT * FROM compacted.main.${table} ORDER BY ALL`, + ); + expect(await compacted.getRowObjects()).toEqual(await original.getRowObjects()); + } + for (const catalog of [ + "SELECT table_name FROM duckdb_tables()", + "SELECT view_name FROM duckdb_views()", + "SELECT table_name, index_name, is_unique, expressions FROM duckdb_indexes()", + "SELECT table_name, constraint_type, constraint_text FROM duckdb_constraints()", + ]) { + const original = await connection.run( + `${catalog} WHERE database_name = 'original' ORDER BY ALL`, + ); + const compacted = await connection.run( + `${catalog} WHERE database_name = 'compacted' ORDER BY ALL`, + ); + expect(await compacted.getRowObjects()).toEqual(await original.getRowObjects()); + } + await connection.run("CHECKPOINT compacted"); + } finally { + connection.closeSync(); + } + } finally { + db.closeSync(); + } + expect(sourceDigest(readFileSync(source))).toBe(originalDigest); + expect(existsSync(`${destination}.wal`)).toBe(false); + const allocated = { + original: statSync(source).blocks * 512, + compacted: statSync(destination).blocks * 512, + }; + expect(allocated.compacted).toBeLessThan(32 * 1024 * 1024); + console.info("compaction fixture allocated bytes", allocated); + return allocated; +} diff --git a/tests/observability/duckdb-migration.test.ts b/tests/observability/duckdb-migration.test.ts index 9d77b858..d211859d 100644 --- a/tests/observability/duckdb-migration.test.ts +++ b/tests/observability/duckdb-migration.test.ts @@ -10,7 +10,7 @@ import * as Effect from "effect/Effect"; const emptyResult = (): DuckDbQueryResult => ({ getRowObjects: async () => [] }); -test("runs the historical v4 rebuild once, then applies v5-v9 migrations", async () => { +test("runs the historical v4 rebuild once, then applies v5-v12 migrations", async () => { const statements: string[] = []; let version = 3; const factory: DuckDbInstanceFactory = { @@ -29,6 +29,9 @@ test("runs the historical v4 rebuild once, then applies v5-v9 migrations", async if (sql.includes("VALUES (7)")) version = 7; if (sql.includes("VALUES (8)")) version = 8; if (sql.includes("VALUES (9)")) version = 9; + if (sql.includes("VALUES (10)")) version = 10; + if (sql.includes("VALUES (11)")) version = 11; + if (sql.includes("VALUES (12)")) version = 12; return emptyResult(); }, }), @@ -43,7 +46,7 @@ test("runs the historical v4 rebuild once, then applies v5-v9 migrations", async const firstOpenStatementCount = statements.length; await Effect.runPromise(openStore()); - expect(version).toBe(9); + expect(version).toBe(12); expect( statements.filter((statement) => statement.includes("DROP TABLE IF EXISTS observability_spans_v4"), @@ -122,7 +125,7 @@ test("does not apply historical migrations to a future schema version", async () run: async (sql) => { statements.push(sql); if (sql.includes("SELECT MAX(version)")) { - return { getRowObjects: async () => [{ version: 10 }] }; + return { getRowObjects: async () => [{ version: 13 }] }; } return emptyResult(); }, @@ -141,3 +144,38 @@ test("does not apply historical migrations to a future schema version", async () expect(statements.some((statement) => statement.includes("observability_spans_v4"))).toBe(false); expect(statements.some((statement) => statement.startsWith("ALTER TABLE"))).toBe(false); }); + +test.each([9, 10, 11])( + "upgrades schema %i without rebuilding the historical corpus", + async (version) => { + const statements: string[] = []; + const factory: DuckDbInstanceFactory = { + open: async () => ({ + closeSync: () => undefined, + connect: async () => ({ + appendRows: async () => undefined, + closeSync: () => undefined, + run: async (sql) => { + statements.push(sql); + return sql.includes("SELECT MAX(version)") + ? { getRowObjects: async () => [{ version }] } + : emptyResult(); + }, + }), + }), + }; + await Effect.runPromise( + Effect.gen(function* () { + yield* DuckDbAnalyticalStore; + }).pipe(Effect.provide(makeDuckDbAnalyticalStoreLive(factory, ":memory:")), Effect.scoped), + ); + expect( + statements.some((sql) => sql.includes("INSERT INTO observability_historical_metric_rollups")), + ).toBe(false); + expect(statements.some((sql) => sql.includes("observability_spans_v4"))).toBe(false); + expect(statements.some((sql) => sql.includes("INSERT INTO observability_span_summaries"))).toBe( + false, + ); + expect(statements.at(-1)).toContain("VALUES (12)"); + }, +); diff --git a/tests/observability/duckdb-node-api.test.ts b/tests/observability/duckdb-node-api.test.ts index 6c508697..3e824ad9 100644 --- a/tests/observability/duckdb-node-api.test.ts +++ b/tests/observability/duckdb-node-api.test.ts @@ -25,6 +25,7 @@ import { type DuckDbWalRecoveryDependencies, } from "@selftune/observability/duckdb-node-api"; import * as Effect from "effect/Effect"; +import { availableStorageBytes } from "@selftune/observability/storage-capacity"; const temporaryDirectories: string[] = []; @@ -49,8 +50,9 @@ function recoveryDependencies( warnings: string[], ): DuckDbWalRecoveryDependencies { return { + availableBytes: availableStorageBytes, copyFile, - lstat, + lstat: (path) => lstat(path, { bigint: true }), mkdir, now: () => new Date("2026-08-01T12:34:56.789Z"), open, @@ -257,6 +259,50 @@ test("an ENOENT WAL race retries after another process already moved the WAL", a expect(warnings).toEqual([]); }); +test.each(["before-copy", "after-copy", "capacity-unavailable", "copy-enospc"])( + "preserves original checkpoint and WAL when recovery cannot proceed: %s", + async (stage) => { + const directory = mkdtempSync(join(tmpdir(), "selftune-recovery-pressure-")); + temporaryDirectories.push(directory); + const databasePath = join(directory, "observability.duckdb"); + const walPath = `${databasePath}.wal`; + writeFileSync(databasePath, "checkpoint"); + writeFileSync(walPath, "unreplayable wal"); + const warnings: string[] = []; + let copies = 0; + let reads = 0; + let opens = 0; + const dependencies = recoveryDependencies(async () => { + opens += 1; + throw knownWalReplayFailure(); + }, warnings); + await expect( + openDuckDbWithWalRecovery(databasePath, { + ...dependencies, + availableBytes: async () => { + reads += 1; + if (stage === "capacity-unavailable") throw new Error("capacity unavailable"); + return stage === "before-copy" || (stage === "after-copy" && reads > 1) + ? 0n + : 1024n ** 4n; + }, + copyFile: async (source, destination, mode) => { + copies += 1; + if (stage === "copy-enospc") + throw Object.assign(new Error("disk full"), { code: "ENOSPC" }); + await copyFile(source, destination, mode); + }, + }), + ).rejects.toThrow(); + expect(opens).toBe(1); + expect(copies).toBe(stage === "before-copy" || stage === "capacity-unavailable" ? 0 : 1); + expect(readFileSync(databasePath, "utf8")).toBe("checkpoint"); + expect(readFileSync(walPath, "utf8")).toBe("unreplayable wal"); + expect(warnings).toEqual([]); + if (copies === 0) expect(existsSync(join(directory, "backups"))).toBe(false); + }, +); + const batch: typeof DuckDbAnalyticalBatch.Encoded = { schema_version: "1.0.0", batch_id: "batch-codex-001", @@ -405,8 +451,8 @@ test("upgrades an indexed v2 span table through the v4 rebuild and restarts clea }).pipe(Effect.provide(makeDuckDbNodeApiAnalyticalStoreLive(databasePath)), Effect.scoped), ); - expect(await openStore()).toMatchObject({ schema_version: 9 }); - expect(await openStore()).toMatchObject({ schema_version: 9 }); + expect(await openStore()).toMatchObject({ schema_version: 12 }); + expect(await openStore()).toMatchObject({ schema_version: 12 }); const instance = await DuckDBInstance.create(databasePath); const connection = await instance.connect(); @@ -434,6 +480,9 @@ test("upgrades an indexed v2 span table through the v4 rebuild and restarts clea { version: 7 }, { version: 8 }, { version: 9 }, + { version: 10 }, + { version: 11 }, + { version: 12 }, ]); expect(indexes).toEqual( expect.arrayContaining([ diff --git a/tests/observability/duckdb-store.test.ts b/tests/observability/duckdb-store.test.ts index e6d5b3f0..3dd567a8 100644 --- a/tests/observability/duckdb-store.test.ts +++ b/tests/observability/duckdb-store.test.ts @@ -239,7 +239,7 @@ test("creates the analytical schema, derives metrics, and ignores a replayed bat ]); expect(result.health).toEqual({ database_path: ":memory:", - schema_version: 9, + schema_version: 12, span_count: 1, metric_count: 5, link_count: 1, @@ -794,7 +794,7 @@ test("v8 rebuilds materialized rollups deterministically for an existing v7 poin "DELETE FROM observability_schema_migrations WHERE version = 8", ); await inspectionConnection.run( - "DELETE FROM observability_schema_migrations WHERE version = 9", + "DELETE FROM observability_schema_migrations WHERE version >= 9", ); } finally { inspectionConnection.closeSync(); diff --git a/tests/observability/durable-summary.test.ts b/tests/observability/durable-summary.test.ts new file mode 100644 index 00000000..26669824 --- /dev/null +++ b/tests/observability/durable-summary.test.ts @@ -0,0 +1,118 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DuckDBInstance } from "@duckdb/node-api"; +import { + DuckDbAnalyticalStore, + type DuckDbAnalyticalBatch, +} from "@selftune/observability/duckdb-store"; +import { makeDuckDbNodeApiAnalyticalStoreLive } from "@selftune/observability/duckdb-node-api"; +import * as Effect from "effect/Effect"; +import { compactFixture } from "./compact-fixture.js"; + +const batch = { + schema_version: "1.0.0", + batch_id: "source", + source_revision: "r1", + normalizer_version: "v1", + spans: [ + { + trace_id: "a".repeat(32), + span_id: "b".repeat(16), + name: "task", + started_at: "2026-09-01T00:00:00Z", + ended_at: "2026-09-01T00:00:01Z", + platform: "codex", + capture_mode: "rollout", + source_authority: "source_truth", + trace_boundary: "actionable_turn", + operation_name: "invoke_agent", + source_id: "source", + input_tokens: 100, + output_tokens: 50, + error_count: 1, + tool_call_count: 2, + }, + ], + links: [ + { + link_id: "c".repeat(32), + trace_id: "a".repeat(32), + span_id: "b".repeat(16), + skill_invocation_id: "invocation", + skill_name: "test-skill", + }, + ], +} satisfies typeof DuckDbAnalyticalBatch.Encoded; + +test("discovery, recommendations and candidates survive absent detail and repeated corrections", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-durable-summary-")); + let path = join(directory, "analytics.duckdb"); + const read = (input?: typeof DuckDbAnalyticalBatch.Encoded) => + Effect.runPromise( + Effect.gen(function* () { + const store = yield* DuckDbAnalyticalStore; + if (input) yield* store.ingest(input); + return { + signals: yield* store.querySkillSignals(), + tasks: yield* store.queryHistoricalSkillTaskReferences({ + skill_id: "test-skill", + limit: 10, + }), + candidates: yield* store.queryEvidenceCohortCandidates({ + pattern: { + pattern_id: "pattern", + kind: "repeated_correlated_errors", + skill_id: "test-skill", + skill_name: "test-skill", + }, + }), + }; + }).pipe(Effect.provide(makeDuckDbNodeApiAnalyticalStoreLive(path)), Effect.scoped), + ); + try { + const before = await read(batch); + expect(before.signals[0]?.input_tokens).toBe(100); + const db = await DuckDBInstance.create(path); + const connection = await db.connect(); + try { + await connection.run("DELETE FROM observability_spans"); + await connection.run("DELETE FROM observability_metrics"); + } finally { + connection.closeSync(); + db.closeSync(); + } + expect(await read()).toEqual(before); + const compactedPath = join(directory, "compacted.duckdb"); + const allocation = await compactFixture(path, compactedPath); + expect(allocation.compacted).toBeLessThan(allocation.original); + path = compactedPath; + expect(await read()).toEqual(before); + expect(await read(batch)).toEqual(before); + let warmedBytes = 0; + for (let revision = 2; revision <= 40; revision++) { + const result = await read({ + ...batch, + source_revision: `r${revision}`, + spans: [{ ...batch.spans[0], input_tokens: revision }], + }); + expect(result.signals[0]?.input_tokens).toBe(revision); + expect(result.signals[0]?.invocation_count).toBe(1); + expect(result.tasks[0]?.source_revision).toBe(`r${revision}`); + if (revision === 10) warmedBytes = statSync(path).blocks * 512; + } + const allocatedBytes = statSync(path).blocks * 512; + console.info("durable-summary fixture allocated bytes", { + after10: warmedBytes, + after40: allocatedBytes, + }); + expect(allocatedBytes).toBeLessThan(32 * 1024 * 1024); + expect(allocatedBytes - warmedBytes).toBeLessThan(8 * 1024 * 1024); + const removed = await read({ ...batch, source_revision: "r41", spans: [], links: [] }); + expect(removed).toEqual({ signals: [], tasks: [], candidates: [] }); + expect(await read()).toEqual(removed); + } finally { + rmSync(directory, { recursive: true }); + } +}); diff --git a/tests/observability/qualified-copy.test.ts b/tests/observability/qualified-copy.test.ts new file mode 100644 index 00000000..3489c4a7 --- /dev/null +++ b/tests/observability/qualified-copy.test.ts @@ -0,0 +1,88 @@ +import { test, expect } from "bun:test"; +import { DuckDBInstance } from "@duckdb/node-api"; +import { + mkdtempSync, + rmSync, + statSync, + existsSync, + readFileSync, + writeFileSync, + readdirSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { qualifyAnalyticalCopy } from "../../scripts/qualify-analytical-copy"; + +test("qualified copy preserves raw rows, constraints, indexes, views and source bytes", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-qualified-copy-")); + const source = join(directory, "snapshot.duckdb"), + destination = join(directory, "qualified.duckdb"); + const budgets = { maxOutputMiB: 16, reserveMiB: 256, tempMiB: 0, memoryMiB: 128 }; + try { + const db = await DuckDBInstance.create(source); + const connection = await db.connect(); + await connection.run( + "CREATE TABLE evidence (id INTEGER PRIMARY KEY, value VARCHAR NOT NULL CHECK (length(value) > 0), raw BLOB)", + ); + await connection.run( + "INSERT INTO evidence VALUES (1, 'private fact', '\\x00\\x01'::BLOB), (2, 'another fact', NULL)", + ); + await connection.run("CREATE INDEX evidence_value ON evidence(value)"); + await connection.run("CREATE VIEW evidence_view AS SELECT id, value FROM evidence"); + connection.closeSync(); + db.closeSync(); + const original = readFileSync(source); + const receipt = await qualifyAnalyticalCopy(source, destination, budgets); + expect(receipt.qualified).toBe(true); + expect(receipt.tables).toBe(1); + expect(receipt.destinationBytes).toBe(statSync(destination).size); + expect(readFileSync(source)).toEqual(original); + const reader = await DuckDBInstance.create(destination, { access_mode: "READ_ONLY" }); + const read = await reader.connect(); + expect( + await (await read.run("SELECT COUNT(*) AS count FROM evidence_view")).getRowObjects(), + ).toEqual([{ count: 2n }]); + read.closeSync(); + reader.closeSync(); + await expect(qualifyAnalyticalCopy(source, destination, budgets)).rejects.toThrow( + "Destination must not exist", + ); + const before = statSync(source).size; + writeFileSync(`${source}.wal`, "writer marker"); + await expect( + qualifyAnalyticalCopy(source, join(directory, "blocked.duckdb"), budgets), + ).rejects.toThrow("without a WAL"); + expect(existsSync(join(directory, "blocked.duckdb"))).toBe(false); + expect(statSync(source).size).toBe(before); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("unsupported catalogs and invalid budgets never publish an unqualified copy", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-qualified-reject-")); + const source = join(directory, "snapshot.duckdb"), + destination = join(directory, "must-not-exist.duckdb"); + try { + const db = await DuckDBInstance.create(source); + const connection = await db.connect(); + await connection.run("CREATE TABLE facts (id INTEGER)"); + await connection.run("CREATE SEQUENCE outside_supported_catalog"); + connection.closeSync(); + db.closeSync(); + const budgets = { maxOutputMiB: 16, reserveMiB: 256, tempMiB: 0, memoryMiB: 128 }; + await expect(qualifyAnalyticalCopy(source, destination, budgets)).rejects.toThrow( + "outside this qualifier", + ); + expect(existsSync(destination)).toBe(false); + expect(readdirSync(directory).some((entry) => entry.startsWith(".selftune-qualified-"))).toBe( + false, + ); + await expect( + qualifyAnalyticalCopy(source, destination, { ...budgets, memoryMiB: 8192 }), + ).rejects.toThrow("memoryMiB"); + expect(existsSync(destination)).toBe(false); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); diff --git a/tests/observability/rollup-revision-isolation.test.ts b/tests/observability/rollup-revision-isolation.test.ts new file mode 100644 index 00000000..4f8d17a2 --- /dev/null +++ b/tests/observability/rollup-revision-isolation.test.ts @@ -0,0 +1,117 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DuckDBInstance } from "@duckdb/node-api"; +import { + DuckDbAnalyticalStore, + type DuckDbAnalyticalBatch, +} from "@selftune/observability/duckdb-store"; +import { makeDuckDbNodeApiAnalyticalStoreLive } from "@selftune/observability/duckdb-node-api"; +import * as Effect from "effect/Effect"; +import { makeDuckDbTraceEvidenceReader } from "@selftune/observability/reader-parity"; +import { compactFixture } from "./compact-fixture.js"; + +function pointBatch(id: string, trace: string, time: string, value: number) { + return { + schema_version: "1.0.0", + batch_id: id, + source_revision: "r1", + normalizer_version: "fixture-v1", + spans: [], + links: [], + metric_points: [ + { + metric_id: `metric-${id}`, + trace_id: trace.repeat(32), + observed_at: time, + name: "input_tokens", + value, + unit: "count", + temporality: "cumulative", + evidence_quality: "source_exact", + source_kind: "codex", + source_id: id, + source_reference: `fixture/${id}`, + }, + ], + } satisfies typeof DuckDbAnalyticalBatch.Encoded; +} + +test("revising one source preserves an unrelated retained summary after restart", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-rollup-isolation-")); + let path = join(directory, "observability.duckdb"); + const first = "2026-07-23T10:00:00.000Z"; + const second = "2026-07-23T11:00:00.000Z"; + const old = pointBatch("older", "a", first, 100); + const revised = pointBatch("revised", "a", second, 200); + const retained = pointBatch("retained", "b", first, 777); + const ingest = (batches: ReadonlyArray) => + Effect.runPromise( + Effect.gen(function* () { + const store = yield* DuckDbAnalyticalStore; + for (const batch of batches) yield* store.ingest(batch); + return yield* store.queryHistoricalMetricRollups({ limit: 10 }); + }).pipe(Effect.provide(makeDuckDbNodeApiAnalyticalStoreLive(path)), Effect.scoped), + ); + try { + const originalRollups = await ingest([old, revised, retained]); + const fixture = await DuckDBInstance.create(path); + const connection = await fixture.connect(); + try { + const reader = makeDuckDbTraceEvidenceReader( + { + run: (sql, parameters) => connection.run(sql, parameters), + closeSync: () => connection.closeSync(), + appendRows: async () => { + throw new Error("Evidence reader must not append rows"); + }, + }, + "current", + ); + const evidenceBefore = await reader.readPage({ limit: 10 }); + expect(evidenceBefore.items).toHaveLength(3); + // Synthetic future-eviction condition only. Production has no eviction API. + await connection.run( + "DELETE FROM observability_historical_metric_points WHERE batch_id IN ('retained', 'older')", + ); + const evidenceAfter = await reader.readPage({ limit: 10 }); + expect(evidenceAfter.items).toHaveLength(1); + expect(evidenceAfter.items).not.toEqual(evidenceBefore.items); + } finally { + connection.closeSync(); + fixture.closeSync(); + } + // Rollup parity is insufficient: the point-evidence reader above lost two facts. + expect(await ingest([])).toEqual(originalRollups); + const compactedPath = join(directory, "compacted.duckdb"); + await compactFixture(path, compactedPath); + path = compactedPath; + expect(await ingest([])).toEqual(originalRollups); + const correction = { ...revised, source_revision: "r2", metric_points: [] }; + const result = await ingest([correction]); + expect(result.items.map(({ source_id, value }) => ({ source_id, value }))).toEqual([ + { source_id: "older", value: 100 }, + { source_id: "retained", value: 777 }, + ]); + expect((await ingest([correction])).items).toEqual(result.items); + await expect( + ingest([ + { + ...revised, + source_revision: "conflicting-r3", + metric_points: [old.metric_points[0], old.metric_points[0]], + }, + ]), + ).rejects.toThrow(); + expect((await ingest([])).items).toEqual(result.items); + const moved = pointBatch("revised", "c", second, 55); + expect( + (await ingest([{ ...moved, source_revision: "r3" }])).items.map(({ value }) => value), + ).toEqual([100, 777, 55]); + // The fixture must remain small, not silently become a disk stress test. + expect(statSync(path).blocks * 512).toBeLessThan(32 * 1024 * 1024); + } finally { + rmSync(directory, { recursive: true }); + } +}); diff --git a/tests/observability/source-lifecycle.test.ts b/tests/observability/source-lifecycle.test.ts new file mode 100644 index 00000000..51ec4cf0 --- /dev/null +++ b/tests/observability/source-lifecycle.test.ts @@ -0,0 +1,190 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DuckDBInstance } from "@duckdb/node-api"; +import { openDb } from "@selftune/local-store"; +import { + DuckDbAnalyticalStore, + type DuckDbAnalyticalBatch, + type DuckDbAnalyticalStoreService, +} from "@selftune/observability/duckdb-store"; +import { makeDuckDbNodeApiAnalyticalStoreLive } from "@selftune/observability/duckdb-node-api"; +import { sourceIdentityKey, SourceIdentities } from "@selftune/observability/source-identity"; +import { normalizeHistoricalBackfill } from "@selftune/observability/historical-backfill"; +import { LocalTraceImporter } from "@selftune/observability/local-trace-importer"; +import { makeLocalTraceImporterLive } from "@selftune/orchestration/sync/local-trace-importer"; +import { runHistoricalBackfill } from "@selftune/orchestration/historical-backfill"; +import { Effect, Layer, Schema } from "effect"; + +const identity = { provider: "codex", session_id: "one" } as const; +const base = { + schema_version: "1.0.0", + batch_id: "original", + source_revision: "r1", + normalizer_version: "v1", + spans: [], + links: [], +} satisfies typeof DuckDbAnalyticalBatch.Encoded; + +test("logical source keys are provider-namespaced and request identity lists are bounded", () => { + expect(sourceIdentityKey(identity)).toBe( + sourceIdentityKey({ session_id: "one", provider: "codex" }), + ); + expect(sourceIdentityKey(identity)).not.toBe(sourceIdentityKey({ ...identity, provider: "pi" })); + expect(Schema.is(SourceIdentities)([])).toBe(false); + expect(Schema.is(SourceIdentities)(Array.from({ length: 257 }, () => identity))).toBe(false); +}); + +test("exact, revised, mixed and backfilled sources cannot bypass expiration or advance checkpoints", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-source-lifecycle-")); + const path = join(directory, "analytics.duckdb"); + const sqlite = openDb(":memory:"); + const storeLayer = () => makeDuckDbNodeApiAnalyticalStoreLive(path); + const query = (run: (store: DuckDbAnalyticalStoreService) => Effect.Effect) => + Effect.runPromise( + Effect.gen(function* () { + return yield* run(yield* DuckDbAnalyticalStore); + }).pipe(Effect.provide(storeLayer()), Effect.scoped), + ); + const importerLayer = () => Layer.provide(makeLocalTraceImporterLive(sqlite), storeLayer()); + const fixtureSql = async (sql: string) => { + const db = await DuckDBInstance.create(path); + const connection = await db.connect(); + try { + return await (await connection.run(sql)).getRowObjects(); + } finally { + connection.closeSync(); + db.closeSync(); + } + }; + try { + await query((store) => store.ingest(base)); + const qualified = { ...base, source_identities: [identity] }; + // An old exact receipt must acquire provenance without rewriting existing detail. + expect(await query((store) => store.hasExactBatchReceipt(qualified))).toBe(false); + expect((await query((store) => store.ingest(qualified))).disposition).toBe("duplicate"); + expect(await query((store) => store.hasExactBatchReceipt(qualified))).toBe(true); + await expect( + query((store) => + store.ingest({ ...qualified, source_identities: [{ ...identity, session_id: "two" }] }), + ), + ).rejects.toThrow("cannot change"); + await expect( + query((store) => + store.hasExactBatchReceipt({ + ...qualified, + source_identities: [identity, { ...identity, session_id: "two" }], + }), + ), + ).rejects.toThrow("cannot change"); + await query((store) => store.ingest({ ...qualified, source_identities: [identity, identity] })); + await fixtureSql( + `INSERT INTO observability_expired_sources VALUES ('${sourceIdentityKey(identity)}')`, + ); + const before = await fixtureSql("SELECT * FROM observability_ingested_batches"); + for (const input of [ + base, + qualified, + { ...qualified, source_revision: "r2", normalizer_version: "v2", batch_id: "different" }, + { + ...qualified, + batch_id: "mixed", + source_identities: [identity, { ...identity, session_id: "two" }], + }, + ]) { + await expect(query((store) => store.hasExactBatchReceipt(input))).rejects.toThrow( + "cannot resurrect", + ); + await expect(query((store) => store.ingest(input))).rejects.toThrow("cannot resurrect"); + } + expect(await fixtureSql("SELECT * FROM observability_ingested_batches")).toEqual(before); + expect(await fixtureSql("SELECT batch_id FROM observability_batch_sources")).toEqual([ + { batch_id: "original" }, + ]); + // Native session IDs can overlap between harnesses without sharing expiration. + await query((store) => + store.ingest({ + ...base, + batch_id: "pi", + source_identities: [{ ...identity, provider: "pi" }], + }), + ); + await query((store) => store.ingest({ ...base, batch_id: "legacy-expired" })); + await fixtureSql( + "INSERT INTO observability_source_reconstruction VALUES ('legacy-expired', 'r1', 'v1', 'unused', '{}', 'expired')", + ); + await expect( + query((store) => store.hasExactBatchReceipt({ ...base, batch_id: "legacy-expired" })), + ).rejects.toThrow("cannot resurrect"); + await expect( + query((store) => store.ingest({ ...base, batch_id: "legacy-expired" })), + ).rejects.toThrow("cannot resurrect"); + for (const id of ["one", "two"]) + sqlite.run( + "INSERT INTO sessions (session_id, platform, started_at, ended_at, capture_mode) VALUES (?, 'codex', '2026-09-01T00:00:00Z', '2026-09-01T00:00:01Z', 'rollout')", + [id], + ); + const normalize = (revision: string) => + Effect.runPromise( + normalizeHistoricalBackfill({ + source_cursor: revision, + source_revision: revision, + source_domain: "sessions", + include_session_spans: true, + sessions: ["one", "two"].map((session_id) => ({ + session_id, + platform: "codex", + started_at: "2026-09-01T00:00:00Z", + ended_at: "2026-09-01T00:00:01Z", + })), + prompts: [], + skill_invocations: [], + execution_facts: [], + }), + ); + const original = (await normalize("backfill-1")).imports[0]; + const revised = (await normalize("backfill-2")).imports[0]; + expect(original.batch.batch_id).not.toBe(revised.batch.batch_id); + expect(original.source_session_ids).toEqual(["one", "two"]); + expect(revised.source_session_ids).toEqual(original.source_session_ids); + for (const request of [original, revised]) { + await expect( + Effect.runPromise( + Effect.gen(function* () { + return yield* (yield* LocalTraceImporter).importTrace(request); + }).pipe(Effect.provide(importerLayer()), Effect.scoped), + ), + ).rejects.toThrow("cannot resurrect"); + } + const allocatedBefore = statSync(path).blocks * 512; + for (let retry = 0; retry < 10; retry++) { + await expect( + Effect.runPromise( + runHistoricalBackfill(sqlite, { batchSize: 2 }).pipe( + Effect.provide(importerLayer()), + Effect.scoped, + ), + ), + ).rejects.toThrow("cannot resurrect"); + } + expect( + sqlite + .query( + "SELECT * FROM analytical_import_checkpoints WHERE source_kind != 'historical-backfill-boundary'", + ) + .all(), + ).toEqual([]); + expect((await query((store) => store.health())).span_count).toBe(0); + const allocatedAfter = statSync(path).blocks * 512; + console.info("source-lifecycle fixture allocated bytes", { + beforeRetries: allocatedBefore, + after10Retries: allocatedAfter, + }); + expect(allocatedAfter - allocatedBefore).toBeLessThan(4 * 1024 * 1024); + expect(allocatedAfter).toBeLessThan(16 * 1024 * 1024); + } finally { + sqlite.close(); + rmSync(directory, { recursive: true }); + } +}); diff --git a/tests/observability/source-reconstruction.test.ts b/tests/observability/source-reconstruction.test.ts new file mode 100644 index 00000000..d3aa0e68 --- /dev/null +++ b/tests/observability/source-reconstruction.test.ts @@ -0,0 +1,49 @@ +import { expect, test } from "bun:test"; +import { + closeSync, + mkdtempSync, + openSync, + rmSync, + symlinkSync, + ftruncateSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + MAX_RECONSTRUCTION_BYTES, + readBoundedSource, +} from "@selftune/observability/source-reconstruction"; + +test("source reads enforce their byte budget and distinguish missing, unsafe and available files", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-bounded-source-")); + try { + const path = join(directory, "source.jsonl"); + expect(await readBoundedSource(path)).toEqual({ + state: "unavailable", + reason: "source_missing", + }); + writeFileSync(path, "fixture source"); + const result = await readBoundedSource(path); + expect(result.state === "available" && result.bytes.toString()).toBe("fixture source"); + const link = join(directory, "symlink"); + symlinkSync(path, link); + expect(await readBoundedSource(link)).toEqual({ + state: "unavailable", + reason: "source_unavailable", + }); + expect(await readBoundedSource(directory)).toEqual({ + state: "unavailable", + reason: "source_unavailable", + }); + const fd = openSync(path, "r+"); + try { + ftruncateSync(fd, MAX_RECONSTRUCTION_BYTES + 1); + } finally { + closeSync(fd); + } + expect(await readBoundedSource(path)).toEqual({ state: "unavailable", reason: "over_budget" }); + } finally { + rmSync(directory, { recursive: true }); + } +}); diff --git a/tests/observability/storage-capacity.test.ts b/tests/observability/storage-capacity.test.ts new file mode 100644 index 00000000..e54caeb9 --- /dev/null +++ b/tests/observability/storage-capacity.test.ts @@ -0,0 +1,40 @@ +import { afterEach, expect, test } from "bun:test"; +import { lstatSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + inspectAnalyticalStorageFiles, + requireStorageCapacity, +} from "@selftune/observability/storage-capacity"; + +const directories: string[] = []; +afterEach(() => { + for (const directory of directories.splice(0)) rmSync(directory, { recursive: true }); +}); + +test("reports allocated and logical bytes without reading or returning file contents or paths", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-storage-metadata-")); + directories.push(directory); + const path = join(directory, "observability.duckdb"); + const payload = "not-a-database-private-payload"; + writeFileSync(path, payload); + const result = await inspectAnalyticalStorageFiles(path); + const metadata = lstatSync(path, { bigint: true }); + expect(result.database).toEqual({ + state: "present", + logical_bytes: metadata.size.toString(), + allocated_bytes: (metadata.blocks * 512n).toString(), + }); + expect(result.wal).toEqual({ state: "missing" }); + expect(BigInt(result.available_bytes)).toBeGreaterThan(0n); + expect(JSON.stringify(result)).not.toContain(payload); + expect(JSON.stringify(result)).not.toContain(directory); + symlinkSync(path, `${path}.wal`); + expect((await inspectAnalyticalStorageFiles(path)).wal).toEqual({ state: "unsafe_file_type" }); +}); + +test("headroom comparisons remain exact beyond Number.MAX_SAFE_INTEGER", () => { + const required = 2n ** 54n; + expect(() => requireStorageCapacity(required, required)).not.toThrow(); + expect(() => requireStorageCapacity(required - 1n, required)).toThrow("maintenance deferred"); +}); diff --git a/tests/observability/storage-inspection.test.ts b/tests/observability/storage-inspection.test.ts new file mode 100644 index 00000000..c35b81eb --- /dev/null +++ b/tests/observability/storage-inspection.test.ts @@ -0,0 +1,79 @@ +import { afterEach, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DuckDBInstance } from "@duckdb/node-api"; +import { inspectAnalyticalStorage } from "@selftune/observability/duckdb-node-api"; + +const directories: string[] = []; +afterEach(() => { + for (const directory of directories.splice(0)) rmSync(directory, { recursive: true }); +}); + +test("catalog diagnostics leave an old schema byte-identical and omit private rows", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-storage-profile-")); + directories.push(directory); + const path = join(directory, "observability.duckdb"); + const db = await DuckDBInstance.create(path); + const connection = await db.connect(); + await connection.run("CREATE TABLE observability_old_fixture (private_payload VARCHAR)"); + await connection.run("INSERT INTO observability_old_fixture VALUES ('secret-session-text')"); + connection.closeSync(); + db.closeSync(); + const digest = () => createHash("sha256").update(readFileSync(path)).digest("hex"); + const before = digest(); + const report = await inspectAnalyticalStorage(path); + expect(report.catalog.state).toBe("available"); + expect("stored_schema" in report.catalog && report.catalog.stored_schema).toEqual({ + state: "unavailable", + reason: "missing_ledger", + }); + expect(JSON.stringify(report)).toContain("observability_old_fixture"); + expect(JSON.stringify(report)).toContain("estimates_not_exact"); + expect(JSON.stringify(report)).not.toContain("secret-session-text"); + expect(JSON.stringify(report)).not.toContain(directory); + expect(digest()).toBe(before); + expect(readdirSync(directory)).toEqual(["observability.duckdb"]); +}); + +test.each([{ versions: [] }, { versions: [1, 8, 9] }, { versions: [1, 42] }])( + "reports the stored migration ledger without upgrading or downgrading it: %j", + async ({ versions }) => { + const directory = mkdtempSync(join(tmpdir(), "selftune-storage-schema-")); + directories.push(directory); + const path = join(directory, "observability.duckdb"); + const db = await DuckDBInstance.create(path); + const connection = await db.connect(); + try { + await connection.run( + "CREATE TABLE observability_schema_migrations (version INTEGER PRIMARY KEY)", + ); + for (const version of versions) { + await connection.run("INSERT INTO observability_schema_migrations VALUES ($version)", { + version, + }); + } + } finally { + connection.closeSync(); + db.closeSync(); + } + const before = createHash("sha256").update(readFileSync(path)).digest("hex"); + const report = await inspectAnalyticalStorage(path); + expect("stored_schema" in report.catalog && report.catalog.stored_schema).toEqual( + versions.length > 0 + ? { state: "available", version: String(Math.max(...versions)) } + : { state: "unavailable", reason: "empty_ledger" }, + ); + expect(createHash("sha256").update(readFileSync(path)).digest("hex")).toBe(before); + expect(readdirSync(directory)).toEqual(["observability.duckdb"]); + }, +); + +test("missing database is unavailable, never created as an empty successful inspection", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-storage-absent-")); + directories.push(directory); + const report = await inspectAnalyticalStorage(join(directory, "missing.duckdb")); + expect(report.catalog).toEqual({ state: "unavailable", reason: "missing" }); + expect(readdirSync(directory)).toEqual([]); +}); diff --git a/tests/orchestration/local-trace-importer.test.ts b/tests/orchestration/local-trace-importer.test.ts index 3793a47f..00899c2b 100644 --- a/tests/orchestration/local-trace-importer.test.ts +++ b/tests/orchestration/local-trace-importer.test.ts @@ -1,4 +1,8 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { makeDuckDbNodeApiAnalyticalStoreLive } from "@selftune/observability/duckdb-node-api"; import { _setTestDb, getDb, openDb } from "@selftune/local-store"; import { @@ -122,6 +126,7 @@ const recordingStore = (received: DuckDbAnalyticalBatch[], receipts = new Set Effect.die("unused"), hasExactBatchReceipt: (input) => Schema.decodeUnknownEffect(DuckDbAnalyticalBatch)(input).pipe( Effect.map((batch) => receipts.has(batch.batch_id)), @@ -217,6 +222,39 @@ test("imports a source revision before acknowledging its SQLite checkpoint", asy }); }); +test("disk-pressure refusal leaves no checkpoint and a restarted import retries exactly once", async () => { + const directory = mkdtempSync(join(tmpdir(), "selftune-import-pressure-")); + try { + const path = join(directory, "observability.duckdb"); + const run = (bytes: bigint) => + Effect.runPromise( + Effect.gen(function* () { + return yield* (yield* LocalTraceImporter).importTrace(request); + }).pipe( + Effect.provide( + Layer.provide( + makeLocalTraceImporterLive(getDb()), + makeDuckDbNodeApiAnalyticalStoreLive(path, async () => bytes), + ), + ), + Effect.scoped, + ), + ); + await expect(run(0n)).rejects.toThrow("maintenance deferred"); + expect( + getDb().query("SELECT source_identity FROM analytical_import_checkpoints").all(), + ).toEqual([]); + await run(1024n ** 4n); + const checkpoint = getDb().query("SELECT * FROM analytical_import_checkpoints").all(); + expect(checkpoint).toHaveLength(1); + // Exact receipts remain readable under pressure; no redundant write is required. + await run(0n); + expect(getDb().query("SELECT * FROM analytical_import_checkpoints").all()).toEqual(checkpoint); + } finally { + rmSync(directory, { recursive: true }); + } +}); + const importBatch = (input: LocalTraceImportRequest, received: DuckDbAnalyticalBatch[]) => Effect.gen(function* () { return yield* (yield* LocalTraceImporter).importTrace(input); diff --git a/tests/runtime/service-launchd-backend.test.ts b/tests/runtime/service-launchd-backend.test.ts index 0f4859cb..ca039907 100644 --- a/tests/runtime/service-launchd-backend.test.ts +++ b/tests/runtime/service-launchd-backend.test.ts @@ -64,7 +64,7 @@ function appBundledExecutable(bundleIdentifier: string): string { } describe("launchd service backend", () => { - it("preserves the launchd plist byte format", () => { + it("keeps the dashboard LaunchAgent interactive and preserves the plist format", () => { expect( generateLaunchdPlist({ environment: { KEY: '<&"' }, @@ -95,7 +95,7 @@ describe("launchd service backend", () => { KeepAlive SuccessfulExit ProcessType - Background + Interactive WorkingDirectory /tmp/selftune StandardOutPath diff --git a/tests/sandbox/docker/output-contracts.ts b/tests/sandbox/docker/output-contracts.ts index 154564cc..6fb8ffe6 100644 --- a/tests/sandbox/docker/output-contracts.ts +++ b/tests/sandbox/docker/output-contracts.ts @@ -1,18 +1,15 @@ import * as Schema from "effect/Schema"; import { GradingResult } from "@selftune/runtime/types"; +import { preservingJsonDecoder } from "@selftune/runtime/utils/preserving-schema"; export const parseGradingOutput = Schema.decodeUnknownSync(Schema.fromJsonString(GradingResult)); -const decodeDryRunEvolution = Schema.decodeUnknownSync( - Schema.fromJsonString( - Schema.Struct({ - deployed: Schema.Literal(false), - reason: Schema.String.check(Schema.isNonEmpty()), - }), - ), +export const parseDryRunEvolutionOutput = preservingJsonDecoder( + Schema.Struct({ + deployed: Schema.Literal(false), + reason: Schema.String.check(Schema.isNonEmpty()), + }), ); -export const parseDryRunEvolutionOutput = (raw: string) => - decodeDryRunEvolution(raw, { onExcessProperty: "preserve" }); export const parseDoctorOutput = Schema.decodeUnknownSync( Schema.fromJsonString( diff --git a/tests/skill-sets/skill-intelligence-catalog-duckdb-failsoft.test.ts b/tests/skill-sets/skill-intelligence-catalog-duckdb-failsoft.test.ts index ffdb0504..7b22d411 100644 --- a/tests/skill-sets/skill-intelligence-catalog-duckdb-failsoft.test.ts +++ b/tests/skill-sets/skill-intelligence-catalog-duckdb-failsoft.test.ts @@ -63,6 +63,7 @@ function storeWithQuery(querySkillSignals: DuckDbAnalyticalStoreService["querySk return Layer.succeed( DuckDbAnalyticalStore, DuckDbAnalyticalStore.of({ + resolveSourceTask: () => Effect.die("unused"), hasExactBatchReceipt: () => Effect.succeed(false), ingest: () => Effect.fail( diff --git a/tests/testing-readiness-evidence.test.ts b/tests/testing-readiness-evidence.test.ts new file mode 100644 index 00000000..3bc708c5 --- /dev/null +++ b/tests/testing-readiness-evidence.test.ts @@ -0,0 +1,36 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { openDb } from "@selftune/local-store"; +import { listSkillTestingReadiness } from "../packages/runtime/testing-readiness"; + +test("readiness keeps the latest valid evidence count when newer evidence is malformed or empty", () => { + const root = mkdtempSync(join(tmpdir(), "selftune-readiness-evidence-")); + const previous = process.env.SELFTUNE_CONFIG_DIR; + process.env.SELFTUNE_CONFIG_DIR = root; + const db = openDb(":memory:"); + try { + const insert = db.prepare( + "INSERT INTO evolution_evidence (timestamp, proposal_id, skill_name, skill_path, eval_set_json) VALUES (?, ?, 'readiness-evidence', '/missing/SKILL.md', ?)", + ); + insert.run( + "2026-10-01", + "valid", + JSON.stringify([{ query: "real task", should_trigger: true }]), + ); + insert.run("2026-10-02", "empty", "[]"); + insert.run("2026-10-03", "malformed", "{broken"); + insert.run("2026-10-04", "mixed", '[{"query":"task"},42]'); + const row = listSkillTestingReadiness(db, []).find( + (entry) => entry.skill_name === "readiness-evidence", + ); + expect(row?.eval_set_entries).toBe(1); + expect(row?.latest_eval_at).toBe("2026-10-01"); + } finally { + db.close(); + if (previous === undefined) delete process.env.SELFTUNE_CONFIG_DIR; + else process.env.SELFTUNE_CONFIG_DIR = previous; + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/tests/testing-readiness.test.ts b/tests/testing-readiness.test.ts index 7b62dbc7..cea00c9c 100644 --- a/tests/testing-readiness.test.ts +++ b/tests/testing-readiness.test.ts @@ -1,5 +1,13 @@ import { afterEach, beforeEach, describe, expect, it } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + unlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -34,6 +42,29 @@ afterEach(() => { }); describe("listSkillTestingReadiness", () => { + it("recognizes an unused on-demand library package in the default report lookup", async () => { + const skillPath = join( + tempRoot, + ".selftune", + "library", + "packages", + "content-hash", + "adversarial-reviewer", + "SKILL.md", + ); + mkdirSync(join(skillPath, ".."), { recursive: true }); + writeFileSync(skillPath, "# adversarial-reviewer\n"); + const mod = await loadTestingReadinessModule(); + const readiness = mod.getSkillTestingReadiness(db, "adversarial-reviewer"); + expect(readiness?.skill_path).toBe(realpathSync(skillPath)); + const { handleSkillReport } = await import("@selftune/local/routes/skill-report"); + const response = handleSkillReport(db, "adversarial-reviewer"); + expect(response.status).toBe(200); + const report = await response.json(); + expect(report.usage.total_checks).toBe(0); + expect(report.testing_readiness.skill_path).toBe(realpathSync(skillPath)); + expect(handleSkillReport(db, "definitely-missing-report-fixture").status).toBe(404); + }); it("stores portable eval contracts beside SKILL.md and prefers them over cached copies", async () => { const mod = await loadTestingReadinessModule(); const skillRoot = join(tempRoot, "skills"); diff --git a/tests/trust-floor/publish-deps.test.ts b/tests/trust-floor/publish-deps.test.ts index 548f1a3f..07ef0d3f 100644 --- a/tests/trust-floor/publish-deps.test.ts +++ b/tests/trust-floor/publish-deps.test.ts @@ -88,20 +88,20 @@ describe("publish dependency protocol", () => { [ "apps/cli/package.json", { - "@effect/platform-bun": "4.0.0-beta.66", - "@effect/platform-node-shared": "4.0.0-beta.66", - effect: "4.0.0-beta.66", + "@effect/platform-bun": "4.0.0-rc.115", + "@effect/platform-node-shared": "4.0.0-rc.115", + effect: "4.0.0-rc.115", }, ], - ["apps/local/package.json", { "@xmldom/xmldom": "^0.8.13", effect: "4.0.0-beta.66" }], - ["packages/config/package.json", { effect: "4.0.0-beta.66" }], - ["packages/control-plane/package.json", { effect: "4.0.0-beta.66" }], + ["apps/local/package.json", { "@xmldom/xmldom": "^0.8.13", effect: "4.0.0-rc.115" }], + ["packages/config/package.json", { effect: "4.0.0-rc.115" }], + ["packages/control-plane/package.json", { effect: "4.0.0-rc.115" }], [ "packages/observability/package.json", - { "@duckdb/node-api": "1.4.5-r.1", effect: "4.0.0-beta.66" }, + { "@duckdb/node-api": "1.4.5-r.1", effect: "4.0.0-rc.115" }, ], - ["packages/orchestration/package.json", { effect: "4.0.0-beta.66" }], - ["packages/runtime/package.json", { "drizzle-orm": "^0.45.0", effect: "4.0.0-beta.66" }], + ["packages/orchestration/package.json", { effect: "4.0.0-rc.115" }], + ["packages/runtime/package.json", { "drizzle-orm": "^0.45.0", effect: "4.0.0-rc.115" }], ["packages/telemetry-contract/package.json", { zod: "^4.3.6" }], ]); diff --git a/tests/utils/frontmatter.test.ts b/tests/utils/frontmatter.test.ts index 61dc6c40..dd310d21 100644 --- a/tests/utils/frontmatter.test.ts +++ b/tests/utils/frontmatter.test.ts @@ -3,6 +3,13 @@ import { describe, expect, test } from "bun:test"; import { parseFrontmatter, replaceDescription } from "../../packages/runtime/utils/frontmatter.js"; describe("parseFrontmatter", () => { + test.each([">-", ">+", "|-", "|+"])("reads descriptions with chomping marker %s", (marker) => { + const result = parseFrontmatter( + `---\nname: example\ndescription: ${marker}\n Build a UI.\n Use for interface work.\n---\n\nInstructions`, + ); + expect(result.description).toBe("Build a UI. Use for interface work."); + expect(result.body).toBe("Instructions"); + }); test("single-line description", () => { const content = `--- name: seo-audit diff --git a/tests/utils/jsonl.test.ts b/tests/utils/jsonl.test.ts index c6b72425..d443e28f 100644 --- a/tests/utils/jsonl.test.ts +++ b/tests/utils/jsonl.test.ts @@ -1,11 +1,20 @@ import { decodeJsonLine } from "../../packages/runtime/utils/jsonl.js"; import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + appendFileSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, + utimesSync, + renameSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fingerprintIngestionFile, + fileIngestionRevision, isFileIngestionCurrent, loadFileIngestionMarker, loadMarker, @@ -68,6 +77,41 @@ describe("loadMarker / saveMarker", () => { }); describe("append-aware file ingestion markers", () => { + test("invalidates same-size rewrites and replacement files with preserved modification time", () => { + const path = join(tmpDir, "same-size.jsonl"); + const replacement = join(tmpDir, "replacement.jsonl"); + const fixedTime = 1_700_000_000; + writeFileSync(path, "first"); + utimesSync(path, fixedTime, fixedTime); + const original = fingerprintIngestionFile(path, "v1"); + const marker = new Map([[path, original]]); + writeFileSync(path, "other"); + utimesSync(path, fixedTime, fixedTime); + const rewritten = fingerprintIngestionFile(path, "v1"); + expect(rewritten.size).toBe(original.size); + expect(rewritten.mtime_ms).toBe(original.mtime_ms); + expect(isFileIngestionCurrent(marker, path, rewritten)).toBe(false); + expect(fileIngestionRevision(rewritten)).not.toBe(fileIngestionRevision(original)); + marker.set(path, rewritten); + writeFileSync(replacement, "final"); + utimesSync(replacement, fixedTime, fixedTime); + renameSync(replacement, path); + const replaced = fingerprintIngestionFile(path, "v1"); + expect(replaced.size).toBe(rewritten.size); + expect(replaced.mtime_ms).toBe(rewritten.mtime_ms); + expect(replaced.file_identity).not.toBe(rewritten.file_identity); + expect(isFileIngestionCurrent(marker, path, replaced)).toBe(false); + }); + test("refreshes legacy fingerprints once, then accepts unchanged stat-only state", () => { + const path = join(tmpDir, "legacy-fingerprint.jsonl"); + writeFileSync(path, "unchanged"); + const fingerprint = fingerprintIngestionFile(path, "v1"); + const { ctime_ns: _ctime, file_identity: _identity, ...legacy } = fingerprint; + const marker = new Map([[path, legacy]]); + expect(isFileIngestionCurrent(marker, path, fingerprint)).toBe(false); + marker.set(path, fingerprint); + expect(isFileIngestionCurrent(marker, path, fingerprintIngestionFile(path, "v1"))).toBe(true); + }); test("round-trips deterministic file fingerprints", () => { const markerPath = join(tmpDir, "marker.json"); const sourcePath = join(tmpDir, "session.jsonl"); diff --git a/tests/utils/skill-discovery.test.ts b/tests/utils/skill-discovery.test.ts index c4a9c4fb..8d58dbaa 100644 --- a/tests/utils/skill-discovery.test.ts +++ b/tests/utils/skill-discovery.test.ts @@ -1,7 +1,40 @@ import { describe, expect, test } from "bun:test"; import { join } from "node:path"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; -import { classifySkillPath } from "../../packages/runtime/utils/skill-discovery.js"; +import { + classifySkillPath, + findInstalledSkillPath, + findInstalledSkillPaths, +} from "../../packages/runtime/utils/skill-discovery.js"; + +test("report path index preserves registry precedence, direct lookup, nested scopes, and links", () => { + const root = mkdtempSync(join(tmpdir(), "skill-path-index-")); + const dirs = [join(root, "first"), join(root, "second")]; + const create = (path: string) => { + mkdirSync(path, { recursive: true }); + writeFileSync(join(path, "SKILL.md"), "# Skill\n"); + }; + try { + create(join(dirs[0], "z-direct")); + create(join(dirs[0], ".system", "z-direct")); + create(join(dirs[0], ".system", "nested")); + create(join(dirs[1], "nested")); + create(join(dirs[1], "other")); + symlinkSync(join(dirs[1], "other"), join(dirs[0], "linked")); + symlinkSync(join(root, "missing"), join(dirs[0], "broken")); + const names = ["z-direct", "Z-Direct", "nested", "linked", "other", "missing", "broken"]; + const paths = findInstalledSkillPaths(dirs, names); + for (const name of names) { + expect(paths.get(name)).toBe(findInstalledSkillPath(name, dirs)); + } + expect(paths.get("z-direct")).toBe(realpathSync(join(dirs[0], "z-direct", "SKILL.md"))); + expect(paths.get("nested")).toBe(realpathSync(join(dirs[0], ".system", "nested", "SKILL.md"))); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); describe("classifySkillPath", () => { test("classifies project, global, admin, system, and unknown skill paths", () => { From 7f5632e91e83b916b691f78fef0bba74864df530 Mon Sep 17 00:00:00 2001 From: selftune-bot Date: Wed, 21 Oct 2026 10:17:32 +0300 Subject: [PATCH 2/2] fix(release): patch updater runtime and native test deadline --- .changeset/patched-desktop-updater.md | 5 +++ .github/release-notes.json | 11 +++++++ .github/sbom-toolchain/package-lock.json | 18 +++++------ apps/desktop/package.json | 2 +- bun.lock | 36 ++++++--------------- tests/observability/durable-summary.test.ts | 2 +- 6 files changed, 36 insertions(+), 38 deletions(-) create mode 100644 .changeset/patched-desktop-updater.md diff --git a/.changeset/patched-desktop-updater.md b/.changeset/patched-desktop-updater.md new file mode 100644 index 00000000..fbbf7876 --- /dev/null +++ b/.changeset/patched-desktop-updater.md @@ -0,0 +1,5 @@ +--- +"@selftune/desktop": patch +--- + +Update the pinned Electron 41 runtime to 41.10.5, including the macOS Squirrel updater target-path repair and earlier 41.x security fixes. diff --git a/.github/release-notes.json b/.github/release-notes.json index f54202e7..3861f631 100644 --- a/.github/release-notes.json +++ b/.github/release-notes.json @@ -3,6 +3,17 @@ "generatedFrom": "sites/docs/changelog.mdx", "docsUrl": "https://docs.selftune.dev/changelog", "entries": [ + { + "label": "2026-10-21", + "description": "Desktop update runtime", + "tags": ["Desktop"], + "rss": { + "title": null, + "description": null + }, + "bullets": [], + "versionRange": null + }, { "label": "2026-10-20", "description": "macOS desktop loading", diff --git a/.github/sbom-toolchain/package-lock.json b/.github/sbom-toolchain/package-lock.json index 7f43e86f..fd14f0b7 100644 --- a/.github/sbom-toolchain/package-lock.json +++ b/.github/sbom-toolchain/package-lock.json @@ -640,9 +640,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", - "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "funding": [ { "type": "github", @@ -868,9 +868,9 @@ "optional": true }, "node_modules/ip-address": { - "version": "10.4.0", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.4.0.tgz", - "integrity": "sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==", + "version": "10.7.4", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz", + "integrity": "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==", "license": "MIT", "optional": true, "engines": { @@ -914,9 +914,9 @@ } }, "node_modules/js-yaml": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", - "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "funding": [ { "type": "github", diff --git a/apps/desktop/package.json b/apps/desktop/package.json index b84f1405..e0d05998 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -43,7 +43,7 @@ "@selftune/runtime": "workspace:*", "@types/node": "^20", "bun-types": "^1.3.11", - "electron": "41.2.1", + "electron": "41.10.5", "electron-builder": "^26.0.12", "electron-vite": "^5.0.0", "playwright": "1.61.1", diff --git a/bun.lock b/bun.lock index abb8e427..9745abba 100644 --- a/bun.lock +++ b/bun.lock @@ -100,7 +100,7 @@ "@selftune/runtime": "workspace:*", "@types/node": "^20", "bun-types": "^1.3.11", - "electron": "41.2.1", + "electron": "41.10.5", "electron-builder": "^26.0.12", "electron-vite": "^5.0.0", "playwright": "1.61.1", @@ -740,11 +740,13 @@ "@effect/vitest": ["@effect/vitest@4.0.0-rc.115", "", { "peerDependencies": { "effect": "^4.0.0-rc.115", "vitest": ">=5.0.0 <6.0.0" } }, "sha512-DJR0hfdr3HNXAkzW8AzfvUz6VmrNFLrKk9tZGDURi33faMyxkc7ZewxELMMZwGpOTGN4mfqYVbX2CXgI+ZJBeQ=="], + "@electron-internal/extract-zip": ["@electron-internal/extract-zip@1.0.5", "", {}, "sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA=="], + "@electron/asar": ["@electron/asar@3.4.1", "", { "dependencies": { "commander": "^5.0.0", "glob": "^7.1.6", "minimatch": "^3.0.4" }, "bin": { "asar": "bin/asar.js" } }, "sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA=="], "@electron/fuses": ["@electron/fuses@1.8.0", "", { "dependencies": { "chalk": "^4.1.1", "fs-extra": "^9.0.1", "minimist": "^1.2.5" }, "bin": { "electron-fuses": "dist/bin.js" } }, "sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw=="], - "@electron/get": ["@electron/get@2.0.3", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="], + "@electron/get": ["@electron/get@5.1.0", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^3.0.0", "graceful-fs": "^4.2.11", "progress": "^2.0.3", "semver": "^7.6.3", "sumchecker": "^3.0.1" }, "optionalDependencies": { "undici": "^7.24.4" } }, "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA=="], "@electron/notarize": ["@electron/notarize@2.5.0", "", { "dependencies": { "debug": "^4.1.1", "fs-extra": "^9.0.1", "promise-retry": "^2.0.1" } }, "sha512-jNT8nwH1f9X5GEITXaQ8IF/KdskvIkOFfB2CvwumsveVidzpSc+mvhhTMdAGSYF3O+Nq49lJ7y+ssODRXu06+A=="], @@ -1414,8 +1416,6 @@ "@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="], - "@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="], - "@typescript/native": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="], "@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="], @@ -1554,8 +1554,6 @@ "browserslist": ["browserslist@4.28.6", "", { "dependencies": { "baseline-browser-mapping": "^2.10.42", "caniuse-lite": "^1.0.30001803", "electron-to-chromium": "^1.5.389", "node-releases": "^2.0.51", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-FQBYNK15VMslhLHpA7+n+n1GOlF1kId2xcCg7/j95f24AOF6VDYMNH4mFxF7KuaTdv627faazpOAjFzMrfJOUw=="], - "buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="], - "buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="], "builder-util": ["builder-util@26.15.3", "", { "dependencies": { "@types/debug": "^4.1.6", "builder-util-runtime": "9.7.0", "chalk": "^4.1.2", "cross-spawn": "^7.0.6", "debug": "^4.3.4", "fs-extra": "^10.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.0", "js-yaml": "^4.1.0", "sanitize-filename": "^1.6.3", "source-map-support": "^0.5.19", "stat-mode": "^1.0.0", "temp-file": "^3.4.0", "tiny-async-pool": "1.3.0" } }, "sha512-q2hn7Mbo2nFNkVekPiHFx6Nfo3hURmES3tfBn+k5Pqxl2RkmP3QGqZUhH/q9Pch/4G05NRhPjDlVj1O8q4Txvw=="], @@ -1772,7 +1770,7 @@ "ejs": ["ejs@3.1.10", "", { "dependencies": { "jake": "^10.8.5" }, "bin": { "ejs": "bin/cli.js" } }, "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA=="], - "electron": ["electron@41.2.1", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-teeRThiYGTPKf/2yOW7zZA1bhb91KEQ4yLBPOg7GxpmnkLFLugKgQaAKOrCgdzwsXh/5mFIfmkm+4+wACJKwaA=="], + "electron": ["electron@41.10.5", "", { "dependencies": { "@electron-internal/extract-zip": "^1.0.1", "@electron/get": "^5.0.0", "@types/node": "^24.9.0" }, "bin": { "electron": "cli.js" } }, "sha512-grSJOhLddanWX1UfE8B4xA2kOOduUCfpYoOQ2D4zEYte8lSQtrd1HYbV4xErsZmm+V+1Q3yzCQLBsCxEIiw/QQ=="], "electron-builder": ["electron-builder@26.15.3", "", { "dependencies": { "app-builder-lib": "26.15.3", "builder-util": "26.15.3", "builder-util-runtime": "9.7.0", "chalk": "^4.1.2", "ci-info": "^4.2.0", "dmg-builder": "26.15.3", "fs-extra": "^10.1.0", "lazy-val": "^1.0.5", "simple-update-notifier": "2.0.0", "yargs": "^17.6.2" }, "bin": { "electron-builder": "./cli.js", "install-app-deps": "./install-app-deps.js" } }, "sha512-a1KM5heqS3gQCZzizXEI8RjJy3QVogULPdeSknt76uLDpBIW/HDGsMg/XgP0riP6PI9COsRvFITKKGDqA8fJxA=="], @@ -1864,8 +1862,6 @@ "extendable-error": ["extendable-error@0.1.7", "", {}, "sha512-UOiS2in6/Q0FK0R0q6UY9vYpQ21mr/Qn1KOnte7vsACuNJf514WvCCUHSRCPcgjPT2bAhNIJdlE6bVap1GKmeg=="], - "extract-zip": ["extract-zip@2.0.1", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="], - "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], @@ -1874,8 +1870,6 @@ "fastq": ["fastq@1.20.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="], - "fd-slicer": ["fd-slicer@1.1.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="], - "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], "figures": ["figures@6.1.0", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="], @@ -2360,8 +2354,6 @@ "pe-library": ["pe-library@0.4.1", "", {}, "sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw=="], - "pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="], - "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], @@ -2594,7 +2586,7 @@ "spawndamnit": ["spawndamnit@3.0.1", "", { "dependencies": { "cross-spawn": "^7.0.5", "signal-exit": "^4.0.1" } }, "sha512-MmnduQUuHCoFckZoWnXsTg7JaiLBJrKFj9UI2MbRPGaJeVpsLcVBu6P/IGZovziM/YBsellCmsprgNA+w0CzVg=="], - "sprintf-js": ["sprintf-js@1.1.3", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="], + "sprintf-js": ["sprintf-js@1.0.3", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="], "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], @@ -2792,8 +2784,6 @@ "yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], - "yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="], - "yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], "yocto-spinner": ["yocto-spinner@1.2.2", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-DODGl1wJjA/s5pnJFKau9lIYHT81lnhob1i3e1TjxZRxEhWRKl74nTbWE6H5KlkViQQTo/Z29YFdxzTZAMY3ng=="], @@ -2828,9 +2818,7 @@ "@electron/fuses/fs-extra": ["fs-extra@9.1.0", "", { "dependencies": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ=="], - "@electron/get/fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="], - - "@electron/get/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "@electron/get/env-paths": ["env-paths@3.0.0", "", {}, "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A=="], "@electron/notarize/fs-extra": ["fs-extra@9.1.0", "", { "dependencies": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ=="], @@ -2922,8 +2910,6 @@ "@types/ws/@types/node": ["@types/node@24.13.3", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q=="], - "@types/yauzl/@types/node": ["@types/node@24.13.3", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q=="], - "app-builder-lib/@electron/get": ["@electron/get@3.1.0", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ=="], "app-builder-lib/ci-info": ["ci-info@4.3.1", "", {}, "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA=="], @@ -2974,8 +2960,6 @@ "express/cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="], - "extract-zip/get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="], - "filelist/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="], "form-data/mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], @@ -3036,6 +3020,8 @@ "rimraf/glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="], + "roarr/sprintf-js": ["sprintf-js@1.1.3", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="], + "rolldown/@oxc-project/types": ["@oxc-project/types@0.139.0", "", {}, "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw=="], "shadcn/fs-extra": ["fs-extra@11.3.6", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA=="], @@ -3214,8 +3200,6 @@ "@types/ws/@types/node/undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="], - "@types/yauzl/@types/node/undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="], - "app-builder-lib/@electron/get/fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="], "app-builder-lib/@electron/get/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], @@ -3430,8 +3414,6 @@ "pkg-up/find-up/locate-path/path-exists": ["path-exists@3.0.0", "", {}, "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ=="], - "read-yaml-file/js-yaml/argparse/sprintf-js": ["sprintf-js@1.0.3", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="], - "rimraf/glob/minimatch/brace-expansion": ["brace-expansion@1.1.16", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw=="], "storybook/@vitest/expect/@vitest/utils/@vitest/pretty-format": ["@vitest/pretty-format@3.2.4", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA=="], diff --git a/tests/observability/durable-summary.test.ts b/tests/observability/durable-summary.test.ts index 26669824..9e42d52f 100644 --- a/tests/observability/durable-summary.test.ts +++ b/tests/observability/durable-summary.test.ts @@ -115,4 +115,4 @@ test("discovery, recommendations and candidates survive absent detail and repeat } finally { rmSync(directory, { recursive: true }); } -}); +}, 30_000);