@blackbelt-technology/pi-agent-dashboard 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -5
- package/docs/architecture.md +1673 -75
- package/package.json +23 -15
- package/packages/extension/package.json +8 -8
- package/packages/extension/src/ask-user-tool.ts +65 -3
- package/packages/extension/src/auto-session-namer.ts +190 -50
- package/packages/extension/src/bridge-handlers/dispatch.ts +450 -0
- package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
- package/packages/extension/src/bridge-handlers/instance.ts +220 -0
- package/packages/extension/src/bridge-handlers/lifecycle.ts +1030 -0
- package/packages/extension/src/bridge-handlers/ui-prompt-patch.ts +198 -0
- package/packages/extension/src/bridge-identity-log.ts +45 -0
- package/packages/extension/src/bridge.ts +480 -2510
- package/packages/extension/src/command-handler.ts +180 -11
- package/packages/extension/src/connection.ts +265 -18
- package/packages/extension/src/dashboard-context-injector.ts +26 -47
- package/packages/extension/src/empty-actionable-guard.ts +8 -3
- package/packages/extension/src/flow-event-wiring.ts +1 -1
- package/packages/extension/src/followup-buffer.ts +1 -1
- package/packages/extension/src/followup-drain.ts +79 -0
- package/packages/extension/src/local-token-header.ts +161 -17
- package/packages/extension/src/message-update-coalescer.ts +3 -1
- package/packages/extension/src/model-refresh.ts +19 -0
- package/packages/extension/src/multiselect-list.ts +6 -2
- package/packages/extension/src/multiselect-polyfill.ts +2 -2
- package/packages/extension/src/openspec-cli-shim.ts +1 -1
- package/packages/extension/src/path-gate/decide.ts +15 -41
- package/packages/extension/src/path-gate/grant-cache.ts +3 -1
- package/packages/extension/src/path-gate/handler.ts +51 -2
- package/packages/extension/src/path-gate/index.ts +12 -1
- package/packages/extension/src/path-gate/resolve.ts +6 -124
- package/packages/extension/src/path-gate/roots.ts +4 -1
- package/packages/extension/src/path-gate/suppression.ts +4 -1
- package/packages/extension/src/path-gate/yolo-link.ts +104 -0
- package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
- package/packages/extension/src/project-trust.ts +119 -25
- package/packages/extension/src/prompt-expander.ts +5 -1
- package/packages/extension/src/prompt-meta.ts +64 -0
- package/packages/extension/src/provider-register.ts +87 -20
- package/packages/extension/src/role-manager.ts +5 -4
- package/packages/extension/src/server-auto-start.ts +12 -5
- package/packages/extension/src/server-launcher.ts +11 -13
- package/packages/extension/src/session-move.ts +19 -0
- package/packages/extension/src/session-sync.ts +31 -38
- package/packages/extension/src/spawn-token.ts +46 -0
- package/packages/extension/src/stream-forward-buffer.ts +161 -0
- package/packages/extension/src/subagent-frame-buffer.ts +6 -2
- package/packages/extension/src/subagent-tick-throttle.ts +3 -1
- package/packages/extension/src/vault-delivery.ts +394 -0
- package/packages/extension/src/vault-forwarder.ts +128 -0
- package/packages/extension/src/vault-masker.ts +165 -0
- package/packages/extension/src/vault-redaction.ts +181 -0
- package/packages/extension/src/vcs-info.ts +5 -2
- package/packages/server/bin/pi-dashboard.mjs +26 -89
- package/packages/server/package.json +29 -15
- package/packages/server/src/access/access-grants.ts +18 -0
- package/packages/server/src/access/agent-confirm-registry.ts +31 -13
- package/packages/server/src/access/agent-grant.ts +1 -1
- package/packages/server/src/access/agent-yolo.ts +91 -0
- package/packages/server/src/access/containment-gate.ts +28 -1
- package/packages/server/src/access/cwd-admission-log.ts +46 -0
- package/packages/server/src/access/cwd-verdict.ts +144 -0
- package/packages/server/src/access/grant-coordinator.ts +3 -1
- package/packages/server/src/access/pi-trust-mirror-service.ts +374 -0
- package/packages/server/src/access/planes.ts +10 -1
- package/packages/server/src/access/refusal-ledger.ts +6 -6
- package/packages/server/src/access/yolo-session.ts +73 -12
- package/packages/server/src/acp-bridge/acp-connection.ts +225 -0
- package/packages/server/src/acp-bridge/acp-restore.ts +41 -0
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +544 -0
- package/packages/server/src/acp-bridge/child-env.ts +73 -0
- package/packages/server/src/acp-bridge/event-log.ts +194 -0
- package/packages/server/src/acp-bridge/gateway-client.ts +136 -0
- package/packages/server/src/acp-bridge/local-bridge-socket.ts +67 -0
- package/packages/server/src/acp-bridge/local-host.ts +132 -0
- package/packages/server/src/acp-bridge/main.ts +118 -0
- package/packages/server/src/acp-bridge/models.ts +33 -0
- package/packages/server/src/acp-bridge/permission-bridge.ts +106 -0
- package/packages/server/src/acp-bridge/server-requests.ts +136 -0
- package/packages/server/src/acp-bridge/session-state.ts +127 -0
- package/packages/server/src/addons/addon-toggle-restore.ts +110 -0
- package/packages/server/src/addons/addons-catalog.ts +408 -0
- package/packages/server/src/addons/addons-folder-service.ts +347 -0
- package/packages/server/src/addons/addons-folder.ts +310 -0
- package/packages/server/src/addons/addons-service.ts +470 -0
- package/packages/server/src/addons/package-contents.ts +99 -0
- package/packages/server/src/addons/settings-entries.ts +120 -0
- package/packages/server/src/attachments/fit-worker-pool.ts +12 -17
- package/packages/server/src/auth/approval-refusal.ts +87 -0
- package/packages/server/src/auth/auth-plugin.ts +292 -79
- package/packages/server/src/auth/auth.ts +78 -7
- package/packages/server/src/auth/bearer-auth.ts +23 -1
- package/packages/server/src/auth/cors-origin.ts +10 -0
- package/packages/server/src/auth/csp.ts +6 -0
- package/packages/server/src/auth/host-admission.ts +26 -0
- package/packages/server/src/auth/host-gate.ts +6 -1
- package/packages/server/src/auth/local-credential.ts +258 -0
- package/packages/server/src/auth/local-proof.ts +7 -4
- package/packages/server/src/auth/local-token.ts +16 -0
- package/packages/server/src/auth/localhost-guard.ts +251 -8
- package/packages/server/src/auth/network-trust-telemetry.ts +126 -0
- package/packages/server/src/auth/node-guard.ts +43 -0
- package/packages/server/src/auth/operate-required.ts +126 -0
- package/packages/server/src/auth/passkey/challenge-store.ts +90 -0
- package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
- package/packages/server/src/auth/passkey/passkey-pages.ts +173 -0
- package/packages/server/src/auth/passkey/passkey-routes.ts +224 -0
- package/packages/server/src/auth/passkey/passkey-service.ts +247 -0
- package/packages/server/src/auth/passkey/phone-signin.ts +211 -0
- package/packages/server/src/auth/passkey/requester.ts +83 -0
- package/packages/server/src/auth/passkey/rp-context.ts +98 -0
- package/packages/server/src/auth/passkey/user-directory.ts +348 -0
- package/packages/server/src/auth/pi-legacy-credentials.ts +321 -0
- package/packages/server/src/auth/provider-auth-registry.ts +35 -1
- package/packages/server/src/auth/provider-auth-storage.ts +55 -8
- package/packages/server/src/auth/radius-override.ts +13 -0
- package/packages/server/src/auth/route-tier-gate.ts +27 -11
- package/packages/server/src/auth/runtime-provider-catalogue.ts +107 -0
- package/packages/server/src/auth/scan-legacy-provider-ids.ts +80 -0
- package/packages/server/src/auth/serve-app-host.ts +97 -0
- package/packages/server/src/auth/trust-mode-boot.ts +93 -0
- package/packages/server/src/auth/trust-mode.ts +83 -0
- package/packages/server/src/auto-name-outcome-store.ts +4 -1
- package/packages/server/src/browse.ts +114 -2
- package/packages/server/src/browser-handlers/acp-guard.ts +79 -0
- package/packages/server/src/browser-handlers/directory-handler.ts +128 -6
- package/packages/server/src/browser-handlers/session-action-handler.ts +129 -62
- package/packages/server/src/browser-handlers/session-meta-handler.ts +16 -6
- package/packages/server/src/browser-handlers/spawn-choice.ts +99 -0
- package/packages/server/src/cli.ts +883 -97
- package/packages/server/src/config-api.ts +143 -1
- package/packages/server/src/config-snapshot.ts +5 -0
- package/packages/server/src/directory-service.ts +435 -32
- package/packages/server/src/embed-lifecycle/caps.ts +35 -4
- package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +45 -4
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +195 -20
- package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +38 -0
- package/packages/server/src/embed-lifecycle/plugin-session-close.ts +123 -0
- package/packages/server/src/embed-lifecycle/quiescence.ts +29 -3
- package/packages/server/src/embed-lifecycle/reclaim-give-up.ts +54 -0
- package/packages/server/src/event-wiring.ts +208 -35
- package/packages/server/src/file-watch-manager.ts +187 -39
- package/packages/server/src/git-worktree/git-operations.ts +16 -5
- package/packages/server/src/git-worktree/worktree-init-trust.ts +48 -5
- package/packages/server/src/git-worktree/worktree-init.ts +7 -56
- package/packages/server/src/identity/host-resources.ts +3 -0
- package/packages/server/src/identity/http-road-classification.ts +18 -0
- package/packages/server/src/identity/identity-registration-tracker.ts +4 -1
- package/packages/server/src/identity/plugin-identity.ts +19 -0
- package/packages/server/src/identity/policy-registry.ts +4 -1
- package/packages/server/src/identity/resolver-registry.ts +12 -3
- package/packages/server/src/identity/ws-message-scope.ts +9 -0
- package/packages/server/src/identity/ws-road-classification.ts +9 -0
- package/packages/server/src/known-server-moves.ts +175 -0
- package/packages/server/src/lib/browse-roots.ts +36 -0
- package/packages/server/src/lib/digest-gate.ts +82 -0
- package/packages/server/src/lib/file-write-lock.ts +24 -0
- package/packages/server/src/lib/folder-project.ts +439 -0
- package/packages/server/src/lib/purify.ts +13 -5
- package/packages/server/src/lib/writable-handler-target.ts +66 -0
- package/packages/server/src/lib/writable-md-target.ts +12 -1
- package/packages/server/src/lifecycle/classify-dashboard-port.ts +134 -0
- package/packages/server/src/lifecycle/home-lock.ts +344 -130
- package/packages/server/src/lifecycle/home-rendezvous.ts +41 -11
- package/packages/server/src/lifecycle/recovery-server.ts +77 -1
- package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
- package/packages/server/src/live-server/live-capability.ts +254 -0
- package/packages/server/src/live-server/live-server-proxy.ts +173 -26
- package/packages/server/src/metrics/eventloop-spike-metrics.ts +2 -2
- package/packages/server/src/model-proxy/internal-auth-storage.ts +27 -26
- package/packages/server/src/model-proxy/internal-registry.ts +6 -0
- package/packages/server/src/model-proxy/server-model-runtime.ts +6 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +109 -16
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +132 -0
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +90 -35
- package/packages/server/src/openspec/openspec-poll-worker.ts +200 -44
- package/packages/server/src/openspec/proposal-attach-naming.ts +5 -3
- package/packages/server/src/openspec/readiness.ts +9 -0
- package/packages/server/src/openspec/workflow-schema.ts +1128 -0
- package/packages/server/src/package/installed-package-enricher.ts +38 -3
- package/packages/server/src/package/package-health-scanner.ts +133 -0
- package/packages/server/src/package/package-manager-wrapper.ts +18 -2
- package/packages/server/src/package/provider-catalogue-cache.ts +17 -3
- package/packages/server/src/package/provider-probe.ts +5 -3
- package/packages/server/src/pairing/browser-gateway.ts +108 -8
- package/packages/server/src/pairing/knock-admission.ts +277 -0
- package/packages/server/src/pairing/pairing.ts +154 -27
- package/packages/server/src/pairing/subagent-resync-routing.ts +4 -1
- package/packages/server/src/pairing/ws-tier-gate.ts +34 -0
- package/packages/server/src/peer-servers.ts +77 -0
- package/packages/server/src/pending/pending-plugin-ref-registry.ts +57 -2
- package/packages/server/src/persistence/boot-state.ts +48 -1
- package/packages/server/src/persistence/memory-event-store.ts +216 -237
- package/packages/server/src/persistence/meta-persistence.ts +12 -1
- package/packages/server/src/persistence/preferences-store.ts +116 -7
- package/packages/server/src/pi/bridge-upgrade-auth.ts +32 -21
- package/packages/server/src/pi/folder-commands.ts +141 -0
- package/packages/server/src/pi/gateway-socket-bind.ts +9 -3
- package/packages/server/src/pi/gateway-transport-policy.ts +13 -0
- package/packages/server/src/pi/host-project-trust.ts +158 -33
- package/packages/server/src/pi/pi-gateway.ts +93 -9
- package/packages/server/src/pi/pi-resource-scanner.ts +15 -0
- package/packages/server/src/pi/resource-activation-toggle.ts +6 -0
- package/packages/server/src/pi/resource-toggle-trust.ts +34 -2
- package/packages/server/src/pi/session-skill-registry.ts +13 -3
- package/packages/server/src/pi/settings-write-lock.ts +32 -0
- package/packages/server/src/pi/trust-challenges.ts +38 -0
- package/packages/server/src/pi-agent-settings.ts +701 -100
- package/packages/server/src/pi-settings-themes.ts +104 -0
- package/packages/server/src/questions/brief-generator.ts +138 -0
- package/packages/server/src/questions/brief-model.ts +55 -0
- package/packages/server/src/questions/brief-policy.ts +36 -0
- package/packages/server/src/questions/brief-prompt.ts +92 -0
- package/packages/server/src/questions/brief-runtime.ts +50 -0
- package/packages/server/src/questions/question-answer.ts +55 -0
- package/packages/server/src/questions/question-broadcast.ts +106 -0
- package/packages/server/src/questions/question-files.ts +128 -0
- package/packages/server/src/questions/question-routes.ts +126 -0
- package/packages/server/src/questions/question-snapshot.ts +150 -0
- package/packages/server/src/questions/question-stack.ts +57 -0
- package/packages/server/src/questions/question-store.ts +477 -0
- package/packages/server/src/routes/access-prompt-routes.ts +5 -3
- package/packages/server/src/routes/access-routes.ts +123 -5
- package/packages/server/src/routes/acme-routes.ts +190 -0
- package/packages/server/src/routes/acp-routes.ts +16 -0
- package/packages/server/src/routes/addons-routes.ts +221 -0
- package/packages/server/src/routes/file-routes.ts +366 -75
- package/packages/server/src/routes/file-write-binary-routes.ts +473 -0
- package/packages/server/src/routes/folder-project-routes.ts +99 -0
- package/packages/server/src/routes/git-routes.ts +17 -2
- package/packages/server/src/routes/known-servers-routes.ts +333 -53
- package/packages/server/src/routes/live-server-routes.ts +72 -4
- package/packages/server/src/routes/local-proof-routes.ts +12 -7
- package/packages/server/src/routes/mermaid-repair-routes.ts +254 -0
- package/packages/server/src/routes/model-proxy-routes.ts +4 -2
- package/packages/server/src/routes/openspec-routes.ts +270 -40
- package/packages/server/src/routes/package-health-routes.ts +140 -0
- package/packages/server/src/routes/package-routes.ts +28 -1
- package/packages/server/src/routes/pairing-routes.ts +158 -24
- package/packages/server/src/routes/pi-retry-routes.ts +18 -2
- package/packages/server/src/routes/pi-settings-routes.ts +264 -0
- package/packages/server/src/routes/plugin-activation-routes.ts +87 -27
- package/packages/server/src/routes/provider-auth-routes.ts +22 -5
- package/packages/server/src/routes/provider-routes.ts +29 -0
- package/packages/server/src/routes/resource-activation-routes.ts +16 -32
- package/packages/server/src/routes/session-routes.ts +49 -5
- package/packages/server/src/routes/system-routes.ts +207 -23
- package/packages/server/src/routes/tls-routes.ts +55 -0
- package/packages/server/src/routes/user-routes.ts +192 -0
- package/packages/server/src/runtime-overlay/runtime-stager.ts +15 -2
- package/packages/server/src/runtime-overlay/runtime-update-checker.ts +11 -2
- package/packages/server/src/server.ts +919 -139
- package/packages/server/src/services/attached-driver.ts +175 -0
- package/packages/server/src/services/change-notifier.ts +55 -0
- package/packages/server/src/services/cli-service.ts +450 -0
- package/packages/server/src/services/command-runner.ts +92 -0
- package/packages/server/src/services/definitions-store.ts +121 -0
- package/packages/server/src/services/driver.ts +112 -0
- package/packages/server/src/services/health.ts +94 -0
- package/packages/server/src/services/leases.ts +117 -0
- package/packages/server/src/services/log-text.ts +97 -0
- package/packages/server/src/services/native-driver.ts +283 -0
- package/packages/server/src/services/oci-driver.ts +590 -0
- package/packages/server/src/services/output-capture.ts +183 -0
- package/packages/server/src/services/paths.ts +82 -0
- package/packages/server/src/services/ports.ts +26 -0
- package/packages/server/src/services/routes.ts +140 -0
- package/packages/server/src/services/runtime-detect.ts +108 -0
- package/packages/server/src/services/secret-delivery.ts +61 -0
- package/packages/server/src/services/secrets-resolver.ts +145 -0
- package/packages/server/src/services/secrets-store.ts +137 -0
- package/packages/server/src/services/service-manager.ts +1565 -0
- package/packages/server/src/services/start-record.ts +66 -0
- package/packages/server/src/services/state-machine.ts +241 -0
- package/packages/server/src/session/archive-sweeper.ts +92 -3
- package/packages/server/src/session/custom-event-group-matcher.ts +4 -3
- package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
- package/packages/server/src/session/memory-session-manager.ts +53 -0
- package/packages/server/src/session/name-provenance.ts +102 -0
- package/packages/server/src/session/open-tool-calls.ts +15 -6
- package/packages/server/src/session/session-api.ts +47 -12
- package/packages/server/src/session/session-archive.ts +56 -4
- package/packages/server/src/session/session-diff-cache.ts +11 -4
- package/packages/server/src/session/session-load-worker-pool.ts +4 -3
- package/packages/server/src/session/session-scanner.ts +73 -3
- package/packages/server/src/session/session-to-meta.ts +15 -0
- package/packages/server/src/spawn-process/abort-spawned-run.ts +55 -0
- package/packages/server/src/spawn-process/acp-spawn.ts +131 -0
- package/packages/server/src/spawn-process/process-manager.ts +164 -30
- package/packages/server/src/spawn-process/restart-helper.ts +9 -8
- package/packages/server/src/spawn-process/server-pid.ts +16 -7
- package/packages/server/src/spawn-process/session-terminator.ts +218 -0
- package/packages/server/src/spawn-process/spawn-env-contributors.ts +159 -0
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +10 -1
- package/packages/server/src/terminal/terminal-manager.ts +67 -1
- package/packages/server/src/tls/cert-files.ts +228 -0
- package/packages/server/src/tls/cert-manager.ts +703 -0
- package/packages/server/src/tls/cert-store.ts +69 -0
- package/packages/server/src/tls/source-registry.ts +71 -0
- package/packages/server/src/tls/sources/acme/accounts.ts +76 -0
- package/packages/server/src/tls/sources/acme/acme-source.ts +508 -0
- package/packages/server/src/tls/sources/acme/config-projection.ts +34 -0
- package/packages/server/src/tls/sources/acme/credentials.ts +185 -0
- package/packages/server/src/tls/sources/acme/dns.ts +303 -0
- package/packages/server/src/tls/sources/acme/e2e-overrides.ts +49 -0
- package/packages/server/src/tls/sources/acme/entry.ts +180 -0
- package/packages/server/src/tls/sources/acme/gc.ts +78 -0
- package/packages/server/src/tls/sources/acme/runtime.ts +51 -0
- package/packages/server/src/tls/sources/acme/solvers/acme-dns.ts +154 -0
- package/packages/server/src/tls/sources/acme/solvers/cloudflare.ts +147 -0
- package/packages/server/src/tls/sources/acme/types.ts +72 -0
- package/packages/server/src/tls/sources/tailscale-cert.ts +172 -0
- package/packages/server/src/tls/tls-config-validation.ts +92 -0
- package/packages/server/src/tls/tls-listener.ts +351 -0
- package/packages/server/src/tls/types.ts +80 -0
- package/packages/server/src/tunnel/tunnel-block-events.ts +4 -1
- package/packages/server/src/tunnel/tunnel-core.ts +4 -1
- package/packages/server/src/tunnel/tunnel-endpoints.ts +4 -0
- package/packages/server/src/tunnel-providers/tailscale.ts +27 -6
- package/packages/server/src/vault/vault-bindings.ts +101 -0
- package/packages/server/src/vault/vault-delivery-hub.ts +294 -0
- package/packages/server/src/vault/vault-grants.ts +260 -0
- package/packages/server/src/vault/vault-import.ts +161 -0
- package/packages/server/src/vault/vault-permissions.ts +39 -0
- package/packages/server/src/vault/vault-plugin-read.ts +64 -0
- package/packages/server/src/vault/vault-projects.ts +156 -0
- package/packages/server/src/vault/vault-routes.ts +277 -0
- package/packages/server/src/vault/vault-store.ts +371 -0
- package/packages/shared/package.json +5 -2
- package/packages/shared/src/acp/acp-config.ts +123 -0
- package/packages/shared/src/acp/normalize-v1.ts +92 -0
- package/packages/shared/src/acp/paths.ts +36 -0
- package/packages/shared/src/acp/to-dashboard-events.ts +533 -0
- package/packages/shared/src/acp/update-model.ts +574 -0
- package/packages/shared/src/anthropic-messages-source.ts +8 -0
- package/packages/shared/src/bind-reachability.ts +21 -2
- package/packages/shared/src/boot-state.ts +6 -0
- package/packages/shared/src/browser-host-identity.ts +49 -0
- package/packages/shared/src/browser-host-ipc.ts +107 -0
- package/packages/shared/src/browser-protocol.ts +385 -71
- package/packages/shared/src/canonical-subject.ts +27 -2
- package/packages/shared/src/card-sections.ts +185 -1
- package/packages/shared/src/chrome-profiles.ts +188 -0
- package/packages/shared/src/config.ts +473 -26
- package/packages/shared/src/custom-event-groups.ts +5 -2
- package/packages/shared/src/cwd-guard.ts +381 -1
- package/packages/shared/src/dashboard-paths.ts +12 -0
- package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
- package/packages/shared/src/dashboard-plugin/file-handler.ts +71 -0
- package/packages/shared/src/dashboard-plugin/index.ts +7 -3
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +106 -2
- package/packages/shared/src/dashboard-plugin/project-identity.ts +42 -0
- package/packages/shared/src/dashboard-plugin/project-markers.ts +60 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +95 -0
- package/packages/shared/src/dashboard-plugin/slot-types.ts +64 -4
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +22 -3
- package/packages/shared/src/dashboard-starter.ts +30 -0
- package/packages/shared/src/display-name.ts +42 -0
- package/packages/shared/src/doctor-core.ts +25 -107
- package/packages/shared/src/enabled-models-match.ts +47 -0
- package/packages/shared/src/event-forward-declaration.ts +187 -0
- package/packages/shared/src/file-kind.ts +54 -2
- package/packages/shared/src/git-worktree-helpers.ts +8 -4
- package/packages/shared/src/grammar-types.ts +3 -1
- package/packages/shared/src/host-admission.ts +2 -1
- package/packages/shared/src/host-port.ts +34 -0
- package/packages/shared/src/launcher-origin.ts +26 -0
- package/packages/shared/src/local-credential-proof.ts +219 -0
- package/packages/shared/src/markup-repair/asciidoc.ts +130 -0
- package/packages/shared/src/markup-repair/types.ts +13 -0
- package/packages/shared/src/md-table-cell.ts +11 -0
- package/packages/shared/src/mdns-discovery.ts +392 -42
- package/packages/shared/src/models-json-reader.ts +6 -0
- package/packages/shared/src/openspec-design-evidence.ts +25 -1
- package/packages/shared/src/openspec-poller.ts +210 -9
- package/packages/shared/src/openspec-status-all.ts +393 -0
- package/packages/shared/src/operate-required.ts +29 -0
- package/packages/shared/src/pairing-knock-client.ts +261 -0
- package/packages/shared/src/pairing-knock.ts +71 -0
- package/packages/shared/src/pairing-refusal.ts +32 -0
- package/packages/shared/src/path-containment-guard-name.ts +8 -0
- package/packages/shared/src/pi-settings-keys.ts +9 -0
- package/packages/shared/src/pi-settings-schema.ts +285 -0
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +200 -0
- package/packages/shared/src/pi-trust-mirror-types.ts +57 -0
- package/packages/shared/src/pi-trust-mirror.ts +328 -0
- package/packages/shared/src/platform/binary-lookup.ts +2 -194
- package/packages/shared/src/platform/git.ts +204 -4
- package/packages/shared/src/platform/native-ts-hooks.mjs +93 -40
- package/packages/shared/src/platform/native-ts-register.mjs +22 -10
- package/packages/shared/src/platform/native-ts-tier.d.mts +1 -0
- package/packages/shared/src/platform/native-ts-tier.mjs +17 -0
- package/packages/shared/src/platform/node-spawn.ts +1 -2
- package/packages/shared/src/platform/openspec.ts +129 -31
- package/packages/shared/src/platform/process-scan.ts +199 -1
- package/packages/shared/src/platform/process.ts +51 -0
- package/packages/shared/src/platform/runner.ts +46 -2
- package/packages/shared/src/platform/spawn-mechanism.ts +14 -2
- package/packages/shared/src/platform/ts-loader-select.d.mts +1 -7
- package/packages/shared/src/platform/ts-loader-select.mjs +14 -43
- package/packages/shared/src/plugin-bridge-register.ts +24 -1
- package/packages/shared/src/project-name.ts +42 -0
- package/packages/shared/src/prompt-answer.ts +183 -0
- package/packages/shared/src/protocol.ts +133 -8
- package/packages/shared/src/question-types.ts +73 -0
- package/packages/shared/src/recommended-extensions.ts +80 -23
- package/packages/shared/src/recovery-timing.ts +12 -0
- package/packages/shared/src/redaction.ts +50 -0
- package/packages/shared/src/rest-api.ts +484 -1
- package/packages/shared/src/role-config-disk.ts +23 -0
- package/packages/shared/src/role-schema.ts +79 -0
- package/packages/shared/src/route-tiers.ts +127 -0
- package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +17 -0
- package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +119 -8
- package/packages/shared/src/server-identity.ts +51 -15
- package/packages/shared/src/server-launcher.ts +12 -33
- package/packages/shared/src/server-pinning.ts +81 -0
- package/packages/shared/src/services/offers.ts +114 -0
- package/packages/shared/src/services/schema.ts +628 -0
- package/packages/shared/src/services/status.ts +169 -0
- package/packages/shared/src/session-meta.ts +59 -2
- package/packages/shared/src/session-name.ts +8 -0
- package/packages/shared/src/skill-block-parser.ts +14 -0
- package/packages/shared/src/source-matching.ts +5 -1
- package/packages/shared/src/state-replay.ts +19 -0
- package/packages/shared/src/terminal-safe.ts +24 -0
- package/packages/shared/src/tls-status.ts +69 -0
- package/packages/shared/src/tool-path-resolve.ts +243 -0
- package/packages/shared/src/tool-registry/definitions.ts +26 -4
- package/packages/shared/src/tool-registry/index.ts +2 -2
- package/packages/shared/src/tool-registry/pi-tools.ts +32 -3
- package/packages/shared/src/tunnel-provider.ts +3 -2
- package/packages/shared/src/types.ts +104 -9
- package/packages/shared/src/vault-delivery.ts +73 -0
- package/packages/shared/src/vault-origin.ts +51 -0
- package/packages/shared/src/vault-project-key.ts +53 -0
- package/packages/shared/src/worktree-init-hook.ts +69 -0
- package/packages/shared/src/ws-message-tiers.ts +135 -0
- package/tsconfig.base.json +1 -0
|
@@ -0,0 +1,1128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dashboard-managed OpenSpec workflow schema `pi-spec-driven`.
|
|
3
|
+
*
|
|
4
|
+
* Generation (scratch root + empty XDG_DATA_HOME, `schema which/fork/validate`,
|
|
5
|
+
* anchor-checked YAML patch, stamp, staged swap), component-wise stamp
|
|
6
|
+
* comparison, the six writing actions (enable / disable / update / adopt / pin /
|
|
7
|
+
* remove) behind one write guard, and the poll-side status. The filesystem
|
|
8
|
+
* parts (`inspectSchema`, `computeWorkflowSchemaStatus`, `fingerprintDir`,
|
|
9
|
+
* `enumerateActiveChanges`) never spawn the CLI so they can run in a worker
|
|
10
|
+
* thread; every CLI call goes through the injectable `CliRunner`.
|
|
11
|
+
*
|
|
12
|
+
* See change: add-pi-spec-driven-schema.
|
|
13
|
+
*/
|
|
14
|
+
import crypto from "node:crypto";
|
|
15
|
+
import fsp from "node:fs/promises";
|
|
16
|
+
import os from "node:os";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
import {
|
|
19
|
+
OPENSPEC_SCHEMA_FORK,
|
|
20
|
+
OPENSPEC_SCHEMA_VALIDATE,
|
|
21
|
+
OPENSPEC_SCHEMA_WHICH,
|
|
22
|
+
OPENSPEC_STATUS_ALL,
|
|
23
|
+
OPENSPEC_VERSION,
|
|
24
|
+
userSchemasDir,
|
|
25
|
+
} from "@blackbelt-technology/pi-dashboard-shared/platform/openspec.js";
|
|
26
|
+
import { type Recipe, runAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/runner.js";
|
|
27
|
+
import type { Semaphore } from "@blackbelt-technology/pi-dashboard-shared/semaphore.js";
|
|
28
|
+
import type {
|
|
29
|
+
OpenSpecWorkflowSchemaStatus,
|
|
30
|
+
WorkflowSchemaGenerated,
|
|
31
|
+
} from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
32
|
+
import semver from "semver";
|
|
33
|
+
import YAML from "yaml";
|
|
34
|
+
|
|
35
|
+
export const CURRENT_PATCH = 1;
|
|
36
|
+
const WORKFLOW_SCHEMA_NAME = "pi-spec-driven";
|
|
37
|
+
const BASE_SCHEMA = "spec-driven";
|
|
38
|
+
const STAMP_KEY = "x-pi-dashboard";
|
|
39
|
+
const DESIGN_ANCHOR = "When to include design.md (create only if any apply):";
|
|
40
|
+
const DESIGN_REPLACEMENT =
|
|
41
|
+
'When a full design.md is warranted (otherwise still create design.md containing one line "Not needed: <reason>"):';
|
|
42
|
+
const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
43
|
+
const RETRYABLE_CODES = new Set(["EPERM", "EBUSY", "EACCES"]);
|
|
44
|
+
/** Windows rename retry: initial attempt + 5 retries, delays sum to 1.55 s (< 2 s window). */
|
|
45
|
+
const RETRY_DELAYS_MS: readonly number[] = [50, 100, 200, 400, 800];
|
|
46
|
+
|
|
47
|
+
// ── Dependency injection ────────────────────────────────────────────────────
|
|
48
|
+
|
|
49
|
+
/** One CLI invocation; stubs switch on `op`. */
|
|
50
|
+
export type CliCall =
|
|
51
|
+
| { op: "version" }
|
|
52
|
+
| { op: "which"; name: string }
|
|
53
|
+
| { op: "fork"; source: string; name: string }
|
|
54
|
+
| { op: "validate"; name: string }
|
|
55
|
+
| { op: "statusAll" };
|
|
56
|
+
|
|
57
|
+
export type CliResult =
|
|
58
|
+
| { ok: true; stdout: string }
|
|
59
|
+
| { ok: false; stdout: string; stderr: string; message: string };
|
|
60
|
+
|
|
61
|
+
export interface CliCtx {
|
|
62
|
+
cwd: string;
|
|
63
|
+
/** When set, `XDG_DATA_HOME` is pointed at this (empty) dir so no user-level schema is visible. */
|
|
64
|
+
xdgDataHome?: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type CliRunner = (call: CliCall, ctx: CliCtx) => Promise<CliResult>;
|
|
68
|
+
|
|
69
|
+
export interface FsOps {
|
|
70
|
+
rename(from: string, to: string): Promise<void>;
|
|
71
|
+
/** Recursive + force. */
|
|
72
|
+
rm(target: string): Promise<void>;
|
|
73
|
+
/** Recursive directory copy. */
|
|
74
|
+
cp(from: string, to: string): Promise<void>;
|
|
75
|
+
/** Exclusive create (`wx`): throws `EEXIST` if present. */
|
|
76
|
+
writeExclusive(file: string, data: string): Promise<void>;
|
|
77
|
+
/** temp-file + rename. */
|
|
78
|
+
writeAtomic(file: string, data: string): Promise<void>;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface WorkflowSchemaDeps {
|
|
82
|
+
cli: CliRunner;
|
|
83
|
+
fs: FsOps;
|
|
84
|
+
sleep: (ms: number) => Promise<void>;
|
|
85
|
+
now: () => number;
|
|
86
|
+
pid: number;
|
|
87
|
+
platform: NodeJS.Platform;
|
|
88
|
+
random: () => string;
|
|
89
|
+
/** Spawn semaphore for the `newer`/`conflict` validate. Default: pass-through (the route wiring injects the directory-service one). */
|
|
90
|
+
semaphore: Semaphore;
|
|
91
|
+
/** Memo of the local validate keyed by (cwd, fingerprint, CLI version). */
|
|
92
|
+
validateMemo: Map<string, boolean>;
|
|
93
|
+
/** True when `name` resolves from the project schema dir or the package built-ins (never user XDG). */
|
|
94
|
+
resolveSchema: (root: string, name: string) => Promise<boolean>;
|
|
95
|
+
/** Forced OpenSpec refresh after an action that wrote. */
|
|
96
|
+
refresh: (cwd: string) => Promise<void>;
|
|
97
|
+
/** Scratch parent dir. */
|
|
98
|
+
tmpDir: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function defaultCli(): CliRunner {
|
|
102
|
+
const exec = async <I extends { cwd: string }>(recipe: Recipe<I, string>, input: I, ctx: CliCtx): Promise<CliResult> => {
|
|
103
|
+
const r = await runAsync(recipe, input, {
|
|
104
|
+
cwd: ctx.cwd,
|
|
105
|
+
...(ctx.xdgDataHome !== undefined ? { env: { XDG_DATA_HOME: ctx.xdgDataHome } } : {}),
|
|
106
|
+
});
|
|
107
|
+
if (r.ok) return { ok: true, stdout: r.value };
|
|
108
|
+
const e = r.error;
|
|
109
|
+
if (e.kind === "exit") return { ok: false, stdout: e.stdout, stderr: e.stderr, message: `exit ${e.code}` };
|
|
110
|
+
if (e.kind === "timeout") return { ok: false, stdout: e.stdout ?? "", stderr: e.stderr ?? "", message: `timed out after ${e.timeoutMs}ms` };
|
|
111
|
+
return { ok: false, stdout: "", stderr: "", message: "message" in e ? e.message : `${e.kind}: ${"binary" in e ? e.binary : ""}` };
|
|
112
|
+
};
|
|
113
|
+
return (call, ctx) => {
|
|
114
|
+
const base = { cwd: ctx.cwd };
|
|
115
|
+
switch (call.op) {
|
|
116
|
+
case "version":
|
|
117
|
+
return exec(OPENSPEC_VERSION, base, ctx);
|
|
118
|
+
case "which":
|
|
119
|
+
return exec(OPENSPEC_SCHEMA_WHICH, { ...base, name: call.name }, ctx);
|
|
120
|
+
case "fork":
|
|
121
|
+
return exec(OPENSPEC_SCHEMA_FORK, { ...base, source: call.source, name: call.name }, ctx);
|
|
122
|
+
case "validate":
|
|
123
|
+
return exec(OPENSPEC_SCHEMA_VALIDATE, { ...base, name: call.name }, ctx);
|
|
124
|
+
case "statusAll":
|
|
125
|
+
return exec(OPENSPEC_STATUS_ALL, base, ctx);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function defaultFs(): FsOps {
|
|
131
|
+
return {
|
|
132
|
+
rename: (from, to) => fsp.rename(from, to),
|
|
133
|
+
rm: (target) => fsp.rm(target, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }),
|
|
134
|
+
cp: (from, to) => fsp.cp(from, to, { recursive: true, errorOnExist: true, force: false }),
|
|
135
|
+
writeExclusive: (file, data) => fsp.writeFile(file, data, { flag: "wx" }),
|
|
136
|
+
writeAtomic: async (file, data) => {
|
|
137
|
+
const tmp = path.join(path.dirname(file), `.${path.basename(file)}.tmp-${process.pid}-${crypto.randomBytes(4).toString("hex")}`);
|
|
138
|
+
try {
|
|
139
|
+
await fsp.writeFile(tmp, data, { flag: "wx" });
|
|
140
|
+
await fsp.rename(tmp, file);
|
|
141
|
+
} catch (err) {
|
|
142
|
+
await fsp.rm(tmp, { force: true }).catch(() => undefined);
|
|
143
|
+
throw err;
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const sharedValidateMemo = new Map<string, boolean>();
|
|
150
|
+
|
|
151
|
+
export function resolveDeps(partial: Partial<WorkflowSchemaDeps> = {}): WorkflowSchemaDeps {
|
|
152
|
+
const cli = partial.cli ?? defaultCli();
|
|
153
|
+
return {
|
|
154
|
+
cli,
|
|
155
|
+
fs: partial.fs ?? defaultFs(),
|
|
156
|
+
sleep: partial.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))),
|
|
157
|
+
now: partial.now ?? Date.now,
|
|
158
|
+
pid: partial.pid ?? process.pid,
|
|
159
|
+
platform: partial.platform ?? process.platform,
|
|
160
|
+
random: partial.random ?? (() => crypto.randomBytes(4).toString("hex")),
|
|
161
|
+
semaphore: partial.semaphore ?? passThroughSemaphore,
|
|
162
|
+
validateMemo: partial.validateMemo ?? sharedValidateMemo,
|
|
163
|
+
resolveSchema: partial.resolveSchema ?? ((root, name) => defaultResolveSchema(cli, root, name)),
|
|
164
|
+
refresh: partial.refresh ?? (async () => undefined),
|
|
165
|
+
tmpDir: partial.tmpDir ?? os.tmpdir(),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const passThroughSemaphore: Semaphore = {
|
|
170
|
+
run: (fn) => fn(),
|
|
171
|
+
setMax: () => undefined,
|
|
172
|
+
size: () => 0,
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// ── Small helpers ───────────────────────────────────────────────────────────
|
|
176
|
+
|
|
177
|
+
function errCode(err: unknown): string | undefined {
|
|
178
|
+
return (err as NodeJS.ErrnoException | null)?.code;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function errMsg(err: unknown): string {
|
|
182
|
+
return err instanceof Error ? err.message : String(err);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Parse the first JSON object in `stdout` (the CLI prints its "experimental" note on stderr, but be defensive). */
|
|
186
|
+
function parseJsonObject(stdout: string): Record<string, unknown> | null {
|
|
187
|
+
const i = stdout.indexOf("{");
|
|
188
|
+
if (i < 0) return null;
|
|
189
|
+
try {
|
|
190
|
+
const v: unknown = JSON.parse(stdout.slice(i));
|
|
191
|
+
return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
|
|
192
|
+
} catch {
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function lstatOrNull(p: string): Promise<import("node:fs").Stats | null> {
|
|
198
|
+
try {
|
|
199
|
+
return await fsp.lstat(p);
|
|
200
|
+
} catch {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const schemasDirOf = (root: string): string => path.join(root, "openspec", "schemas");
|
|
206
|
+
const schemaDirOf = (root: string): string => path.join(schemasDirOf(root), WORKFLOW_SCHEMA_NAME);
|
|
207
|
+
const changesDirOf = (root: string): string => path.join(root, "openspec", "changes");
|
|
208
|
+
const rel = (root: string, p: string): string => path.relative(root, p).split(path.sep).join("/");
|
|
209
|
+
|
|
210
|
+
function isKebabCaseName(name: unknown): name is string {
|
|
211
|
+
return typeof name === "string" && KEBAB.test(name);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Retry a rename on Windows `EPERM`/`EBUSY`/`EACCES`: 5 retries, 1.55 s of backoff in total. */
|
|
215
|
+
async function renameWithRetry(deps: WorkflowSchemaDeps, from: string, to: string): Promise<void> {
|
|
216
|
+
for (let attempt = 0; ; attempt++) {
|
|
217
|
+
try {
|
|
218
|
+
await deps.fs.rename(from, to);
|
|
219
|
+
return;
|
|
220
|
+
} catch (err) {
|
|
221
|
+
const retryable = deps.platform === "win32" && RETRYABLE_CODES.has(errCode(err) ?? "");
|
|
222
|
+
if (!retryable || attempt >= RETRY_DELAYS_MS.length) throw err;
|
|
223
|
+
await deps.sleep(RETRY_DELAYS_MS[attempt]);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// ── Fingerprint, stamp, comparison ──────────────────────────────────────────
|
|
229
|
+
|
|
230
|
+
/** sha256 over every file's relative path + content hash (symlinks by target). `null` when `dir` is absent. */
|
|
231
|
+
export async function fingerprintDir(dir: string): Promise<string | null> {
|
|
232
|
+
if (!(await lstatOrNull(dir))) return null;
|
|
233
|
+
const lines: string[] = [];
|
|
234
|
+
const walk = async (d: string): Promise<void> => {
|
|
235
|
+
const entries = (await fsp.readdir(d, { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : 1));
|
|
236
|
+
for (const e of entries) {
|
|
237
|
+
const full = path.join(d, e.name);
|
|
238
|
+
const r = path.relative(dir, full).split(path.sep).join("/");
|
|
239
|
+
if (e.isDirectory()) {
|
|
240
|
+
lines.push(`${r}/`);
|
|
241
|
+
await walk(full);
|
|
242
|
+
} else if (e.isSymbolicLink()) {
|
|
243
|
+
lines.push(`${r}\0L:${await fsp.readlink(full)}`);
|
|
244
|
+
} else {
|
|
245
|
+
lines.push(`${r}\0${crypto.createHash("sha256").update(await fsp.readFile(full)).digest("hex")}`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
await walk(dir);
|
|
250
|
+
return crypto.createHash("sha256").update(lines.join("\n")).digest("hex");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export interface WorkflowSchemaStamp {
|
|
254
|
+
/** Version of the CLI that generated the schema (`spec-driven@<base>`). */
|
|
255
|
+
base: string;
|
|
256
|
+
patch: number;
|
|
257
|
+
/** Syntactically valid previous default, else `null` (treated as absent). */
|
|
258
|
+
previousDefault: string | null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function parseStamp(yamlText: string): WorkflowSchemaStamp | null {
|
|
262
|
+
let parsed: unknown;
|
|
263
|
+
try {
|
|
264
|
+
parsed = YAML.parse(yamlText);
|
|
265
|
+
} catch {
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
const raw = (parsed as Record<string, unknown> | null)?.[STAMP_KEY];
|
|
269
|
+
if (!raw || typeof raw !== "object") return null;
|
|
270
|
+
const s = raw as Record<string, unknown>;
|
|
271
|
+
const m = typeof s.derivedFrom === "string" ? /^spec-driven@(.+)$/.exec(s.derivedFrom) : null;
|
|
272
|
+
if (!m || !semver.valid(m[1])) return null;
|
|
273
|
+
if (typeof s.patch !== "number" || !Number.isInteger(s.patch) || s.patch < 0) return null;
|
|
274
|
+
const prev = isKebabCaseName(s.previousDefault) && s.previousDefault !== WORKFLOW_SCHEMA_NAME ? s.previousDefault : null;
|
|
275
|
+
return { base: m[1], patch: s.patch, previousDefault: prev };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export type StampComparison = "current" | "outdated" | "newer" | "conflict";
|
|
279
|
+
|
|
280
|
+
/** Component-wise: base by semver, patch numerically. Never lexicographic. */
|
|
281
|
+
export function compareStamp(
|
|
282
|
+
stamp: { base: string; patch: number },
|
|
283
|
+
local: { base: string; patch: number },
|
|
284
|
+
): StampComparison {
|
|
285
|
+
const base = semver.compare(stamp.base, local.base);
|
|
286
|
+
const patch = Math.sign(stamp.patch - local.patch);
|
|
287
|
+
const newer = base > 0 || patch > 0;
|
|
288
|
+
const older = base < 0 || patch < 0;
|
|
289
|
+
if (newer && older) return "conflict";
|
|
290
|
+
if (newer) return "newer";
|
|
291
|
+
if (older) return "outdated";
|
|
292
|
+
return "current";
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export interface SchemaInspection {
|
|
296
|
+
generated: WorkflowSchemaGenerated;
|
|
297
|
+
stamp: WorkflowSchemaStamp | null;
|
|
298
|
+
/** Whole-directory fingerprint; `null` when the dir is absent or a symlink. */
|
|
299
|
+
fingerprint: string | null;
|
|
300
|
+
symlink: boolean;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export interface InspectOptions {
|
|
304
|
+
/** Version of the resolved CLI. */
|
|
305
|
+
localVersion: string;
|
|
306
|
+
/** CLI part for `newer`/`conflict`: does `schema validate` pass locally? Default: assumed valid. */
|
|
307
|
+
validateLocal?: (fingerprint: string) => Promise<boolean>;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Filesystem-only status of `<root>/openspec/schemas/pi-spec-driven` (no CLI spawn except via `validateLocal`). */
|
|
311
|
+
export async function inspectSchema(root: string, opts: InspectOptions): Promise<SchemaInspection> {
|
|
312
|
+
const dir = schemaDirOf(root);
|
|
313
|
+
const st = await lstatOrNull(dir);
|
|
314
|
+
if (!st) return { generated: "none", stamp: null, fingerprint: null, symlink: false };
|
|
315
|
+
if (st.isSymbolicLink()) return { generated: "unmanaged", stamp: null, fingerprint: null, symlink: true };
|
|
316
|
+
let stamp: WorkflowSchemaStamp | null = null;
|
|
317
|
+
if (st.isDirectory()) {
|
|
318
|
+
try {
|
|
319
|
+
stamp = parseStamp(await fsp.readFile(path.join(dir, "schema.yaml"), "utf8"));
|
|
320
|
+
} catch {
|
|
321
|
+
stamp = null;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const fingerprint = st.isDirectory() ? await fingerprintDir(dir).catch(() => null) : null;
|
|
325
|
+
if (!stamp || !fingerprint) return { generated: "unmanaged", stamp: null, fingerprint, symlink: false };
|
|
326
|
+
const localBase = semver.valid(opts.localVersion);
|
|
327
|
+
if (!localBase) return { generated: "incompatible", stamp, fingerprint, symlink: false };
|
|
328
|
+
let generated: WorkflowSchemaGenerated = compareStamp(stamp, { base: localBase, patch: CURRENT_PATCH });
|
|
329
|
+
if ((generated === "newer" || generated === "conflict") && opts.validateLocal) {
|
|
330
|
+
if (!(await opts.validateLocal(fingerprint))) generated = "incompatible";
|
|
331
|
+
}
|
|
332
|
+
return { generated, stamp, fingerprint, symlink: false };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async function runValidate(deps: WorkflowSchemaDeps, cwd: string, name: string, xdg?: string): Promise<boolean> {
|
|
336
|
+
const r = await deps.cli({ op: "validate", name }, { cwd, ...(xdg ? { xdgDataHome: xdg } : {}) });
|
|
337
|
+
return r.ok && parseJsonObject(r.stdout)?.valid === true;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Status for the main thread: `inspectSchema` + the `newer`/`conflict` local
|
|
342
|
+
* `schema validate` through the spawn semaphore, memoized by (cwd,
|
|
343
|
+
* fingerprint, CLI version) so it runs at most once per combination.
|
|
344
|
+
*/
|
|
345
|
+
export async function evaluateSchemaStatus(
|
|
346
|
+
root: string,
|
|
347
|
+
localVersion: string,
|
|
348
|
+
depsIn: Partial<WorkflowSchemaDeps> = {},
|
|
349
|
+
): Promise<WorkflowSchemaGenerated> {
|
|
350
|
+
return (await inspectWithValidate(root, localVersion, resolveDeps(depsIn))).generated;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* The `validateLocal` callback for `inspectSchema` / `computeWorkflowSchemaStatus`:
|
|
355
|
+
* runs `schema validate` through `deps.semaphore`, memoized by (cwd,
|
|
356
|
+
* fingerprint, CLI version) in `deps.validateMemo`.
|
|
357
|
+
*/
|
|
358
|
+
export function makeValidateLocal(
|
|
359
|
+
root: string,
|
|
360
|
+
localVersion: string,
|
|
361
|
+
depsIn: Partial<WorkflowSchemaDeps> = {},
|
|
362
|
+
): (fingerprint: string) => Promise<boolean> {
|
|
363
|
+
const deps = resolveDeps(depsIn);
|
|
364
|
+
return async (fingerprint) => {
|
|
365
|
+
const key = [root, fingerprint, localVersion].join("\0");
|
|
366
|
+
const memo = deps.validateMemo.get(key);
|
|
367
|
+
if (memo !== undefined) return memo;
|
|
368
|
+
const ok = await deps.semaphore.run(() => runValidate(deps, root, WORKFLOW_SCHEMA_NAME));
|
|
369
|
+
if (deps.validateMemo.size > 500) deps.validateMemo.clear();
|
|
370
|
+
deps.validateMemo.set(key, ok);
|
|
371
|
+
return ok;
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function inspectWithValidate(root: string, localVersion: string, deps: WorkflowSchemaDeps): Promise<SchemaInspection> {
|
|
376
|
+
return inspectSchema(root, { localVersion, validateLocal: makeValidateLocal(root, localVersion, deps) });
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// ── Config + change enumeration (filesystem only) ───────────────────────────
|
|
380
|
+
|
|
381
|
+
interface ConfigFile {
|
|
382
|
+
path: string;
|
|
383
|
+
doc: YAML.Document;
|
|
384
|
+
/** `schema:` value; `null` when the key is absent. */
|
|
385
|
+
configured: string | null;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** `config.yaml` wins over `config.yml`, as the CLI reads. `null` when neither exists; throws on unparseable YAML / non-string `schema`. */
|
|
389
|
+
async function readConfigFile(root: string): Promise<ConfigFile | null> {
|
|
390
|
+
for (const name of ["config.yaml", "config.yml"]) {
|
|
391
|
+
const p = path.join(root, "openspec", name);
|
|
392
|
+
let text: string;
|
|
393
|
+
try {
|
|
394
|
+
text = await fsp.readFile(p, "utf8");
|
|
395
|
+
} catch (err) {
|
|
396
|
+
if (errCode(err) === "ENOENT") continue;
|
|
397
|
+
throw err;
|
|
398
|
+
}
|
|
399
|
+
const doc = YAML.parseDocument(text);
|
|
400
|
+
if (doc.errors.length > 0) throw new Error(`${name} is not valid YAML: ${doc.errors[0].message}`);
|
|
401
|
+
const v: unknown = doc.get("schema");
|
|
402
|
+
if (v != null && typeof v !== "string") throw new Error(`${name} has a non-string \`schema:\``);
|
|
403
|
+
return { path: p, doc, configured: typeof v === "string" ? v : null };
|
|
404
|
+
}
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** Active changes as OpenSpec enumerates them: real directories only, no `archive/`, no dot-dirs, no symlinks. Sorted. */
|
|
409
|
+
async function enumerateActiveChanges(root: string): Promise<string[]> {
|
|
410
|
+
let entries: import("node:fs").Dirent[];
|
|
411
|
+
try {
|
|
412
|
+
entries = await fsp.readdir(changesDirOf(root), { withFileTypes: true });
|
|
413
|
+
} catch {
|
|
414
|
+
return [];
|
|
415
|
+
}
|
|
416
|
+
return entries
|
|
417
|
+
.filter((e) => e.isDirectory() && !e.isSymbolicLink() && e.name !== "archive" && !e.name.startsWith("."))
|
|
418
|
+
.map((e) => e.name)
|
|
419
|
+
.sort();
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** `schema:` of `<dir>/.openspec.yaml`: `undefined` = no file, `null` = file without a usable `schema:`. */
|
|
423
|
+
async function readChangeSchema(dir: string): Promise<string | null | undefined> {
|
|
424
|
+
let text: string;
|
|
425
|
+
try {
|
|
426
|
+
text = await fsp.readFile(path.join(dir, ".openspec.yaml"), "utf8");
|
|
427
|
+
} catch {
|
|
428
|
+
return undefined;
|
|
429
|
+
}
|
|
430
|
+
try {
|
|
431
|
+
const v = (YAML.parse(text) as Record<string, unknown> | null)?.schema;
|
|
432
|
+
return typeof v === "string" ? v : null;
|
|
433
|
+
} catch {
|
|
434
|
+
return null;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
export interface ComputeStatusOptions extends InspectOptions {
|
|
439
|
+
/** `<openspec package>/schemas`; `null` = unknown (the schema is then never reported missing). A function is resolved lazily, only when the config names a schema. */
|
|
440
|
+
packageSchemasDir: string | null | (() => Promise<string | null>);
|
|
441
|
+
/** Default: `userSchemasDir()`. */
|
|
442
|
+
userSchemasDirPath?: string;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Project-authored schema names under `<cwd>/openspec/schemas/`: real
|
|
447
|
+
* directories only (no symlinks), excluding dot-prefixed staging dirs,
|
|
448
|
+
* `*.fork-*` backups and the managed `pi-spec-driven`; sorted.
|
|
449
|
+
*/
|
|
450
|
+
async function listProjectSchemas(cwd: string): Promise<string[]> {
|
|
451
|
+
const dir = schemasDirOf(cwd);
|
|
452
|
+
let names: string[];
|
|
453
|
+
try {
|
|
454
|
+
names = await fsp.readdir(dir);
|
|
455
|
+
} catch {
|
|
456
|
+
return [];
|
|
457
|
+
}
|
|
458
|
+
const kept = await Promise.all(
|
|
459
|
+
names.map(async (name) => {
|
|
460
|
+
if (name.startsWith(".") || name.includes(".fork-") || name === WORKFLOW_SCHEMA_NAME) return null;
|
|
461
|
+
const st = await lstatOrNull(path.join(dir, name));
|
|
462
|
+
return st?.isDirectory() ? name : null;
|
|
463
|
+
}),
|
|
464
|
+
);
|
|
465
|
+
return kept.filter((n): n is string => n !== null).sort();
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* `OpenSpecData.workflowSchema` from files + the stamp (poll-worker safe: no
|
|
470
|
+
* CLI spawn except through `opts.validateLocal`). See "Workflow schema status
|
|
471
|
+
* is reported separately from readiness". Runs on the poll hot path, so the
|
|
472
|
+
* independent filesystem reads are issued concurrently (one `.openspec.yaml`
|
|
473
|
+
* read per change, all in flight at once).
|
|
474
|
+
*/
|
|
475
|
+
export async function computeWorkflowSchemaStatus(
|
|
476
|
+
cwd: string,
|
|
477
|
+
opts: ComputeStatusOptions,
|
|
478
|
+
): Promise<OpenSpecWorkflowSchemaStatus> {
|
|
479
|
+
const configuredP = readConfigFile(cwd).then(
|
|
480
|
+
(c) => c?.configured ?? null,
|
|
481
|
+
() => null,
|
|
482
|
+
);
|
|
483
|
+
const inspectP = inspectSchema(cwd, opts);
|
|
484
|
+
const missingP = configuredP.then(async (configured) => {
|
|
485
|
+
if (configured === null) return false;
|
|
486
|
+
const pkgDir = typeof opts.packageSchemasDir === "function" ? await opts.packageSchemasDir() : opts.packageSchemasDir;
|
|
487
|
+
if (pkgDir === null) return false;
|
|
488
|
+
const dirs = [schemasDirOf(cwd), opts.userSchemasDirPath ?? userSchemasDir(), pkgDir];
|
|
489
|
+
const found = await Promise.all(dirs.map(async (d) => !!(await lstatOrNull(path.join(d, configured, "schema.yaml")))));
|
|
490
|
+
return !found.some(Boolean);
|
|
491
|
+
});
|
|
492
|
+
const pinsP = enumerateActiveChanges(cwd).then((names) =>
|
|
493
|
+
Promise.all(names.map(async (name) => ({ name, pinned: await readChangeSchema(path.join(changesDirOf(cwd), name)) }))),
|
|
494
|
+
);
|
|
495
|
+
const [configured, { generated }, missing, pins, projectSchemas] = await Promise.all([
|
|
496
|
+
configuredP,
|
|
497
|
+
inspectP,
|
|
498
|
+
missingP,
|
|
499
|
+
pinsP,
|
|
500
|
+
listProjectSchemas(cwd),
|
|
501
|
+
]);
|
|
502
|
+
|
|
503
|
+
const unpinnedChanges: string[] = [];
|
|
504
|
+
const affectedChanges: string[] = [];
|
|
505
|
+
for (const { name, pinned } of pins) {
|
|
506
|
+
if (pinned === undefined) {
|
|
507
|
+
if (configured === WORKFLOW_SCHEMA_NAME) {
|
|
508
|
+
unpinnedChanges.push(name);
|
|
509
|
+
affectedChanges.push(name);
|
|
510
|
+
}
|
|
511
|
+
} else if (pinned === WORKFLOW_SCHEMA_NAME) {
|
|
512
|
+
affectedChanges.push(name);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
return { configured, generated, missing, unpinnedChanges, affectedChanges, projectSchemas };
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// ── Patch v1 + stamp ────────────────────────────────────────────────────────
|
|
519
|
+
|
|
520
|
+
type PatchResult = { ok: true; text: string } | { ok: false; error: string };
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Comment-preserving patch v1 + stamp. Aborts when the design-instruction
|
|
524
|
+
* anchor line is not found exactly once (a stamp never claims an unapplied patch).
|
|
525
|
+
*/
|
|
526
|
+
function patchAndStampSchemaYaml(
|
|
527
|
+
yamlText: string,
|
|
528
|
+
stamp: { cliVersion: string; previousDefault: string },
|
|
529
|
+
): PatchResult {
|
|
530
|
+
const doc = YAML.parseDocument(yamlText);
|
|
531
|
+
if (doc.errors.length > 0) return { ok: false, error: `forked schema.yaml is not valid YAML: ${doc.errors[0].message}` };
|
|
532
|
+
const artifacts = doc.get("artifacts");
|
|
533
|
+
const design = YAML.isSeq(artifacts)
|
|
534
|
+
? artifacts.items.find((a) => YAML.isMap(a) && a.get("id") === "design")
|
|
535
|
+
: undefined;
|
|
536
|
+
const node = YAML.isMap(design) ? design.get("instruction", true) : undefined;
|
|
537
|
+
if (!YAML.isScalar(node) || typeof node.value !== "string") {
|
|
538
|
+
return { ok: false, error: "patch anchor not found: design artifact has no instruction" };
|
|
539
|
+
}
|
|
540
|
+
const lines = node.value.split("\n");
|
|
541
|
+
const hits = lines.filter((l) => l.trim() === DESIGN_ANCHOR).length;
|
|
542
|
+
if (hits !== 1) {
|
|
543
|
+
return { ok: false, error: `patch anchor not found exactly once (${hits}): "${DESIGN_ANCHOR}"` };
|
|
544
|
+
}
|
|
545
|
+
node.value = lines
|
|
546
|
+
.map((l) => (l.trim() === DESIGN_ANCHOR ? l.slice(0, l.indexOf(DESIGN_ANCHOR)) + DESIGN_REPLACEMENT : l))
|
|
547
|
+
.join("\n");
|
|
548
|
+
doc.set(
|
|
549
|
+
STAMP_KEY,
|
|
550
|
+
doc.createNode({
|
|
551
|
+
derivedFrom: `${BASE_SCHEMA}@${stamp.cliVersion}`,
|
|
552
|
+
patch: CURRENT_PATCH,
|
|
553
|
+
previousDefault: stamp.previousDefault,
|
|
554
|
+
}),
|
|
555
|
+
);
|
|
556
|
+
return { ok: true, text: doc.toString({ lineWidth: 0 }) };
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// ── Generation + staged swap ────────────────────────────────────────────────
|
|
560
|
+
|
|
561
|
+
export interface GenerateOptions {
|
|
562
|
+
/** Project root (realpath'd by the caller). */
|
|
563
|
+
root: string;
|
|
564
|
+
previousDefault: string;
|
|
565
|
+
/**
|
|
566
|
+
* Whole-directory fingerprint of the existing `pi-spec-driven/` read when its
|
|
567
|
+
* status was read; `null` = expected absent; `undefined` = read it now.
|
|
568
|
+
*/
|
|
569
|
+
expectedFingerprint?: string | null;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
export type GenerateResult =
|
|
573
|
+
| { ok: true; warnings: string[] }
|
|
574
|
+
| { ok: false; error: string };
|
|
575
|
+
|
|
576
|
+
export async function generateWorkflowSchema(
|
|
577
|
+
opts: GenerateOptions,
|
|
578
|
+
depsIn: Partial<WorkflowSchemaDeps> = {},
|
|
579
|
+
): Promise<GenerateResult> {
|
|
580
|
+
const deps = resolveDeps(depsIn);
|
|
581
|
+
const { root, previousDefault } = opts;
|
|
582
|
+
const schemasDir = schemasDirOf(root);
|
|
583
|
+
const target = schemaDirOf(root);
|
|
584
|
+
const scratch = await fsp.mkdtemp(path.join(deps.tmpDir, "pi-wfs-"));
|
|
585
|
+
let staging: string | null = null;
|
|
586
|
+
try {
|
|
587
|
+
const scratchRoot = path.join(scratch, "root");
|
|
588
|
+
const xdg = path.join(scratch, "xdg");
|
|
589
|
+
await fsp.mkdir(path.join(scratchRoot, "openspec", "schemas"), { recursive: true });
|
|
590
|
+
await fsp.mkdir(xdg, { recursive: true });
|
|
591
|
+
const ctx: CliCtx = { cwd: scratchRoot, xdgDataHome: xdg };
|
|
592
|
+
|
|
593
|
+
const ver = await deps.cli({ op: "version" }, ctx);
|
|
594
|
+
const cliVersion = ver.ok ? ver.stdout.trim() : "";
|
|
595
|
+
if (!ver.ok || !semver.valid(cliVersion)) return { ok: false, error: "cannot determine the OpenSpec CLI version" };
|
|
596
|
+
|
|
597
|
+
const which = await deps.cli({ op: "which", name: BASE_SCHEMA }, ctx);
|
|
598
|
+
const w = parseJsonObject(which.stdout);
|
|
599
|
+
if (!which.ok || !w || w.source !== "package" || !Array.isArray(w.shadows) || w.shadows.length > 0) {
|
|
600
|
+
return { ok: false, error: `base schema "${BASE_SCHEMA}" does not resolve to the package built-in without shadows` };
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
const fork = await deps.cli({ op: "fork", source: BASE_SCHEMA, name: WORKFLOW_SCHEMA_NAME }, ctx);
|
|
604
|
+
if (!fork.ok) return { ok: false, error: `schema fork failed: ${fork.message} ${fork.stderr}`.trim() };
|
|
605
|
+
|
|
606
|
+
const scratchSchema = path.join(scratchRoot, "openspec", "schemas", WORKFLOW_SCHEMA_NAME);
|
|
607
|
+
const yamlPath = path.join(scratchSchema, "schema.yaml");
|
|
608
|
+
const patched = patchAndStampSchemaYaml(await fsp.readFile(yamlPath, "utf8"), { cliVersion, previousDefault });
|
|
609
|
+
if (!patched.ok) return { ok: false, error: patched.error };
|
|
610
|
+
await fsp.writeFile(yamlPath, patched.text);
|
|
611
|
+
|
|
612
|
+
if (!(await runValidate(deps, scratchRoot, WORKFLOW_SCHEMA_NAME, xdg))) {
|
|
613
|
+
return { ok: false, error: "generated schema failed `openspec schema validate`" };
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// Copy (not rename): avoids EXDEV across volumes.
|
|
617
|
+
await fsp.mkdir(schemasDir, { recursive: true });
|
|
618
|
+
staging = path.join(schemasDir, `.fork-staging-${deps.random()}`);
|
|
619
|
+
try {
|
|
620
|
+
await deps.fs.cp(scratchSchema, staging);
|
|
621
|
+
} catch (err) {
|
|
622
|
+
await deps.fs.rm(staging).catch(() => undefined);
|
|
623
|
+
staging = null;
|
|
624
|
+
return { ok: false, error: `copying the generated schema failed: ${errMsg(err)}` };
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
const expected = opts.expectedFingerprint === undefined ? await fingerprintDir(target) : opts.expectedFingerprint;
|
|
628
|
+
const current = await fingerprintDir(target);
|
|
629
|
+
if (current !== expected) {
|
|
630
|
+
return { ok: false, error: `${rel(root, target)} changed since its status was read; aborting before the swap` };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const warnings: string[] = [];
|
|
634
|
+
let backup: string | null = null;
|
|
635
|
+
if (current !== null || (await lstatOrNull(target))) {
|
|
636
|
+
backup = path.join(schemasDir, `${WORKFLOW_SCHEMA_NAME}.fork-backup-${deps.pid}-${deps.now()}`);
|
|
637
|
+
try {
|
|
638
|
+
await renameWithRetry(deps, target, backup);
|
|
639
|
+
} catch (err) {
|
|
640
|
+
return { ok: false, error: `could not move the existing schema aside: ${errMsg(err)}` };
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
try {
|
|
644
|
+
await renameWithRetry(deps, staging, target);
|
|
645
|
+
staging = null;
|
|
646
|
+
} catch (err) {
|
|
647
|
+
if (backup) {
|
|
648
|
+
try {
|
|
649
|
+
await renameWithRetry(deps, backup, target);
|
|
650
|
+
} catch (restoreErr) {
|
|
651
|
+
return {
|
|
652
|
+
ok: false,
|
|
653
|
+
error: `swap failed (${errMsg(err)}) and the restore failed (${errMsg(restoreErr)}); the previous schema is kept at ${backup}`,
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
return { ok: false, error: `swap failed: ${errMsg(err)}` };
|
|
658
|
+
}
|
|
659
|
+
if (backup) {
|
|
660
|
+
try {
|
|
661
|
+
await deps.fs.rm(backup);
|
|
662
|
+
} catch (err) {
|
|
663
|
+
warnings.push(`could not delete the previous schema backup ${backup}: ${errMsg(err)}`);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return { ok: true, warnings };
|
|
667
|
+
} catch (err) {
|
|
668
|
+
return { ok: false, error: `workflow schema generation failed: ${errMsg(err)}` };
|
|
669
|
+
} finally {
|
|
670
|
+
if (staging) await deps.fs.rm(staging).catch(() => undefined);
|
|
671
|
+
await fsp.rm(scratch, { recursive: true, force: true }).catch(() => undefined);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// ── Schema-name resolution ──────────────────────────────────────────────────
|
|
676
|
+
|
|
677
|
+
/** Resolvable from the project dir or the package with an EMPTY `XDG_DATA_HOME` (user-level schemas never count). */
|
|
678
|
+
async function defaultResolveSchema(cli: CliRunner, root: string, name: string): Promise<boolean> {
|
|
679
|
+
const xdg = await fsp.mkdtemp(path.join(os.tmpdir(), "pi-wfs-xdg-"));
|
|
680
|
+
try {
|
|
681
|
+
const r = await cli({ op: "which", name }, { cwd: root, xdgDataHome: xdg });
|
|
682
|
+
const w = parseJsonObject(r.stdout);
|
|
683
|
+
return r.ok && (w?.source === "project" || w?.source === "package");
|
|
684
|
+
} catch {
|
|
685
|
+
return false;
|
|
686
|
+
} finally {
|
|
687
|
+
await fsp.rm(xdg, { recursive: true, force: true }).catch(() => undefined);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// ── Actions ─────────────────────────────────────────────────────────────────
|
|
692
|
+
|
|
693
|
+
export type WorkflowSchemaAction = "enable" | "disable" | "update" | "adopt" | "pin" | "remove";
|
|
694
|
+
|
|
695
|
+
export interface WorkflowSchemaRequest {
|
|
696
|
+
cwd: string;
|
|
697
|
+
action: WorkflowSchemaAction;
|
|
698
|
+
confirm?: boolean;
|
|
699
|
+
pinTo?: string;
|
|
700
|
+
changes?: string[];
|
|
701
|
+
previousDefault?: string;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
export interface WorkflowSchemaResult {
|
|
705
|
+
ok: boolean;
|
|
706
|
+
status: WorkflowSchemaGenerated;
|
|
707
|
+
configured: string | null;
|
|
708
|
+
/** Paths relative to the project root (forward slashes). */
|
|
709
|
+
written: string[];
|
|
710
|
+
/** Pin: change names left alone. */
|
|
711
|
+
skipped?: string[];
|
|
712
|
+
warnings?: string[];
|
|
713
|
+
worktree: { isWorktree: boolean; branch: string | null };
|
|
714
|
+
error?: string;
|
|
715
|
+
/** A step failed after earlier steps wrote; re-running enable completes it. */
|
|
716
|
+
partial?: boolean;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
type Verdict = { verdict: "run" } | { verdict: "noop"; reason: string } | { verdict: "refuse"; reason: string };
|
|
720
|
+
|
|
721
|
+
/** The "Actions are allowed only in defined states" table. `noop` = nothing to do, reported as success. */
|
|
722
|
+
export function checkActionState(
|
|
723
|
+
action: WorkflowSchemaAction,
|
|
724
|
+
configured: string | null,
|
|
725
|
+
generated: WorkflowSchemaGenerated,
|
|
726
|
+
symlink = false,
|
|
727
|
+
): Verdict {
|
|
728
|
+
const enabled = configured === WORKFLOW_SCHEMA_NAME;
|
|
729
|
+
const refuse = (reason: string): Verdict => ({ verdict: "refuse", reason });
|
|
730
|
+
switch (action) {
|
|
731
|
+
case "enable":
|
|
732
|
+
if (enabled) return { verdict: "noop", reason: "already enabled" };
|
|
733
|
+
return ["none", "current", "outdated", "newer", "conflict"].includes(generated)
|
|
734
|
+
? { verdict: "run" }
|
|
735
|
+
: refuse(`cannot enable while the schema is ${generated}`);
|
|
736
|
+
case "disable":
|
|
737
|
+
return enabled ? { verdict: "run" } : { verdict: "noop", reason: `the default is ${configured ?? "spec-driven"}, not ${WORKFLOW_SCHEMA_NAME}` };
|
|
738
|
+
case "update":
|
|
739
|
+
return generated === "outdated" || generated === "current" || (generated === "none" && enabled)
|
|
740
|
+
? { verdict: "run" }
|
|
741
|
+
: refuse(`cannot update while the schema is ${generated}`);
|
|
742
|
+
case "adopt":
|
|
743
|
+
if (symlink) return refuse("cannot adopt a symlinked schema directory");
|
|
744
|
+
return generated === "unmanaged" ? { verdict: "run" } : refuse(`adopt needs an unmanaged schema (it is ${generated})`);
|
|
745
|
+
case "pin":
|
|
746
|
+
return enabled ? { verdict: "run" } : refuse(`pin is only allowed while the default is ${WORKFLOW_SCHEMA_NAME}`);
|
|
747
|
+
case "remove":
|
|
748
|
+
return ["current", "outdated", "newer", "conflict", "incompatible"].includes(generated)
|
|
749
|
+
? { verdict: "run" }
|
|
750
|
+
: refuse(`cannot remove while the schema is ${generated}`);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
interface Guarded {
|
|
755
|
+
root: string;
|
|
756
|
+
deps: WorkflowSchemaDeps;
|
|
757
|
+
req: WorkflowSchemaRequest;
|
|
758
|
+
config: ConfigFile | null;
|
|
759
|
+
localVersion: string;
|
|
760
|
+
info: SchemaInspection;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
interface Outcome {
|
|
764
|
+
ok: boolean;
|
|
765
|
+
written: string[];
|
|
766
|
+
skipped?: string[];
|
|
767
|
+
warnings?: string[];
|
|
768
|
+
error?: string;
|
|
769
|
+
partial?: boolean;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
const refused = (error: string, extra: Partial<Outcome> = {}): Outcome => ({ ok: false, written: [], error, ...extra });
|
|
773
|
+
|
|
774
|
+
/** Fresh `status --all` root checks + symlink refusals. Returns the canonical root or an error. */
|
|
775
|
+
async function writeGuard(cwd: string, deps: WorkflowSchemaDeps): Promise<{ root: string } | { error: string }> {
|
|
776
|
+
let real: string;
|
|
777
|
+
try {
|
|
778
|
+
real = await fsp.realpath(cwd);
|
|
779
|
+
} catch {
|
|
780
|
+
return { error: "cwd does not exist" };
|
|
781
|
+
}
|
|
782
|
+
const r = await deps.cli({ op: "statusAll" }, { cwd: real });
|
|
783
|
+
const top = parseJsonObject(r.stdout);
|
|
784
|
+
const root = top?.root;
|
|
785
|
+
if (!root || typeof root !== "object") {
|
|
786
|
+
return { error: "the OpenSpec CLI reported no root (a CLI without `status --all` cannot write)" };
|
|
787
|
+
}
|
|
788
|
+
const { path: rootPath, source } = root as { path?: unknown; source?: unknown };
|
|
789
|
+
if (source !== "nearest") return { error: `OpenSpec root source is "${String(source)}", not "nearest"; refusing to write` };
|
|
790
|
+
if (typeof rootPath !== "string") return { error: "OpenSpec root has no path" };
|
|
791
|
+
let rootReal: string;
|
|
792
|
+
try {
|
|
793
|
+
rootReal = await fsp.realpath(rootPath);
|
|
794
|
+
} catch {
|
|
795
|
+
return { error: "OpenSpec root path does not exist" };
|
|
796
|
+
}
|
|
797
|
+
if (rootReal !== real) return { error: `OpenSpec root ${rootReal} is not the project directory ${real}` };
|
|
798
|
+
|
|
799
|
+
const os_ = await lstatOrNull(path.join(real, "openspec"));
|
|
800
|
+
if (!os_ || os_.isSymbolicLink() || !os_.isDirectory()) return { error: "openspec/ is missing or a symlink" };
|
|
801
|
+
for (const p of ["changes", "schemas", "config.yaml", "config.yml"]) {
|
|
802
|
+
const st = await lstatOrNull(path.join(real, "openspec", p));
|
|
803
|
+
if (st?.isSymbolicLink()) return { error: `openspec/${p} is a symlink; refusing to write` };
|
|
804
|
+
}
|
|
805
|
+
return { root: real };
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/** Every write target must stay below `<root>/openspec/` (the parent is realpath'd; symlinked structure dirs are already refused). */
|
|
809
|
+
async function assertContained(root: string, target: string): Promise<void> {
|
|
810
|
+
const base = path.join(root, "openspec") + path.sep;
|
|
811
|
+
const parent = await fsp.realpath(path.dirname(target));
|
|
812
|
+
if (!(parent + path.sep).startsWith(base)) throw new Error(`write target escapes ${base}: ${target}`);
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
async function validateSchemaName(
|
|
816
|
+
c: Pick<Guarded, "root" | "deps">,
|
|
817
|
+
name: unknown,
|
|
818
|
+
opts: { allowPi?: boolean; label: string },
|
|
819
|
+
): Promise<string | null> {
|
|
820
|
+
if (!isKebabCaseName(name)) return `${opts.label} must be a kebab-case schema id`;
|
|
821
|
+
if (!opts.allowPi && name === WORKFLOW_SCHEMA_NAME) return `${opts.label} cannot be ${WORKFLOW_SCHEMA_NAME}`;
|
|
822
|
+
if (!(await c.deps.resolveSchema(c.root, name))) {
|
|
823
|
+
return `${opts.label} "${name}" does not resolve from the project or package schemas (user-level schemas cannot be committed defaults)`;
|
|
824
|
+
}
|
|
825
|
+
return null;
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
async function worktreeInfo(root: string): Promise<{ isWorktree: boolean; branch: string | null }> {
|
|
829
|
+
try {
|
|
830
|
+
const dotGit = path.join(root, ".git");
|
|
831
|
+
const st = await fsp.lstat(dotGit);
|
|
832
|
+
let gitDir = dotGit;
|
|
833
|
+
let isWorktree = false;
|
|
834
|
+
if (st.isFile()) {
|
|
835
|
+
const m = /^gitdir:\s*(.+)$/m.exec(await fsp.readFile(dotGit, "utf8"));
|
|
836
|
+
if (!m) return { isWorktree: false, branch: null };
|
|
837
|
+
gitDir = path.resolve(root, m[1].trim());
|
|
838
|
+
isWorktree = /[\\/]worktrees[\\/]/.test(gitDir);
|
|
839
|
+
}
|
|
840
|
+
const head = (await fsp.readFile(path.join(gitDir, "HEAD"), "utf8")).trim();
|
|
841
|
+
const b = /^ref: refs\/heads\/(.+)$/.exec(head);
|
|
842
|
+
return { isWorktree, branch: b ? b[1] : null };
|
|
843
|
+
} catch {
|
|
844
|
+
return { isWorktree: false, branch: null };
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/** Exclusive-create `.openspec.yaml` for each name lacking one. Throws on a real write error (caller reports partial). */
|
|
849
|
+
async function createPins(
|
|
850
|
+
c: Guarded,
|
|
851
|
+
names: string[],
|
|
852
|
+
schemaName: string,
|
|
853
|
+
out: { written: string[]; skipped: string[] },
|
|
854
|
+
): Promise<void> {
|
|
855
|
+
const data = YAML.stringify({ schema: schemaName });
|
|
856
|
+
const changesReal = await fsp.realpath(changesDirOf(c.root)).catch(() => changesDirOf(c.root));
|
|
857
|
+
for (const name of names) {
|
|
858
|
+
const dir = path.join(changesDirOf(c.root), name);
|
|
859
|
+
const file = path.join(dir, ".openspec.yaml");
|
|
860
|
+
const st = await lstatOrNull(dir);
|
|
861
|
+
if (!st || !st.isDirectory() || st.isSymbolicLink() || (await fsp.realpath(dir)) !== path.join(changesReal, name)) {
|
|
862
|
+
out.skipped.push(name);
|
|
863
|
+
continue;
|
|
864
|
+
}
|
|
865
|
+
if (await lstatOrNull(file)) {
|
|
866
|
+
out.skipped.push(name);
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
869
|
+
await assertContained(c.root, file);
|
|
870
|
+
try {
|
|
871
|
+
await c.deps.fs.writeExclusive(file, data);
|
|
872
|
+
out.written.push(rel(c.root, file));
|
|
873
|
+
} catch (err) {
|
|
874
|
+
if (errCode(err) === "EEXIST") out.skipped.push(name);
|
|
875
|
+
else throw err;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
async function switchDefault(c: Guarded, schemaName: string): Promise<string> {
|
|
881
|
+
const cfg = c.config;
|
|
882
|
+
if (!cfg) throw new Error("no config file");
|
|
883
|
+
cfg.doc.set("schema", schemaName);
|
|
884
|
+
await assertContained(c.root, cfg.path);
|
|
885
|
+
await c.deps.fs.writeAtomic(cfg.path, cfg.doc.toString({ lineWidth: 0 }));
|
|
886
|
+
return rel(c.root, cfg.path);
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
async function generateStep(c: Guarded, previousDefault: string): Promise<{ error: string } | { warnings: string[] }> {
|
|
890
|
+
const g = await generateWorkflowSchema(
|
|
891
|
+
{ root: c.root, previousDefault, expectedFingerprint: c.info.fingerprint },
|
|
892
|
+
c.deps,
|
|
893
|
+
);
|
|
894
|
+
return g.ok ? { warnings: g.warnings } : { error: g.error };
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
const SCHEMA_REL = (root: string): string => rel(root, schemaDirOf(root));
|
|
898
|
+
|
|
899
|
+
async function doEnable(c: Guarded): Promise<Outcome> {
|
|
900
|
+
if (!c.config) return refused("openspec/config.yaml or config.yml is required to enable the workflow schema");
|
|
901
|
+
const prev = c.config.configured ?? BASE_SCHEMA;
|
|
902
|
+
const bad = await validateSchemaName(c, prev, { label: "the current default schema" });
|
|
903
|
+
if (bad) return refused(bad);
|
|
904
|
+
|
|
905
|
+
const written: string[] = [];
|
|
906
|
+
const warnings: string[] = [];
|
|
907
|
+
if (c.info.generated === "none") {
|
|
908
|
+
const g = await generateStep(c, prev);
|
|
909
|
+
if ("error" in g) return refused(g.error);
|
|
910
|
+
warnings.push(...g.warnings);
|
|
911
|
+
written.push(SCHEMA_REL(c.root));
|
|
912
|
+
} else if (c.info.stamp?.previousDefault !== prev) {
|
|
913
|
+
return refused(
|
|
914
|
+
`the schema stamp records previousDefault ${c.info.stamp?.previousDefault ?? "(none)"} but the config default is ${prev}; run Update with previousDefault: ${prev}`,
|
|
915
|
+
);
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
const pins = { written: [] as string[], skipped: [] as string[] };
|
|
919
|
+
try {
|
|
920
|
+
const toPin: string[] = [];
|
|
921
|
+
for (const name of await enumerateActiveChanges(c.root)) {
|
|
922
|
+
if (!(await lstatOrNull(path.join(changesDirOf(c.root), name, ".openspec.yaml")))) toPin.push(name);
|
|
923
|
+
}
|
|
924
|
+
await createPins(c, toPin, prev, pins);
|
|
925
|
+
written.push(...pins.written);
|
|
926
|
+
written.push(await switchDefault(c, WORKFLOW_SCHEMA_NAME));
|
|
927
|
+
} catch (err) {
|
|
928
|
+
written.push(...pins.written);
|
|
929
|
+
return { ok: false, written, warnings, partial: written.length > 0, error: `enable stopped part-way: ${errMsg(err)}; re-run enable to complete` };
|
|
930
|
+
}
|
|
931
|
+
return { ok: true, written, warnings, ...(pins.skipped.length ? { skipped: pins.skipped } : {}) };
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
async function doDisable(c: Guarded): Promise<Outcome> {
|
|
935
|
+
if (!c.config) return refused("no config file");
|
|
936
|
+
const stampPrev = c.info.generated === "none" || c.info.generated === "unmanaged" ? null : c.info.stamp?.previousDefault ?? null;
|
|
937
|
+
let target: string;
|
|
938
|
+
if (stampPrev) {
|
|
939
|
+
target = stampPrev;
|
|
940
|
+
} else {
|
|
941
|
+
if (!c.req.previousDefault || c.req.confirm !== true) {
|
|
942
|
+
return refused("the schema has no usable previousDefault; Disable needs previousDefault and confirm: true");
|
|
943
|
+
}
|
|
944
|
+
target = c.req.previousDefault;
|
|
945
|
+
}
|
|
946
|
+
const bad = await validateSchemaName(c, target, { label: "previousDefault" });
|
|
947
|
+
if (bad) return refused(bad);
|
|
948
|
+
try {
|
|
949
|
+
return { ok: true, written: [await switchDefault(c, target)] };
|
|
950
|
+
} catch (err) {
|
|
951
|
+
return refused(errMsg(err));
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
async function doUpdate(c: Guarded): Promise<Outcome> {
|
|
956
|
+
const prev = c.req.previousDefault ?? c.info.stamp?.previousDefault ?? undefined;
|
|
957
|
+
if (!prev) return refused("update needs previousDefault (the schema has no usable stamp value)");
|
|
958
|
+
const bad = await validateSchemaName(c, prev, { label: "previousDefault" });
|
|
959
|
+
if (bad) return refused(bad);
|
|
960
|
+
const g = await generateStep(c, prev);
|
|
961
|
+
if ("error" in g) return refused(g.error);
|
|
962
|
+
return { ok: true, written: [SCHEMA_REL(c.root)], warnings: g.warnings };
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
async function doAdopt(c: Guarded): Promise<Outcome> {
|
|
966
|
+
if (c.req.confirm !== true) return refused("adopt replaces the unmanaged schema directory (hand customizations are discarded); confirm: true required");
|
|
967
|
+
if (!c.req.previousDefault) return refused("adopt needs previousDefault");
|
|
968
|
+
const bad = await validateSchemaName(c, c.req.previousDefault, { label: "previousDefault" });
|
|
969
|
+
if (bad) return refused(bad);
|
|
970
|
+
const g = await generateStep(c, c.req.previousDefault);
|
|
971
|
+
if ("error" in g) return refused(g.error);
|
|
972
|
+
return { ok: true, written: [SCHEMA_REL(c.root)], warnings: g.warnings };
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
async function doPin(c: Guarded): Promise<Outcome> {
|
|
976
|
+
const stampPrev = c.info.stamp?.previousDefault ?? null;
|
|
977
|
+
const pinTo = c.req.pinTo;
|
|
978
|
+
if (pinTo !== WORKFLOW_SCHEMA_NAME && pinTo !== stampPrev) {
|
|
979
|
+
return refused(`pinTo must be ${WORKFLOW_SCHEMA_NAME} or the stamp's previousDefault (${stampPrev ?? "none"})`);
|
|
980
|
+
}
|
|
981
|
+
const bad = await validateSchemaName(c, pinTo, { allowPi: true, label: "pinTo" });
|
|
982
|
+
if (bad) return refused(bad);
|
|
983
|
+
const active = await enumerateActiveChanges(c.root);
|
|
984
|
+
const requested = c.req.changes ?? active;
|
|
985
|
+
const unknown = requested.filter((n) => !active.includes(n));
|
|
986
|
+
if (unknown.length > 0) return refused(`unknown change(s): ${unknown.join(", ")}`);
|
|
987
|
+
const pins = { written: [] as string[], skipped: [] as string[] };
|
|
988
|
+
try {
|
|
989
|
+
await createPins(c, requested, pinTo as string, pins);
|
|
990
|
+
} catch (err) {
|
|
991
|
+
return { ok: false, written: pins.written, skipped: pins.skipped, partial: pins.written.length > 0, error: errMsg(err) };
|
|
992
|
+
}
|
|
993
|
+
return { ok: true, written: pins.written, skipped: pins.skipped };
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
async function doRemove(c: Guarded): Promise<Outcome> {
|
|
997
|
+
if (c.config?.configured === WORKFLOW_SCHEMA_NAME) return refused("the config default is still pi-spec-driven; disable first");
|
|
998
|
+
const active: string[] = [];
|
|
999
|
+
for (const name of await enumerateActiveChanges(c.root)) {
|
|
1000
|
+
if ((await readChangeSchema(path.join(changesDirOf(c.root), name))) === WORKFLOW_SCHEMA_NAME) active.push(name);
|
|
1001
|
+
}
|
|
1002
|
+
if (active.length > 0) return refused(`active change(s) still pin ${WORKFLOW_SCHEMA_NAME}: ${active.join(", ")}`);
|
|
1003
|
+
|
|
1004
|
+
const archived: string[] = [];
|
|
1005
|
+
const archiveDir = path.join(changesDirOf(c.root), "archive");
|
|
1006
|
+
for (const e of await fsp.readdir(archiveDir, { withFileTypes: true }).catch(() => [])) {
|
|
1007
|
+
if (e.isDirectory() && !e.isSymbolicLink() && (await readChangeSchema(path.join(archiveDir, e.name))) === WORKFLOW_SCHEMA_NAME) {
|
|
1008
|
+
archived.push(e.name);
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
const warnings = ["Unmerged branches may still pin pi-spec-driven; they break once this removal lands."];
|
|
1012
|
+
if (archived.length > 0) {
|
|
1013
|
+
const w = `archived change(s) reference ${WORKFLOW_SCHEMA_NAME}: ${archived.join(", ")}`;
|
|
1014
|
+
if (c.req.confirm !== true) return refused(`${w}; confirm: true required`, { warnings: [w, ...warnings] });
|
|
1015
|
+
warnings.unshift(w);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
const target = schemaDirOf(c.root);
|
|
1019
|
+
const backup = path.join(schemasDirOf(c.root), `${WORKFLOW_SCHEMA_NAME}.fork-backup-${c.deps.pid}-${c.deps.now()}`);
|
|
1020
|
+
try {
|
|
1021
|
+
await renameWithRetry(c.deps, target, backup);
|
|
1022
|
+
} catch (err) {
|
|
1023
|
+
return refused(`could not remove the schema: ${errMsg(err)}`, { warnings });
|
|
1024
|
+
}
|
|
1025
|
+
try {
|
|
1026
|
+
await c.deps.fs.rm(backup);
|
|
1027
|
+
} catch (err) {
|
|
1028
|
+
warnings.push(`removed, but could not delete the backup ${backup}: ${errMsg(err)}`);
|
|
1029
|
+
}
|
|
1030
|
+
return { ok: true, written: [SCHEMA_REL(c.root)], warnings };
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
const ACTIONS: Record<WorkflowSchemaAction, (c: Guarded) => Promise<Outcome>> = {
|
|
1034
|
+
enable: doEnable,
|
|
1035
|
+
disable: doDisable,
|
|
1036
|
+
update: doUpdate,
|
|
1037
|
+
adopt: doAdopt,
|
|
1038
|
+
pin: doPin,
|
|
1039
|
+
remove: doRemove,
|
|
1040
|
+
};
|
|
1041
|
+
|
|
1042
|
+
async function snapshot(
|
|
1043
|
+
root: string,
|
|
1044
|
+
deps: WorkflowSchemaDeps,
|
|
1045
|
+
localVersion: string | null,
|
|
1046
|
+
): Promise<{ status: WorkflowSchemaGenerated; configured: string | null }> {
|
|
1047
|
+
let configured: string | null = null;
|
|
1048
|
+
try {
|
|
1049
|
+
configured = (await readConfigFile(root))?.configured ?? null;
|
|
1050
|
+
} catch {
|
|
1051
|
+
configured = null;
|
|
1052
|
+
}
|
|
1053
|
+
try {
|
|
1054
|
+
const info = localVersion
|
|
1055
|
+
? await inspectWithValidate(root, localVersion, deps)
|
|
1056
|
+
: await inspectSchema(root, { localVersion: "" });
|
|
1057
|
+
return { status: info.generated, configured };
|
|
1058
|
+
} catch {
|
|
1059
|
+
return { status: "none", configured };
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* Single dispatcher for all six actions: write guard → state table → action →
|
|
1065
|
+
* forced refresh. Refusals carry the current status; nothing is written on a
|
|
1066
|
+
* refusal except by an action that reports `partial`.
|
|
1067
|
+
*/
|
|
1068
|
+
export async function runWorkflowSchemaAction(
|
|
1069
|
+
req: WorkflowSchemaRequest,
|
|
1070
|
+
depsIn: Partial<WorkflowSchemaDeps> = {},
|
|
1071
|
+
): Promise<WorkflowSchemaResult> {
|
|
1072
|
+
const deps = resolveDeps(depsIn);
|
|
1073
|
+
let root = req.cwd;
|
|
1074
|
+
let localVersion: string | null = null;
|
|
1075
|
+
|
|
1076
|
+
const finish = async (o: Outcome): Promise<WorkflowSchemaResult> => {
|
|
1077
|
+
if (o.written.length > 0 || o.partial) {
|
|
1078
|
+
try {
|
|
1079
|
+
await deps.refresh(req.cwd);
|
|
1080
|
+
} catch (err) {
|
|
1081
|
+
(o.warnings ??= []).push(`forced refresh failed: ${errMsg(err)}`);
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
const snap = await snapshot(root, deps, localVersion);
|
|
1085
|
+
return {
|
|
1086
|
+
ok: o.ok,
|
|
1087
|
+
status: snap.status,
|
|
1088
|
+
configured: snap.configured,
|
|
1089
|
+
written: o.written,
|
|
1090
|
+
...(o.skipped ? { skipped: o.skipped } : {}),
|
|
1091
|
+
...(o.warnings?.length ? { warnings: o.warnings } : {}),
|
|
1092
|
+
worktree: await worktreeInfo(root),
|
|
1093
|
+
...(o.error ? { error: o.error } : {}),
|
|
1094
|
+
...(o.partial ? { partial: true } : {}),
|
|
1095
|
+
};
|
|
1096
|
+
};
|
|
1097
|
+
|
|
1098
|
+
try {
|
|
1099
|
+
const guard = await writeGuard(req.cwd, deps);
|
|
1100
|
+
if ("error" in guard) return await finish(refused(guard.error));
|
|
1101
|
+
root = guard.root;
|
|
1102
|
+
|
|
1103
|
+
const ver = await deps.cli({ op: "version" }, { cwd: root });
|
|
1104
|
+
localVersion = ver.ok ? ver.stdout.trim() : null;
|
|
1105
|
+
if (!localVersion) return await finish(refused("cannot determine the OpenSpec CLI version"));
|
|
1106
|
+
|
|
1107
|
+
let config: ConfigFile | null;
|
|
1108
|
+
try {
|
|
1109
|
+
config = await readConfigFile(root);
|
|
1110
|
+
} catch (err) {
|
|
1111
|
+
return await finish(refused(errMsg(err)));
|
|
1112
|
+
}
|
|
1113
|
+
const info = await inspectWithValidate(root, localVersion, deps);
|
|
1114
|
+
const state = checkActionState(req.action, config?.configured ?? null, info.generated, info.symlink);
|
|
1115
|
+
if (state.verdict === "refuse") return await finish(refused(state.reason));
|
|
1116
|
+
if (state.verdict === "noop") return await finish({ ok: true, written: [], warnings: [state.reason] });
|
|
1117
|
+
|
|
1118
|
+
return await finish(await ACTIONS[req.action]({ root, deps, req, config, localVersion, info }));
|
|
1119
|
+
} catch (err) {
|
|
1120
|
+
return await finish(refused(errMsg(err)));
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
/** Pin wrapper over the single dispatcher (the contract), used by the poll tests. */
|
|
1125
|
+
export const pinWorkflowSchema = (
|
|
1126
|
+
req: Omit<WorkflowSchemaRequest, "action">,
|
|
1127
|
+
deps?: Partial<WorkflowSchemaDeps>,
|
|
1128
|
+
): Promise<WorkflowSchemaResult> => runWorkflowSchemaAction({ ...req, action: "pin" }, deps);
|