@unbrained/pm-cli 2026.11.20 → 2026.11.22
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/.agents/skills/pm-developer/SKILL.md +1 -1
- package/.agents/skills/pm-sdk/SKILL.md +1 -1
- package/.agents/skills/pm-test-audit/SKILL.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/CONTRIBUTING.md +2 -1
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +9 -0
- package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +125 -0
- package/dist/cli-bundle/chunks/{chunk-4TZW4NLM.js → chunk-5ZMVLWE3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +33 -0
- package/dist/cli-bundle/chunks/{chunk-GXGW6KHB.js → chunk-AR4NP5HI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6X2AGUOT.js → chunk-B4PPFOPY.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-XK25TAJZ.js → chunk-B76TFRO2.js} +47 -45
- package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-KDDIHGAO.js → chunk-EIGUKEV6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZAO7VGX3.js → chunk-GTPCAJMZ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-KQSPKWFH.js → chunk-HC2OPETM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5LF5QZT3.js → chunk-HKUV74K3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +115 -0
- package/dist/cli-bundle/chunks/{chunk-FF4TXJDH.js → chunk-J2LABXBL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3BOR22MC.js → chunk-J52BEBSS.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +3 -0
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +3 -0
- package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-DG2EOOFX.js → chunk-TC6XLIYO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MGYAJONE.js → chunk-U7EL3AYA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-ZVEHACE6.js → chunk-X6MIWTTT.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-KEBLUTC3.js → chunk-XFHPKXAE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OXG5XPC7.js → chunk-YHVLVSEZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Y4LXVPA5.js → chunk-YMUSRWV4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HQYIKAC6.js → chunk-YR2KEBHP.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-ELEMA7IW.js → indexed-receipt-blobs-ITTXIN4K.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-GE2CQECR.js → item-revision-4QBMZXKX.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-5GYX7LP3.js → mutation-actor-FWLYWJ37.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-72TYKPGU.js → mutation-admission-7ZDCK3G2.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-OQZZEWEB.js → register-list-query-RR5KACJ3.js} +10 -10
- package/dist/cli-bundle/chunks/{register-mutation-YZEUZ6XT.js → register-mutation-57AJQWFV.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-JNVCF7EW.js → register-operations-RKWST7CU.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-LDKULZSD.js → register-setup-CMI23PC5.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-E5LHZ4RD.js → settlement-hook-BXN5LEQD.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-Q2QZ2IBG.js → stage-4KDVXC5Z.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JUYJ7NXL.js → chunk-2ZD7275J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7SB6VKEI.js → chunk-324AHXJO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IXYBN6D2.js → chunk-3IRCYJI5.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-DH4DHL6V.js → chunk-3V53UBHN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-V55XZFOP.js → chunk-4JZITIJB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BZCLW5V7.js → chunk-BRZV7BFV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PKMDWIP3.js → chunk-HDEKFSOK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-O25KFLLA.js → chunk-IWOXAUDU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UATP3RK3.js → chunk-ML3JHCC6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZKGGGU2K.js → chunk-OPGOOP25.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PRFEOCNZ.js → chunk-RE7ZWT7D.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KQJNJZKP.js → chunk-URGHTTT3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +13 -0
- package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +102 -0
- package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PQXTZLK3.js → chunk-WZWXGDYY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5VSXKA35.js → chunk-YKSLZPLT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +2 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-ZTRFCPH7.js → indexed-receipt-blobs-AF4U3F3D.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-revision-OXDZHMJ7.js → item-revision-2O6MLPEX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{mutation-actor-6DYIF6NH.js → mutation-actor-TCYDPUGG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-2BYXANVJ.js → mutation-admission-LY73EJWM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-OUBUN45C.js → settlement-hook-ARYCZQY4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-FGHSB3QX.js → stage-DQ7RQQ52.js} +2 -2
- package/dist/cli-bundle/main.js +25 -25
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +70 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/extensions/index.d.ts +2 -0
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/file-glob.js +1 -1
- package/dist/core/fs/fs-utils.d.ts +3 -1
- package/dist/core/fs/fs-utils.js +1 -1
- package/dist/core/history/bridge.js +2 -0
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/history.d.ts +12 -0
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.d.ts +20 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.d.ts +46 -5
- package/dist/core/history/replay.js +2 -2
- package/dist/core/history/stream-summary.d.ts +129 -0
- package/dist/core/history/stream-summary.js +3 -0
- package/dist/core/shared/errors.d.ts +8 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
- package/dist/sdk/completion/fish.js +3 -2
- package/dist/sdk/completion/zsh.js +3 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workspace-position.js +1 -1
- package/dist/sdk/history/append-only-repair.d.ts +30 -0
- package/dist/sdk/history/append-only-repair.js +6 -0
- package/dist/sdk/history/maintenance.d.ts +8 -2
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/reanchor-refusal.js +2 -0
- package/dist/sdk/history/reseed.d.ts +15 -0
- package/dist/sdk/history/reseed.js +2 -0
- package/dist/sdk/history/salvage.d.ts +19 -8
- package/dist/sdk/history/salvage.js +5 -3
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.d.ts +8 -2
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/merge/index.d.ts +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/install.d.ts +20 -6
- package/dist/sdk/merge/install.js +3 -3
- package/dist/sdk/merge/three-way.d.ts +22 -3
- package/dist/sdk/merge/three-way.js +8 -2
- package/dist/sdk/merge/worktree-config.js +2 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.d.ts +67 -5
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/context.d.ts +13 -3
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query.d.ts +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-input.d.ts +6 -2
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +7 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +5 -5
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/transactions/item-finalization.js +2 -0
- package/dist/types.d.ts +20 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
- package/docs/COMMANDS.md +62 -4
- package/docs/HISTORY_RECOVERY.md +229 -5
- package/docs/MERGE_SAFETY.md +8 -0
- package/docs/MUTATION_INTEGRITY.md +3 -1
- package/docs/README.md +8 -6
- package/docs/SDK.md +128 -5
- package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
- package/docs/TESTING.md +8 -697
- package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +1 -1
- package/marketplace.json +1 -1
- package/node_modules/tar/package.json +2 -3
- package/package.json +35 -3
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2IZGNOGT.js +0 -6
- package/dist/cli-bundle/chunks/chunk-4QQPM3IY.js +0 -2
- package/dist/cli-bundle/chunks/chunk-5OFMWP3Q.js +0 -3
- package/dist/cli-bundle/chunks/chunk-6HRPGEBF.js +0 -2
- package/dist/cli-bundle/chunks/chunk-7ESF676D.js +0 -125
- package/dist/cli-bundle/chunks/chunk-7EZZ4W7O.js +0 -20
- package/dist/cli-bundle/chunks/chunk-FOYRE23V.js +0 -115
- package/dist/cli-bundle/chunks/chunk-HJQ3XPS3.js +0 -31
- package/dist/cli-bundle/chunks/chunk-M5D3CEMY.js +0 -9
- package/dist/cli-bundle/chunks/chunk-VS565KBX.js +0 -2
- package/dist/cli-bundle/chunks/chunk-W4TLA5H3.js +0 -8
- package/dist/cli-bundle/chunks/item-transaction-YSAWJRA2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3LRSQXCN.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-FPKVHC3Q.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I7XBR2RM.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-MJP3TFVW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PZSTRYTA.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-QNJQPJWO.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-SIPDQBJI.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-SJE3PYPI.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-TNKI6WKG.js +0 -66
- package/dist/cli-bundle/focused-chunks/chunk-TRCXANRR.js +0 -12
- package/dist/cli-bundle/focused-chunks/item-transaction-54VSTT6L.js +0 -2
- package/dist/sdk/agent/refusal-closure.js +0 -2
- package/dist/sdk/agent/refusal-reachability.js +0 -4
- package/dist/sdk/agent/task-transcript-contracts.js +0 -2
- package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
- package/dist/sdk/authoring.js +0 -2
- package/dist/sdk/compose.js +0 -2
- package/dist/sdk/contracts.js +0 -2
- package/dist/sdk/core-governance.js +0 -2
- package/dist/sdk/core.js +0 -2
- package/dist/sdk/corpus-shape.js +0 -2
- package/dist/sdk/define.js +0 -2
- package/dist/sdk/environment/agent-environment.js +0 -2
- package/dist/sdk/governance/artifact-ledgers.js +0 -2
- package/dist/sdk/governance/coverage-assurance.js +0 -2
- package/dist/sdk/governance/reliability.js +0 -2
- package/dist/sdk/governance.js +0 -2
- package/dist/sdk/graph/adapter.js +0 -2
- package/dist/sdk/graph/conformance.js +0 -2
- package/dist/sdk/graph/index.js +0 -2
- package/dist/sdk/graph.js +0 -2
- package/dist/sdk/index.js +0 -2
- package/dist/sdk/query.js +0 -2
- package/dist/sdk/relationship-migration.js +0 -2
- package/dist/sdk/testing.js +0 -8
- package/dist/sdk/workspace-recipe.js +0 -2
- package/docs/AGENT_PROVENANCE_ADR.md +0 -206
- package/docs/DEFECT_RECURRENCE.md +0 -257
- package/docs/MCP_2026_07_28_CONFORMANCE.md +0 -41
- package/docs/PERFORMANCE.md +0 -189
- package/docs/QUALITY_EVIDENCE.md +0 -130
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +0 -117
- package/docs/performance/cli-transport-overhead.md +0 -51
- package/docs/performance/runner-qualification.md +0 -36
- package/docs/performance/sdk-entrypoint-import-costs.md +0 -32
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f9317f5b-f007-5882-aafe-898d1f76f2ae")}catch{}})();const REMEDIATION_REGISTRY=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function resolveRemediation(warning){if(typeof warning!="string")return;const normalized=warning.trim();for(const entry of REMEDIATION_REGISTRY)if(normalized===entry.code||normalized.startsWith(`${entry.code}:`))return entry}function buildRemediationMap(warnings){const map={};for(const warning of warnings){const entry=resolveRemediation(warning);entry!==void 0&&!Object.prototype.hasOwnProperty.call(map,entry.code)&&(map[entry.code]=entry.command)}return map}function buildRemediationCommands(warnings){return Object.values(buildRemediationMap(warnings))}export{REMEDIATION_REGISTRY,buildRemediationCommands,buildRemediationMap,resolveRemediation};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2000c9e7-7cba-5f6f-adea-d980569b4869")}catch{}})();const REMEDIATION_REGISTRY=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history record; the repair rebuilds the stream as one audited baseline from the on-disk item, and earlier versions stay unrecorded. When the stream was deleted by mistake, restore it from version control first (pm history-repair --all, with or without --append-only, rebuilds every missing stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"The item's history stream cannot be read; preview salvage, which removes lines that cannot hold a record and an invalid tail after a verified prefix, then apply it without --dry-run. Salvage refuses interior corruption, which needs recovery from version control, and a permission error needs the file's access fixed."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id> --append-only",summary:"The item's history chain is broken; append one record that bridges every break in the stream and keeps every recorded line byte-identical (pm history-repair <id> re-anchors the recorded entries instead). pm health previews the bridge for every chain mismatch, so a break a bridge cannot repair is reported as history_drift_chain_unbridgeable, and a stream no repair can keep as history_drift_unrepairable_stream, instead."},{code:"history_drift_chain_unbridgeable",command:"pm history-repair <id>",summary:"The item's history chain is broken in a way an append-only bridge cannot repair, for example a recorded patch that applies only on top of the unrecorded change (details.repair_refusals names the refusal reason); re-anchor the recorded entries instead (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unrepairable_stream",command:"pm history <id> --verify --full",summary:"Neither history repair can keep this stream (details.repair_refusals names both refusal reasons). Inspect it: a record that no longer matches its seal, or a malformed chain, needs the item's own stream restored from version control or a backup; a stream entry that is a link (reason stream_not_regular_file) needs the item's own stream restored as a regular file. Then run pm history <id> --verify --strict-exit."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Rebuild the history streams of the items without a history record as one audited baseline from each on-disk item."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"Preview salvage of the unreadable history streams, then apply it without --dry-run; interior corruption needs recovery from version control."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function resolveRemediation(warning){if(typeof warning!="string")return;const normalized=warning.trim();for(const entry of REMEDIATION_REGISTRY)if(normalized===entry.code||normalized.startsWith(`${entry.code}:`))return entry}function buildRemediationMap(warnings){const map={};for(const warning of warnings){const entry=resolveRemediation(warning);entry!==void 0&&!Object.prototype.hasOwnProperty.call(map,entry.code)&&(map[entry.code]=entry.command)}return map}function buildRemediationCommands(warnings){return Object.values(buildRemediationMap(warnings))}export{REMEDIATION_REGISTRY,buildRemediationCommands,buildRemediationMap,resolveRemediation};
|
|
2
2
|
//# sourceMappingURL=remediation.js.map
|
|
@@ -82,6 +82,8 @@ export declare function getActiveExtensionHooks():ExtensionHookRegistry|null;
|
|
|
82
82
|
export declare function runActiveBeforeMutationHooks(input:BeforeMutationHookInput):Promise<void>;
|
|
83
83
|
/** Implements run active on read hooks for the public runtime surface of this module. */
|
|
84
84
|
export declare function runActiveOnReadHooks(context:OnReadHookContext):Promise<string[]>;
|
|
85
|
+
/** Synchronous predicate: true only when at least one onWrite hook is registered, so a bulk writer can keep per-path ordering for hooks that may touch later paths. */
|
|
86
|
+
export declare function hasActiveOnWriteHooks():boolean;
|
|
85
87
|
/** Synchronous fast-path predicate: true only when at least one onRead hook is registered. Bulk readers (e.g. the metadata cache scanning hundreds of files) use this to skip per-file `await runActiveOnReadHooks(...)` calls entirely when no extension observes reads, avoiding hundreds of needless microtasks. */
|
|
86
88
|
export declare function hasActiveOnReadHooks():boolean;
|
|
87
89
|
/** Implements run active on index hooks for the public runtime surface of this module. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1ee579e0-2d07-5519-b071-bac39d3ec594")}catch{}})();import{existsSync}from"node:fs";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";import{ownedTransactionCompensation}from"../store/item-mutation-precondition.js";import{runCommandHandler,runBeforeMutationHooks,runCommandOverride,runOnIndexHooks,runParserOverride,runPreflightOverride,runOnReadHooks,runRendererOverride,runServiceOverride,runServiceOverrideSync,runOnWriteHooks}from"./loader.js";let activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult,activeAfterCommandAffectedItems=[];const isolatedExtensionRuntime=new AsyncLocalStorage;function runtimeState(){return isolatedExtensionRuntime.getStore()}function runWithIsolatedExtensionRuntime(run){return isolatedExtensionRuntime.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},run)}const AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function findSourceRepositoryRoot(candidate){let cursor=path.resolve(candidate);for(;;){if(existsSync(path.join(cursor,".git")))return cursor;const parent=path.dirname(cursor);if(parent===cursor)return;cursor=parent}}function resolvePortableWorkspaceContext(pmRoot){const sourceCandidate=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),sourceWorkspaceRoot=findSourceRepositoryRoot(sourceCandidate)??path.resolve(sourceCandidate),repoRoot=findSourceRepositoryRoot(sourceWorkspaceRoot);if(!pmRoot)return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{}};const relativePmRoot=path.relative(sourceWorkspaceRoot,path.resolve(pmRoot)),contained=relativePmRoot.length>0&&!relativePmRoot.startsWith(`..${path.sep}`)&&relativePmRoot!==".."&&!path.isAbsolute(relativePmRoot);return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{},...contained?{pm_root_rel:relativePmRoot.split(path.sep).join("/")}:{}}}function setActiveExtensionHooks(hooks){const state=runtimeState();if(state){state.hooks=hooks;return}activeExtensionHooks=hooks}function setActiveExtensionCommands(commands){const state=runtimeState();if(state){state.commands=commands;return}activeExtensionCommands=commands}function setActiveExtensionParsers(parsers){const state=runtimeState();if(state){state.parsers=parsers;return}activeExtensionParsers=parsers}function setActiveExtensionPreflight(preflight){const state=runtimeState();if(state){state.preflight=preflight;return}activeExtensionPreflight=preflight}function setActiveExtensionServices(services){const state=runtimeState();if(state){state.services=services;return}activeExtensionServices=services}function setActiveExtensionRenderers(renderers){const state=runtimeState();if(state){state.renderers=renderers;return}activeExtensionRenderers=renderers}function setActiveExtensionRegistrations(registrations){const state=runtimeState();if(state){state.registrations=registrations;return}activeExtensionRegistrations=registrations}function getActiveExtensionRegistrations(){const state=runtimeState();return state?state.registrations:activeExtensionRegistrations}function resetActiveExtensionRuntimeState(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=null,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=null}function setActiveCommandContext(context){const resolved=context?{...context,...resolvePortableWorkspaceContext(context.pm_root)}:null,state=runtimeState();if(state){state.commandContext=resolved;return}activeCommandContext=resolved}function getActiveCommandContext(){const state=runtimeState(),context=state?state.commandContext:activeCommandContext;return context?{...context,args:[...context.args],options:context.options?{...context.options}:{},global:context.global?{...context.global}:void 0}:null}function isActiveCommandUnextended(command){const state=runtimeState()??{commandContext:activeCommandContext,hooks:activeExtensionHooks,commands:activeExtensionCommands,parsers:activeExtensionParsers,preflight:activeExtensionPreflight,services:activeExtensionServices,renderers:activeExtensionRenderers,registrations:activeExtensionRegistrations};return state.commandContext?.command!==command||[state.hooks,state.preflight,state.services,state.renderers].some(registry=>Object.values(registry??{}).some(entries=>entries.length>0))||[state.commands,state.parsers].some(registry=>Object.values(registry??{}).some(entries=>entries.some(entry=>entry.command===command)))?!1:!Object.entries(state.registrations??{}).some(([key,entries])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(key)&&entries.length>0)}function setActiveCommandResult(result){const state=runtimeState();if(state){state.commandResult=result;return}activeCommandResult=result}function getActiveCommandResult(){const state=runtimeState();return state?state.commandResult:activeCommandResult}function recordAfterCommandAffectedItem(item){if(!item)return;const state=runtimeState();state?state.affectedItems.push(item):activeAfterCommandAffectedItems.push(item)}function projectAfterCommandItemSnapshot(metadata,changedFields){if(!metadata||!metadata.id)return{};const snapshot={id:metadata.id,type:metadata.type,status:metadata.status};if(!Array.isArray(changedFields))return snapshot;const source=metadata;for(const field of changedFields){if(typeof field!="string")continue;const actualField=field.startsWith("unset:")?field.slice(6):field;actualField==="id"||actualField==="type"||actualField==="status"||AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS.has(actualField)||Object.hasOwn(source,actualField)&&source[actualField]!==void 0&&(snapshot[actualField]=source[actualField])}return snapshot}function consumeAfterCommandAffectedItems(){const state=runtimeState(),affectedItems=state?.affectedItems??activeAfterCommandAffectedItems;if(affectedItems.length===0)return;const affected=affectedItems;return state?state.affectedItems=[]:activeAfterCommandAffectedItems=[],affected}function clearActiveExtensionHooks(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=void 0,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=void 0,activeAfterCommandAffectedItems=[]}async function runActiveOnWriteHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnWriteHooks(hooks,context):[]}const previewMutationGuards=new AsyncLocalStorage;function runWithPreviewMutationGuards(hooks,run){return!hooks||(hooks.beforeMutation?.length??0)===0?run():previewMutationGuards.run(hooks,run)}function getActiveExtensionHooks(){const state=runtimeState();return state?state.hooks:activeExtensionHooks}async function runActiveBeforeMutationHooks(input){const preview=previewMutationGuards.getStore(),hooks=preview??getActiveExtensionHooks();if(!hooks)return;const{resolveMutationActor}=await import("./mutation-actor.js"),isDryRun=preview!==void 0||input.dry_run===!0,compensation=isDryRun?void 0:ownedTransactionCompensation(input.pm_root,[input.before?.metadata.id,input.after?.metadata.id],input.operation),overrides=await runBeforeMutationHooks(hooks,{pm_root:input.pm_root,operation:input.operation,before:input.before,after:input.after,changed_fields:input.changed_fields,sdk:input.sdk,actor:resolveMutationActor(input.author),dry_run:isDryRun,...compensation===void 0?{}:{compensation:{transaction_id:compensation.transaction_id,step_id:compensation.step_id}}});compensation?.overrides.push(...overrides.map(override=>({source:"mutation_guard",...override})))}async function runActiveOnReadHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnReadHooks(hooks,context):[]}function hasActiveOnReadHooks(){const state=runtimeState();return((state?state.hooks:activeExtensionHooks)?.onRead?.length??0)>0}async function runActiveOnIndexHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnIndexHooks(hooks,context):[]}function runActiveCommandOverride(result){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands,commandContext=state?state.commandContext:activeCommandContext;return!commands||!commandContext?{overridden:!1,result,warnings:[]}:runCommandOverride(commands,{command:commandContext.command,args:[...commandContext.args],options:commandContext.options?{...commandContext.options}:{},global:commandContext.global?{...commandContext.global}:void 0,pm_root:commandContext.pm_root,source_workspace_root:commandContext.source_workspace_root,repo_root:commandContext.repo_root,pm_root_rel:commandContext.pm_root_rel,result})}async function runActiveCommandHandler(context){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands;return commands?runCommandHandler(commands,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{handled:!1,result:null,warnings:[]}}async function runActiveParserOverride(context){const state=runtimeState(),parsers=state?state.parsers:activeExtensionParsers;return parsers?runParserOverride(parsers,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},warnings:[]}}async function runActivePreflightOverride(context){const state=runtimeState(),preflight=state?state.preflight:activeExtensionPreflight;return preflight?runPreflightOverride(preflight,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},decision:{...context.decision},warnings:[]}}function runActiveRendererOverride(format,result){const state=runtimeState(),renderers=state?state.renderers:activeExtensionRenderers,commandContext=state?state.commandContext:activeCommandContext;return renderers?runRendererOverride(renderers,{format,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,result}):{overridden:!1,rendered:null,warnings:[]}}function buildServiceContext(service,payload){const state=runtimeState(),commandContext=state?state.commandContext:activeCommandContext;return{service,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,payload}}async function runActiveServiceOverride(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverride(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}function runActiveServiceOverrideSync(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverrideSync(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}export*from"./loader.js";export*from"./command-hook-context.js";import{createSerialQueue}from"../shared/serial-queue.js";import{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabilities,reconcileExtensionCapabilityUsage}from"./capability-usage.js";export{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,clearActiveExtensionHooks,collectUsedExtensionCapabilities,consumeAfterCommandAffectedItems,createSerialQueue,getActiveCommandContext,getActiveCommandResult,getActiveExtensionHooks,getActiveExtensionRegistrations,hasActiveOnReadHooks,isActiveCommandUnextended,projectAfterCommandItemSnapshot,reconcileExtensionCapabilityUsage,recordAfterCommandAffectedItem,resetActiveExtensionRuntimeState,resolvePortableWorkspaceContext,runActiveBeforeMutationHooks,runActiveCommandHandler,runActiveCommandOverride,runActiveOnIndexHooks,runActiveOnReadHooks,runActiveOnWriteHooks,runActiveParserOverride,runActivePreflightOverride,runActiveRendererOverride,runActiveServiceOverride,runActiveServiceOverrideSync,runWithIsolatedExtensionRuntime,runWithPreviewMutationGuards,setActiveCommandContext,setActiveCommandResult,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="67666bab-2e73-549c-bf95-ba505143a9b5")}catch{}})();import{existsSync}from"node:fs";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";import{ownedTransactionCompensation}from"../store/item-mutation-precondition.js";import{runCommandHandler,runBeforeMutationHooks,runCommandOverride,runOnIndexHooks,runParserOverride,runPreflightOverride,runOnReadHooks,runRendererOverride,runServiceOverride,runServiceOverrideSync,runOnWriteHooks}from"./loader.js";let activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult,activeAfterCommandAffectedItems=[];const isolatedExtensionRuntime=new AsyncLocalStorage;function runtimeState(){return isolatedExtensionRuntime.getStore()}function runWithIsolatedExtensionRuntime(run){return isolatedExtensionRuntime.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},run)}const AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function findSourceRepositoryRoot(candidate){let cursor=path.resolve(candidate);for(;;){if(existsSync(path.join(cursor,".git")))return cursor;const parent=path.dirname(cursor);if(parent===cursor)return;cursor=parent}}function resolvePortableWorkspaceContext(pmRoot){const sourceCandidate=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),sourceWorkspaceRoot=findSourceRepositoryRoot(sourceCandidate)??path.resolve(sourceCandidate),repoRoot=findSourceRepositoryRoot(sourceWorkspaceRoot);if(!pmRoot)return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{}};const relativePmRoot=path.relative(sourceWorkspaceRoot,path.resolve(pmRoot)),contained=relativePmRoot.length>0&&!relativePmRoot.startsWith(`..${path.sep}`)&&relativePmRoot!==".."&&!path.isAbsolute(relativePmRoot);return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{},...contained?{pm_root_rel:relativePmRoot.split(path.sep).join("/")}:{}}}function setActiveExtensionHooks(hooks){const state=runtimeState();if(state){state.hooks=hooks;return}activeExtensionHooks=hooks}function setActiveExtensionCommands(commands){const state=runtimeState();if(state){state.commands=commands;return}activeExtensionCommands=commands}function setActiveExtensionParsers(parsers){const state=runtimeState();if(state){state.parsers=parsers;return}activeExtensionParsers=parsers}function setActiveExtensionPreflight(preflight){const state=runtimeState();if(state){state.preflight=preflight;return}activeExtensionPreflight=preflight}function setActiveExtensionServices(services){const state=runtimeState();if(state){state.services=services;return}activeExtensionServices=services}function setActiveExtensionRenderers(renderers){const state=runtimeState();if(state){state.renderers=renderers;return}activeExtensionRenderers=renderers}function setActiveExtensionRegistrations(registrations){const state=runtimeState();if(state){state.registrations=registrations;return}activeExtensionRegistrations=registrations}function getActiveExtensionRegistrations(){const state=runtimeState();return state?state.registrations:activeExtensionRegistrations}function resetActiveExtensionRuntimeState(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=null,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=null}function setActiveCommandContext(context){const resolved=context?{...context,...resolvePortableWorkspaceContext(context.pm_root)}:null,state=runtimeState();if(state){state.commandContext=resolved;return}activeCommandContext=resolved}function getActiveCommandContext(){const state=runtimeState(),context=state?state.commandContext:activeCommandContext;return context?{...context,args:[...context.args],options:context.options?{...context.options}:{},global:context.global?{...context.global}:void 0}:null}function isActiveCommandUnextended(command){const state=runtimeState()??{commandContext:activeCommandContext,hooks:activeExtensionHooks,commands:activeExtensionCommands,parsers:activeExtensionParsers,preflight:activeExtensionPreflight,services:activeExtensionServices,renderers:activeExtensionRenderers,registrations:activeExtensionRegistrations};return state.commandContext?.command!==command||[state.hooks,state.preflight,state.services,state.renderers].some(registry=>Object.values(registry??{}).some(entries=>entries.length>0))||[state.commands,state.parsers].some(registry=>Object.values(registry??{}).some(entries=>entries.some(entry=>entry.command===command)))?!1:!Object.entries(state.registrations??{}).some(([key,entries])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(key)&&entries.length>0)}function setActiveCommandResult(result){const state=runtimeState();if(state){state.commandResult=result;return}activeCommandResult=result}function getActiveCommandResult(){const state=runtimeState();return state?state.commandResult:activeCommandResult}function recordAfterCommandAffectedItem(item){if(!item)return;const state=runtimeState();state?state.affectedItems.push(item):activeAfterCommandAffectedItems.push(item)}function projectAfterCommandItemSnapshot(metadata,changedFields){if(!metadata||!metadata.id)return{};const snapshot={id:metadata.id,type:metadata.type,status:metadata.status};if(!Array.isArray(changedFields))return snapshot;const source=metadata;for(const field of changedFields){if(typeof field!="string")continue;const actualField=field.startsWith("unset:")?field.slice(6):field;actualField==="id"||actualField==="type"||actualField==="status"||AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS.has(actualField)||Object.hasOwn(source,actualField)&&source[actualField]!==void 0&&(snapshot[actualField]=source[actualField])}return snapshot}function consumeAfterCommandAffectedItems(){const state=runtimeState(),affectedItems=state?.affectedItems??activeAfterCommandAffectedItems;if(affectedItems.length===0)return;const affected=affectedItems;return state?state.affectedItems=[]:activeAfterCommandAffectedItems=[],affected}function clearActiveExtensionHooks(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=void 0,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=void 0,activeAfterCommandAffectedItems=[]}async function runActiveOnWriteHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnWriteHooks(hooks,context):[]}const previewMutationGuards=new AsyncLocalStorage;function runWithPreviewMutationGuards(hooks,run){return!hooks||(hooks.beforeMutation?.length??0)===0?run():previewMutationGuards.run(hooks,run)}function getActiveExtensionHooks(){const state=runtimeState();return state?state.hooks:activeExtensionHooks}async function runActiveBeforeMutationHooks(input){const preview=previewMutationGuards.getStore(),hooks=preview??getActiveExtensionHooks();if(!hooks)return;const{resolveMutationActor}=await import("./mutation-actor.js"),isDryRun=preview!==void 0||input.dry_run===!0,compensation=isDryRun?void 0:ownedTransactionCompensation(input.pm_root,[input.before?.metadata.id,input.after?.metadata.id],input.operation),overrides=await runBeforeMutationHooks(hooks,{pm_root:input.pm_root,operation:input.operation,before:input.before,after:input.after,changed_fields:input.changed_fields,sdk:input.sdk,actor:resolveMutationActor(input.author),dry_run:isDryRun,...compensation===void 0?{}:{compensation:{transaction_id:compensation.transaction_id,step_id:compensation.step_id}}});compensation?.overrides.push(...overrides.map(override=>({source:"mutation_guard",...override})))}async function runActiveOnReadHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnReadHooks(hooks,context):[]}function hasActiveOnWriteHooks(){const state=runtimeState();return((state?state.hooks:activeExtensionHooks)?.onWrite?.length??0)>0}function hasActiveOnReadHooks(){const state=runtimeState();return((state?state.hooks:activeExtensionHooks)?.onRead?.length??0)>0}async function runActiveOnIndexHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnIndexHooks(hooks,context):[]}function runActiveCommandOverride(result){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands,commandContext=state?state.commandContext:activeCommandContext;return!commands||!commandContext?{overridden:!1,result,warnings:[]}:runCommandOverride(commands,{command:commandContext.command,args:[...commandContext.args],options:commandContext.options?{...commandContext.options}:{},global:commandContext.global?{...commandContext.global}:void 0,pm_root:commandContext.pm_root,source_workspace_root:commandContext.source_workspace_root,repo_root:commandContext.repo_root,pm_root_rel:commandContext.pm_root_rel,result})}async function runActiveCommandHandler(context){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands;return commands?runCommandHandler(commands,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{handled:!1,result:null,warnings:[]}}async function runActiveParserOverride(context){const state=runtimeState(),parsers=state?state.parsers:activeExtensionParsers;return parsers?runParserOverride(parsers,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},warnings:[]}}async function runActivePreflightOverride(context){const state=runtimeState(),preflight=state?state.preflight:activeExtensionPreflight;return preflight?runPreflightOverride(preflight,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},decision:{...context.decision},warnings:[]}}function runActiveRendererOverride(format,result){const state=runtimeState(),renderers=state?state.renderers:activeExtensionRenderers,commandContext=state?state.commandContext:activeCommandContext;return renderers?runRendererOverride(renderers,{format,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,result}):{overridden:!1,rendered:null,warnings:[]}}function buildServiceContext(service,payload){const state=runtimeState(),commandContext=state?state.commandContext:activeCommandContext;return{service,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,payload}}async function runActiveServiceOverride(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverride(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}function runActiveServiceOverrideSync(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverrideSync(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}export*from"./loader.js";export*from"./command-hook-context.js";import{createSerialQueue}from"../shared/serial-queue.js";import{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabilities,reconcileExtensionCapabilityUsage}from"./capability-usage.js";export{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,clearActiveExtensionHooks,collectUsedExtensionCapabilities,consumeAfterCommandAffectedItems,createSerialQueue,getActiveCommandContext,getActiveCommandResult,getActiveExtensionHooks,getActiveExtensionRegistrations,hasActiveOnReadHooks,hasActiveOnWriteHooks,isActiveCommandUnextended,projectAfterCommandItemSnapshot,reconcileExtensionCapabilityUsage,recordAfterCommandAffectedItem,resetActiveExtensionRuntimeState,resolvePortableWorkspaceContext,runActiveBeforeMutationHooks,runActiveCommandHandler,runActiveCommandOverride,runActiveOnIndexHooks,runActiveOnReadHooks,runActiveOnWriteHooks,runActiveParserOverride,runActivePreflightOverride,runActiveRendererOverride,runActiveServiceOverride,runActiveServiceOverrideSync,runWithIsolatedExtensionRuntime,runWithPreviewMutationGuards,setActiveCommandContext,setActiveCommandResult,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1c52c822-3fe3-5afd-8ac1-182e7a18dbde")}catch{}})();import{link,mkdir,mkdtemp,open,rm,writeFile}from"node:fs/promises";import path from"node:path";const HARD_LINK_UNSUPPORTED=new Set(["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS"]);class AtomicLinkUnsupportedError extends Error{code;constructor(code,cause){super(`The filesystem cannot publish a file by hard link (${code}).`,{cause}),this.name="AtomicLinkUnsupportedError",this.code=code}}async function writeDurably(file,contents){const handle=await open(file,"wx");try{await handle.writeFile(contents,"utf8"),await handle.sync()}finally{await handle.close()}}async function createFileAtomic(targetPath,contents,options={}){const parent=path.dirname(targetPath);await mkdir(parent,{recursive:!0});const staging=await mkdtemp(path.join(parent,".pm-seed-")),stagedFile=path.join(staging,"value");try{await(options.sync===!0?writeDurably(stagedFile,contents):writeFile(stagedFile,contents,"utf8"));try{return await link(stagedFile,targetPath),!0}catch(error){const code=error.code??"";if(code==="EEXIST")return!1;throw HARD_LINK_UNSUPPORTED.has(code)?new AtomicLinkUnsupportedError(code,error):error}}finally{await rm(staging,{recursive:!0,force:!0}).catch(()=>{})}}export{AtomicLinkUnsupportedError,createFileAtomic};
|
|
2
2
|
//# sourceMappingURL=atomic-create.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="30379998-be47-5176-bfd4-a02bca99bd16")}catch{}})();import{readdir,realpath,stat}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_PATTERN_LENGTH=4096,MAX_NESTING=32,MAX_RANGE_SIZE=1e3,MAX_STATES=5e4,DFA_LIMITS={nodes:1e4,edges:4e4,stateIds:2e6},SLASH=47;class GlobTooComplex extends Error{}const POSIX_CLASSES=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function negationRefusal(){return new PmCliError("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",EXIT_CODE.USAGE)}function bracketEnd(chars,start){let index=start+1;for((chars[index]==="!"||chars[index]==="^")&&(index+=1),chars[index]==="]"&&(index+=1);index<chars.length;){const char=chars[index];if(char==="\\")index+=2;else if(char==="["&&chars[index+1]===":"){const close=chars.indexOf(":",index+2);close===-1||chars[close+1]!=="]"?index+=1:index=close+2}else{if(char==="]")return index+1;index+=1}}return-1}function openerAt(chars,index,open){const char=chars[index];if(char==="{")return{index,kind:"{"};if(char!=="(")return;const operator=chars[index-1];return operator!==void 0&&"@?*+!".includes(operator)&&!isEscaped(chars,index-1)?{index:index-1,kind:"("}:open.some(opener=>opener.kind==="(")?{index,kind:"plain"}:void 0}function closeAt(chars,index,open,closers,groups){const char=chars[index],top=open.at(-1);if(char===")"&&top?.kind==="plain"){open.pop(),groups.set(top.index,index);return}const kind=char==="}"?"{":char===")"?"(":void 0;if(!(kind===void 0||top?.kind!==kind)&&(open.pop(),closers.set(top.index,index),chars[top.index]==="!"))throw negationRefusal()}function pairConstructs(chars){const closers=new Map,brackets=new Map,groups=new Map,open=[];let index=0;for(;index<chars.length;){if(chars[index]==="\\"){index+=2;continue}const end=chars[index]==="["?bracketEnd(chars,index):-1;if(end!==-1){brackets.set(index,end),index=end;continue}const opener=openerAt(chars,index,open);if(opener!==void 0?open.push(opener):closeAt(chars,index,open,closers,groups),open.length>MAX_NESTING)throw new GlobTooComplex;index+=1}return{closers,brackets,groups}}function isEscaped(chars,index){let count=0;for(let cursor=index-1;cursor>=0&&chars[cursor]==="\\";cursor-=1)count+=1;return count%2===1}function literalNodes(text){return Array.from(text,char=>({kind:"char",value:char.codePointAt(0)}))}function braceRange(content){const numeric=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(content),alphabetic=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(content);if(numeric===null&&alphabetic===null)return;const[from,to]=numeric!==null?[Number(numeric[1]),Number(numeric[2])]:[alphabetic[1].codePointAt(0),alphabetic[2].codePointAt(0)];if(Math.abs(to-from)+1>MAX_RANGE_SIZE)throw new GlobTooComplex;const step=from<=to?1:-1,values=[];for(let value=from;value!==to+step;value+=step)values.push(numeric!==null?String(value):String.fromCodePoint(value));return values}function posixClassAt(chars,index){if(chars[index]!=="["||chars[index+1]!==":")return;const colon=chars.indexOf(":",index+2);if(!(colon===-1||chars[colon+1]!=="]"))return{ranges:POSIX_CLASSES.get(chars.slice(index+2,colon).join(""))??[],next:colon+2}}function memberAt(chars,index,close){const escaped=chars[index]==="\\"&&index+1<close;return{codePoint:chars[escaped?index+1:index].codePointAt(0),next:index+(escaped?2:1)}}function bracketLiteral(chars,start,end){const literal=[];for(let cursor=start;cursor<end;cursor+=1)chars[cursor]==="\\"&&cursor+1<end&&(cursor+=1),literal.push(chars[cursor].codePointAt(0));return literal}function parseClass(chars,start,end){let index=start+1;const negated=chars[index]==="!"||chars[index]==="^";negated&&(index+=1);const ranges=[],close=end-1;for(;index<close;){const posix=posixClassAt(chars,index);if(posix!==void 0){ranges.push(...posix.ranges),index=posix.next;continue}const low=memberAt(chars,index,close);if(index=low.next,chars[index]!=="-"||index+1>=close){ranges.push([low.codePoint,low.codePoint]);continue}const high=memberAt(chars,index+1,close);index=high.next,low.codePoint<=high.codePoint&&ranges.push([low.codePoint,high.codePoint])}return{kind:"class",negated,ranges,literal:bracketLiteral(chars,start,end)}}class Parser{chars;closers;brackets;groups;constructor(chars,pairs){this.chars=chars,this.closers=pairs.closers,this.brackets=pairs.brackets,this.groups=pairs.groups}alternatives(start,end,separator){const options=[];let cursor=start;for(;;){const{nodes,stop}=this.sequence(cursor,end,separator);if(options.push(nodes),stop>=end)return options;cursor=stop+1}}sequence(start,end,separator){const nodes=[];let index=start;for(;index<end;){if(this.chars[index]===separator)return{nodes,stop:index};const token=this.token(index,end);nodes.push(...token.nodes),index=token.next}return{nodes,stop:end}}token(index,end){const char=this.chars[index];if(char==="\\")return{nodes:literalNodes(index+1<end?this.chars[index+1]:"\\"),next:index+2};const closer=this.closers.get(index);if(closer!==void 0)return{nodes:char==="{"?this.brace(index,closer):this.extglob(char,index,closer),next:closer+1};const group=this.groups.get(index);if(group!==void 0)return{nodes:[...literalNodes("("),...this.sequence(index+1,group,void 0).nodes,...literalNodes(")")],next:group+1};const bracket=this.brackets.get(index);return bracket!==void 0?{nodes:[parseClass(this.chars,index,bracket)],next:bracket}:char==="*"?this.stars(index,end):{nodes:char==="?"?[{kind:"any"}]:literalNodes(char),next:index+1}}extglob(operator,index,closer){const options=this.alternatives(index+2,closer,"|");return[operator==="@"?{kind:"alt",options}:{kind:"repeat",optional:operator!=="+",many:operator!=="?",options}]}brace(index,closer){const options=this.alternatives(index+1,closer,",");if(options.length>1)return[{kind:"alt",options}];const range=braceRange(this.chars.slice(index+1,closer).join(""));return range!==void 0?[{kind:"alt",options:range.map(literalNodes)}]:[...literalNodes("{"),...options[0],...literalNodes("}")]}stars(index,end){let run=1;for(;this.chars[index+run]==="*"&&index+run<end&&!this.closers.has(index+run);)run+=1;if(run!==2)return{nodes:[{kind:"star"}],next:index+run};const slash=index+run<end&&this.chars[index+run]==="/";return{nodes:[{kind:"globstar",slash}],next:index+run+(slash?1:0)}}}const END_KINDS=["segment","inside"],ANY={kind:"any"};function entriesOf(ends){return END_KINDS.flatMap(kind=>ends[kind]===void 0?[]:[ends[kind]])}class Nfa{states=[];add(){if(this.states.length>=MAX_STATES)throw new GlobTooComplex;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(from,to,syntactic=!0){this.states[from].epsilon.push(to),syntactic&&this.states[from].syntactic.push(to)}consume(from,test,kind){const to=this.add();for(const entry of entriesOf(from))this.states[entry].edges.push({test,to});return{[kind]:to}}join(parts){const joined={};for(const kind of END_KINDS){const states=parts.flatMap(part=>part[kind]===void 0?[]:[part[kind]]);if(states.length===1&&(joined[kind]=states[0]),states.length>1){const merged=this.add();for(const state of states)this.epsilon(state,merged);joined[kind]=merged}}return joined}feed(ends,loop){for(const kind of END_KINDS)ends[kind]!==void 0&&this.epsilon(ends[kind],loop[kind])}build(nodes,from){let current=from;for(const node of nodes)current=this.node(node,current);return current}alternation(options,from){return this.join(options.map(option=>this.build(option,from)))}star(from){const loop=this.add();for(const entry of entriesOf(from))this.epsilon(entry,loop,!1);return this.states[loop].edges.push({test:ANY,to:loop}),{inside:loop}}segments(from){const between=this.add();this.epsilon(from,between,!1);const inside=this.add();return this.states[between].edges.push({test:ANY,to:inside}),this.states[inside].edges.push({test:ANY,to:inside},{test:{kind:"char",value:SLASH},to:between}),between}globstar(from,slash){if(slash){const parts=[];return from.segment!==void 0&&parts.push({segment:this.segments(from.segment)}),from.inside!==void 0&&parts.push(this.consume(this.star({inside:from.inside}),{kind:"char",value:SLASH},"segment")),this.join(parts)}const star=this.star(from);return from.segment!==void 0&&this.globstars.push({continuation:star.inside,entry:from.segment}),star}globstars=[];syntacticClosure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.states[stack.pop()].syntactic)seen.has(next)||(seen.add(next),stack.push(next));return seen}resolveGlobstars(accept){for(const{continuation,entry}of this.globstars){const reachable=this.syntacticClosure([continuation]);if(reachable.has(accept)){const rest=this.add();this.epsilon(entry,rest,!1),this.states[rest].edges.push({test:{kind:"all"},to:rest}),this.epsilon(rest,accept,!1)}const targets=new Set;for(const state of reachable)for(const{test,to}of this.states[state].edges)accepts(test,SLASH)&&targets.add(to);if(targets.size===0)continue;const segments=this.segments(entry);for(const target of targets)this.epsilon(segments,target,!1)}}repeat(node,from){if(!node.many)return this.join([from,this.alternation(node.options,from)]);const loop={segment:this.add(),inside:this.add()};return this.feed(node.optional?from:this.alternation(node.options,from),loop),this.feed(this.alternation(node.options,loop),loop),loop}node(node,from){switch(node.kind){case"char":return this.consume(from,{kind:"char",value:node.value},node.value===SLASH?"segment":"inside");case"any":return this.consume(from,ANY,"inside");case"star":return this.star(from);case"globstar":return this.globstar(from,node.slash);case"class":return this.join([this.consume(from,{kind:"class",negated:node.negated,ranges:node.ranges},"inside"),this.build(node.literal.map(value=>({kind:"char",value})),from)]);case"alt":return this.alternation(node.options,from);case"repeat":return this.repeat(node,from)}}}function accepts(test,codePoint){switch(test.kind){case"char":return test.value===codePoint;case"any":return codePoint!==SLASH;case"all":return!0;case"class":return codePoint!==SLASH&&test.ranges.some(([low,high])=>codePoint>=low&&codePoint<=high)!==test.negated}}class PathMatcher{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(nfa,startState,acceptState,limits){this.nfa=nfa,this.acceptState=acceptState,this.limits=limits,this.start=this.node(this.closure([startState]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.nfa.states[stack.pop()].epsilon)seen.has(next)||(seen.add(next),stack.push(next));return[...seen].sort((left,right)=>left-right)}node(states){const key=states.join(","),cached=this.nodes.get(key);if(cached!==void 0)return cached;(this.nodes.size>=this.limits.nodes||this.stateIds+states.length>this.limits.stateIds)&&this.reset();const created={id:this.nextId,generation:this.generation,states,accepting:states.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(key,created),this.stateIds+=states.length,created}step(from,codePoint){const key=`${from.id}:${codePoint}`,known=from.generation===this.generation?this.edges.get(key):void 0;if(known!==void 0)return known;const reached=[];for(const state of from.states)for(const{test,to}of this.nfa.states[state].edges)accepts(test,codePoint)&&reached.push(to);const next=this.node(this.closure(reached));return this.edges.size>=this.limits.edges&&this.reset(),from.generation===this.generation&&this.edges.set(key,next),next}advance(from,text){let node=from;for(const char of text){if(node.states.length===0)return node;node=this.step(node,char.codePointAt(0))}return node}}function compile(text,limits=DFA_LIMITS){const chars=Array.from(text),nodes=new Parser(chars,pairConstructs(chars)).sequence(0,chars.length,void 0).nodes,nfa=new Nfa,start=nfa.add(),accept=nfa.add();for(const end of entriesOf(nfa.build(nodes,{segment:start})))nfa.epsilon(end,accept);return nfa.resolveGlobstars(accept),new PathMatcher(nfa,start,accept,limits)}function isStaticSegment(segment){return!/[*?[\]{}()!@+\\]/u.test(segment)}function kindOf(entry){return entry.isFile()?"file":entry.isDirectory()?"directory":"other"}async function resolveEntry(directory,real,entry){if(!entry.isSymbolicLink())return{kind:kindOf(entry),real:path.join(real,entry.name)};try{const target=await realpath(path.join(directory,entry.name));return{kind:kindOf(await stat(target)),real:target}}catch{return}}async function walk(matcher,directory,real,prefix,node,ancestors,out){let entries;try{entries=await readdir(directory,{withFileTypes:!0})}catch{return}for(const entry of entries){const afterName=matcher.advance(node,entry.name);if(afterName.states.length===0)continue;const resolved=await resolveEntry(directory,real,entry);if(resolved===void 0)continue;const relative=path.posix.join(prefix,entry.name);if(resolved.kind==="file"&&afterName.accepting&&out.push(relative),resolved.kind!=="directory")continue;const afterSlash=matcher.step(afterName,SLASH);afterSlash.states.length===0||ancestors.has(resolved.real)||(ancestors.add(resolved.real),await walk(matcher,path.join(directory,entry.name),resolved.real,relative,afterSlash,ancestors,out),ancestors.delete(resolved.real))}}function normalizePattern(pattern){const normalized=path.posix.normalize(pattern);return/^\/\/[^/]/u.test(pattern)?`/${normalized}`:normalized}function trimTrailingSeparators(pattern){let text=pattern;for(;text.length>1&&text.endsWith("/")&&!isEscaped(text,text.length-1);)text=text.slice(0,-1);return text}async function listed(directory,name){return(await readdir(directory).catch(()=>[])).includes(name)}async function exactCase(cwd,segments){let directory=cwd,index=0;for(;segments[index]==="..";)directory=path.dirname(directory),index+=1;for(;index<segments.length;index+=1){if(!await listed(directory,segments[index]))return!1;directory=path.join(directory,segments[index])}return!0}function isAbsolutePattern(text,platform=process.platform){return text.startsWith("/")||platform==="win32"&&/^[A-Za-z]:\//u.test(text)}async function literalMatch(text,cwd){const target=path.resolve(cwd,text),found=await stat(target).catch(()=>{});if(found===void 0||!found.isFile())return[];const absolute=isAbsolutePattern(text);return(absolute?await listed(path.dirname(target),path.basename(target)):await exactCase(cwd,text.split("/")))?[absolute?target.replaceAll("\\","/"):path.posix.normalize(text)]:[]}function splitStatic(text,cwd){const segments=text.split("/");let count=0;for(;count<segments.length&&isStaticSegment(segments[count]);)count+=1;if(count===segments.length)return;const prefix=count===0?"":`${segments.slice(0,count).join("/")}/`,root=path.resolve(cwd,prefix),rest=segments.slice(count).join("/");if(isAbsolutePattern(text))return{root,base:root.replaceAll("\\","/"),rest,prefix:[]};const relative=path.posix.normalize(prefix===""?".":prefix).replace(/\/$/u,"");return{root,base:relative==="."?"":relative,rest,prefix:segments.slice(0,count)}}function compileWithinBounds(text){try{return compile(text)}catch(error){if(error instanceof GlobTooComplex)return;throw error}}async function expandFileGlob(pattern,cwd){if(pattern.startsWith("!"))throw negationRefusal();if(Array.from(pattern).length>MAX_PATTERN_LENGTH)return[];const text=trimTrailingSeparators(normalizePattern(pattern)),parts=splitStatic(text,cwd);if(parts===void 0)return literalMatch(text,cwd);const matcher=compileWithinBounds(parts.rest);if(matcher===void 0||!await exactCase(cwd,parts.prefix))return[];const real=await realpath(parts.root).catch(()=>{});if(real===void 0)return[];const out=[];return await walk(matcher,parts.root,real,"",matcher.start,new Set([real]),out),out.map(relative=>joinOutput(parts.base,relative))}function joinOutput(base,relative){return base.startsWith("//")?`/${path.posix.join(base.slice(1),relative)}`:path.posix.join(base,relative)}const _testOnly={compile,isAbsolutePattern,joinOutput,normalizePattern};export{_testOnly,expandFileGlob};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="427dd932-a013-557c-b3d8-5d7bb042e88c")}catch{}})();import{readdir,realpath,stat}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_PATTERN_LENGTH=4096,MAX_NESTING=32,MAX_RANGE_SIZE=1e3,MAX_STATES=5e4,DFA_LIMITS={nodes:1e4,edges:4e4,stateIds:2e6},SLASH=47;class GlobTooComplex extends Error{}const POSIX_CLASSES=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function negationRefusal(){return new PmCliError("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",EXIT_CODE.USAGE)}function bracketEnd(chars,start){let index=start+1;for((chars[index]==="!"||chars[index]==="^")&&(index+=1),chars[index]==="]"&&(index+=1);index<chars.length;){const char=chars[index];if(char==="\\")index+=2;else if(char==="["&&chars[index+1]===":"){const close=chars.indexOf(":",index+2);close===-1||chars[close+1]!=="]"?index+=1:index=close+2}else{if(char==="]")return index+1;index+=1}}return-1}function openerAt(chars,index,open){const char=chars[index];if(char==="{")return{index,kind:"{"};if(char!=="(")return;const operator=chars[index-1];return operator!==void 0&&"@?*+!".includes(operator)&&!isEscaped(chars,index-1)?{index:index-1,kind:"("}:open.some(opener=>opener.kind==="(")?{index,kind:"plain"}:void 0}function closeAt(chars,index,open,closers,groups){const char=chars[index],top=open.at(-1);if(char===")"&&top?.kind==="plain"){open.pop(),groups.set(top.index,index);return}const kind=char==="}"?"{":char===")"?"(":void 0;if(!(kind===void 0||top?.kind!==kind)&&(open.pop(),closers.set(top.index,index),chars[top.index]==="!"))throw negationRefusal()}function pairConstructs(chars){const closers=new Map,brackets=new Map,groups=new Map,open=[];let index=0;for(;index<chars.length;){if(chars[index]==="\\"){index+=2;continue}const end=chars[index]==="["?bracketEnd(chars,index):-1;if(end!==-1){brackets.set(index,end),index=end;continue}const opener=openerAt(chars,index,open);if(opener!==void 0?open.push(opener):closeAt(chars,index,open,closers,groups),open.length>MAX_NESTING)throw new GlobTooComplex;index+=1}return{closers,brackets,groups}}function isEscaped(chars,index){let count=0;for(let cursor=index-1;cursor>=0&&chars[cursor]==="\\";cursor-=1)count+=1;return count%2===1}function literalNodes(text){return Array.from(text,char=>({kind:"char",value:char.codePointAt(0)}))}function braceRange(content){const numeric=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(content),alphabetic=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(content);if(numeric===null&&alphabetic===null)return;const[from,to]=numeric!==null?[Number(numeric[1]),Number(numeric[2])]:[alphabetic[1].codePointAt(0),alphabetic[2].codePointAt(0)];if(Math.abs(to-from)+1>MAX_RANGE_SIZE)throw new GlobTooComplex;const step=from<=to?1:-1,values=[];for(let value=from;value!==to+step;value+=step)values.push(numeric!==null?String(value):String.fromCodePoint(value));return values}function posixClassAt(chars,index){if(chars[index]!=="["||chars[index+1]!==":")return;const colon=chars.indexOf(":",index+2);if(!(colon===-1||chars[colon+1]!=="]"))return{ranges:POSIX_CLASSES.get(chars.slice(index+2,colon).join(""))??[],next:colon+2}}function memberAt(chars,index,close){const escaped=chars[index]==="\\"&&index+1<close;return{codePoint:chars[escaped?index+1:index].codePointAt(0),next:index+(escaped?2:1)}}function bracketLiteral(chars,start,end){const literal=[];for(let cursor=start;cursor<end;cursor+=1)chars[cursor]==="\\"&&cursor+1<end&&(cursor+=1),literal.push(chars[cursor].codePointAt(0));return literal}function parseClass(chars,start,end){let index=start+1;const negated=chars[index]==="!"||chars[index]==="^";negated&&(index+=1);const ranges=[],close=end-1;for(;index<close;){const posix=posixClassAt(chars,index);if(posix!==void 0){ranges.push(...posix.ranges),index=posix.next;continue}const low=memberAt(chars,index,close);if(index=low.next,chars[index]!=="-"||index+1>=close){ranges.push([low.codePoint,low.codePoint]);continue}const high=memberAt(chars,index+1,close);index=high.next,low.codePoint<=high.codePoint&&ranges.push([low.codePoint,high.codePoint])}return{kind:"class",negated,ranges,literal:bracketLiteral(chars,start,end)}}class Parser{chars;closers;brackets;groups;constructor(chars,pairs){this.chars=chars,this.closers=pairs.closers,this.brackets=pairs.brackets,this.groups=pairs.groups}alternatives(start,end,separator){const options=[];let cursor=start;for(;;){const{nodes,stop}=this.sequence(cursor,end,separator);if(options.push(nodes),stop>=end)return options;cursor=stop+1}}sequence(start,end,separator){const nodes=[];let index=start;for(;index<end;){if(this.chars[index]===separator)return{nodes,stop:index};const token=this.token(index,end);nodes.push(...token.nodes),index=token.next}return{nodes,stop:end}}token(index,end){const char=this.chars[index];if(char==="\\")return{nodes:literalNodes(index+1<end?this.chars[index+1]:"\\"),next:index+2};const closer=this.closers.get(index);if(closer!==void 0)return{nodes:char==="{"?this.brace(index,closer):this.extglob(char,index,closer),next:closer+1};const group=this.groups.get(index);if(group!==void 0)return{nodes:[...literalNodes("("),...this.sequence(index+1,group,void 0).nodes,...literalNodes(")")],next:group+1};const bracket=this.brackets.get(index);return bracket!==void 0?{nodes:[parseClass(this.chars,index,bracket)],next:bracket}:char==="*"?this.stars(index,end):{nodes:char==="?"?[{kind:"any"}]:literalNodes(char),next:index+1}}extglob(operator,index,closer){const options=this.alternatives(index+2,closer,"|");return[operator==="@"?{kind:"alt",options}:{kind:"repeat",optional:operator!=="+",many:operator!=="?",options}]}brace(index,closer){const options=this.alternatives(index+1,closer,",");if(options.length>1)return[{kind:"alt",options}];const range=braceRange(this.chars.slice(index+1,closer).join(""));return range!==void 0?[{kind:"alt",options:range.map(literalNodes)}]:[...literalNodes("{"),...options[0],...literalNodes("}")]}stars(index,end){let run=1;for(;this.chars[index+run]==="*"&&index+run<end&&!this.closers.has(index+run);)run+=1;if(run!==2)return{nodes:[{kind:"star"}],next:index+run};const slash=index+run<end&&this.chars[index+run]==="/";return{nodes:[{kind:"globstar",slash}],next:index+run+(slash?1:0)}}}const END_KINDS=["segment","inside"],ANY={kind:"any"};function entriesOf(ends){return END_KINDS.flatMap(kind=>ends[kind]===void 0?[]:[ends[kind]])}class Nfa{states=[];add(){if(this.states.length>=MAX_STATES)throw new GlobTooComplex;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(from,to,syntactic=!0){this.states[from].epsilon.push(to),syntactic&&this.states[from].syntactic.push(to)}consume(from,test,kind){const to=this.add();for(const entry of entriesOf(from))this.states[entry].edges.push({test,to});return{[kind]:to}}join(parts){const joined={};for(const kind of END_KINDS){const states=parts.flatMap(part=>part[kind]===void 0?[]:[part[kind]]);if(states.length===1&&(joined[kind]=states[0]),states.length>1){const merged=this.add();for(const state of states)this.epsilon(state,merged);joined[kind]=merged}}return joined}feed(ends,loop){for(const kind of END_KINDS)ends[kind]!==void 0&&this.epsilon(ends[kind],loop[kind])}build(nodes,from){let current=from;for(const node of nodes)current=this.node(node,current);return current}alternation(options,from){return this.join(options.map(option=>this.build(option,from)))}star(from){const loop=this.add();for(const entry of entriesOf(from))this.epsilon(entry,loop,!1);return this.states[loop].edges.push({test:ANY,to:loop}),{inside:loop}}segments(from){const between=this.add();this.epsilon(from,between,!1);const inside=this.add();return this.states[between].edges.push({test:ANY,to:inside}),this.states[inside].edges.push({test:ANY,to:inside},{test:{kind:"char",value:SLASH},to:between}),between}globstar(from,slash){if(slash){const parts=[];return from.segment!==void 0&&parts.push({segment:this.segments(from.segment)}),from.inside!==void 0&&parts.push(this.consume(this.star({inside:from.inside}),{kind:"char",value:SLASH},"segment")),this.join(parts)}const star=this.star(from);return from.segment!==void 0&&this.globstars.push({continuation:star.inside,entry:from.segment}),star}globstars=[];syntacticClosure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.states[stack.pop()].syntactic)seen.has(next)||(seen.add(next),stack.push(next));return seen}resolveGlobstars(accept){for(const{continuation,entry}of this.globstars){const reachable=this.syntacticClosure([continuation]);if(reachable.has(accept)){const rest=this.add();this.epsilon(entry,rest,!1),this.states[rest].edges.push({test:{kind:"all"},to:rest}),this.epsilon(rest,accept,!1)}const targets=new Set;for(const state of reachable)for(const{test,to}of this.states[state].edges)accepts(test,SLASH)&&targets.add(to);if(targets.size===0)continue;const segments=this.segments(entry);for(const target of targets)this.epsilon(segments,target,!1)}}repeat(node,from){if(!node.many)return this.join([from,this.alternation(node.options,from)]);const loop={segment:this.add(),inside:this.add()};return this.feed(node.optional?from:this.alternation(node.options,from),loop),this.feed(this.alternation(node.options,loop),loop),loop}node(node,from){switch(node.kind){case"char":return this.consume(from,{kind:"char",value:node.value},node.value===SLASH?"segment":"inside");case"any":return this.consume(from,ANY,"inside");case"star":return this.star(from);case"globstar":return this.globstar(from,node.slash);case"class":return this.join([this.consume(from,{kind:"class",negated:node.negated,ranges:node.ranges},"inside"),this.build(node.literal.map(value=>({kind:"char",value})),from)]);case"alt":return this.alternation(node.options,from);case"repeat":return this.repeat(node,from)}}}function accepts(test,codePoint){switch(test.kind){case"char":return test.value===codePoint;case"any":return codePoint!==SLASH;case"all":return!0;case"class":return codePoint!==SLASH&&test.ranges.some(([low,high])=>codePoint>=low&&codePoint<=high)!==test.negated}}class PathMatcher{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(nfa,startState,acceptState,limits){this.nfa=nfa,this.acceptState=acceptState,this.limits=limits,this.start=this.node(this.closure([startState]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.nfa.states[stack.pop()].epsilon)seen.has(next)||(seen.add(next),stack.push(next));return[...seen].sort((left,right)=>left-right)}node(states){const key=states.join(","),cached=this.nodes.get(key);if(cached!==void 0)return cached;(this.nodes.size>=this.limits.nodes||this.stateIds+states.length>this.limits.stateIds)&&this.reset();const created={id:this.nextId,generation:this.generation,states,accepting:states.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(key,created),this.stateIds+=states.length,created}step(from,codePoint){const key=`${from.id}:${codePoint}`,known=from.generation===this.generation?this.edges.get(key):void 0;if(known!==void 0)return known;const reached=[];for(const state of from.states)for(const{test,to}of this.nfa.states[state].edges)accepts(test,codePoint)&&reached.push(to);const next=this.node(this.closure(reached));return this.edges.size>=this.limits.edges&&this.reset(),from.generation===this.generation&&this.edges.set(key,next),next}advance(from,text){let node=from;for(const char of text){if(node.states.length===0)return node;node=this.step(node,char.codePointAt(0))}return node}}function compile(text,limits=DFA_LIMITS){const chars=Array.from(text),nodes=new Parser(chars,pairConstructs(chars)).sequence(0,chars.length,void 0).nodes,nfa=new Nfa,start=nfa.add(),accept=nfa.add();for(const end of entriesOf(nfa.build(nodes,{segment:start})))nfa.epsilon(end,accept);return nfa.resolveGlobstars(accept),new PathMatcher(nfa,start,accept,limits)}function isStaticSegment(segment){return!/[*?[\]{}()!@+\\]/u.test(segment)}function kindOf(entry){return entry.isFile()?"file":entry.isDirectory()?"directory":"other"}async function resolveEntry(directory,real,entry){if(!entry.isSymbolicLink())return{kind:kindOf(entry),real:path.join(real,entry.name)};try{const target=await realpath(path.join(directory,entry.name));return{kind:kindOf(await stat(target)),real:target}}catch{return}}async function walk(matcher,directory,real,prefix,node,ancestors,out){let entries;try{entries=await readdir(directory,{withFileTypes:!0})}catch{return}for(const entry of entries){const afterName=matcher.advance(node,entry.name);if(afterName.states.length===0)continue;const resolved=await resolveEntry(directory,real,entry);if(resolved===void 0)continue;const relative=path.posix.join(prefix,entry.name);if(resolved.kind==="file"&&afterName.accepting&&out.push(relative),resolved.kind!=="directory")continue;const afterSlash=matcher.step(afterName,SLASH);afterSlash.states.length===0||ancestors.has(resolved.real)||(ancestors.add(resolved.real),await walk(matcher,path.join(directory,entry.name),resolved.real,relative,afterSlash,ancestors,out),ancestors.delete(resolved.real))}}function normalizePattern(pattern){const normalized=path.posix.normalize(pattern);return/^\/\/[^/]/u.test(pattern)?`/${normalized}`:normalized}function trimTrailingSeparators(pattern){let text=pattern;for(;text.length>1&&text.endsWith("/")&&!isEscaped(text,text.length-1);)text=text.slice(0,-1);return text}async function listed(directory,name){return(await readdir(directory).catch(()=>[])).includes(name)}async function exactCase(cwd,segments){let directory=cwd,index=0;for(;segments[index]==="..";)directory=path.dirname(directory),index+=1;for(;index<segments.length;index+=1){if(!await listed(directory,segments[index]))return!1;directory=path.join(directory,segments[index])}return!0}function isAbsolutePattern(text,platform=process.platform){return text.startsWith("/")||platform==="win32"&&/^[A-Za-z]:\//u.test(text)}async function literalMatch(text,cwd){const target=path.resolve(cwd,text),found=await stat(target).catch(()=>{});if(found===void 0||!found.isFile())return[];const absolute=isAbsolutePattern(text);return(absolute?await listed(path.dirname(target),path.basename(target)):await exactCase(cwd,text.split("/")))?[absolute?target.replaceAll("\\","/"):path.posix.normalize(text)]:[]}function splitStatic(text,cwd){const segments=text.split("/");let count=0;for(;count<segments.length&&isStaticSegment(segments[count]);)count+=1;if(count===segments.length)return;const prefix=count===0?"":`${segments.slice(0,count).join("/")}/`,root=path.resolve(cwd,prefix),rest=segments.slice(count).join("/");if(isAbsolutePattern(text))return{root,base:root.replaceAll("\\","/"),rest,prefix:[]};const relative=path.posix.normalize(prefix===""?".":prefix).replace(/\/$/u,"");return{root,base:relative==="."?"":relative,rest,prefix:segments.slice(0,count)}}function compileWithinBounds(text){try{return compile(text)}catch(error){if(error instanceof GlobTooComplex)return;throw error}}async function expandFileGlob(pattern,cwd){if(pattern.startsWith("!"))throw negationRefusal();if(Array.from(pattern).length>MAX_PATTERN_LENGTH)return[];const text=trimTrailingSeparators(normalizePattern(pattern)),parts=splitStatic(text,cwd);if(parts===void 0)return literalMatch(text,cwd);const matcher=compileWithinBounds(parts.rest);if(matcher===void 0||!await exactCase(cwd,parts.prefix))return[];const real=await realpath(parts.root).catch(()=>{});if(real===void 0)return[];const out=[];return await walk(matcher,parts.root,real,"",matcher.start,new Set([real]),out),out.map(relative=>joinOutput(parts.base,relative))}function joinOutput(base,relative){return base.startsWith("//")?`/${path.posix.join(base.slice(1),relative)}`:path.posix.join(base,relative)}const _testOnly={compile,isAbsolutePattern,joinOutput,normalizePattern};export{_testOnly,expandFileGlob};
|
|
2
2
|
//# sourceMappingURL=file-glob.js.map
|
|
@@ -40,8 +40,10 @@ export declare function transactionPreviewNonRegularFileError(relativePath?:stri
|
|
|
40
40
|
* Parent directories are created by default. Background consumers can disable
|
|
41
41
|
* that behavior to respect removal of their storage while work is in flight;
|
|
42
42
|
* missing parents then produce the native filesystem error without recreation.
|
|
43
|
+
* `mode` creates the temporary file, and so the result, with those permission
|
|
44
|
+
* bits (subject to the umask), for derived state that must stay private.
|
|
43
45
|
*/
|
|
44
|
-
export declare function writeFileAtomic(targetPath:string,contents:string,options?:{createParentDirectories?:boolean;}):Promise<void>;
|
|
46
|
+
export declare function writeFileAtomic(targetPath:string,contents:string,options?:{createParentDirectories?:boolean;mode?:number;}):Promise<void>;
|
|
45
47
|
/**
|
|
46
48
|
* Append a single newline-terminated line to a file, opened with `O_APPEND`.
|
|
47
49
|
*
|
package/dist/core/fs/fs-utils.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="af07b34f-9e45-561f-aa8c-2415ee4a46b9")}catch{}})();import*as fs from"node:fs/promises";import{constants}from"node:fs";import path from"node:path";import crypto from"node:crypto";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const WINDOWS_RENAME_RETRY_DELAYS_MS=[10,25,50,100];async function ensureDir(dirPath){await fs.mkdir(dirPath,{recursive:!0})}async function pathExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isFileAbsentError(error){return isFileMissingError(error)||isErrno(error,"ENOTDIR")}function isFileMissingError(error){return isErrno(error,"ENOENT")}async function readFileIfExists(targetPath){try{return await fs.readFile(targetPath,"utf8")}catch(error){if(isFileAbsentError(error))return null;throw error}}async function readRegularFile(targetPath,rejectionError){const handle=await fs.open(targetPath,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{if(!(await handle.stat()).isFile())throw rejectionError;return await handle.readFile("utf8")}finally{await handle.close()}}function transactionPreviewNonRegularFileError(relativePath){const relative=relativePath?.replaceAll(path.sep,"/"),contained=relative!==void 0&&!path.posix.isAbsolute(relative)&&!path.win32.isAbsolute(relative)&&!relative.split("/").includes(".."),first=contained?relative.split("/")[0]:void 0,areas={"settings.json":"settings",runtime:"runtime",schema:"schema",history:"history",transactions:"transactions"},area=first===void 0?"tracker_storage":Object.hasOwn(areas,first)?areas[first]:"tracker_storage",safe=contained&&relative.length>0&&relative.length<=160&&relative.split("/").every(part=>part!=="."&&/^[a-zA-Z0-9_.-]+$/u.test(part)),location=safe?relative:`${area} (entry name redacted)`;return new PmCliError(`Transaction preview requires regular files and directories. Inspect ${location} relative to the selected tracker root.`,EXIT_CODE.USAGE,{code:"transaction_preview_non_regular_file",preview_storage:{storage_area:area,...safe?{relative_entry:relative}:{},entry_redacted:!safe},required:"regular files and directories within the configured tracker storage",why:"Preview does not follow linked entries or read special files.",nextSteps:[`Inspect ${location} within the selected tracker for links, directories used as files, or special files; do not follow link targets.`,"Restore the intended regular files and directories, then retry the original dry-run command."]})}async function unlinkQuietly(filePath){try{await fs.unlink(filePath)}catch{}}async function writeFileAtomic(targetPath,contents,options={}){const dirPath=path.dirname(targetPath);options.createParentDirectories!==!1&&await ensureDir(dirPath);const tempPath=path.join(dirPath,`.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}.tmp`);try{await fs.writeFile(tempPath,contents,options.mode===void 0?"utf8":{encoding:"utf8",mode:options.mode})}catch(error){throw await unlinkQuietly(tempPath),error}try{await fs.rename(tempPath,targetPath)}catch(error){if(process.platform==="win32"&&(isErrno(error,"EPERM")||isErrno(error,"EBUSY"))){let lastError=error;for(const delayMs of WINDOWS_RENAME_RETRY_DELAYS_MS){await new Promise(resolve=>setTimeout(resolve,delayMs));try{await fs.rename(tempPath,targetPath);return}catch(retryError){if(lastError=retryError,!isErrno(retryError,"EPERM")&&!isErrno(retryError,"EBUSY"))break}}throw await unlinkQuietly(tempPath),lastError}if(isErrno(error,"EXDEV")){try{await fs.copyFile(tempPath,targetPath)}finally{await unlinkQuietly(tempPath)}return}throw await unlinkQuietly(tempPath),error}}async function appendLineAtomic(targetPath,line){const dirPath=path.dirname(targetPath);await ensureDir(dirPath);const handle=await fs.open(targetPath,"a");try{await handle.writeFile(`${line}
|
|
2
2
|
`,"utf8")}finally{await handle.close()}}async function removeFileIfExists(targetPath){try{await fs.unlink(targetPath)}catch(error){if(!isFileAbsentError(error))throw error}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}export{appendLineAtomic,ensureDir,isFileAbsentError,isFileMissingError,pathExists,readFileIfExists,readRegularFile,removeFileIfExists,transactionPreviewNonRegularFileError,writeFileAtomic};
|
|
3
3
|
//# sourceMappingURL=fs-utils.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="01a75358-2a0c-531d-bf79-ff353e1990c9")}catch{}})();import{historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";const HISTORY_BRIDGE_VERSION=1;function isHistoryBridgeBreak(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const candidate=value;return Object.keys(candidate).length===3&&typeof candidate.gap_from=="string"&&typeof candidate.gap_to=="string"&&candidate.gap_from!==candidate.gap_to&&(candidate.record_hash===null||typeof candidate.record_hash=="string")}function readHistoryBridge(entry){if(!Object.hasOwn(entry,"bridge"))return;const bridge=entry.bridge;if(entry.op!=="history_repair"||typeof entry.record_hash!="string"||typeof bridge!="object"||bridge===null||Array.isArray(bridge))return"invalid";const candidate=bridge;return candidate.version===HISTORY_BRIDGE_VERSION&&Object.keys(candidate).length===3&&typeof candidate.segment_digest=="string"&&Array.isArray(candidate.breaks)&&candidate.breaks.length>0&&[...candidate.breaks].every(isHistoryBridgeBreak)?candidate:"invalid"}function describeHistoryBreak(previous,entry){return{gap_from:previous.after_hash,gap_to:entry.before_hash,record_hash:entry.record_hash??null}}function matchesHistoryBreak(descriptor,previous,entry){return descriptor!==void 0&&descriptor.gap_from===previous.after_hash&&descriptor.gap_to===entry.before_hash&&descriptor.record_hash===(entry.record_hash??null)}function digestBridgedSegment(segment,bridge){return historyDigest(canonicalBridgeJson(segment),resolveHistoryHashAlgorithm(bridge.hash_algorithm))}const ARRAY_INDEX_KEY=/^(?:0|[1-9]\d*)$/u,isArrayIndexKey=key=>ARRAY_INDEX_KEY.test(key)&&Number(key)<2**32-1;function canonicalBridgeJson(value){if(Array.isArray(value))return`[${value.map(item=>canonicalBridgeJson(item??null)).join(",")}]`;if(value===null||typeof value!="object")return JSON.stringify(value);const record=value,keys=Object.keys(record).filter(key=>record[key]!==void 0);return`{${[...keys.filter(isArrayIndexKey),...keys.filter(key=>!isArrayIndexKey(key)).sort()].map(key=>`${JSON.stringify(key)}:${canonicalBridgeJson(record[key])}`).join(",")}}`}function findNextHistoryBridge(entries,index){for(let candidate=index+1;candidate<entries.length;candidate+=1)if(Object.hasOwn(entries[candidate],"bridge"))return candidate;return-1}function safeSegmentDigest(segment,bridge){try{return digestBridgedSegment(segment,bridge)}catch{return null}}function findBridgedSegmentStart(entries,bridge,floor,end){const first=bridge.breaks[0];let materialized=-1;for(let start=Math.max(1,floor);start<end;start+=1){const entry=entries[start],anchored=entries[start-1].after_hash===first.gap_from&&entry.before_hash===first.gap_to,named=first.record_hash!==null&&entry.record_hash===first.record_hash;if(!anchored&&!named)continue;const covered=entries.slice(start,end);if(safeSegmentDigest(covered,entries[end])===bridge.segment_digest)return{start,digest:!0};materialized<0&&anchored&&covered.every(record=>record.replay_inexact===!0)&&(materialized=start)}return{start:materialized,digest:!1}}function locateBridgedSegments(entries){const located={segments:[],unlocated:[],undigested:[]};let floor=1;return entries.forEach((entry,index)=>{if(!Object.hasOwn(entry,"bridge"))return;const bridge=readHistoryBridge(entry),found=typeof bridge=="object"?findBridgedSegmentStart(entries,bridge,floor,index):{start:-1,digest:!1},start=found.start;start<0?located.unlocated.push(index):found.digest||located.undigested.push(index),located.segments.push({start:start<0?floor:start,end:index,exact:start>=0}),start>=0&&(floor=index+1)}),located}export{HISTORY_BRIDGE_VERSION,describeHistoryBreak,digestBridgedSegment,findNextHistoryBridge,locateBridgedSegments,matchesHistoryBreak,readHistoryBridge};
|
|
2
|
+
//# sourceMappingURL=bridge.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="97537e2a-b8cb-559e-82bc-3c98b0c51db1")}catch{}})();import{HISTORY_HASH_ALGORITHMS,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import{createHash}from"node:crypto";import path from"node:path";import{getHistoryPath}from"../store/paths.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates}from"./history.js";import{verifyHistoryChainWithVersion}from"./replay.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{getWorkspaceHistoryPath,inspectWorkspaceHistoryState,WORKSPACE_HISTORY_ID}from"./workspace-history.js";const READABLE_HISTORY_HASH_ALGORITHMS=new Set([void 0,...HISTORY_HASH_ALGORITHMS]),DRIFT_CACHE_VERSION=11,DRIFT_CACHE_FILENAME="history-drift-cache.json";function getDriftCachePath(pmRoot){return path.join(pmRoot,"runtime",DRIFT_CACHE_FILENAME)}async function loadDriftCache(pmRoot){try{const raw=await fs.readFile(getDriftCachePath(pmRoot),"utf8"),parsed=JSON.parse(raw);return parsed.version!==DRIFT_CACHE_VERSION||parsed.history_item_hash_version!==CURRENT_HISTORY_ITEM_HASH_VERSION||typeof parsed.entries!="object"||parsed.entries===null||Object.values(parsed.entries).some(entry=>typeof entry.chain_ok!="boolean"||typeof entry.latest_hash_comparable!="boolean"||!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&entry.version_skew!==!0||entry.chain_ok&&entry.version_skew!==!0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&!entry.latest_hash_comparable)?null:parsed}catch{return null}}function createDriftScanAccumulator(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function buildDriftScanResult(accumulator){const driftedItems=[...new Set([...accumulator.missingStreams,...accumulator.unreadableStreams,...accumulator.hashMismatches,...accumulator.chainMismatches,...accumulator.versionSkews,...accumulator.workspaceStateMismatches.length>0||accumulator.workspaceStateMissing.length>0||accumulator.workspaceStateUnreadable.length>0?[WORKSPACE_HISTORY_ID]:[]])].sort((a,b)=>a.localeCompare(b));return{...accumulator,driftedItems}}async function scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator){const historyPath=getWorkspaceHistoryPath(pmRoot);let stat;try{stat=await fs.stat(historyPath)}catch(error){return isFileMissingError(error)||accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID),!1}const missingCount=accumulator.missingStreams.length,resolved=await resolveStreamVerification({itemId:WORKSPACE_HISTORY_ID,historyPath,stat,cached:previousEntries[WORKSPACE_HISTORY_ID],verifyCacheHitByContent,accumulator});return resolved.verification?(resolved.verification.versionSkew&&accumulator.versionSkews.push(WORKSPACE_HISTORY_ID),resolved.verification.chainOk||accumulator.chainMismatches.push(WORKSPACE_HISTORY_ID),nextEntries[WORKSPACE_HISTORY_ID]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm},resolved.cacheDirty):(accumulator.missingStreams.splice(missingCount),resolved.cacheDirty)}function hasUnsupportedHistoryCapability(entry){return!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||entry.item_hash_version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)}async function verifyHistoryStream(historyPath){const raw=await fs.readFile(historyPath,"utf8"),contentHash=createHash("sha256").update(raw).digest("hex");if(raw.trim().length===0)return null;const entries=[];let latestAfterHash=null;for(const line of raw.split(/\r?\n/)){const trimmed=line.trim();if(trimmed.length===0)continue;const parsed=JSON.parse(trimmed);if(typeof parsed.after_hash!="string"||parsed.after_hash.trim().length===0)throw new Error("missing after_hash");entries.push(parsed),latestAfterHash=parsed.after_hash}if(!latestAfterHash)return null;const verification=verifyHistoryChainWithVersion(entries),versionSkew=entries.some(hasUnsupportedHistoryCapability),latestEntry=entries[entries.length-1],algorithmSupported=READABLE_HISTORY_HASH_ALGORITHMS.has(latestEntry.hash_algorithm),latestExplicitVersion=latestEntry.item_hash_version,latestExplicitVersionSupported=latestExplicitVersion!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(latestExplicitVersion),latestHashVersion=latestExplicitVersionSupported?latestExplicitVersion:verification.item_hash_version;return{latestAfterHash,hashAlgorithm:algorithmSupported?resolveHistoryHashAlgorithm(latestEntry.hash_algorithm):void 0,identityDiscontinuities:findHistoryIdentityDiscontinuities(entries),chainOk:verification.ok,versionSkew,latestHashComparable:algorithmSupported&&latestHashVersion!==void 0&&(!versionSkew||latestExplicitVersionSupported||latestExplicitVersion===void 0),contentHash,itemHashVersion:latestHashVersion??CURRENT_HISTORY_ITEM_HASH_VERSION}}function cacheMetadataMatches(cached,stat){return cached!==void 0&&cached.mtime_ms===stat.mtimeMs&&cached.ctime_ms===stat.ctimeMs&&cached.size===stat.size}async function loadFreshStreamVerification(itemId,historyPath,accumulator){try{return await verifyHistoryStream(historyPath)||(accumulator.missingStreams.push(itemId),null)}catch{return accumulator.unreadableStreams.push(itemId),null}}function matchesCachedVerification(verification,cached){return verification!==null&&verification.contentHash===cached.content_hash&&verification.latestAfterHash===cached.latest_after_hash&&verification.chainOk===cached.chain_ok&&verification.versionSkew===(cached.version_skew===!0)&&verification.latestHashComparable===cached.latest_hash_comparable&&verification.itemHashVersion===cached.item_hash_version&&verification.hashAlgorithm===cached.hash_algorithm}async function resolveStreamVerification(params){const cachedContentHash=typeof params.cached?.content_hash=="string"&¶ms.cached.content_hash.length>0?params.cached.content_hash:void 0;if(!(cacheMetadataMatches(params.cached,params.stat)&&cachedContentHash!==void 0)||!params.cached||!params.cached.chain_ok)return{verification:await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator),cacheDirty:!0};if(params.verifyCacheHitByContent){const verification=await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator);return{verification,cacheDirty:!matchesCachedVerification(verification,params.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:params.cached.latest_after_hash,chainOk:params.cached.chain_ok,versionSkew:params.cached.version_skew===!0,latestHashComparable:params.cached.latest_hash_comparable&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(params.cached.item_hash_version),contentHash:cachedContentHash,itemHashVersion:params.cached.item_hash_version,hashAlgorithm:params.cached.hash_algorithm},cacheDirty:!1}}async function scanItemHistory(pmRoot,item,cache,accumulator){let historyPath,stat;try{historyPath=getHistoryPath(pmRoot,item.id),stat=await fs.stat(historyPath)}catch(error){return(isFileMissingError(error)?accumulator.missingStreams:accumulator.unreadableStreams).push(item.id),!1}const resolved=await resolveStreamVerification({itemId:item.id,historyPath,stat,cached:cache.previousEntries[item.id],verifyCacheHitByContent:cache.verifyCacheHitByContent,accumulator});if(!resolved.verification)return resolved.cacheDirty;resolved.verification.identityDiscontinuities.length>0&&(accumulator.identityDiscontinuities??=[]).push(...resolved.verification.identityDiscontinuities.map(finding=>({...finding,item_id:item.id}))),resolved.verification.versionSkew&&accumulator.versionSkews.push(item.id),resolved.verification.chainOk||accumulator.chainMismatches.push(item.id),cache.nextEntries[item.id]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm};const{body,...itemMetadata}=item;return resolved.verification.latestHashComparable&&(hashDocumentVerificationCandidates({metadata:itemMetadata,body},resolved.verification.itemHashVersion,resolved.verification.hashAlgorithm).includes(resolved.verification.latestAfterHash)||accumulator.hashMismatches.push(item.id)),resolved.cacheDirty}async function scanWorkspaceStateAgreement(pmRoot,accumulator){if(!(accumulator.unreadableStreams.includes(WORKSPACE_HISTORY_ID)||accumulator.chainMismatches.includes(WORKSPACE_HISTORY_ID)||accumulator.versionSkews.includes(WORKSPACE_HISTORY_ID)))try{const agreement=await inspectWorkspaceHistoryState(pmRoot);accumulator.workspaceStateMismatches.push(...agreement.mismatched_documents),accumulator.workspaceStateMissing.push(...agreement.missing_documents),accumulator.workspaceStateUnreadable.push(...agreement.unreadable_documents)}catch{accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID)}}async function scanItemHistoryDrift(pmRoot,item){const accumulator=createDriftScanAccumulator();return await scanItemHistory(pmRoot,item,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},accumulator),buildDriftScanResult(accumulator)}async function scanHistoryDrift(pmRoot,items,options={}){const accumulator=createDriftScanAccumulator(),previousEntries=(await loadDriftCache(pmRoot))?.entries??{},nextEntries={};let cacheDirty=!1;const verifyCacheHitByContent=options.cacheHitVerification!=="metadata",cacheState={previousEntries,nextEntries,verifyCacheHitByContent};for(const item of items)await scanItemHistory(pmRoot,item,cacheState,accumulator)&&(cacheDirty=!0);const workspaceCacheDirty=await scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator);if(cacheDirty||=workspaceCacheDirty,await scanWorkspaceStateAgreement(pmRoot,accumulator),cacheDirty||Object.keys(previousEntries).length!==Object.keys(nextEntries).length){const cachePath=getDriftCachePath(pmRoot);try{await fs.mkdir(path.dirname(cachePath),{recursive:!0}),await writeFileAtomic(cachePath,JSON.stringify({version:DRIFT_CACHE_VERSION,history_item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,entries:nextEntries}))}catch{}}return buildDriftScanResult(accumulator)}export{scanHistoryDrift,scanItemHistoryDrift};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a535e1be-f99b-5898-af76-0c9d5b8a681d")}catch{}})();import{HISTORY_HASH_ALGORITHMS,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import{createHash}from"node:crypto";import path from"node:path";import{getHistoryPath}from"../store/paths.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hasNewerRecordSealFormat,hashDocumentVerificationCandidates}from"./history.js";import{verifyHistoryChainWithVersion}from"./replay.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{getWorkspaceHistoryPath,inspectWorkspaceHistoryState,WORKSPACE_HISTORY_ID}from"./workspace-history.js";const READABLE_HISTORY_HASH_ALGORITHMS=new Set([void 0,...HISTORY_HASH_ALGORITHMS]),DRIFT_CACHE_VERSION=13,DRIFT_CACHE_FILENAME="history-drift-cache.json";function getDriftCachePath(pmRoot){return path.join(pmRoot,"runtime",DRIFT_CACHE_FILENAME)}async function loadDriftCache(pmRoot){try{const raw=await fs.readFile(getDriftCachePath(pmRoot),"utf8"),parsed=JSON.parse(raw);return parsed.version!==DRIFT_CACHE_VERSION||parsed.history_item_hash_version!==CURRENT_HISTORY_ITEM_HASH_VERSION||typeof parsed.entries!="object"||parsed.entries===null||Object.values(parsed.entries).some(entry=>typeof entry.chain_ok!="boolean"||typeof entry.latest_hash_comparable!="boolean"||!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&entry.version_skew!==!0||entry.chain_ok&&entry.version_skew!==!0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&!entry.latest_hash_comparable)?null:parsed}catch{return null}}function createDriftScanAccumulator(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function buildDriftScanResult(accumulator){const driftedItems=[...new Set([...accumulator.missingStreams,...accumulator.unreadableStreams,...accumulator.hashMismatches,...accumulator.chainMismatches,...accumulator.versionSkews,...accumulator.workspaceStateMismatches.length>0||accumulator.workspaceStateMissing.length>0||accumulator.workspaceStateUnreadable.length>0?[WORKSPACE_HISTORY_ID]:[]])].sort((a,b)=>a.localeCompare(b));return{...accumulator,driftedItems}}async function scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator){const historyPath=getWorkspaceHistoryPath(pmRoot);let stat;try{stat=await fs.stat(historyPath)}catch(error){return isFileMissingError(error)||accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID),!1}const missingCount=accumulator.missingStreams.length,resolved=await resolveStreamVerification({itemId:WORKSPACE_HISTORY_ID,historyPath,stat,cached:previousEntries[WORKSPACE_HISTORY_ID],verifyCacheHitByContent,accumulator});return resolved.verification?(resolved.verification.versionSkew&&accumulator.versionSkews.push(WORKSPACE_HISTORY_ID),resolved.verification.chainOk||accumulator.chainMismatches.push(WORKSPACE_HISTORY_ID),nextEntries[WORKSPACE_HISTORY_ID]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm},resolved.cacheDirty):(accumulator.missingStreams.splice(missingCount),resolved.cacheDirty)}function hasUnsupportedHistoryCapability(entry){return!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||entry.item_hash_version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)||hasNewerRecordSealFormat(entry)}async function verifyHistoryStream(historyPath){const raw=await fs.readFile(historyPath,"utf8"),contentHash=createHash("sha256").update(raw).digest("hex");if(raw.trim().length===0)return null;const entries=[];let latestAfterHash=null;for(const line of raw.split(/\r?\n/)){const trimmed=line.trim();if(trimmed.length===0)continue;const parsed=JSON.parse(trimmed);if(typeof parsed.after_hash!="string"||parsed.after_hash.trim().length===0)throw new Error("missing after_hash");entries.push(parsed),latestAfterHash=parsed.after_hash}if(!latestAfterHash)return null;const verification=verifyHistoryChainWithVersion(entries),versionSkew=entries.some(hasUnsupportedHistoryCapability),latestEntry=entries[entries.length-1],algorithmSupported=READABLE_HISTORY_HASH_ALGORITHMS.has(latestEntry.hash_algorithm),latestExplicitVersion=latestEntry.item_hash_version,latestExplicitVersionSupported=latestExplicitVersion!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(latestExplicitVersion),latestHashVersion=latestExplicitVersionSupported?latestExplicitVersion:verification.item_hash_version;return{latestAfterHash,hashAlgorithm:algorithmSupported?resolveHistoryHashAlgorithm(latestEntry.hash_algorithm):void 0,identityDiscontinuities:findHistoryIdentityDiscontinuities(entries),chainOk:verification.ok,versionSkew,latestHashComparable:algorithmSupported&&latestHashVersion!==void 0&&(!versionSkew||latestExplicitVersionSupported||latestExplicitVersion===void 0),contentHash,itemHashVersion:latestHashVersion??CURRENT_HISTORY_ITEM_HASH_VERSION}}function cacheMetadataMatches(cached,stat){return cached!==void 0&&cached.mtime_ms===stat.mtimeMs&&cached.ctime_ms===stat.ctimeMs&&cached.size===stat.size}async function loadFreshStreamVerification(itemId,historyPath,accumulator){try{return await verifyHistoryStream(historyPath)||(accumulator.missingStreams.push(itemId),null)}catch{return accumulator.unreadableStreams.push(itemId),null}}function matchesCachedVerification(verification,cached){return verification!==null&&verification.contentHash===cached.content_hash&&verification.latestAfterHash===cached.latest_after_hash&&verification.chainOk===cached.chain_ok&&verification.versionSkew===(cached.version_skew===!0)&&verification.latestHashComparable===cached.latest_hash_comparable&&verification.itemHashVersion===cached.item_hash_version&&verification.hashAlgorithm===cached.hash_algorithm}async function resolveStreamVerification(params){const cachedContentHash=typeof params.cached?.content_hash=="string"&¶ms.cached.content_hash.length>0?params.cached.content_hash:void 0;if(!(cacheMetadataMatches(params.cached,params.stat)&&cachedContentHash!==void 0)||!params.cached||!params.cached.chain_ok)return{verification:await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator),cacheDirty:!0};if(params.verifyCacheHitByContent){const verification=await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator);return{verification,cacheDirty:!matchesCachedVerification(verification,params.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:params.cached.latest_after_hash,chainOk:params.cached.chain_ok,versionSkew:params.cached.version_skew===!0,latestHashComparable:params.cached.latest_hash_comparable&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(params.cached.item_hash_version),contentHash:cachedContentHash,itemHashVersion:params.cached.item_hash_version,hashAlgorithm:params.cached.hash_algorithm},cacheDirty:!1}}async function scanItemHistory(pmRoot,item,cache,accumulator){let historyPath,stat;try{historyPath=getHistoryPath(pmRoot,item.id),stat=await fs.stat(historyPath)}catch(error){return(isFileMissingError(error)?accumulator.missingStreams:accumulator.unreadableStreams).push(item.id),!1}const resolved=await resolveStreamVerification({itemId:item.id,historyPath,stat,cached:cache.previousEntries[item.id],verifyCacheHitByContent:cache.verifyCacheHitByContent,accumulator});if(!resolved.verification)return resolved.cacheDirty;resolved.verification.identityDiscontinuities.length>0&&(accumulator.identityDiscontinuities??=[]).push(...resolved.verification.identityDiscontinuities.map(finding=>({...finding,item_id:item.id}))),resolved.verification.versionSkew&&accumulator.versionSkews.push(item.id),resolved.verification.chainOk||accumulator.chainMismatches.push(item.id),cache.nextEntries[item.id]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm};const{body,...itemMetadata}=item;return resolved.verification.latestHashComparable&&(hashDocumentVerificationCandidates({metadata:itemMetadata,body},resolved.verification.itemHashVersion,resolved.verification.hashAlgorithm).includes(resolved.verification.latestAfterHash)||accumulator.hashMismatches.push(item.id)),resolved.cacheDirty}async function scanWorkspaceStateAgreement(pmRoot,accumulator){if(!(accumulator.unreadableStreams.includes(WORKSPACE_HISTORY_ID)||accumulator.chainMismatches.includes(WORKSPACE_HISTORY_ID)||accumulator.versionSkews.includes(WORKSPACE_HISTORY_ID)))try{const agreement=await inspectWorkspaceHistoryState(pmRoot);accumulator.workspaceStateMismatches.push(...agreement.mismatched_documents),accumulator.workspaceStateMissing.push(...agreement.missing_documents),accumulator.workspaceStateUnreadable.push(...agreement.unreadable_documents)}catch{accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID)}}async function scanItemHistoryDrift(pmRoot,item){const accumulator=createDriftScanAccumulator();return await scanItemHistory(pmRoot,item,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},accumulator),buildDriftScanResult(accumulator)}async function scanHistoryDrift(pmRoot,items,options={}){const accumulator=createDriftScanAccumulator(),previousEntries=(await loadDriftCache(pmRoot))?.entries??{},nextEntries={};let cacheDirty=!1;const verifyCacheHitByContent=options.cacheHitVerification!=="metadata",cacheState={previousEntries,nextEntries,verifyCacheHitByContent};for(const item of items)await scanItemHistory(pmRoot,item,cacheState,accumulator)&&(cacheDirty=!0);const workspaceCacheDirty=await scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator);if(cacheDirty||=workspaceCacheDirty,await scanWorkspaceStateAgreement(pmRoot,accumulator),cacheDirty||Object.keys(previousEntries).length!==Object.keys(nextEntries).length){const cachePath=getDriftCachePath(pmRoot);try{await fs.mkdir(path.dirname(cachePath),{recursive:!0}),await writeFileAtomic(cachePath,JSON.stringify({version:DRIFT_CACHE_VERSION,history_item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,entries:nextEntries}))}catch{}}return buildDriftScanResult(accumulator)}export{scanHistoryDrift,scanItemHistoryDrift};
|
|
2
2
|
//# sourceMappingURL=drift-scan.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="be6f35e2-0762-5188-b373-bdc7d7302d1c")}catch{}})();import fs from"node:fs/promises";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{locateItem,readLocatedItem}from"../store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,hasActiveItemRevisionScope}from"../store/item-mutation-precondition.js";import{resolveGovernanceKnobs}from"../store/settings.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{redactOptionalIdentityCredentials}from"../shared/url-credentials.js";function checkHistoryRewriteOwnership(params){if(!params.itemDocument||params.force)return[];const stored=params.itemDocument.metadata?.assignee?.trim();if(!stored||stored===params.author)return[];const assigned=redactOptionalIdentityCredentials(stored),governance=resolveGovernanceKnobs(params.settings);if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${params.subjectId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return governance.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.subjectId}:${assigned}`]:[]}async function assertDeclaredRevisionOnDrift(params){if(!hasActiveItemRevisionScope(params.pmRoot))return;const located=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),document=located===null?EMPTY_CANONICAL_DOCUMENT:(await readLocatedItem(located,{schema:params.settings.schema}).catch(()=>null))?.document;document!==void 0&&assertItemMutationPreconditions(params.pmRoot,document,params.subject.id)}async function verifyHistoryRewriteNoDrift(params){const historyRawUnderLock=await readFileIfExists(params.subject.historyPath);if(historyRawUnderLock!==params.historyRawBeforeLock)throw await assertDeclaredRevisionOnDrift(params),new PmCliError(`History for ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);const locatedUnderLock=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),loadedItemUnderLock=locatedUnderLock?params.readItem?await params.readItem(locatedUnderLock):await readLocatedItem(locatedUnderLock,{schema:params.settings.schema}):null;if((loadedItemUnderLock?.raw??null)!==(params.currentItemRawBeforeLock??null))throw await assertDeclaredRevisionOnDrift(params),new PmCliError(`Item ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);return{historyRawUnderLock,locatedUnderLock,loadedItemUnderLock}}async function writeHistoryRawWithRollback(params){const writeHistoryRaw=params.writeHistoryRaw??writeFileAtomic;try{await writeHistoryRaw(params.historyPath,params.nextHistoryRaw),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(error){try{params.historyRawUnderLock===null?await fs.rm(params.historyPath,{force:!0}):await writeHistoryRaw(params.historyPath,params.historyRawUnderLock),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(rollbackError){throw new AggregateError([error,rollbackError],`History rewrite failed and rollback also failed: ${String(error)}`)}throw error}}async function executeHistoryRewrite(params){const warnings=[...checkHistoryRewriteOwnership({itemDocument:params.itemDocument,subjectId:params.subject.id,author:params.author,force:params.force,settings:params.settings})],releaseLock=await acquireLock(params.pmRoot,params.subject.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:params.operation}),tombstone=EMPTY_CANONICAL_DOCUMENT;if(assertItemMutationPreconditions(params.pmRoot,verified.loadedItemUnderLock?.document??tombstone,params.subject.id),await params.applyRewrite(verified),hasActiveItemRevisionScope(params.pmRoot)){const relocated=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),rewritten=relocated===null?tombstone:(await readLocatedItem(relocated,{schema:params.settings.schema})).document;advanceItemMutationPreconditions(params.pmRoot,rewritten,params.subject.id)}return params.applyPostRewrite&&warnings.push(...await params.applyPostRewrite(verified)),warnings}finally{await releaseLock()}}export{checkHistoryRewriteOwnership,executeHistoryRewrite,verifyHistoryRewriteNoDrift,writeHistoryRawWithRollback};
|
|
2
2
|
//# sourceMappingURL=history-rewrite.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2e67dcb3-0d34-5884-8b79-5e98458f8c57")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{hasActiveOnWriteHooks,runActiveOnWriteHooks}from"../extensions/index.js";import{ensureDir,pathExists}from"../fs/fs-utils.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{getHistoryPath}from"../store/paths.js";const EXISTENCE_PROBE_CONCURRENCY=64;function toSortedUniqueItemIds(itemIds){return[...new Set(itemIds.filter(value=>value.trim().length>0))].sort((left,right)=>left.localeCompare(right))}function strictMissingStreamError(itemId,commandLabel){return new PmCliError(`Missing history stream for ${itemId}. ${commandLabel} requires history streams when settings.history.missing_stream is strict_error.`,EXIT_CODE.NOT_FOUND)}async function createStream(historyPath,commandLabel){return await ensureDir(path.dirname(historyPath)),await(await fs.open(historyPath,"a")).close(),runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${commandLabel}:history:auto_create`})}async function probeMissingStreams(pmRoot,ids,stopAtFirstMissing){const missing=[];for(let start=0;start<ids.length;start+=EXISTENCE_PROBE_CONCURRENCY){const chunk=ids.slice(start,start+EXISTENCE_PROBE_CONCURRENCY),present=await Promise.all(chunk.map(itemId=>{let historyPath;try{historyPath=getHistoryPath(pmRoot,itemId)}catch{return!1}return pathExists(historyPath)}));if(chunk.forEach((itemId,index)=>{present[index]||missing.push(itemId)}),stopAtFirstMissing&&missing.length>0)break}return missing}async function enforceHistoryStreamPolicyForItem(params){return enforceHistoryStreamPolicyForItems({pmRoot:params.pmRoot,settings:params.settings,itemIds:[params.itemId],commandLabel:params.commandLabel})}async function enforceHistoryStreamPolicyForItems(params){const ids=toSortedUniqueItemIds(params.itemIds),autoCreated=[],warnings=[],sequential=hasActiveOnWriteHooks(),strict=params.settings.history.missing_stream==="strict_error",candidates=sequential?ids:await probeMissingStreams(params.pmRoot,ids,strict);for(const itemId of candidates.length===0?[]:ids){const historyPath=getHistoryPath(params.pmRoot,itemId);if(!await pathExists(historyPath)){if(strict)throw strictMissingStreamError(itemId,params.commandLabel);warnings.push(...await createStream(historyPath,params.commandLabel)),warnings.push(`history_stream_auto_created:${itemId}`),autoCreated.push(itemId)}}return{auto_created_ids:autoCreated,warnings}}export{enforceHistoryStreamPolicyForItem,enforceHistoryStreamPolicyForItems};
|
|
2
2
|
//# sourceMappingURL=history-stream-policy.js.map
|
|
@@ -19,10 +19,22 @@ export declare function hashHistoryPatch(patch:readonly HistoryPatchOp[]):string
|
|
|
19
19
|
export declare function hashHistoryStream(entries:readonly HistoryEntry[]):string;
|
|
20
20
|
/** Attach the current immutable-record integrity envelope to one history event. */
|
|
21
21
|
export declare function sealHistoryRecord(entry:HistoryEntry):HistoryEntry;
|
|
22
|
+
/**
|
|
23
|
+
* Whether a record carries a complete seal in a numeric record format newer
|
|
24
|
+
* than this runtime reads. A malformed or incomplete seal is damage, not a
|
|
25
|
+
* newer format, so it never qualifies (pm-3os5p6).
|
|
26
|
+
*/
|
|
27
|
+
export declare function hasNewerRecordSealFormat(entry:HistoryEntry):boolean;
|
|
22
28
|
/** Verify record-level attribution coverage while accepting explicit legacy item-state-only entries. */
|
|
23
29
|
export declare function verifyHistoryRecordHash(entry:HistoryEntry):{ok:true;coverage:"record_and_item_state"|"item_state_only";}|{ok:false;error:"incomplete_record_hash_envelope"|"record_hash_mismatch"|"unsupported_record_hash_version"|"unsupported_history_hash_algorithm";};
|
|
24
30
|
/** Reseal a maintenance rewrite and retain the anchors and patch digest it replaced. */
|
|
25
31
|
export declare function resealHistoryRewrite(original:HistoryEntry,rewritten:HistoryEntry,options?:Readonly<{retainOriginalPatch?:boolean;retainPriorRecord?:boolean;retainPriorRecordHash?:boolean;}>):HistoryEntry;
|
|
32
|
+
/**
|
|
33
|
+
* Whether an entry carries every field replay and chain verification read:
|
|
34
|
+
* string ts, author, op and anchors, and a well-formed patch. Bridged segments
|
|
35
|
+
* check recorded links instead of replayed states, so they require this.
|
|
36
|
+
*/
|
|
37
|
+
export declare function isCompleteHistoryRecord(entry:HistoryEntry):boolean;
|
|
26
38
|
/** Verify that retained rewrite evidence reconstructs every available prior record envelope. */
|
|
27
39
|
export declare function verifyHistoryRewriteEvidence(entry:HistoryEntry):{ok:true;coverage:"complete"|"digest_only"|"legacy_anchor_only"|"none";}|{ok:false;error:"rewrite_evidence_invalid"|"rewrite_evidence_patch_hash_mismatch"|"rewrite_evidence_record_hash_mismatch";};declare function decodeJsonPointer(path:string):string[];declare function isDefinedPointerPath(document:unknown,path:string):boolean;
|
|
28
40
|
/** Implements hash document for the public runtime surface of this module. */
|