create-principles-disciple 1.148.11 → 1.150.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_release/product-identity.json +1 -1
- package/codex-adapter/dist/pd-hook.d.ts +22 -1
- package/codex-adapter/dist/pd-hook.js +81 -7
- package/codex-adapter/dist/worker/workspace-worker.d.ts +15 -0
- package/codex-adapter/dist/worker/workspace-worker.js +7 -36
- package/codex-adapter/package.json +1 -1
- package/console/dist/server/index.js +21 -0
- package/console/dist/server/models/ActivationsConsoleModel.d.ts +3 -17
- package/console/dist/server/models/ActivationsConsoleModel.js +5 -44
- package/console/dist/server/routes/compatibility-scan.d.ts +18 -0
- package/console/dist/server/routes/compatibility-scan.js +33 -0
- package/console/dist/server/routes/diagnostician.d.ts +50 -0
- package/console/dist/server/routes/diagnostician.js +388 -0
- package/console/dist/shared/compatibility-scan-contract.d.ts +26 -0
- package/console/dist/shared/compatibility-scan-contract.js +1 -0
- package/console/dist/web/assets/app.js +31 -31
- package/core/dist/host/host-installer.d.ts +7 -0
- package/core/dist/host/host-installer.d.ts.map +1 -1
- package/core/dist/host/host-installer.js.map +1 -1
- package/core/dist/runtime/activation/index.d.ts +3 -3
- package/core/dist/runtime/activation/index.d.ts.map +1 -1
- package/core/dist/runtime/activation/index.js +1 -1
- package/core/dist/runtime/activation/index.js.map +1 -1
- package/core/dist/runtime/activation/promotion-readiness-evaluator.d.ts +25 -1
- package/core/dist/runtime/activation/promotion-readiness-evaluator.d.ts.map +1 -1
- package/core/dist/runtime/activation/promotion-readiness-evaluator.js +58 -1
- package/core/dist/runtime/activation/promotion-readiness-evaluator.js.map +1 -1
- package/core/dist/runtime/activation/promotion-readiness-reader.d.ts.map +1 -1
- package/core/dist/runtime/activation/promotion-readiness-reader.js +4 -2
- package/core/dist/runtime/activation/promotion-readiness-reader.js.map +1 -1
- package/core/dist/runtime/activation/rulecode-owner-decision-service.d.ts +28 -0
- package/core/dist/runtime/activation/rulecode-owner-decision-service.d.ts.map +1 -1
- package/core/dist/runtime/activation/rulecode-owner-decision-service.js +2 -0
- package/core/dist/runtime/activation/rulecode-owner-decision-service.js.map +1 -1
- package/core/dist/runtime/activation-compatibility-read-model.d.ts +20 -5
- package/core/dist/runtime/activation-compatibility-read-model.d.ts.map +1 -1
- package/core/dist/runtime/activation-compatibility-read-model.js +15 -3
- package/core/dist/runtime/activation-compatibility-read-model.js.map +1 -1
- package/core/dist/runtime/admission-gate.d.ts +8 -1
- package/core/dist/runtime/admission-gate.d.ts.map +1 -1
- package/core/dist/runtime/admission-gate.js +2 -1
- package/core/dist/runtime/admission-gate.js.map +1 -1
- package/core/dist/runtime/config/pd-config-defaults.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-defaults.js +20 -2
- package/core/dist/runtime/config/pd-config-defaults.js.map +1 -1
- package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-validate.js +18 -0
- package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
- package/core/dist/runtime/context-payload.d.ts +48 -3
- package/core/dist/runtime/context-payload.d.ts.map +1 -1
- package/core/dist/runtime/context-payload.js +38 -0
- package/core/dist/runtime/context-payload.js.map +1 -1
- package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts +8 -2
- package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts.map +1 -1
- package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js +28 -2
- package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js.map +1 -1
- package/core/dist/runtime/diagnostician-candidate.d.ts +24 -0
- package/core/dist/runtime/diagnostician-candidate.d.ts.map +1 -0
- package/core/dist/runtime/diagnostician-candidate.js +55 -0
- package/core/dist/runtime/diagnostician-candidate.js.map +1 -0
- package/core/dist/runtime/evidence-guards.d.ts +10 -4
- package/core/dist/runtime/evidence-guards.d.ts.map +1 -1
- package/core/dist/runtime/evidence-guards.js +12 -5
- package/core/dist/runtime/evidence-guards.js.map +1 -1
- package/core/dist/runtime/evolution/evolution-types.d.ts +4 -4
- package/core/dist/runtime/evolution/evolution-types.d.ts.map +1 -1
- package/core/dist/runtime/evolution/evolution-types.js +1 -0
- package/core/dist/runtime/evolution/evolution-types.js.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-contract.js +14 -0
- package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +16 -0
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
- package/core/dist/runtime/index.d.ts +5 -2
- package/core/dist/runtime/index.d.ts.map +1 -1
- package/core/dist/runtime/index.js +6 -1
- package/core/dist/runtime/index.js.map +1 -1
- package/core/dist/runtime/internalization/index.d.ts +1 -0
- package/core/dist/runtime/internalization/index.d.ts.map +1 -1
- package/core/dist/runtime/internalization/index.js +2 -0
- package/core/dist/runtime/internalization/index.js.map +1 -1
- package/core/dist/runtime/internalization/rule-host-contracts.d.ts +10 -0
- package/core/dist/runtime/internalization/rule-host-contracts.d.ts.map +1 -1
- package/core/dist/runtime/internalization/rule-host-evaluator.js +10 -10
- package/core/dist/runtime/internalization/rule-host-evaluator.js.map +1 -1
- package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +7 -6
- package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
- package/core/dist/runtime/internalization/rule-host-input-builder.js +6 -2
- package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
- package/core/dist/runtime/internalization/rule-host-result-normalizer.d.ts +33 -0
- package/core/dist/runtime/internalization/rule-host-result-normalizer.d.ts.map +1 -0
- package/core/dist/runtime/internalization/rule-host-result-normalizer.js +61 -0
- package/core/dist/runtime/internalization/rule-host-result-normalizer.js.map +1 -0
- package/core/dist/runtime/internalization/rule-host-validator.d.ts.map +1 -1
- package/core/dist/runtime/internalization/rule-host-validator.js +17 -0
- package/core/dist/runtime/internalization/rule-host-validator.js.map +1 -1
- package/core/dist/runtime/pain-ingress-payload.d.ts +27 -2
- package/core/dist/runtime/pain-ingress-payload.d.ts.map +1 -1
- package/core/dist/runtime/pain-ingress-payload.js +45 -3
- package/core/dist/runtime/pain-ingress-payload.js.map +1 -1
- package/core/dist/runtime/pain-ingress.d.ts +4 -2
- package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
- package/core/dist/runtime/pain-ingress.js +23 -3
- package/core/dist/runtime/pain-ingress.js.map +1 -1
- package/core/dist/runtime/pain-severity.d.ts +14 -0
- package/core/dist/runtime/pain-severity.d.ts.map +1 -0
- package/core/dist/runtime/pain-severity.js +14 -0
- package/core/dist/runtime/pain-severity.js.map +1 -0
- package/core/dist/runtime/pain-signal-bridge.d.ts +17 -3
- package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
- package/core/dist/runtime/pain-signal-bridge.js +6 -0
- package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
- package/core/dist/runtime/pain-signal-observability.d.ts.map +1 -1
- package/core/dist/runtime/pain-signal-observability.js +3 -2
- package/core/dist/runtime/pain-signal-observability.js.map +1 -1
- package/core/dist/runtime/pain-submit-capability.d.ts +164 -0
- package/core/dist/runtime/pain-submit-capability.d.ts.map +1 -0
- package/core/dist/runtime/pain-submit-capability.js +442 -0
- package/core/dist/runtime/pain-submit-capability.js.map +1 -0
- package/core/dist/runtime/pain-to-principle-service.d.ts +4 -0
- package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
- package/core/dist/runtime/pain-to-principle-service.js +2 -0
- package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
- package/core/dist/runtime/stalled-diagnostician-task-read-model.d.ts +56 -10
- package/core/dist/runtime/stalled-diagnostician-task-read-model.d.ts.map +1 -1
- package/core/dist/runtime/stalled-diagnostician-task-read-model.js +80 -4
- package/core/dist/runtime/stalled-diagnostician-task-read-model.js.map +1 -1
- package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
- package/core/dist/runtime/store/context/sqlite-context-assembler.js +11 -0
- package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
- package/core/dist/runtime/store/run/memory-run-store.d.ts +10 -0
- package/core/dist/runtime/store/run/memory-run-store.d.ts.map +1 -1
- package/core/dist/runtime/store/run/memory-run-store.js +21 -0
- package/core/dist/runtime/store/run/memory-run-store.js.map +1 -1
- package/core/dist/runtime/store/run/run-store.d.ts +12 -0
- package/core/dist/runtime/store/run/run-store.d.ts.map +1 -1
- package/core/dist/runtime/store/run/sqlite-run-store.d.ts +1 -0
- package/core/dist/runtime/store/run/sqlite-run-store.d.ts.map +1 -1
- package/core/dist/runtime/store/run/sqlite-run-store.js +14 -0
- package/core/dist/runtime/store/run/sqlite-run-store.js.map +1 -1
- package/core/dist/runtime/task-status.d.ts +9 -0
- package/core/dist/runtime/task-status.d.ts.map +1 -1
- package/core/dist/runtime/task-status.js +7 -1
- package/core/dist/runtime/task-status.js.map +1 -1
- package/core/dist/runtime/types/evidence-chain-contract.d.ts +18 -0
- package/core/dist/runtime/types/evidence-chain-contract.d.ts.map +1 -1
- package/core/dist/runtime/types/evidence-chain-contract.js +37 -7
- package/core/dist/runtime/types/evidence-chain-contract.js.map +1 -1
- package/core/package.json +5 -1
- package/dist/install-summary.d.ts +7 -0
- package/dist/install-summary.d.ts.map +1 -1
- package/dist/install-summary.js +4 -0
- package/dist/install-summary.js.map +1 -1
- package/dist/installer.d.ts +92 -8
- package/dist/installer.d.ts.map +1 -1
- package/dist/installer.js +215 -10
- package/dist/installer.js.map +1 -1
- package/dist/installers/codex-host-installer.d.ts +88 -1
- package/dist/installers/codex-host-installer.d.ts.map +1 -1
- package/dist/installers/codex-host-installer.js +350 -11
- package/dist/installers/codex-host-installer.js.map +1 -1
- package/dist/installers/index.d.ts +23 -0
- package/dist/installers/index.d.ts.map +1 -1
- package/dist/installers/index.js +38 -1
- package/dist/installers/index.js.map +1 -1
- package/dist/installers/legacy-workbuddy-skill.d.ts +59 -0
- package/dist/installers/legacy-workbuddy-skill.d.ts.map +1 -0
- package/dist/installers/legacy-workbuddy-skill.js +168 -0
- package/dist/installers/legacy-workbuddy-skill.js.map +1 -0
- package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
- package/dist/installers/workbuddy-host-installer.js +7 -0
- package/dist/installers/workbuddy-host-installer.js.map +1 -1
- package/host-runtime/dist/adaptive-priority-provider.d.ts +94 -0
- package/host-runtime/dist/adaptive-priority-provider.js +162 -0
- package/host-runtime/dist/adaptive-selection.d.ts +164 -0
- package/host-runtime/dist/adaptive-selection.js +506 -0
- package/host-runtime/dist/diagnostician-auto-run.d.ts +28 -0
- package/host-runtime/dist/diagnostician-auto-run.js +100 -0
- package/host-runtime/dist/host-tool-semantic-resolver.d.ts +42 -1
- package/host-runtime/dist/host-tool-semantic-resolver.js +80 -14
- package/host-runtime/dist/index.d.ts +4 -0
- package/host-runtime/dist/index.js +6 -0
- package/host-runtime/dist/production-rulehost-gate.js +17 -17
- package/host-runtime/dist/rulecode-event-collection.d.ts +31 -0
- package/host-runtime/dist/rulecode-event-collection.js +62 -0
- package/host-runtime/package.json +1 -1
- package/install-layout/dist/index.d.ts +1 -1
- package/install-layout/dist/index.js +1 -1
- package/install-layout/dist/pd-home.d.ts +9 -2
- package/install-layout/dist/pd-home.js +77 -14
- package/install-layout/package.json +1 -1
- package/package.json +4 -4
- package/pd-cli/dist/commands/diagnose.d.ts +30 -0
- package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
- package/pd-cli/dist/commands/diagnose.js +75 -0
- package/pd-cli/dist/commands/diagnose.js.map +1 -1
- package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
- package/pd-cli/dist/commands/pain-record.js +5 -4
- package/pd-cli/dist/commands/pain-record.js.map +1 -1
- package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
- package/pd-cli/dist/commands/pain-retry.js +2 -1
- package/pd-cli/dist/commands/pain-retry.js.map +1 -1
- package/pd-cli/dist/commands/runtime-activation.d.ts +6 -17
- package/pd-cli/dist/commands/runtime-activation.d.ts.map +1 -1
- package/pd-cli/dist/commands/runtime-activation.js +42 -48
- package/pd-cli/dist/commands/runtime-activation.js.map +1 -1
- package/pd-cli/dist/commands/runtime-compatibility-scan.d.ts +5 -2
- package/pd-cli/dist/commands/runtime-compatibility-scan.d.ts.map +1 -1
- package/pd-cli/dist/commands/runtime-compatibility-scan.js +22 -2
- package/pd-cli/dist/commands/runtime-compatibility-scan.js.map +1 -1
- package/pd-cli/dist/index.js +1 -0
- package/pd-cli/dist/index.js.map +1 -1
- package/pd-cli/dist/services/config-doctor.d.ts +9 -0
- package/pd-cli/dist/services/config-doctor.d.ts.map +1 -1
- package/pd-cli/dist/services/config-doctor.js +15 -0
- package/pd-cli/dist/services/config-doctor.js.map +1 -1
- package/pd-cli/dist/services/delivery-surfaces.js +1 -1
- package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
- package/pd-cli/package.json +1 -1
- package/pd-mcp-server/dist/budget.d.ts +1 -1
- package/pd-mcp-server/dist/budget.js +2 -2
- package/pd-mcp-server/dist/envelope.d.ts +15 -0
- package/pd-mcp-server/dist/envelope.js +49 -1
- package/pd-mcp-server/dist/index.d.ts +2 -0
- package/pd-mcp-server/dist/index.js +6 -0
- package/pd-mcp-server/dist/server.d.ts +83 -14
- package/pd-mcp-server/dist/server.js +251 -4
- package/pd-mcp-server/dist/version.d.ts +1 -1
- package/pd-mcp-server/dist/version.js +1 -1
- package/pd-mcp-server/dist/workspace.d.ts +4 -2
- package/pd-mcp-server/dist/workspace.js +5 -2
- package/pd-mcp-server/package.json +1 -1
- package/plugin/dist/bundle.js +443 -431
- package/plugin/dist/core/evolution-reducer.d.ts +2 -2
- package/plugin/dist/hooks/hook-tool-semantics.d.ts +25 -0
- package/plugin/dist/hooks/pain-ingress-adapter.d.ts +1 -1
- package/plugin/dist/openclaw.plugin.json +1 -1
- package/plugin/dist/rulehost-evidence.js +1 -1
- package/plugin/openclaw.plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/release-manager/dist/installer.js +215 -10
- package/release-manager/dist/installers/codex-host-installer.js +350 -11
- package/release-manager/dist/installers/index.js +38 -1
- package/release-manager/dist/installers/legacy-workbuddy-skill.js +168 -0
- package/release-manager/dist/installers/workbuddy-host-installer.js +7 -0
- package/release-manager/package.json +1 -1
- package/workbuddy-adapter/dist/pd-hook.js +20 -4
- package/workbuddy-adapter/package.json +1 -1
- package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +123 -20
|
@@ -16,7 +16,7 @@ export interface EvolutionReducer {
|
|
|
16
16
|
*/
|
|
17
17
|
createPrincipleFromDiagnosis(params: {
|
|
18
18
|
painId: string;
|
|
19
|
-
painType: 'tool_failure' | 'subagent_error' | 'user_frustration';
|
|
19
|
+
painType: 'tool_failure' | 'subagent_error' | 'user_frustration' | 'principle_deviation';
|
|
20
20
|
triggerPattern: string;
|
|
21
21
|
action: string;
|
|
22
22
|
source: string;
|
|
@@ -72,7 +72,7 @@ export declare class EvolutionReducerImpl implements EvolutionReducer {
|
|
|
72
72
|
*/
|
|
73
73
|
createPrincipleFromDiagnosis(params: {
|
|
74
74
|
painId: string;
|
|
75
|
-
painType: 'tool_failure' | 'subagent_error' | 'user_frustration';
|
|
75
|
+
painType: 'tool_failure' | 'subagent_error' | 'user_frustration' | 'principle_deviation';
|
|
76
76
|
triggerPattern: string;
|
|
77
77
|
action: string;
|
|
78
78
|
source: string;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* B3 — the OpenClaw gate's tool semantics resolution.
|
|
3
|
+
*
|
|
4
|
+
* The gate classifies every dispatched tool's canonical kind here. Before B3
|
|
5
|
+
* it used `OPENCLAW_TOOL_SEMANTICS` (the compiled-in declaration) alone, so a
|
|
6
|
+
* persisted workspace declaration — the SAME source replay, evidence and the
|
|
7
|
+
* Console read — could disagree with production on the same tool call.
|
|
8
|
+
*
|
|
9
|
+
* Lives outside `constants/tool-semantics.ts` because it pulls
|
|
10
|
+
* `@principles/host-runtime`: that module is reachable from the
|
|
11
|
+
* `rulehost-evidence` satellite entry, and a value import of the host-runtime
|
|
12
|
+
* barrel there would re-pull the whole LLM graph (OPT-002 / satellite-purity).
|
|
13
|
+
*/
|
|
14
|
+
import type { ToolSemanticRegistry } from '@principles/core/runtime/internalization/tool-semantic-registry';
|
|
15
|
+
/**
|
|
16
|
+
* Resolve the workspace's durable host declarations, with
|
|
17
|
+
* `OPENCLAW_TOOL_SEMANTICS` as the fallback data source.
|
|
18
|
+
*
|
|
19
|
+
* Not cached: gateway start persists the declaration and may run after the
|
|
20
|
+
* first hook invocation, so caching a fallback would pin the hook to the
|
|
21
|
+
* static list for the rest of the process lifetime.
|
|
22
|
+
*/
|
|
23
|
+
export declare function resolveOpenClawHookToolSemantics(workspaceDir: string, logger: {
|
|
24
|
+
warn?: (msg: string) => void;
|
|
25
|
+
}): ToolSemanticRegistry;
|
|
@@ -3,7 +3,7 @@ import type { WorkspaceContext } from '../core/workspace-context.js';
|
|
|
3
3
|
export interface PluginIngressInput {
|
|
4
4
|
wctx: WorkspaceContext;
|
|
5
5
|
painId: string;
|
|
6
|
-
painType: 'tool_failure' | 'subagent_error' | 'user_frustration';
|
|
6
|
+
painType: 'tool_failure' | 'subagent_error' | 'user_frustration' | 'principle_deviation';
|
|
7
7
|
source: string;
|
|
8
8
|
reason: string;
|
|
9
9
|
score?: number;
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
|
-
"version": "3.1
|
|
5
|
+
"version": "3.2.1",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
|
@@ -2,7 +2,7 @@ import { createRequire } from 'module'; const require = createRequire(import.met
|
|
|
2
2
|
var Pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var re=Object.freeze([Object.freeze({capabilityId:"pd_status",channel:"cli",cliCommand:"pd activation list --json"}),Object.freeze({capabilityId:"rulecode_deactivate",channel:"cli",cliCommand:"pd activation deactivate --activation-id recovery-probe"}),Object.freeze({capabilityId:"rulecode_global_pause",channel:"console",consoleRoute:"/api/activations/emergency-pause"}),Object.freeze({capabilityId:"owner_review_access",channel:"console",consoleRoute:"/api/activations/{activationId}/owner-review"})]);var oe="",je="|;&<>()";function L(t){return je.includes(t)?`${oe}${t}`:t}function se(t){if(t.includes(oe))return null;let e=[],n="",r=!1,s=0,o=t.length,i="plain";for(;s<o;){let c=t[s];if(c===void 0)break;if(i==="single"){c==="'"?i="plain":n+=L(c),s+=1;continue}if(i==="double"){if(c==='"')i="plain";else if(c==="\\"&&s+1<o&&'"\\$`'.includes(t[s+1]??"")){n+=L(t[s+1]??""),s+=2;continue}else n+=L(c);s+=1;continue}if(c==="'"){i="single",r=!0,s+=1;continue}if(c==='"'){i="double",r=!0,s+=1;continue}if(c==="\\"&&s+1<o){n+=L(t[s+1]??""),r=!0,s+=2;continue}if(c==="\r"||c===`
|
|
3
3
|
`){(r||n)&&(e.push(n),n="",r=!1),c==="\r"&&t[s+1]===`
|
|
4
4
|
`&&(s+=1),e.push(`
|
|
5
|
-
`),s+=1;continue}if(" ".includes(c)){(r||n)&&(e.push(n),n="",r=!1),s+=1;continue}if("|;&<>()".includes(c)){(r||n)&&(e.push(n),n="",r=!1);let a=c,d=t[s+1];c==="<"&&d===">"?a="<>":(c==="|"||c==="&"||c===">"||c==="<")&&d===c&&(a+=d),(c===">"||c==="<")&&d==="("&&(a+=d),e.push(a),s+=a.length;continue}n+=c,r=!0,s+=1}return i!=="plain"?null:((r||n)&&e.push(n),e)}function ie(t){if(/[\\$`|;&<>()*?~{}]/.test(t)||[...t].some(s=>s.charCodeAt(0)<32))return;let e=se(t);if(!e)return;let n=[...e],r=n.findIndex(s=>s==="-w"||s==="--workspace");if(r!==-1){let s=n[r+1];if(r!==n.length-2||!s||s.startsWith("-"))return;n.splice(r,2)}for(let s of re){if(s.channel!=="cli"||!s.cliCommand||s.capabilityId!=="pd_status"&&s.capabilityId!=="rulecode_deactivate")continue;let o=se(s.cliCommand);if(!o||o.length!==n.length)continue;if(o.every((c,a)=>s.capabilityId==="rulecode_deactivate"&&o[a-1]==="--activation-id"?/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/.test(n[a]??""):c===n[a]))return s.capabilityId}}var Ue=["verbose","debug"],Be=["erroraction","warningaction","informationaction","progressaction","errorvariable","warningvariable","informationvariable","outvariable","outbuffer","pipelinevariable"];function S(t,e){return{switches:new Set([...Ue,...t]),valued:new Set([...Be,...e])}}var Vt=Object.freeze({"get-content":S(["raw","force","wait","asbytestream"],["path","literalpath","totalcount","first","tail","last","encoding","delimiter","readcount","stream","credential"]),"get-childitem":S(["recurse","force","name","file","directory","hidden","readonly","system","followsymlink"],["path","literalpath","filter","include","exclude","depth","attributes","credential"]),"get-item":S(["force","followsymlink"],["path","literalpath","filter","include","exclude","stream","credential"]),"get-itemproperty":S(["force"],["path","literalpath","name","filter","include","exclude","credential"]),"select-string":S(["simplematch","casesensitive","notmatch","allmatches","quiet","list","raw"],["pattern","path","literalpath","inputobject","encoding","context","include","exclude","credential"]),"test-path":S(["isvalid"],["path","literalpath","pathtype","filter","credential"]),"resolve-path":S(["relative"],["path","literalpath","relativebasepath","credential"]),"get-location":S(["stack"],["psprovider","psdrive"])});function C(t,e=!1){let n=[];for(let r of t.split("/").filter(s=>s.length>0))r!=="."&&(r===".."?n.length>0&&n[n.length-1]!==".."?n.pop():e&&n.push(".."):n.push(r));return n}function $(t){let e=/^([a-zA-Z]):(?:\/|$)/.exec(t);if(e)return{kind:"drive",root:`drive:${(e[1]??"").toUpperCase()}`,segments:C(t.slice(2))};if(/^[a-zA-Z]:/.test(t))return{kind:"drive-relative",root:t.slice(0,2).toUpperCase(),segments:[]};if(/^\/\/[^/]+(?:\/|$)/.test(t)){let n=t.slice(2).split("/").filter(o=>o.length>0),r=n[0]??"",s=n[1]??"";return{kind:"unc",root:`unc:${r}/${s}`,segments:C(n.slice(2).join("/"))}}return t.startsWith("/")?{kind:"posix",root:"posix:/",segments:C(t)}:{kind:"relative",root:"",segments:C(t,!0)}}function ae(t,e,n){return t.length<e.length?!1:e.every((r,s)=>{let o=t[s]??"";return n?o.toLowerCase()===r.toLowerCase():o===r})}function Xe(t,e,n){let r=0;for(;r<t.length&&r<e.length;){let o=t[r]??"",i=e[r]??"";if(!(n?o.toLowerCase()===i.toLowerCase():o===i))break;r++}return[...Array.from({length:t.length-r},()=>".."),...e.slice(r)].join("/")||"."}function ce(t){let[e,n]=t.root.slice(4).split("/"),r=t.segments.join("/");return`//${e??""}/${n??""}${r?`/${r}`:""}`}function le(t,e,n){if(t.kind==="drive-relative"||t.kind==="unc"&&t.root.endsWith("/"))return n;if(t.kind!=="relative")return!(t.kind===e.kind&&(t.kind==="unc"?t.root.toLowerCase()===e.root.toLowerCase():t.root===e.root))||!ae(t.segments,e.segments,t.kind==="drive"||t.kind==="unc")?t.kind==="unc"?ce(t):n:t.segments.slice(e.segments.length).join("/")||".";let r=[...e.segments];for(let o of n.split("/").filter(i=>i.length>0))o!=="."&&(o===".."?r.length>0&&r[r.length-1]!==".."?r.pop():e.kind==="relative"&&r.push(".."):r.push(o));let s=e.kind==="drive"||e.kind==="unc";return ae(r,e.segments,s)?r.slice(e.segments.length).join("/")||".":Xe(e.segments,r,s)}function Fe(t,e){if(!t||typeof t!="string")return"";let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/");if(n.startsWith("<tool:")&&n.endsWith(">"))return n;let s=$(n),o=$(r);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let c=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=$(c),le(s,o,c)}return le(s,o,n)}function We(t,e){let n=t.file_path||t.path||t.file||t.target;if(typeof n=="string"&&n.length>0)return{value:n,isPath:!0};if(e.isBashTool){let r=String(t.command||t.args||"");if(r){let s=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(r);return s&&s[1]?{value:s[1],isPath:!0}:{value:r,isPath:!1}}}return e.isWriteTool&&e.toolName?{value:`<tool:${e.toolName}>`,isPath:!0}:{value:null,isPath:!0}}function $e(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function He(t){if(t.canonicalKind===void 0)return t;let e=$e(t.canonicalKind);return{...t,isBashTool:t.isBashTool??e.isBashTool,isWriteTool:t.isWriteTool??e.isWriteTool}}function D(t,e,n,r={}){let s=He(r),o=We(e,{...s,toolName:t}),i=o.isPath?Fe(o.value,n):o.value,c=e.command??e.args,a=s.isBashTool&&typeof c=="string"?ie(c):void 0;return{toolName:t,normalizedPath:i,...a?{recoveryControl:a}:{},paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var H=new Set(["read","search","write","execute","agent","other"]);function ue(t){return typeof t=="string"&&H.has(t)}var M=Object.freeze({read:"read",read_file:"read",read_many_files:"read",grep:"search",grep_search:"search",search_file_content:"search",glob:"search",write:"write",write_file:"write",edit:"write",edit_file:"write",replace:"write",apply_patch:"write",bash:"execute",exec:"execute",execute:"execute",run_shell_command:"execute",execute_command:"execute",run_script:"execute",code_interpreter:"execute",sessions_spawn:"agent"});function de(t,e,n){if(t.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let r=0,s=0,o=new Set,i=e===null?"unknown":"no",{calls:c}=t;for(let a of c){let d=a.canonicalKind;d==="read"||d==="search"?(r++,e!==null&&a.normalizedPath===e&&(i="yes")):d==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:r,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:n}}var pe={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(pe);var Y={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(Y.calls);Object.freeze(Y);var Ye={version:2,history:Y,facts:pe};Object.freeze(Ye);var Ke=new Set(["__proto__","constructor","prototype"]),fe=3,Ge=5,qe=new Set(["allow","block","propose_correction"]),ze={valid:!0,errors:[]};function K(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ee(t){for(let e of Object.keys(t))if(Ke.has(e))return!1;return!0}function Ve(t){return t.length===0?ze:{valid:!1,errors:t}}function G(t){return typeof t=="string"&&t.trim().length>0}function _e(t,e,n){let r=[];return K(t)?Ee(t)?((!Object.hasOwn(t,"caseId")||!G(t.caseId))&&r.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(t,"kind")||t.kind!==n)&&r.push(`${e}.kind must be '${n}'`),(!Object.hasOwn(t,"toolName")||!G(t.toolName))&&r.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(t,"params")||!K(t.params))&&r.push(`${e}.params must be a plain object`),!Object.hasOwn(t,"expectedDecision")||typeof t.expectedDecision!="string"||!qe.has(t.expectedDecision)?r.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):n==="positive"&&t.expectedDecision!=="allow"&&r.push(`${e}: positive cases must expect allow`),r):(r.push(`${e} must not carry prototype-pollution keys`),r):(r.push(`${e} must be a plain object`),r)}function me(t,e){let{fieldName:n,maxLength:r,requireNonEmpty:s}=e,o=[];if(!Array.isArray(t))return o.push(`${n} must be an array`),o;s&&t.length===0&&o.push(`${n} must contain at least 1 item`),r!==void 0&&t.length>r&&o.push(`${n} must contain at most ${r} items, got ${t.length}`);for(let i=0;i<t.length;i++)typeof t[i]!="string"&&o.push(`${n}[${i}] must be a string`);return o}function P(t){return Array.isArray(t)?`[${t.map(e=>P(e)).join(",")}]`:typeof t=="object"&&t!==null?`{${Object.keys(t).filter(n=>n!=="__proto__"&&n!=="constructor"&&n!=="prototype").sort().map(n=>`${JSON.stringify(n)}:${P(t[n])}`).join(",")}}`:JSON.stringify(t)??"null"}function q(t){if(!K(t))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!Ee(t))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(t,"sourceNegativeCase")?e.push(..._e(t.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(t,"ownerDesiredOutcome")||!G(t.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(t,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(t.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let n=t.positiveCounterexamples;n.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),n.length>fe&&e.push(`positiveCounterexamples must contain at most ${fe} items, got ${n.length}`);for(let r=0;r<n.length;r++)e.push(..._e(n[r],`positiveCounterexamples[${r}]`,"positive"))}if(Object.hasOwn(t,"evidenceRefs")?e.push(...me(t.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Ge,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(t,"redactionNotes")?e.push(...me(t.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let n=t.sourceNegativeCase,r=t.positiveCounterexamples,s=P({toolName:n.toolName,params:n.params,ruleContext:n.ruleContext});for(let o=0;o<r.length;o++){let i=r[o];i!==void 0&&P({toolName:i.toolName,params:i.params,ruleContext:i.ruleContext})===s&&e.push(`positiveCounterexamples[${o}] conflicting_label: identical effective input (toolName + params + ruleContext) as sourceNegativeCase but opposite expectedDecision \u2014 same input cannot carry both labels`)}}return Ve(e)}var Je="OwnerEvidenceScopeError";function A(t,e){let n=new Error(e);return n.name=Je,Object.assign(n,{ownerEvidenceScopeKind:t}),n}var Ze=new Set(["success","failure","blocked"]);function Qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function et(t){return typeof t=="string"&&Ze.has(t)}function I(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function Te(t,e,n){let{projectDir:r,toolSemantics:s}=n,o=[];for(let i of t){let{toolName:c}=i;if(typeof c!="string"||c.length===0)return I(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:a}=i;if(!et(a))return I(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let d=i.paramsJson;if(typeof d!="string")return I(`row id=${i.id}: params_json must be a string`);let h;try{h=JSON.parse(d)}catch{return I(`row id=${i.id}: params_json is not valid JSON`)}if(!Qe(h))return I(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(c),{normalizedPath:g}=D(c,h,r,{canonicalKind:m});o.push({sequenceId:i.id,toolName:c,canonicalKind:m,normalizedPath:g===""?null:g,paramsSummary:h,outcome:a})}return{status:"available",truncated:e,calls:o}}var tt=3,nt=5,rt=100,ge=new Set(["__proto__","constructor","prototype"]);function j(t,e){try{return e()}catch(n){let r=n instanceof Error?n.message:String(n);throw A("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function st(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ot(t){for(let e of Object.keys(t))if(ge.has(e))return!1;return!0}function it(t){if(!Number.isSafeInteger(t.sourceNegativeToolCallId)||t.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(t.positiveToolCallIds)||t.positiveToolCallIds.length===0||t.positiveToolCallIds.length>tt)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[t.sourceNegativeToolCallId,...t.positiveToolCallIds];if(e.some(n=>!Number.isSafeInteger(n)||n<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function he(t,e){if(!t)throw A("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function at(t,e,n){if(typeof t.toolName!="string"||t.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof t.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must be a string (rc-9 fail loud)`);let r;try{r=JSON.parse(t.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!st(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!ot(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${t.id}`,kind:e,toolName:t.toolName,params:r,expectedDecision:n}}function ct(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var lt=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function ut(t){if(t.length<20)return!1;for(let e of lt)if(e.test(t))return!0;return!1}function dt(t,e){let n=[],r={};for(let s of Object.keys(t)){if(ge.has(s))continue;let o=t[s];if(typeof o!="string"){r[s]=o;continue}if(ct(o)&&!o.startsWith(e)){r[s]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(ut(o)){r[s]="<redacted:secret>",n.push(`redacted possible secret in field "${s}"`);continue}r[s]=o}return{redacted:r,notes:n}}var U=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let n=j(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!n)throw A("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);it(e);let r=he(j(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(m=>he(j(`evidence row read for id=${m}`,()=>this.db.getRuleHostEvidenceRow(m)),m));for(let m of[r,...s])if(m.sessionId!==n.sessionId)throw A("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${m.id} session mismatch; all examples must belong to pain session ${n.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(r,"negative",i),a=s.map(m=>this.buildSelectedCase(m,"positive",i)),d={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${n.id}`,`tool_call:${r.id}`,...s.map(m=>`tool_call:${m.id}`)].slice(0,nt),redactionNotes:o},h=q(d);if(!h.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${h.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,n,r){let{projectDir:s,redactionNotes:o}=r,i=at(e,n,n==="negative"?"block":"allow"),c=dt(i.params,s);o.push(...c.notes);let a=j(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,rt)),d=Te(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),h=D(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:d,facts:de(d,h.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:m}}};import kt from"better-sqlite3";import f from"fs";import T from"path";import Q from"crypto";import*as p from"fs";import*as ye from"path";var z=class extends Error{filePath;lockPath;constructor(e,n,r){super(e),this.name="LockAcquisitionError",this.filePath=n,this.lockPath=r}},pt={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function Oe(t){try{return process.kill(t,0),!0}catch{return!1}}function Se(t,e){try{let n=ye.dirname(t);p.existsSync(n)||p.mkdirSync(n,{recursive:!0});let r=p.constants.O_WRONLY|p.constants.O_CREAT|p.constants.O_EXCL,s=p.openSync(t,r);return p.writeSync(s,String(e)),p.fsyncSync(s),p.closeSync(s),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function w(t){try{let e=p.readFileSync(t,"utf8"),n=parseInt(e.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function ft(t,e){try{w(t)===e&&p.unlinkSync(t)}catch{}}function _t(t,e){try{let n=p.statSync(t),r=w(t),s=Date.now()-n.mtimeMs>e,o=r===null||!Oe(r);if(s||o)try{return p.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function mt(t,e,n){let r=Math.min(e*Math.pow(2,t),n),s=r*.2*Math.random();return Math.floor(r+s)}function Et(t){let e=Date.now()+t;for(;Date.now()<e;);}function Tt(t,e){let n=w(e),r=n!==null?Oe(n)?`alive (PID ${n})`:`dead (PID ${n})`:"unknown";return new z(`Failed to acquire lock for ${t}. Lock holder: ${r}.`,t,e)}function ht(t,e,n){let r=t+e.lockSuffix;return Se(r,n)&&w(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(_t(r,e.lockStaleMs),Se(r,n)&&w(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function gt(t,e={}){let n={...pt,...e},{pid:r}=process;for(let s=0;s<n.maxRetries;s++){let o=ht(t,n,r);if(o)return o;if(s<n.maxRetries-1){let i=mt(s,n.baseRetryDelayMs,n.maxRetryDelayMs);Et(i)}}throw Tt(t,t+n.lockSuffix)}function St(t){ft(t.lockPath,t.pid)}function Re(t,e,n={}){let r=gt(t,n);try{return e()}finally{St(r)}}import*as R from"fs";var be=3,yt=50;function B(t,e){let n=t+".tmp";R.writeFileSync(n,e,"utf8");let r;for(let s=0;s<be;s++)try{R.renameSync(n,t);return}catch(o){r=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<be-1){let c=yt*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{Pe("fs").accessSync?.(n)}catch{}d=!0}}continue}break}try{R.unlinkSync(n)}catch{}throw r}import*as y from"path";var l=(...t)=>y.posix.join(...t);function Ot(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function Rt(t,e){return Ot(t)?y.win32.join(t,e):t.startsWith("/")?y.posix.join(t,e):y.join(t,e)}var u={IDENTITY:".principles",MODELS:l(".principles","models"),STATE:".state",MEMORY:"memory",OKR:l("memory","okr"),LOGS:l("memory","logs"),SESSIONS:l(".state","sessions"),PAIN_SAMPLES:l("memory","pain"),LOCKS:l("memory",".locks"),IMPL_CODE_DIR:l(".state","principles","implementations")},bt={PROFILE:l(u.IDENTITY,"PROFILE.json"),PRINCIPLES:l(u.IDENTITY,"PRINCIPLES.md"),THINKING_OS:l(u.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:l(u.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:u.MODELS,STATE_DIR:u.STATE,WORKBOARD:l(u.STATE,"WORKBOARD.json"),AGENT_SCORECARD:l(u.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:l(u.STATE,".pain_flag"),SYSTEM_CAPABILITIES:l(u.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:l(u.STATE,"pain_settings.json"),PAIN_CANDIDATES:l(u.STATE,"pain_candidates.json"),TRAJECTORY_DB:l(u.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:l(u.STATE,"blobs"),EXPORTS_DIR:l(u.STATE,"exports"),SESSION_DIR:u.SESSIONS,DICTIONARY:l(u.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:l(u.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:l(u.STATE,"workflows.yaml"),IMPL_CODE_DIR:u.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:l(u.LOGS,"SYSTEM.log"),REFLECTION_LOG:l(u.MEMORY,"reflection-log.md"),USER_CONTEXT:l(u.MEMORY,"USER_CONTEXT.md"),OKR_DIR:u.OKR,CURRENT_FOCUS:l(u.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:l(u.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:l(u.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:l(u.LOCKS,"evolution")};function O(t,e){return Rt(t,bt[e])}var Nt={LOCK_UNAVAILABLE:"lease_conflict",PATH_RESOLUTION_ERROR:"workspace_invalid",WORKSPACE_NOT_FOUND:"workspace_invalid",SAMPLE_NOT_FOUND:"storage_unavailable",CONFIGURATION_ERROR:"input_invalid",DEPENDENCY_ERROR:"runtime_unavailable",EVOLUTION_PROCESSING_ERROR:"execution_failed",TRAJECTORY_ERROR:"storage_unavailable"},V=class extends Error{constructor(n,r,s){super(n,s);this.code=r;this.name="PdError",this.category=Nt[r]??"execution_failed"}code;category};var x=class extends V{constructor(e,n){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};var At=["schema_version","ingest_checkpoint","sessions","assistant_turns","user_turns","tool_calls","pain_events","gate_blocks","trust_changes","principle_events","task_outcomes","correction_samples","sample_reviews","signal_confirmations","exports_audit"],Ne={sessions:{session_id:"TEXT",started_at:"TEXT",updated_at:"TEXT"},tool_calls:{session_id:"TEXT",tool_name:"TEXT",outcome:"TEXT",duration_ms:"INTEGER",exit_code:"INTEGER",error_type:"TEXT",error_message:"TEXT",params_json:"TEXT",result_preview:"TEXT",created_at:"TEXT",project_dir:"TEXT"},pain_events:{session_id:"TEXT",source:"TEXT",score:"REAL",reason:"TEXT",severity:"TEXT",origin:"TEXT",confidence:"REAL",text:"TEXT",canonical_pain_id:"TEXT",runtime_task_id:"TEXT",host_kind:"TEXT",created_at:"TEXT"}};for(let t of Object.values(Ne))Object.freeze(t);Object.freeze(Ne);function E(t){let e=t instanceof Error?t.message:String(t);return e.includes("duplicate column name")||e.includes("no column named")}function X(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function J(t){if(!X(t,"schema_version"))return;let e=t.prepare("SELECT version FROM schema_version LIMIT 1").get();if(e===void 0){t.prepare("INSERT INTO schema_version (version) VALUES (?)").run(2);return}e.version!==2&&t.prepare("UPDATE schema_version SET version = ?").run(2)}function It(t){if(X(t,"tool_calls"))for(let e of["gfi_before","gfi_after"])t.prepare("SELECT name FROM pragma_table_info('tool_calls') WHERE name = ?").get(e)!==void 0&&t.exec(`ALTER TABLE tool_calls DROP COLUMN ${e}`);X(t,"signal_confirmations")&&t.prepare("UPDATE signal_confirmations SET status = 'abandoned', resolved_at = ?, resolution = ? WHERE status = 'pending' AND suggested_type = 'empathy'").run(new Date().toISOString(),"gfi_removal"),J(t)}function Ae(t,e={}){let n=[],r=[...At];t.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS assistant_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, run_id TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, raw_text TEXT, sanitized_text TEXT NOT NULL, usage_json TEXT NOT NULL, empathy_signal_json TEXT NOT NULL, blob_ref TEXT, raw_excerpt TEXT, stop_reason TEXT, thinking_blocks_count INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS user_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, raw_text TEXT, blob_ref TEXT, raw_excerpt TEXT, correction_detected INTEGER NOT NULL DEFAULT 0, correction_cue TEXT, references_assistant_turn_id INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS tool_calls (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool_name TEXT NOT NULL, outcome TEXT NOT NULL, duration_ms INTEGER, exit_code INTEGER, error_type TEXT, error_message TEXT, params_json TEXT NOT NULL, result_preview TEXT, created_at TEXT NOT NULL, project_dir TEXT, host_kind TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS pain_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, source TEXT NOT NULL, score REAL NOT NULL, reason TEXT, severity TEXT, origin TEXT, confidence REAL, text TEXT, canonical_pain_id TEXT, runtime_task_id TEXT, host_kind TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS gate_blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, tool_name TEXT NOT NULL, file_path TEXT, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS trust_changes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, previous_score REAL NOT NULL, new_score REAL NOT NULL, delta REAL NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS principle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, principle_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS task_outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, task_id TEXT, outcome TEXT NOT NULL, summary TEXT, principle_ids_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS correction_samples (sample_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, bad_assistant_turn_id INTEGER NOT NULL, user_correction_turn_id INTEGER NOT NULL, recovery_tool_span_json TEXT NOT NULL, diff_excerpt TEXT NOT NULL, principle_ids_json TEXT NOT NULL, quality_score REAL NOT NULL, review_status TEXT NOT NULL, export_mode TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sample_reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, sample_id TEXT NOT NULL, review_status TEXT NOT NULL, note TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS signal_confirmations (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_turn_rowid INTEGER NOT NULL UNIQUE, occurrence_id TEXT NOT NULL, excerpt TEXT NOT NULL, terms_json TEXT NOT NULL, suggested_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','confirmed','rejected','abandoned')), attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, resolved_at TEXT, resolution TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS exports_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, export_kind TEXT NOT NULL, mode TEXT NOT NULL, approved_only INTEGER NOT NULL, file_path TEXT NOT NULL, row_count INTEGER NOT NULL, created_at TEXT NOT NULL)");try{t.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!E(s))throw s}t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)");try{t.exec("ALTER TABLE tool_calls ADD COLUMN project_dir TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}if(t.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id ON pain_events(canonical_pain_id) WHERE canonical_pain_id IS NOT NULL"),X(t,"evolution_tasks")){try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!E(s))throw s}}return It(t),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),t.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),t.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(t.exec("CREATE VIEW IF NOT EXISTS v_error_clusters AS SELECT tool_name, COALESCE(error_type, 'unknown') AS error_type, COUNT(*) AS occurrences FROM tool_calls WHERE outcome = 'failure' GROUP BY tool_name, COALESCE(error_type, 'unknown') ORDER BY occurrences DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_principle_effectiveness AS SELECT event_type, COUNT(*) AS total FROM principle_events GROUP BY event_type ORDER BY total DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_sample_queue AS SELECT review_status, COUNT(*) AS total FROM correction_samples GROUP BY review_status")),{tables:r,warnings:n}}import*as Z from"path";import*as Ie from"os";var wt=[/(^|[/\\])fake([/\\]|$)/i,/(^|[/\\])mock([/\\]|$)/i,/(^|[/\\])tmp[/\\]fake-/i],xt=Z.join(Ie.tmpdir(),".pd-test-quarantine");function vt(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return wt.some(n=>n.test(e))}function we(t){if(!t||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!vt(t))return t;let n=t.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;n.startsWith("_");)n=n.slice(1);for(;n.endsWith("_");)n=n.slice(0,-1);return Z.join(xt,n)}var Lt=16*1024,Ct=5e3,Dt=7;function ke(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Mt(t){return!ke(t)||typeof t.id!="number"||typeof t.session_id!="string"?!1:Object.hasOwn(t,"source")&&Object.hasOwn(t,"score")&&Object.hasOwn(t,"reason")&&Object.hasOwn(t,"severity")&&Object.hasOwn(t,"origin")&&Object.hasOwn(t,"confidence")&&Object.hasOwn(t,"text")&&Object.hasOwn(t,"canonical_pain_id")&&Object.hasOwn(t,"runtime_task_id")&&Object.hasOwn(t,"created_at")}function Pt(t){let e=Ae(t,{views:!0});return{tables:e.tables,warnings:e.warnings}}function _(){return new Date().toISOString()}function b(t){return JSON.stringify(t??{})}function xe(t){try{return f.existsSync(t)?f.statSync(t).size:0}catch{return 0}}function jt(t){return t.length>240?`${t.slice(0,237)}...`:t}function ve(t){return t.replace(/[A-Za-z]:\\[^\s"'`]+/g,"<WINDOWS_PATH>").replace(/\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g,"<PATH>").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"<EMAIL>").replace(/\b(sk|rk|pk)_[A-Za-z0-9]+\b/g,"<TOKEN>")}function Ut(t){let e=[],n=!1;try{let r=JSON.parse(String(t.terms_json??"[]"));if(Array.isArray(r))e=r.filter(s=>typeof s=="string");else if(r!==null&&typeof r=="object"){let s=r;if(Object.hasOwn(s,"correction")){let o=s.correction;Array.isArray(o)&&(e=o.filter(i=>typeof i=="string"),n=!0)}}}catch{e=[],n=!1}return{id:String(t.id),sessionId:String(t.session_id),userTurnRowid:Number(t.user_turn_rowid),occurrenceId:String(t.occurrence_id),excerpt:String(t.excerpt),terms:e,termsVerified:n,suggestedType:String(t.suggested_type),status:String(t.status),attempts:Number(t.attempts??0),createdAt:String(t.created_at),resolvedAt:t.resolved_at===null||t.resolved_at===void 0?null:String(t.resolved_at),resolution:t.resolution===null||t.resolution===void 0?null:String(t.resolution)}}var F=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=we(T.resolve(e.workspaceDir)),this.stateDir=O(this.workspaceDir,"STATE_DIR"),this.dbPath=O(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=O(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=O(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??Lt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??Dt)*24*60*60*1e3),f.mkdirSync(this.stateDir,{recursive:!0}),f.mkdirSync(this.blobDir,{recursive:!0}),f.mkdirSync(this.exportDir,{recursive:!0}),this.db=new kt(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.pragma("synchronous = NORMAL"),this.db.pragma(`busy_timeout = ${Math.max(0,e.busyTimeoutMs??Ct)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let n=e.startedAt??_();this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,n)})}upsertSessionUnlocked(e,n){this.db.prepare(`
|
|
5
|
+
`),s+=1;continue}if(" ".includes(c)){(r||n)&&(e.push(n),n="",r=!1),s+=1;continue}if("|;&<>()".includes(c)){(r||n)&&(e.push(n),n="",r=!1);let a=c,d=t[s+1];c==="<"&&d===">"?a="<>":(c==="|"||c==="&"||c===">"||c==="<")&&d===c&&(a+=d),(c===">"||c==="<")&&d==="("&&(a+=d),e.push(a),s+=a.length;continue}n+=c,r=!0,s+=1}return i!=="plain"?null:((r||n)&&e.push(n),e)}function ie(t){if(/[\\$`|;&<>()*?~{}]/.test(t)||[...t].some(s=>s.charCodeAt(0)<32))return;let e=se(t);if(!e)return;let n=[...e],r=n.findIndex(s=>s==="-w"||s==="--workspace");if(r!==-1){let s=n[r+1];if(r!==n.length-2||!s||s.startsWith("-"))return;n.splice(r,2)}for(let s of re){if(s.channel!=="cli"||!s.cliCommand||s.capabilityId!=="pd_status"&&s.capabilityId!=="rulecode_deactivate")continue;let o=se(s.cliCommand);if(!o||o.length!==n.length)continue;if(o.every((c,a)=>s.capabilityId==="rulecode_deactivate"&&o[a-1]==="--activation-id"?/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/.test(n[a]??""):c===n[a]))return s.capabilityId}}var Ue=["verbose","debug"],Be=["erroraction","warningaction","informationaction","progressaction","errorvariable","warningvariable","informationvariable","outvariable","outbuffer","pipelinevariable"];function S(t,e){return{switches:new Set([...Ue,...t]),valued:new Set([...Be,...e])}}var Vt=Object.freeze({"get-content":S(["raw","force","wait","asbytestream"],["path","literalpath","totalcount","first","tail","last","encoding","delimiter","readcount","stream","credential"]),"get-childitem":S(["recurse","force","name","file","directory","hidden","readonly","system","followsymlink"],["path","literalpath","filter","include","exclude","depth","attributes","credential"]),"get-item":S(["force","followsymlink"],["path","literalpath","filter","include","exclude","stream","credential"]),"get-itemproperty":S(["force"],["path","literalpath","name","filter","include","exclude","credential"]),"select-string":S(["simplematch","casesensitive","notmatch","allmatches","quiet","list","raw"],["pattern","path","literalpath","inputobject","encoding","context","include","exclude","credential"]),"test-path":S(["isvalid"],["path","literalpath","pathtype","filter","credential"]),"resolve-path":S(["relative"],["path","literalpath","relativebasepath","credential"]),"get-location":S(["stack"],["psprovider","psdrive"])});function C(t,e=!1){let n=[];for(let r of t.split("/").filter(s=>s.length>0))r!=="."&&(r===".."?n.length>0&&n[n.length-1]!==".."?n.pop():e&&n.push(".."):n.push(r));return n}function $(t){let e=/^([a-zA-Z]):(?:\/|$)/.exec(t);if(e)return{kind:"drive",root:`drive:${(e[1]??"").toUpperCase()}`,segments:C(t.slice(2))};if(/^[a-zA-Z]:/.test(t))return{kind:"drive-relative",root:t.slice(0,2).toUpperCase(),segments:[]};if(/^\/\/[^/]+(?:\/|$)/.test(t)){let n=t.slice(2).split("/").filter(o=>o.length>0),r=n[0]??"",s=n[1]??"";return{kind:"unc",root:`unc:${r}/${s}`,segments:C(n.slice(2).join("/"))}}return t.startsWith("/")?{kind:"posix",root:"posix:/",segments:C(t)}:{kind:"relative",root:"",segments:C(t,!0)}}function ae(t,e,n){return t.length<e.length?!1:e.every((r,s)=>{let o=t[s]??"";return n?o.toLowerCase()===r.toLowerCase():o===r})}function Xe(t,e,n){let r=0;for(;r<t.length&&r<e.length;){let o=t[r]??"",i=e[r]??"";if(!(n?o.toLowerCase()===i.toLowerCase():o===i))break;r++}return[...Array.from({length:t.length-r},()=>".."),...e.slice(r)].join("/")||"."}function ce(t){let[e,n]=t.root.slice(4).split("/"),r=t.segments.join("/");return`//${e??""}/${n??""}${r?`/${r}`:""}`}function le(t,e,n){if(t.kind==="drive-relative"||t.kind==="unc"&&t.root.endsWith("/"))return n;if(t.kind!=="relative")return!(t.kind===e.kind&&(t.kind==="unc"?t.root.toLowerCase()===e.root.toLowerCase():t.root===e.root))||!ae(t.segments,e.segments,t.kind==="drive"||t.kind==="unc")?t.kind==="unc"?ce(t):n:t.segments.slice(e.segments.length).join("/")||".";let r=[...e.segments];for(let o of n.split("/").filter(i=>i.length>0))o!=="."&&(o===".."?r.length>0&&r[r.length-1]!==".."?r.pop():e.kind==="relative"&&r.push(".."):r.push(o));let s=e.kind==="drive"||e.kind==="unc";return ae(r,e.segments,s)?r.slice(e.segments.length).join("/")||".":Xe(e.segments,r,s)}function Fe(t,e){if(!t||typeof t!="string")return"";let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/");if(n.startsWith("<tool:")&&n.endsWith(">"))return n;let s=$(n),o=$(r);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let c=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=$(c),le(s,o,c)}return le(s,o,n)}function We(t,e){let n=t.file_path||t.path||t.file||t.target;if(typeof n=="string"&&n.length>0)return{value:n,isPath:!0};if(e.isBashTool){let r=String(t.command||t.args||"");if(r){let s=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(r);return s&&s[1]?{value:s[1],isPath:!0}:{value:r,isPath:!1}}}return e.isWriteTool&&e.toolName?{value:`<tool:${e.toolName}>`,isPath:!0}:{value:null,isPath:!0}}function $e(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function He(t){if(t.canonicalKind===void 0)return t;let e=$e(t.canonicalKind);return{...t,isBashTool:e.isBashTool,isWriteTool:e.isWriteTool}}function D(t,e,n,r={}){let s=He(r),o=We(e,{...s,toolName:t}),i=o.isPath?Fe(o.value,n):o.value,c=e.command??e.args,a=s.isBashTool&&typeof c=="string"?ie(c):void 0;return{toolName:t,normalizedPath:i,...a?{recoveryControl:a}:{},paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var H=new Set(["read","search","write","execute","agent","other"]);function ue(t){return typeof t=="string"&&H.has(t)}var M=Object.freeze({read:"read",read_file:"read",read_many_files:"read",grep:"search",grep_search:"search",search_file_content:"search",glob:"search",write:"write",write_file:"write",edit:"write",edit_file:"write",replace:"write",apply_patch:"write",bash:"execute",exec:"execute",execute:"execute",run_shell_command:"execute",execute_command:"execute",run_script:"execute",code_interpreter:"execute",sessions_spawn:"agent"});function de(t,e,n){if(t.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let r=0,s=0,o=new Set,i=e===null?"unknown":"no",{calls:c}=t;for(let a of c){let d=a.canonicalKind;d==="read"||d==="search"?(r++,e!==null&&a.normalizedPath===e&&(i="yes")):d==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:r,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:n}}var pe={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(pe);var Y={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(Y.calls);Object.freeze(Y);var Ye={version:2,history:Y,facts:pe};Object.freeze(Ye);var Ke=new Set(["__proto__","constructor","prototype"]),fe=3,Ge=5,qe=new Set(["allow","block","propose_correction"]),ze={valid:!0,errors:[]};function K(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ee(t){for(let e of Object.keys(t))if(Ke.has(e))return!1;return!0}function Ve(t){return t.length===0?ze:{valid:!1,errors:t}}function G(t){return typeof t=="string"&&t.trim().length>0}function _e(t,e,n){let r=[];return K(t)?Ee(t)?((!Object.hasOwn(t,"caseId")||!G(t.caseId))&&r.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(t,"kind")||t.kind!==n)&&r.push(`${e}.kind must be '${n}'`),(!Object.hasOwn(t,"toolName")||!G(t.toolName))&&r.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(t,"params")||!K(t.params))&&r.push(`${e}.params must be a plain object`),!Object.hasOwn(t,"expectedDecision")||typeof t.expectedDecision!="string"||!qe.has(t.expectedDecision)?r.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):n==="positive"&&t.expectedDecision!=="allow"&&r.push(`${e}: positive cases must expect allow`),r):(r.push(`${e} must not carry prototype-pollution keys`),r):(r.push(`${e} must be a plain object`),r)}function me(t,e){let{fieldName:n,maxLength:r,requireNonEmpty:s}=e,o=[];if(!Array.isArray(t))return o.push(`${n} must be an array`),o;s&&t.length===0&&o.push(`${n} must contain at least 1 item`),r!==void 0&&t.length>r&&o.push(`${n} must contain at most ${r} items, got ${t.length}`);for(let i=0;i<t.length;i++)typeof t[i]!="string"&&o.push(`${n}[${i}] must be a string`);return o}function P(t){return Array.isArray(t)?`[${t.map(e=>P(e)).join(",")}]`:typeof t=="object"&&t!==null?`{${Object.keys(t).filter(n=>n!=="__proto__"&&n!=="constructor"&&n!=="prototype").sort().map(n=>`${JSON.stringify(n)}:${P(t[n])}`).join(",")}}`:JSON.stringify(t)??"null"}function q(t){if(!K(t))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!Ee(t))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(t,"sourceNegativeCase")?e.push(..._e(t.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(t,"ownerDesiredOutcome")||!G(t.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(t,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(t.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let n=t.positiveCounterexamples;n.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),n.length>fe&&e.push(`positiveCounterexamples must contain at most ${fe} items, got ${n.length}`);for(let r=0;r<n.length;r++)e.push(..._e(n[r],`positiveCounterexamples[${r}]`,"positive"))}if(Object.hasOwn(t,"evidenceRefs")?e.push(...me(t.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Ge,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(t,"redactionNotes")?e.push(...me(t.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let n=t.sourceNegativeCase,r=t.positiveCounterexamples,s=P({toolName:n.toolName,params:n.params,ruleContext:n.ruleContext});for(let o=0;o<r.length;o++){let i=r[o];i!==void 0&&P({toolName:i.toolName,params:i.params,ruleContext:i.ruleContext})===s&&e.push(`positiveCounterexamples[${o}] conflicting_label: identical effective input (toolName + params + ruleContext) as sourceNegativeCase but opposite expectedDecision \u2014 same input cannot carry both labels`)}}return Ve(e)}var Je="OwnerEvidenceScopeError";function A(t,e){let n=new Error(e);return n.name=Je,Object.assign(n,{ownerEvidenceScopeKind:t}),n}var Ze=new Set(["success","failure","blocked"]);function Qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function et(t){return typeof t=="string"&&Ze.has(t)}function I(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function Te(t,e,n){let{projectDir:r,toolSemantics:s}=n,o=[];for(let i of t){let{toolName:c}=i;if(typeof c!="string"||c.length===0)return I(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:a}=i;if(!et(a))return I(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let d=i.paramsJson;if(typeof d!="string")return I(`row id=${i.id}: params_json must be a string`);let h;try{h=JSON.parse(d)}catch{return I(`row id=${i.id}: params_json is not valid JSON`)}if(!Qe(h))return I(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(c),{normalizedPath:g}=D(c,h,r,{canonicalKind:m});o.push({sequenceId:i.id,toolName:c,canonicalKind:m,normalizedPath:g===""?null:g,paramsSummary:h,outcome:a})}return{status:"available",truncated:e,calls:o}}var tt=3,nt=5,rt=100,ge=new Set(["__proto__","constructor","prototype"]);function j(t,e){try{return e()}catch(n){let r=n instanceof Error?n.message:String(n);throw A("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function st(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ot(t){for(let e of Object.keys(t))if(ge.has(e))return!1;return!0}function it(t){if(!Number.isSafeInteger(t.sourceNegativeToolCallId)||t.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(t.positiveToolCallIds)||t.positiveToolCallIds.length===0||t.positiveToolCallIds.length>tt)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[t.sourceNegativeToolCallId,...t.positiveToolCallIds];if(e.some(n=>!Number.isSafeInteger(n)||n<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function he(t,e){if(!t)throw A("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function at(t,e,n){if(typeof t.toolName!="string"||t.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof t.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must be a string (rc-9 fail loud)`);let r;try{r=JSON.parse(t.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!st(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!ot(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${t.id}`,kind:e,toolName:t.toolName,params:r,expectedDecision:n}}function ct(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var lt=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function ut(t){if(t.length<20)return!1;for(let e of lt)if(e.test(t))return!0;return!1}function dt(t,e){let n=[],r={};for(let s of Object.keys(t)){if(ge.has(s))continue;let o=t[s];if(typeof o!="string"){r[s]=o;continue}if(ct(o)&&!o.startsWith(e)){r[s]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(ut(o)){r[s]="<redacted:secret>",n.push(`redacted possible secret in field "${s}"`);continue}r[s]=o}return{redacted:r,notes:n}}var U=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let n=j(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!n)throw A("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);it(e);let r=he(j(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(m=>he(j(`evidence row read for id=${m}`,()=>this.db.getRuleHostEvidenceRow(m)),m));for(let m of[r,...s])if(m.sessionId!==n.sessionId)throw A("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${m.id} session mismatch; all examples must belong to pain session ${n.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(r,"negative",i),a=s.map(m=>this.buildSelectedCase(m,"positive",i)),d={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${n.id}`,`tool_call:${r.id}`,...s.map(m=>`tool_call:${m.id}`)].slice(0,nt),redactionNotes:o},h=q(d);if(!h.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${h.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,n,r){let{projectDir:s,redactionNotes:o}=r,i=at(e,n,n==="negative"?"block":"allow"),c=dt(i.params,s);o.push(...c.notes);let a=j(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,rt)),d=Te(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),h=D(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:d,facts:de(d,h.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:m}}};import kt from"better-sqlite3";import f from"fs";import T from"path";import Q from"crypto";import*as p from"fs";import*as ye from"path";var z=class extends Error{filePath;lockPath;constructor(e,n,r){super(e),this.name="LockAcquisitionError",this.filePath=n,this.lockPath=r}},pt={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function Oe(t){try{return process.kill(t,0),!0}catch{return!1}}function Se(t,e){try{let n=ye.dirname(t);p.existsSync(n)||p.mkdirSync(n,{recursive:!0});let r=p.constants.O_WRONLY|p.constants.O_CREAT|p.constants.O_EXCL,s=p.openSync(t,r);return p.writeSync(s,String(e)),p.fsyncSync(s),p.closeSync(s),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function w(t){try{let e=p.readFileSync(t,"utf8"),n=parseInt(e.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function ft(t,e){try{w(t)===e&&p.unlinkSync(t)}catch{}}function _t(t,e){try{let n=p.statSync(t),r=w(t),s=Date.now()-n.mtimeMs>e,o=r===null||!Oe(r);if(s||o)try{return p.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function mt(t,e,n){let r=Math.min(e*Math.pow(2,t),n),s=r*.2*Math.random();return Math.floor(r+s)}function Et(t){let e=Date.now()+t;for(;Date.now()<e;);}function Tt(t,e){let n=w(e),r=n!==null?Oe(n)?`alive (PID ${n})`:`dead (PID ${n})`:"unknown";return new z(`Failed to acquire lock for ${t}. Lock holder: ${r}.`,t,e)}function ht(t,e,n){let r=t+e.lockSuffix;return Se(r,n)&&w(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(_t(r,e.lockStaleMs),Se(r,n)&&w(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function gt(t,e={}){let n={...pt,...e},{pid:r}=process;for(let s=0;s<n.maxRetries;s++){let o=ht(t,n,r);if(o)return o;if(s<n.maxRetries-1){let i=mt(s,n.baseRetryDelayMs,n.maxRetryDelayMs);Et(i)}}throw Tt(t,t+n.lockSuffix)}function St(t){ft(t.lockPath,t.pid)}function Re(t,e,n={}){let r=gt(t,n);try{return e()}finally{St(r)}}import*as R from"fs";var be=3,yt=50;function B(t,e){let n=t+".tmp";R.writeFileSync(n,e,"utf8");let r;for(let s=0;s<be;s++)try{R.renameSync(n,t);return}catch(o){r=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<be-1){let c=yt*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{Pe("fs").accessSync?.(n)}catch{}d=!0}}continue}break}try{R.unlinkSync(n)}catch{}throw r}import*as y from"path";var l=(...t)=>y.posix.join(...t);function Ot(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function Rt(t,e){return Ot(t)?y.win32.join(t,e):t.startsWith("/")?y.posix.join(t,e):y.join(t,e)}var u={IDENTITY:".principles",MODELS:l(".principles","models"),STATE:".state",MEMORY:"memory",OKR:l("memory","okr"),LOGS:l("memory","logs"),SESSIONS:l(".state","sessions"),PAIN_SAMPLES:l("memory","pain"),LOCKS:l("memory",".locks"),IMPL_CODE_DIR:l(".state","principles","implementations")},bt={PROFILE:l(u.IDENTITY,"PROFILE.json"),PRINCIPLES:l(u.IDENTITY,"PRINCIPLES.md"),THINKING_OS:l(u.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:l(u.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:u.MODELS,STATE_DIR:u.STATE,WORKBOARD:l(u.STATE,"WORKBOARD.json"),AGENT_SCORECARD:l(u.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:l(u.STATE,".pain_flag"),SYSTEM_CAPABILITIES:l(u.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:l(u.STATE,"pain_settings.json"),PAIN_CANDIDATES:l(u.STATE,"pain_candidates.json"),TRAJECTORY_DB:l(u.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:l(u.STATE,"blobs"),EXPORTS_DIR:l(u.STATE,"exports"),SESSION_DIR:u.SESSIONS,DICTIONARY:l(u.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:l(u.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:l(u.STATE,"workflows.yaml"),IMPL_CODE_DIR:u.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:l(u.LOGS,"SYSTEM.log"),REFLECTION_LOG:l(u.MEMORY,"reflection-log.md"),USER_CONTEXT:l(u.MEMORY,"USER_CONTEXT.md"),OKR_DIR:u.OKR,CURRENT_FOCUS:l(u.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:l(u.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:l(u.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:l(u.LOCKS,"evolution")};function O(t,e){return Rt(t,bt[e])}var Nt={LOCK_UNAVAILABLE:"lease_conflict",PATH_RESOLUTION_ERROR:"workspace_invalid",WORKSPACE_NOT_FOUND:"workspace_invalid",SAMPLE_NOT_FOUND:"storage_unavailable",CONFIGURATION_ERROR:"input_invalid",DEPENDENCY_ERROR:"runtime_unavailable",EVOLUTION_PROCESSING_ERROR:"execution_failed",TRAJECTORY_ERROR:"storage_unavailable"},V=class extends Error{constructor(n,r,s){super(n,s);this.code=r;this.name="PdError",this.category=Nt[r]??"execution_failed"}code;category};var x=class extends V{constructor(e,n){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};var At=["schema_version","ingest_checkpoint","sessions","assistant_turns","user_turns","tool_calls","pain_events","gate_blocks","trust_changes","principle_events","task_outcomes","correction_samples","sample_reviews","signal_confirmations","exports_audit"],Ne={sessions:{session_id:"TEXT",started_at:"TEXT",updated_at:"TEXT"},tool_calls:{session_id:"TEXT",tool_name:"TEXT",outcome:"TEXT",duration_ms:"INTEGER",exit_code:"INTEGER",error_type:"TEXT",error_message:"TEXT",params_json:"TEXT",result_preview:"TEXT",created_at:"TEXT",project_dir:"TEXT"},pain_events:{session_id:"TEXT",source:"TEXT",score:"REAL",reason:"TEXT",severity:"TEXT",origin:"TEXT",confidence:"REAL",text:"TEXT",canonical_pain_id:"TEXT",runtime_task_id:"TEXT",host_kind:"TEXT",created_at:"TEXT"}};for(let t of Object.values(Ne))Object.freeze(t);Object.freeze(Ne);function E(t){let e=t instanceof Error?t.message:String(t);return e.includes("duplicate column name")||e.includes("no column named")}function X(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function J(t){if(!X(t,"schema_version"))return;let e=t.prepare("SELECT version FROM schema_version LIMIT 1").get();if(e===void 0){t.prepare("INSERT INTO schema_version (version) VALUES (?)").run(2);return}e.version!==2&&t.prepare("UPDATE schema_version SET version = ?").run(2)}function It(t){if(X(t,"tool_calls"))for(let e of["gfi_before","gfi_after"])t.prepare("SELECT name FROM pragma_table_info('tool_calls') WHERE name = ?").get(e)!==void 0&&t.exec(`ALTER TABLE tool_calls DROP COLUMN ${e}`);X(t,"signal_confirmations")&&t.prepare("UPDATE signal_confirmations SET status = 'abandoned', resolved_at = ?, resolution = ? WHERE status = 'pending' AND suggested_type = 'empathy'").run(new Date().toISOString(),"gfi_removal"),J(t)}function Ae(t,e={}){let n=[],r=[...At];t.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS assistant_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, run_id TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, raw_text TEXT, sanitized_text TEXT NOT NULL, usage_json TEXT NOT NULL, empathy_signal_json TEXT NOT NULL, blob_ref TEXT, raw_excerpt TEXT, stop_reason TEXT, thinking_blocks_count INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS user_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, raw_text TEXT, blob_ref TEXT, raw_excerpt TEXT, correction_detected INTEGER NOT NULL DEFAULT 0, correction_cue TEXT, references_assistant_turn_id INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS tool_calls (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool_name TEXT NOT NULL, outcome TEXT NOT NULL, duration_ms INTEGER, exit_code INTEGER, error_type TEXT, error_message TEXT, params_json TEXT NOT NULL, result_preview TEXT, created_at TEXT NOT NULL, project_dir TEXT, host_kind TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS pain_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, source TEXT NOT NULL, score REAL NOT NULL, reason TEXT, severity TEXT, origin TEXT, confidence REAL, text TEXT, canonical_pain_id TEXT, runtime_task_id TEXT, host_kind TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS gate_blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, tool_name TEXT NOT NULL, file_path TEXT, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS trust_changes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, previous_score REAL NOT NULL, new_score REAL NOT NULL, delta REAL NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS principle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, principle_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS task_outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, task_id TEXT, outcome TEXT NOT NULL, summary TEXT, principle_ids_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS correction_samples (sample_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, bad_assistant_turn_id INTEGER NOT NULL, user_correction_turn_id INTEGER NOT NULL, recovery_tool_span_json TEXT NOT NULL, diff_excerpt TEXT NOT NULL, principle_ids_json TEXT NOT NULL, quality_score REAL NOT NULL, review_status TEXT NOT NULL, export_mode TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sample_reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, sample_id TEXT NOT NULL, review_status TEXT NOT NULL, note TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS signal_confirmations (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_turn_rowid INTEGER NOT NULL UNIQUE, occurrence_id TEXT NOT NULL, excerpt TEXT NOT NULL, terms_json TEXT NOT NULL, suggested_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','confirmed','rejected','abandoned')), attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, resolved_at TEXT, resolution TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS exports_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, export_kind TEXT NOT NULL, mode TEXT NOT NULL, approved_only INTEGER NOT NULL, file_path TEXT NOT NULL, row_count INTEGER NOT NULL, created_at TEXT NOT NULL)");try{t.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!E(s))throw s}t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)");try{t.exec("ALTER TABLE tool_calls ADD COLUMN project_dir TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}if(t.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id ON pain_events(canonical_pain_id) WHERE canonical_pain_id IS NOT NULL"),X(t,"evolution_tasks")){try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!E(s))throw s}}return It(t),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),t.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),t.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(t.exec("CREATE VIEW IF NOT EXISTS v_error_clusters AS SELECT tool_name, COALESCE(error_type, 'unknown') AS error_type, COUNT(*) AS occurrences FROM tool_calls WHERE outcome = 'failure' GROUP BY tool_name, COALESCE(error_type, 'unknown') ORDER BY occurrences DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_principle_effectiveness AS SELECT event_type, COUNT(*) AS total FROM principle_events GROUP BY event_type ORDER BY total DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_sample_queue AS SELECT review_status, COUNT(*) AS total FROM correction_samples GROUP BY review_status")),{tables:r,warnings:n}}import*as Z from"path";import*as Ie from"os";var wt=[/(^|[/\\])fake([/\\]|$)/i,/(^|[/\\])mock([/\\]|$)/i,/(^|[/\\])tmp[/\\]fake-/i],xt=Z.join(Ie.tmpdir(),".pd-test-quarantine");function vt(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return wt.some(n=>n.test(e))}function we(t){if(!t||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!vt(t))return t;let n=t.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;n.startsWith("_");)n=n.slice(1);for(;n.endsWith("_");)n=n.slice(0,-1);return Z.join(xt,n)}var Lt=16*1024,Ct=5e3,Dt=7;function ke(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Mt(t){return!ke(t)||typeof t.id!="number"||typeof t.session_id!="string"?!1:Object.hasOwn(t,"source")&&Object.hasOwn(t,"score")&&Object.hasOwn(t,"reason")&&Object.hasOwn(t,"severity")&&Object.hasOwn(t,"origin")&&Object.hasOwn(t,"confidence")&&Object.hasOwn(t,"text")&&Object.hasOwn(t,"canonical_pain_id")&&Object.hasOwn(t,"runtime_task_id")&&Object.hasOwn(t,"created_at")}function Pt(t){let e=Ae(t,{views:!0});return{tables:e.tables,warnings:e.warnings}}function _(){return new Date().toISOString()}function b(t){return JSON.stringify(t??{})}function xe(t){try{return f.existsSync(t)?f.statSync(t).size:0}catch{return 0}}function jt(t){return t.length>240?`${t.slice(0,237)}...`:t}function ve(t){return t.replace(/[A-Za-z]:\\[^\s"'`]+/g,"<WINDOWS_PATH>").replace(/\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g,"<PATH>").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"<EMAIL>").replace(/\b(sk|rk|pk)_[A-Za-z0-9]+\b/g,"<TOKEN>")}function Ut(t){let e=[],n=!1;try{let r=JSON.parse(String(t.terms_json??"[]"));if(Array.isArray(r))e=r.filter(s=>typeof s=="string");else if(r!==null&&typeof r=="object"){let s=r;if(Object.hasOwn(s,"correction")){let o=s.correction;Array.isArray(o)&&(e=o.filter(i=>typeof i=="string"),n=!0)}}}catch{e=[],n=!1}return{id:String(t.id),sessionId:String(t.session_id),userTurnRowid:Number(t.user_turn_rowid),occurrenceId:String(t.occurrence_id),excerpt:String(t.excerpt),terms:e,termsVerified:n,suggestedType:String(t.suggested_type),status:String(t.status),attempts:Number(t.attempts??0),createdAt:String(t.created_at),resolvedAt:t.resolved_at===null||t.resolved_at===void 0?null:String(t.resolved_at),resolution:t.resolution===null||t.resolution===void 0?null:String(t.resolution)}}var F=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=we(T.resolve(e.workspaceDir)),this.stateDir=O(this.workspaceDir,"STATE_DIR"),this.dbPath=O(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=O(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=O(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??Lt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??Dt)*24*60*60*1e3),f.mkdirSync(this.stateDir,{recursive:!0}),f.mkdirSync(this.blobDir,{recursive:!0}),f.mkdirSync(this.exportDir,{recursive:!0}),this.db=new kt(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.pragma("synchronous = NORMAL"),this.db.pragma(`busy_timeout = ${Math.max(0,e.busyTimeoutMs??Ct)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let n=e.startedAt??_();this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,n)})}upsertSessionUnlocked(e,n){this.db.prepare(`
|
|
6
6
|
INSERT INTO sessions (session_id, started_at, updated_at)
|
|
7
7
|
VALUES (?, ?, ?)
|
|
8
8
|
ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
|
-
"version": "3.1
|
|
5
|
+
"version": "3.2.1",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
package/plugin/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "principles-disciple",
|
|
3
|
-
"version": "3.1
|
|
3
|
+
"version": "3.2.1",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -12,7 +12,8 @@ import { logger } from './utils/logger.js';
|
|
|
12
12
|
import { checkOpenClawGateway, stopOpenClawGateway, restartOpenClawGateway } from './utils/env.js';
|
|
13
13
|
import { t } from './i18n.js';
|
|
14
14
|
import { generateConfigYamlContent, ExistingConfigVerifyInfraError, validateExistingConfigYamlForPreserve, getConfigYamlPath, readEnabledChannelsFromConfigYaml, getOpenClawDir, getPdDir, getPdRuntimeDir, getInstallManifestPath, getPdRuntimeBackupsDir, getPluginExtDir, getInstalledPluginDir, getInstalledLayoutPackageDir, getPdBackupsDir, getInstalledPdCliDir, getInstalledBinDir, getInstalledConsoleDir, getHomeDir, isWindows, } from './mvp-config.js';
|
|
15
|
-
import { getHostInstallers } from './installers/index.js';
|
|
15
|
+
import { detectInstalledHosts, getHostInstallers } from './installers/index.js';
|
|
16
|
+
import { readCanonicalRuntimeCohort, readInstalledRuntimeCohort, resolvePluginDataRoot } from './installers/codex-host-installer.js';
|
|
16
17
|
import { runWorkbuddyEarlyPreflight } from './installers/workbuddy-host-installer.js';
|
|
17
18
|
import { INSTALL_LAYOUT_VERSION, getInstallLayoutPaths, getWorkbuddyWorkspaceDir, installManifestHostsForPersist, mergeInstallManifestWorkspaces, parseInstallManifest } from '@principles/install-layout';
|
|
18
19
|
import { resolveMcpServerDir } from './mcp-server-layout-compat.js';
|
|
@@ -209,6 +210,25 @@ export function resolveHostRefreshTargets(persistedHosts, host) {
|
|
|
209
210
|
}
|
|
210
211
|
return targets;
|
|
211
212
|
}
|
|
213
|
+
/** Union the detected (already-installed) hosts into the manifest host list. */
|
|
214
|
+
function withDetectedHosts(hosts, detected) {
|
|
215
|
+
const merged = [...hosts];
|
|
216
|
+
for (const host of detected) {
|
|
217
|
+
if (!merged.includes(host.hostId))
|
|
218
|
+
merged.push(host.hostId);
|
|
219
|
+
}
|
|
220
|
+
return merged;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* One upgrade must cover every host that already carries PD (2026-11-11).
|
|
224
|
+
* Pure so the coverage rule is testable without running a whole install.
|
|
225
|
+
*/
|
|
226
|
+
export function planUpgradeHosts(requested, persistedHosts, detected) {
|
|
227
|
+
return {
|
|
228
|
+
refreshTargets: resolveHostRefreshTargets([...persistedHosts, ...detected.map((host) => host.hostId)], requested),
|
|
229
|
+
newlyCovered: detected.filter((host) => !persistedHosts.includes(host.hostId)),
|
|
230
|
+
};
|
|
231
|
+
}
|
|
212
232
|
/**
|
|
213
233
|
* PRI-624 Slice C: the install manifest records every Workspace this install
|
|
214
234
|
* serves so the Companion can discover its per-Workspace workers (SPEC §13
|
|
@@ -1331,16 +1351,52 @@ function protocolInvalid(detail) {
|
|
|
1331
1351
|
remediation: 'The compatibility scanner returned an unexpected result. Re-download/rebuild the installer before upgrading. The current installation has not been replaced.',
|
|
1332
1352
|
};
|
|
1333
1353
|
}
|
|
1354
|
+
const MAX_SKIP_BUCKETS = 50;
|
|
1355
|
+
/** Sentinel so "absent scannedActivations" stays distinguishable from 0. */
|
|
1356
|
+
const INVALID_COUNT = Symbol('invalid-count');
|
|
1357
|
+
/** rc-4: validate every bucket field, not just "is an array". */
|
|
1358
|
+
function parseSkippedBuckets(value) {
|
|
1359
|
+
if (value === undefined)
|
|
1360
|
+
return [];
|
|
1361
|
+
if (!Array.isArray(value) || value.length > MAX_SKIP_BUCKETS)
|
|
1362
|
+
return null;
|
|
1363
|
+
const buckets = [];
|
|
1364
|
+
for (const entry of value) {
|
|
1365
|
+
if (!isRecord(entry))
|
|
1366
|
+
return null;
|
|
1367
|
+
const { reason } = entry;
|
|
1368
|
+
const { count } = entry;
|
|
1369
|
+
const samples = entry.sampleActivationIds;
|
|
1370
|
+
if (typeof reason !== 'string' || reason.length === 0)
|
|
1371
|
+
return null;
|
|
1372
|
+
if (typeof count !== 'number' || !Number.isInteger(count) || count <= 0)
|
|
1373
|
+
return null;
|
|
1374
|
+
if (!Array.isArray(samples) || !samples.every((id) => typeof id === 'string'))
|
|
1375
|
+
return null;
|
|
1376
|
+
buckets.push({ reason, count, sampleActivationIds: [...samples] });
|
|
1377
|
+
}
|
|
1378
|
+
return buckets;
|
|
1379
|
+
}
|
|
1380
|
+
function parseScannedActivations(value) {
|
|
1381
|
+
if (value === undefined)
|
|
1382
|
+
return undefined;
|
|
1383
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0)
|
|
1384
|
+
return INVALID_COUNT;
|
|
1385
|
+
return value;
|
|
1386
|
+
}
|
|
1334
1387
|
/**
|
|
1335
1388
|
* Strict (ok, status) protocol parse (P2, 2026-08-20).
|
|
1336
1389
|
*
|
|
1337
1390
|
* Boolean `ok` alone is NOT authoritative — the (ok, status) pair is the
|
|
1338
|
-
* contract. Only ok=true + (clean|no_state_db) is a successful
|
|
1339
|
-
* other combination fails closed:
|
|
1340
|
-
* - ok=true + refusal
|
|
1341
|
-
* - ok=
|
|
1391
|
+
* contract. Only ok=true + (clean|no_state_db|incomplete) is a successful
|
|
1392
|
+
* scan. Every other combination fails closed:
|
|
1393
|
+
* - ok=true + refusal status → protocol invalid
|
|
1394
|
+
* - ok=true + clean/no_state_db + skipped rows → protocol invalid (a
|
|
1395
|
+
* consumer may never quietly downgrade `incomplete` to `clean`)
|
|
1396
|
+
* - ok=true + incomplete + empty skipped → protocol invalid
|
|
1397
|
+
* - ok=false + clean|no_state_db|incomplete/unknown → protocol invalid
|
|
1342
1398
|
* - ok=false + legacy_dependency|scan_failed|scan_unavailable → refusal
|
|
1343
|
-
* - non-boolean / missing ok
|
|
1399
|
+
* - non-boolean / missing ok → protocol invalid
|
|
1344
1400
|
* The payload is never trusted to self-describe a pass.
|
|
1345
1401
|
*/
|
|
1346
1402
|
export function parseCompatibilityScanStdout(stdout) {
|
|
@@ -1360,9 +1416,34 @@ export function parseCompatibilityScanStdout(stdout) {
|
|
|
1360
1416
|
const status = typeof parsed.status === 'string' ? parsed.status : 'unknown';
|
|
1361
1417
|
const reason = typeof parsed.reason === 'string' ? parsed.reason : undefined;
|
|
1362
1418
|
const remediation = typeof parsed.remediation === 'string' ? parsed.remediation : undefined;
|
|
1419
|
+
const skipped = parseSkippedBuckets(parsed.skipped);
|
|
1420
|
+
if (skipped === null) {
|
|
1421
|
+
return protocolInvalid('skipped is not a valid [{reason,count,sampleActivationIds}] array');
|
|
1422
|
+
}
|
|
1423
|
+
const scannedActivations = parseScannedActivations(parsed.scannedActivations);
|
|
1424
|
+
if (scannedActivations === INVALID_COUNT) {
|
|
1425
|
+
return protocolInvalid('scannedActivations is not a non-negative integer');
|
|
1426
|
+
}
|
|
1427
|
+
const skippedTotal = skipped.reduce((sum, bucket) => sum + bucket.count, 0);
|
|
1428
|
+
const visibility = {
|
|
1429
|
+
skipped,
|
|
1430
|
+
...(scannedActivations !== undefined ? { scannedActivations } : {}),
|
|
1431
|
+
};
|
|
1363
1432
|
if (parsed.ok === true) {
|
|
1364
1433
|
if (status === 'clean' || status === 'no_state_db') {
|
|
1365
|
-
|
|
1434
|
+
// Hard constraint (5B): `incomplete` must never be degraded to `clean`
|
|
1435
|
+
// by a consumer. A payload that admits it skipped rows while claiming
|
|
1436
|
+
// clean is self-contradictory, not a pass.
|
|
1437
|
+
if (skipped.length > 0) {
|
|
1438
|
+
return protocolInvalid(`ok=true with status=${status} but skipped=${skippedTotal}`);
|
|
1439
|
+
}
|
|
1440
|
+
return { ok: true, status, ...visibility };
|
|
1441
|
+
}
|
|
1442
|
+
if (status === 'incomplete') {
|
|
1443
|
+
if (skipped.length === 0) {
|
|
1444
|
+
return protocolInvalid('ok=true with status=incomplete but skipped is empty');
|
|
1445
|
+
}
|
|
1446
|
+
return { ok: true, status, ...visibility };
|
|
1366
1447
|
}
|
|
1367
1448
|
return protocolInvalid(`ok=true with status=${status}`);
|
|
1368
1449
|
}
|
|
@@ -1374,6 +1455,52 @@ export function parseCompatibilityScanStdout(stdout) {
|
|
|
1374
1455
|
}
|
|
1375
1456
|
return protocolInvalid(`ok is not a boolean`);
|
|
1376
1457
|
}
|
|
1458
|
+
/**
|
|
1459
|
+
* 5B: turn the scan's `skipped` buckets into operator-facing lines.
|
|
1460
|
+
*
|
|
1461
|
+
* INTENTIONAL CHOICE — these are warnings, never a refusal. A non-interactive
|
|
1462
|
+
* install that hard-failed here would strand the user: the old installation is
|
|
1463
|
+
* untouched, but the upgrade is blocked with no in-product repair path (they
|
|
1464
|
+
* would have to hand-edit the workspace DB before the installer would run).
|
|
1465
|
+
* Escalate to a hard failure only if a real incident is attributed to an
|
|
1466
|
+
* upgrade that ran with unverified ACTIVE rules; the escalation condition is
|
|
1467
|
+
* then `level === 'critical'` (zero rules verified) and belongs here.
|
|
1468
|
+
*/
|
|
1469
|
+
export function summarizeCompatibilityVisibility(outcome, workspaceDir) {
|
|
1470
|
+
const skipped = outcome.skipped ?? [];
|
|
1471
|
+
if (skipped.length === 0)
|
|
1472
|
+
return { level: 'none', lines: [] };
|
|
1473
|
+
const total = skipped.reduce((sum, bucket) => sum + bucket.count, 0);
|
|
1474
|
+
const rows = skipped.map((bucket) => {
|
|
1475
|
+
const sample = bucket.sampleActivationIds.length > 0 ? ` (sample: ${bucket.sampleActivationIds.join(', ')})` : '';
|
|
1476
|
+
return `${bucket.reason}=${bucket.count}${sample}`;
|
|
1477
|
+
});
|
|
1478
|
+
const nextCommand = `pd runtime compatibility-scan --workspace "${workspaceDir}" --json`;
|
|
1479
|
+
if (outcome.scannedActivations === 0) {
|
|
1480
|
+
const border = '!'.repeat(74);
|
|
1481
|
+
return {
|
|
1482
|
+
level: 'critical',
|
|
1483
|
+
lines: [
|
|
1484
|
+
border,
|
|
1485
|
+
'!! WARNING: THIS UPGRADE DID NOT VERIFY ANY RULE COMPATIBILITY',
|
|
1486
|
+
`!! ${total} ACTIVE rule(s) could not be read and 0 ACTIVE rule(s) were scanned,`,
|
|
1487
|
+
'!! so no ACTIVE rule was checked for retired-contract dependencies.',
|
|
1488
|
+
`!! ${rows.join(' | ')}`,
|
|
1489
|
+
'!! The upgrade proceeds; verify now:',
|
|
1490
|
+
`!! ${nextCommand}`,
|
|
1491
|
+
border,
|
|
1492
|
+
],
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
return {
|
|
1496
|
+
level: 'warning',
|
|
1497
|
+
lines: [
|
|
1498
|
+
`warning: ${total} ACTIVE rule(s) could not be read during the compatibility check — their compatibility is NOT verified.`,
|
|
1499
|
+
...rows.map((row) => ` ${row}`),
|
|
1500
|
+
`next: ${nextCommand}`,
|
|
1501
|
+
],
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1377
1504
|
/**
|
|
1378
1505
|
* PRI-693 / PRI-1060: materialize node_modules links for the BUNDLED (not yet
|
|
1379
1506
|
* deployed) components so the pre-deployment compatibility scan can execute
|
|
@@ -3624,6 +3751,44 @@ export function partitionHostInstallResults(results) {
|
|
|
3624
3751
|
}
|
|
3625
3752
|
return { failures, manualActions };
|
|
3626
3753
|
}
|
|
3754
|
+
/**
|
|
3755
|
+
* UPDATE CHAIN (2026-11-11): the Owner-visible install summary. Every host
|
|
3756
|
+
* this run actually touched gets one line naming the runtime it now resolves,
|
|
3757
|
+
* so covering an already-installed host can never happen silently.
|
|
3758
|
+
*
|
|
3759
|
+
* The two runtime layouts are different authorities, not interchangeable
|
|
3760
|
+
* views: the shared canonical runtime is `<dir>/<component>/package.json`,
|
|
3761
|
+
* while Codex's PLUGIN_DATA copy is `<dir>/node_modules/<pkg>/package.json`.
|
|
3762
|
+
* Reading the canonical dir with the PLUGIN_DATA reader made every
|
|
3763
|
+
* OpenClaw/WorkBuddy line print "runtime not verified".
|
|
3764
|
+
*
|
|
3765
|
+
* Derived from the existing host results plus the installed runtime dirs —
|
|
3766
|
+
* never persisted, never a second install-state authority.
|
|
3767
|
+
*/
|
|
3768
|
+
export function summarizeTouchedHosts(results, deps = {}) {
|
|
3769
|
+
const canonical = readCanonicalRuntimeCohort(deps.canonicalRuntimeDir ?? getPdRuntimeDir());
|
|
3770
|
+
const codexHome = process.env.CODEX_HOME ?? path.join(getHomeDir(), '.codex');
|
|
3771
|
+
// `resolvePluginDataRoot` returns the PLUGIN DATA ROOT; the installed cohort
|
|
3772
|
+
// lives one level below it in `runtime/`. Appending `node_modules` to the
|
|
3773
|
+
// root read a directory that never exists, so an install that had just
|
|
3774
|
+
// refreshed Codex to the payload pin still printed "runtime not verified".
|
|
3775
|
+
const pluginDataRoot = resolvePluginDataRoot(codexHome, 'principles');
|
|
3776
|
+
const codexRuntimeDir = deps.codexRuntimeDir
|
|
3777
|
+
?? (pluginDataRoot === undefined ? undefined : path.join(pluginDataRoot, 'runtime'));
|
|
3778
|
+
const codex = deps.codexRuntimeReadable === false || codexRuntimeDir === undefined
|
|
3779
|
+
? undefined
|
|
3780
|
+
: readInstalledRuntimeCohort(codexRuntimeDir);
|
|
3781
|
+
return results.map((host) => {
|
|
3782
|
+
if (!host.success) {
|
|
3783
|
+
return `Host "${host.hostId}" — not updated: ${host.reason ?? 'unknown failure'}`;
|
|
3784
|
+
}
|
|
3785
|
+
const cohort = host.hostId === 'codex' ? codex : canonical;
|
|
3786
|
+
const version = cohort
|
|
3787
|
+
? `core@${cohort.core}, codex-adapter@${cohort.codexAdapter}, host-runtime@${cohort.hostRuntime}, mcp@${cohort.mcpServer}`
|
|
3788
|
+
: 'runtime not verified';
|
|
3789
|
+
return `Host "${host.hostId}" — ${version} (${host.configAction ?? 'updated'})`;
|
|
3790
|
+
});
|
|
3791
|
+
}
|
|
3627
3792
|
/**
|
|
3628
3793
|
* ADR-0020 §2.3: Run host installers for the selected HostTarget.
|
|
3629
3794
|
*
|
|
@@ -4034,6 +4199,11 @@ transaction) {
|
|
|
4034
4199
|
// a refusal leaves the existing installation completely untouched. Only
|
|
4035
4200
|
// meaningful when the target workspace already has PD state; fresh
|
|
4036
4201
|
// workspaces scan clean (no state.db → nothing persisted to conflict).
|
|
4202
|
+
//
|
|
4203
|
+
// 5B: rows the scan could not read are surfaced as warnings, never as a
|
|
4204
|
+
// refusal — see summarizeCompatibilityVisibility for why, and for the
|
|
4205
|
+
// condition under which that choice should be revisited.
|
|
4206
|
+
let compatibilityVisibility = { level: 'none', lines: [] };
|
|
4037
4207
|
if (existsSync(path.join(path.resolve(options.workspaceDir), '.pd', 'state.db'))) {
|
|
4038
4208
|
if (spinner)
|
|
4039
4209
|
updateProgress(spinner, stepIndex, 'Checking workspace rule compatibility...');
|
|
@@ -4043,6 +4213,11 @@ transaction) {
|
|
|
4043
4213
|
logger.error(compat.reason ?? 'legacy_rule_contract_dependency');
|
|
4044
4214
|
return buildCompatibilityRefusalResult(options, compat);
|
|
4045
4215
|
}
|
|
4216
|
+
compatibilityVisibility = summarizeCompatibilityVisibility(compat, options.workspaceDir);
|
|
4217
|
+
if (!quiet) {
|
|
4218
|
+
for (const line of compatibilityVisibility.lines)
|
|
4219
|
+
logger.warn(line);
|
|
4220
|
+
}
|
|
4046
4221
|
}
|
|
4047
4222
|
stepIndex++;
|
|
4048
4223
|
if (spinner)
|
|
@@ -4081,7 +4256,17 @@ transaction) {
|
|
|
4081
4256
|
// host config. A malformed manifest must not be discovered only after the
|
|
4082
4257
|
// old installation has already been replaced (rc-3/rc-9).
|
|
4083
4258
|
const persistedHostsBeforeRun = readPersistedInstallHosts();
|
|
4084
|
-
|
|
4259
|
+
// UPDATE CHAIN (2026-11-11): a host installed outside the manifest (e.g. a
|
|
4260
|
+
// Codex Marketplace plugin added by hand) used to stay on the old release
|
|
4261
|
+
// while the upgrade reported success. Detect every host that already
|
|
4262
|
+
// carries PD and include it in BOTH the manifest record and the refresh
|
|
4263
|
+
// set, so one upgrade brings all hosts forward without uninstall/reinstall.
|
|
4264
|
+
const detectedHostsBeforeRun = detectInstalledHosts();
|
|
4265
|
+
const hostPlan = planUpgradeHosts(options.host, persistedHostsBeforeRun, detectedHostsBeforeRun);
|
|
4266
|
+
installManifestHosts = withDetectedHosts(resolveInstallManifestHosts(options.host), detectedHostsBeforeRun);
|
|
4267
|
+
for (const detectedHost of hostPlan.newlyCovered) {
|
|
4268
|
+
logger.info(`Detected installed host "${detectedHost.hostId}" (${detectedHost.evidence}) — included in this upgrade.`);
|
|
4269
|
+
}
|
|
4085
4270
|
if (installsOpenClaw(options.host))
|
|
4086
4271
|
migrateLegacyPdBackups();
|
|
4087
4272
|
const { backupDir: backupDirFromResult, runtimeBackupDir: runtimeBackupDirFromResult } = backupExistingInstall(options.host);
|
|
@@ -4389,14 +4574,16 @@ transaction) {
|
|
|
4389
4574
|
// next launch (binding_version_mismatch). Refresh them through their real
|
|
4390
4575
|
// host installers here — best effort only: the requested host succeeded,
|
|
4391
4576
|
// and a sibling refresh failure must not roll back the working runtime.
|
|
4392
|
-
const refreshTargets =
|
|
4577
|
+
const { refreshTargets } = hostPlan;
|
|
4578
|
+
const refreshedResults = [];
|
|
4393
4579
|
for (const refreshTarget of refreshTargets) {
|
|
4394
4580
|
if (spinner)
|
|
4395
4581
|
updateProgress(spinner, stepIndex, `Refreshing ${refreshTarget} host binding...`);
|
|
4396
4582
|
const refreshResults = await runHostInstallers(refreshTarget, hostInstallCtx);
|
|
4583
|
+
refreshedResults.push(...refreshResults);
|
|
4397
4584
|
for (const hr of refreshResults) {
|
|
4398
4585
|
if (hr.success) {
|
|
4399
|
-
logger.info(`Host "${hr.hostId}"
|
|
4586
|
+
logger.info(`Host "${hr.hostId}" refresh: ${hr.configAction === 'updated' ? 'updated' : 'no change needed'}${hr.reason ? ` — ${hr.reason}` : ''}.`);
|
|
4400
4587
|
}
|
|
4401
4588
|
else {
|
|
4402
4589
|
// rc-9: never silent — state the reason and the exact recovery step.
|
|
@@ -4404,6 +4591,15 @@ transaction) {
|
|
|
4404
4591
|
}
|
|
4405
4592
|
}
|
|
4406
4593
|
}
|
|
4594
|
+
// UPDATE CHAIN (2026-11-11): one visible line per host this run touched.
|
|
4595
|
+
// First installs and upgrades share it, so an already-installed host being
|
|
4596
|
+
// brought forward can never be silent (Owner report).
|
|
4597
|
+
const hostSummary = summarizeTouchedHosts([...hostResults, ...refreshedResults]);
|
|
4598
|
+
if (hostSummary.length > 0) {
|
|
4599
|
+
logger.info('Install summary:');
|
|
4600
|
+
for (const line of hostSummary)
|
|
4601
|
+
logger.info(` ${line}`);
|
|
4602
|
+
}
|
|
4407
4603
|
// Manual-action hosts (e.g. Codex awaiting the Marketplace step) STAY in
|
|
4408
4604
|
// the install manifest: the manifest records the hosts PD serves on this
|
|
4409
4605
|
// machine (uninstall reads it to decide shared-runtime removal), not a
|
|
@@ -4522,6 +4718,13 @@ transaction) {
|
|
|
4522
4718
|
spinner.warn(`Install partially complete — ${hostManualActions.length} manual step(s) pending (details below)`);
|
|
4523
4719
|
}
|
|
4524
4720
|
}
|
|
4721
|
+
// 5B: the preflight warning scrolls away during a multi-minute install, so
|
|
4722
|
+
// the end summary repeats the zero-visibility block verbatim. This is
|
|
4723
|
+
// still a warning: the install completed and success is unchanged.
|
|
4724
|
+
if (!quiet && compatibilityVisibility.level === 'critical') {
|
|
4725
|
+
for (const line of compatibilityVisibility.lines)
|
|
4726
|
+
logger.warn(line);
|
|
4727
|
+
}
|
|
4525
4728
|
// P0-2: terminate + join the verified child before any later step that
|
|
4526
4729
|
// may touch the runtime tree (here: none destructive, but a wedged child
|
|
4527
4730
|
// must not leak past the install either).
|
|
@@ -4588,6 +4791,8 @@ transaction) {
|
|
|
4588
4791
|
nextAction: nextActions.join(' | '),
|
|
4589
4792
|
consoleUrl: launchResult.consoleUrl,
|
|
4590
4793
|
hostResults,
|
|
4794
|
+
hostSummary,
|
|
4795
|
+
...(compatibilityVisibility.lines.length > 0 ? { compatibilityWarnings: compatibilityVisibility.lines } : {}),
|
|
4591
4796
|
...(manualActionReason !== undefined ? { reason: manualActionReason, manualActions: hostManualActions } : {}),
|
|
4592
4797
|
journal: installerJournalRecord(journal),
|
|
4593
4798
|
};
|