@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,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]="4a3c3c82-0398-549c-8910-fdc69d971cb2")}catch{}})();import jsonPatch from"fast-json-patch";import{normalizeHistoryOperationForWrite}from"./operation-contract.js";import{CURRENT_HISTORY_HASH_ALGORITHM,historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{runActiveServiceOverride}from"../extensions/index.js";import{appendLineAtomic}from"../fs/fs-utils.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,sha256Hex,stableStringify}from"../shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../shared/time.js";import{diagnoseAgentIdentity,resolveHistoryAgentIdentity,resolveHistoryAuthorSource}from"../shared/author.js";import{appendHistoryEntryWithEventIndex,removeHistoryEventIndexForHistoryPath}from"./event-index.js";import{classifyHistoryEvent}from"./event-classification.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{PmCliError}from"../shared/errors.js";const EMPTY_LEGACY_HASH_DOCUMENT={front_matter:{},body:""},CURRENT_HISTORY_ITEM_HASH_VERSION=3,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS=[1,2,3],CURRENT_HISTORY_RECORD_HASH_VERSION=1,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS=[1];function hashHistoryRecord(entry){return historyDigest(stableStringify(entry),entry.hash_algorithm)}function hashHistoryPatch(patch){return sha256Hex(stableStringify(patch))}function hashHistoryStream(entries){return sha256Hex(stableStringify(entries))}function sealHistoryRecord(entry){const sealed={...entry,record_hash_version:CURRENT_HISTORY_RECORD_HASH_VERSION},{record_hash:_recordHash,...canonical}=sealed;return{...sealed,record_hash:hashHistoryRecord(canonical)}}function verifyHistoryRecordHash(entry){try{resolveHistoryHashAlgorithm(entry.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(entry.record_hash_version===void 0&&entry.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(entry.record_hash_version===void 0||entry.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!SUPPORTED_HISTORY_RECORD_HASH_VERSIONS.includes(entry.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};const{record_hash:_recordHash,...canonical}=entry;return hashHistoryRecord(canonical)===entry.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function createHistoryRewriteEvidence(original,options){const evidence={before_hash:original.before_hash,after_hash:original.after_hash,patch_hash:hashHistoryPatch(original.patch)};return original.hash_algorithm!==void 0&&(evidence.hash_algorithm=original.hash_algorithm),original.item_hash_version!==void 0&&(evidence.item_hash_version=original.item_hash_version),options.retainOriginalPatch&&(evidence.patch=structuredClone(original.patch)),options.retainPriorRecordHash!==!1&&original.record_hash_version!==void 0&&original.record_hash!==void 0&&(evidence.record_hash_version=original.record_hash_version,evidence.record_hash=original.record_hash,evidence.record=structuredClone(original)),evidence}function resealHistoryRewrite(original,rewritten,options={}){const originalRecordVerification=verifyHistoryRecordHash(original);if(!originalRecordVerification.ok)throw new TypeError(originalRecordVerification.error);const originalPatchHash=hashHistoryPatch(original.patch),retainsRewriteEvidence=options.retainPriorRecord===!0||original.before_hash!==rewritten.before_hash||original.after_hash!==rewritten.after_hash||original.item_hash_version!==rewritten.item_hash_version||original.hash_algorithm!==rewritten.hash_algorithm||originalPatchHash!==hashHistoryPatch(rewritten.patch),sealed=sealHistoryRecord({...rewritten,...retainsRewriteEvidence?{reanchor_evidence:[...rewritten.reanchor_evidence??[],createHistoryRewriteEvidence(original,options)]}:{}}),evidenceVerification=verifyHistoryRewriteEvidence(sealed);if(!evidenceVerification.ok)throw new TypeError(evidenceVerification.error);return sealed}function isHistoryPatch(value){return!Array.isArray(value)||Object.keys(value).length!==value.length?!1:value.every(operation=>!isRecord(operation)||typeof operation.path!="string"?!1:operation.op==="move"||operation.op==="copy"?typeof operation.from=="string":["add","replace","test"].includes(operation.op)?Object.hasOwn(operation,"value"):operation.op==="remove")}function isRetainedHistoryRecordShape(value){return isRecord(value)&&typeof value.ts=="string"&&typeof value.author=="string"&&typeof value.op=="string"&&typeof value.before_hash=="string"&&typeof value.after_hash=="string"&&isHistoryPatch(value.patch)}function hasCompleteRetainedRecordHashEnvelope(evidence){const hasVersion=evidence.record_hash_version!==void 0,hasHash=evidence.record_hash!==void 0;return hasVersion===hasHash}function isHistoryReanchorEvidence(evidence){return!isRecord(evidence)||!hasCompleteRetainedRecordHashEnvelope(evidence)||typeof evidence.before_hash!="string"||typeof evidence.after_hash!="string"||typeof evidence.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(evidence.patch_hash)||evidence.patch!==void 0&&!isHistoryPatch(evidence.patch)||evidence.record_hash_version!==void 0&&typeof evidence.record_hash_version!="number"||evidence.record_hash!==void 0&&(typeof evidence.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(evidence.record_hash))?!1:evidence.record===void 0||isRetainedHistoryRecordShape(evidence.record)}function isHistoryRewriteEvidenceList(evidenceEntries){try{for(const evidence of evidenceEntries){if(!isHistoryReanchorEvidence(evidence))return!1;resolveHistoryHashAlgorithm(evidence.hash_algorithm)}return!0}catch{return!1}}function matchesRetainedHistoryRecord(evidence){const record=evidence.record;return record!==void 0&&record.before_hash===evidence.before_hash&&record.after_hash===evidence.after_hash&&record.item_hash_version===evidence.item_hash_version&&record.hash_algorithm===evidence.hash_algorithm&&record.record_hash_version===evidence.record_hash_version&&record.record_hash===evidence.record_hash&&hashHistoryPatch(record.patch)===evidence.patch_hash}function reconstructPriorHistoryRecord(current,evidence,priorEvidence){if(evidence.patch&&hashHistoryPatch(evidence.patch)!==evidence.patch_hash)return{kind:"patch_hash_mismatch"};if(evidence.record)return matchesRetainedHistoryRecord(evidence)?{kind:"record",entry:evidence.record}:{kind:"record_hash_mismatch"};const priorPatch=evidence.patch??current.patch;if(hashHistoryPatch(priorPatch)!==evidence.patch_hash)return{kind:"digest_only"};const priorRecord={...current,before_hash:evidence.before_hash,after_hash:evidence.after_hash,patch:priorPatch,hash_algorithm:evidence.hash_algorithm,...evidence.item_hash_version===void 0?{}:{item_hash_version:evidence.item_hash_version},...evidence.record_hash_version===void 0?{}:{record_hash_version:evidence.record_hash_version},...evidence.record_hash===void 0?{}:{record_hash:evidence.record_hash},...priorEvidence.length===0?{}:{reanchor_evidence:priorEvidence}};return evidence.hash_algorithm===void 0&&delete priorRecord.hash_algorithm,priorEvidence.length===0&&delete priorRecord.reanchor_evidence,evidence.item_hash_version===void 0&&delete priorRecord.item_hash_version,evidence.record_hash_version===void 0||evidence.record_hash===void 0?{kind:"legacy",entry:priorRecord}:{kind:"record",entry:priorRecord}}function verifyHistoryRewriteEvidence(entry){const evidenceEntries=entry.reanchor_evidence;if(evidenceEntries===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(evidenceEntries)||!isHistoryRewriteEvidenceList(evidenceEntries))return{ok:!1,error:"rewrite_evidence_invalid"};if(evidenceEntries.length===0)return{ok:!0,coverage:"none"};let reconstructed=entry;for(let index=evidenceEntries.length-1;index>=0;index-=1){const evidence=evidenceEntries[index],prior=reconstructPriorHistoryRecord(reconstructed,evidence,evidenceEntries.slice(0,index));if(prior.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(prior.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(prior.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(prior.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!verifyHistoryRecordHash(prior.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};reconstructed=prior.entry}return{ok:!0,coverage:"complete"}}function compareOptionalStrings(left,right){return(left??"").localeCompare(right??"")}function compareOptionalNumbers(left,right){return(left??0)-(right??0)}function compareJsonValues(left,right,fallback){return JSON.stringify(left??fallback).localeCompare(JSON.stringify(right??fallback))}function compareLegacyLinkedTests(left,right){return[left.scope.localeCompare(right.scope),compareOptionalStrings(left.path,right.path),compareOptionalStrings(left.command,right.command),compareOptionalNumbers(left.timeout_seconds,right.timeout_seconds),compareOptionalStrings(left.pm_context_mode,right.pm_context_mode),+!!left.shared_host_safe-+!!right.shared_host_safe,compareJsonValues(left.env_clear,right.env_clear,[]),compareJsonValues(left.env_set,right.env_set,{}),compareJsonValues(left.assert_stdout_contains,right.assert_stdout_contains,[]),compareJsonValues(left.assert_stdout_regex,right.assert_stdout_regex,[]),compareJsonValues(left.assert_stderr_contains,right.assert_stderr_contains,[]),compareJsonValues(left.assert_stderr_regex,right.assert_stderr_regex,[]),compareOptionalNumbers(left.assert_stdout_min_lines,right.assert_stdout_min_lines),compareJsonValues(left.assert_json_field_equals,right.assert_json_field_equals,{}),compareJsonValues(left.assert_json_field_gte,right.assert_json_field_gte,{}),compareOptionalStrings(left.note,right.note)].find(comparison=>comparison!==0)??0}function decodeJsonPointer(path2){return!path2||path2==="/"?[]:path2.startsWith("/")?path2.slice(1).split("/").map(segment=>segment.replaceAll("~1","/").replaceAll("~0","~")):[]}function isDefinedPointerPath(document,path2){const segments=decodeJsonPointer(path2);if(segments.length===0)return!0;let cursor=document;for(const segment of segments){const arrayIndex=/^(0|[1-9]\d*)$/.test(segment)?Number(segment):-1,next=Array.isArray(cursor)?arrayIndex>=0&&arrayIndex<cursor.length?cursor[arrayIndex]:void 0:isRecord(cursor)&&Object.prototype.hasOwnProperty.call(cursor,segment)?cursor[segment]:void 0;if(next===void 0)return!1;cursor=next}return!0}function normalizeHistoryPatchOps(beforeDocument,patch){const normalized=[];let replayCursor=structuredClone(beforeDocument);for(const operation of patch){const normalizedOperation=operation.op==="replace"&&!isDefinedPointerPath(replayCursor,operation.path)?{...operation,op:"add"}:operation;normalized.push(normalizedOperation),replayCursor=jsonPatch.applyPatch(replayCursor,[normalizedOperation],!0,!0).newDocument}return normalized}function canonicalHashDocument(document,version,legacyV2Fields=!1){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{front_matter:{},body:document.body??""};const canonical=canonicalDocument(document),epochMetadata=version===1||version===2&&legacyV2Fields?{...canonical.metadata,...canonical.metadata.dependencies===void 0?{}:{dependencies:canonical.metadata.dependencies.map(dependency=>({...dependency,id:dependency.id.toLowerCase()}))},...canonical.metadata.tests===void 0?{}:{tests:canonical.metadata.tests.map(({workspace_context_mode:_workspaceContextMode,provenance:_provenance,provenance_invalid:_provenanceInvalid,...test})=>test)},...canonical.metadata.test_runs===void 0?{}:{test_runs:canonical.metadata.test_runs.map(({executions:_executions,...testRun})=>testRun)}}:canonical.metadata,metadata=version===1&&epochMetadata.tests?{...epochMetadata,tests:[...epochMetadata.tests].sort(compareLegacyLinkedTests)}:epochMetadata;return{front_matter:orderObject(toItemRecord(metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function canonicalPatchDocument(document){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{metadata:{},body:document.body??""};const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function hashDocument(document){return hashDocumentForVersion(document,CURRENT_HISTORY_ITEM_HASH_VERSION)}function hashDocumentForVersion(document,version,algorithm){if(!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(supportedVersion=>supportedVersion===version))throw new TypeError(`unsupported_item_hash_version:${String(version)}`);return historyDigest(stableStringify(canonicalHashDocument(document,version)),algorithm)}function hashDocumentVerificationCandidates(document,version,algorithm){const canonicalHash=hashDocumentForVersion(document,version,algorithm);return version===2?[canonicalHash,historyDigest(stableStringify(canonicalHashDocument(document,version,!0)),algorithm)]:[canonicalHash]}function hashEmptyDocument(){return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT))}function createHistoryEntry(params){const operation=normalizeHistoryOperationForWrite(params.op),beforeHashCanonical=canonicalHashDocument(params.before,CURRENT_HISTORY_ITEM_HASH_VERSION),afterHashCanonical=canonicalHashDocument(params.after,CURRENT_HISTORY_ITEM_HASH_VERSION),beforePatchCanonical=canonicalPatchDocument(params.before),afterPatchCanonical=canonicalPatchDocument(params.after),rawPatch=jsonPatch.compare(beforePatchCanonical,afterPatchCanonical),patch=normalizeHistoryPatchOps(beforePatchCanonical,rawPatch),agentIdentity=resolveHistoryAgentIdentity(params.author),provenanceOutcomes=agentIdentity.harness?Object.fromEntries(Object.entries(diagnoseAgentIdentity().provenance_outcomes).filter(([dimension,outcome])=>outcome.resolver!==void 0&&(outcome.status!=="resolved"||agentIdentity.provenance?.[dimension]?.source==="probe"))):void 0,context=provenanceOutcomes===void 0||Object.keys(provenanceOutcomes).length===0?params.context:{...params.context,agent_provenance_outcomes:provenanceOutcomes},algorithm=params.hashAlgorithm??CURRENT_HISTORY_HASH_ALGORITHM,entry={hash_algorithm:algorithm,ts:params.nowIso,author:params.author,author_source:params.authorSource??resolveHistoryAuthorSource(params.author),...agentIdentity.harness?{agent_harness:agentIdentity.harness}:{},...agentIdentity.model?{agent_model:agentIdentity.model}:{},...agentIdentity.model_source?{agent_model_source:agentIdentity.model_source}:{},...agentIdentity.instance?{agent_instance:agentIdentity.instance}:{},...agentIdentity.provenance?{agent_provenance:agentIdentity.provenance}:{},...agentIdentity.episode?{agent_episode:agentIdentity.episode}:{},op:operation,patch,before_hash:historyDigest(stableStringify(beforeHashCanonical),algorithm),after_hash:historyDigest(stableStringify(afterHashCanonical),algorithm),item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,message:params.message===void 0?void 0:params.message,...context===void 0?{}:{context}};return sealHistoryRecord({...entry,event_class:classifyHistoryEvent(entry)})}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function invalidHistoryTimestamp(message){return new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function fallbackHistoryTimestamp(entry){const ts=entry.ts.trim();if(ts.length===0)return nowIso();if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(ts!==entry.ts)throw invalidHistoryTimestamp("History timestamp must not contain surrounding whitespace");return entry.ts}function withHistoryTimestamp(value,fallbackTs){const ts=value.ts;if(typeof ts=="string"&&ts.trim().length>0){if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return value}return{...value,ts:fallbackTs}}function serializeHistoryLine(value,fallbackEntry){const fallbackTs=fallbackHistoryTimestamp(fallbackEntry);if(typeof value=="string"){let parsed;try{parsed=JSON.parse(value)}catch{return value}return isRecord(parsed)?JSON.stringify(withHistoryTimestamp(parsed,fallbackTs)):value}return isRecord(value)?JSON.stringify(withHistoryTimestamp(value,fallbackTs)):JSON.stringify(value)}async function applyHistoryAppendOverride(historyPath,entry,result){if(result===!1)return!0;if(typeof result=="string"){const line2=serializeHistoryLine(result,entry);return await appendHistoryLineWithIdentityReservation(historyPath,line2),await invalidateHistoryDriftCacheForPath(historyPath),await removeHistoryEventIndexForHistoryPath(historyPath),!0}if(typeof result!="object"||result===null)return!1;const record=result;if(record.skip===!0)return!0;const nextHistoryPath=typeof record.history_path=="string"?record.history_path:historyPath,line=serializeHistoryLine(typeof record.line=="string"?record.line:record.entry??entry,entry);return await appendHistoryLineWithIdentityReservation(nextHistoryPath,line),await invalidateHistoryDriftCacheForPath(nextHistoryPath),await removeHistoryEventIndexForHistoryPath(nextHistoryPath),!0}async function appendHistoryLineWithIdentityReservation(historyPath,line){let record;try{record=JSON.parse(line)}catch{record=null}if(!isRecord(record)||record.op!=="create"){await appendLineAtomic(historyPath,line);return}await fs.mkdir(path.dirname(historyPath),{recursive:!0});try{await fs.writeFile(historyPath,`${line}
|
|
2
|
-
`,{encoding:"utf8",flag:"wx"})}catch(error){throw error.code!=="EEXIST"?error:new PmCliError("This item identity is reserved by an existing history stream.",EXIT_CODE.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function appendHistoryEntry(historyPath,entry){const override=await runActiveServiceOverride("history_append",{history_path:historyPath,entry});if(override.handled&&await applyHistoryAppendOverride(historyPath,entry,override.result))return;const timestampedEntry=entry.ts.trim().length>0?entry:{...entry,ts:fallbackHistoryTimestamp(entry)},normalizedEntry=sealHistoryRecord({...timestampedEntry,hash_algorithm:resolveHistoryHashAlgorithm(timestampedEntry.hash_algorithm),event_class:classifyHistoryEvent(timestampedEntry)});await appendHistoryEntryWithEventIndex(historyPath,normalizedEntry,async()=>{await appendHistoryLineWithIdentityReservation(historyPath,serializeHistoryLine(normalizedEntry,normalizedEntry))}),await invalidateHistoryDriftCacheForPath(historyPath)}const _testOnly={decodeJsonPointer,isDefinedPointerPath};export{CURRENT_HISTORY_ITEM_HASH_VERSION,CURRENT_HISTORY_RECORD_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS,_testOnly,appendHistoryEntry,createHistoryEntry,hashDocument,hashDocumentForVersion,hashDocumentVerificationCandidates,hashEmptyDocument,hashHistoryPatch,hashHistoryRecord,hashHistoryStream,resealHistoryRewrite,sealHistoryRecord,verifyHistoryRecordHash,verifyHistoryRewriteEvidence};
|
|
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]="d7f91395-3d21-5046-a8df-e383d66eace9")}catch{}})();import jsonPatch from"fast-json-patch";import{normalizeHistoryOperationForWrite}from"./operation-contract.js";import{CURRENT_HISTORY_HASH_ALGORITHM,historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{runActiveServiceOverride}from"../extensions/index.js";import{appendLineAtomic}from"../fs/fs-utils.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,sha256Hex,stableStringify}from"../shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../shared/time.js";import{diagnoseAgentIdentity,resolveHistoryAgentIdentity,resolveHistoryAuthorSource}from"../shared/author.js";import{appendHistoryEntryWithEventIndex,removeHistoryEventIndexForHistoryPath}from"./event-index.js";import{classifyHistoryEvent}from"./event-classification.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{PmCliError}from"../shared/errors.js";const EMPTY_LEGACY_HASH_DOCUMENT={front_matter:{},body:""},CURRENT_HISTORY_ITEM_HASH_VERSION=3,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS=[1,2,3],CURRENT_HISTORY_RECORD_HASH_VERSION=1,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS=[1];function hashHistoryRecord(entry){return historyDigest(stableStringify(entry),entry.hash_algorithm)}function hashHistoryPatch(patch){return sha256Hex(stableStringify(patch))}function hashHistoryStream(entries){return sha256Hex(stableStringify(entries))}function sealHistoryRecord(entry){const sealed={...entry,record_hash_version:CURRENT_HISTORY_RECORD_HASH_VERSION},{record_hash:_recordHash,...canonical}=sealed;return{...sealed,record_hash:hashHistoryRecord(canonical)}}function hasNewerRecordSealFormat(entry){const version=entry.record_hash_version;return typeof version=="number"&&Number.isInteger(version)&&version>Math.max(...SUPPORTED_HISTORY_RECORD_HASH_VERSIONS)&&typeof entry.record_hash=="string"&&entry.record_hash.length>0}function verifyHistoryRecordHash(entry){try{resolveHistoryHashAlgorithm(entry.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(entry.record_hash_version===void 0&&entry.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(entry.record_hash_version===void 0||entry.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!SUPPORTED_HISTORY_RECORD_HASH_VERSIONS.includes(entry.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};const{record_hash:_recordHash,...canonical}=entry;return hashHistoryRecord(canonical)===entry.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function createHistoryRewriteEvidence(original,options){const evidence={before_hash:original.before_hash,after_hash:original.after_hash,patch_hash:hashHistoryPatch(original.patch)};return original.hash_algorithm!==void 0&&(evidence.hash_algorithm=original.hash_algorithm),original.item_hash_version!==void 0&&(evidence.item_hash_version=original.item_hash_version),options.retainOriginalPatch&&(evidence.patch=structuredClone(original.patch)),options.retainPriorRecordHash!==!1&&original.record_hash_version!==void 0&&original.record_hash!==void 0&&(evidence.record_hash_version=original.record_hash_version,evidence.record_hash=original.record_hash,evidence.record=structuredClone(original)),evidence}function resealHistoryRewrite(original,rewritten,options={}){const originalRecordVerification=verifyHistoryRecordHash(original);if(!originalRecordVerification.ok)throw new TypeError(originalRecordVerification.error);const originalPatchHash=hashHistoryPatch(original.patch),retainsRewriteEvidence=options.retainPriorRecord===!0||original.before_hash!==rewritten.before_hash||original.after_hash!==rewritten.after_hash||original.item_hash_version!==rewritten.item_hash_version||original.hash_algorithm!==rewritten.hash_algorithm||originalPatchHash!==hashHistoryPatch(rewritten.patch),sealed=sealHistoryRecord({...rewritten,...retainsRewriteEvidence?{reanchor_evidence:[...rewritten.reanchor_evidence??[],createHistoryRewriteEvidence(original,options)]}:{}}),evidenceVerification=verifyHistoryRewriteEvidence(sealed);if(!evidenceVerification.ok)throw new TypeError(evidenceVerification.error);return sealed}function isHistoryPatch(value){return!Array.isArray(value)||Object.keys(value).length!==value.length?!1:value.every(operation=>!isRecord(operation)||typeof operation.path!="string"?!1:operation.op==="move"||operation.op==="copy"?typeof operation.from=="string":["add","replace","test"].includes(operation.op)?Object.hasOwn(operation,"value"):operation.op==="remove")}function isRetainedHistoryRecordShape(value){return isRecord(value)&&typeof value.ts=="string"&&typeof value.author=="string"&&typeof value.op=="string"&&typeof value.before_hash=="string"&&typeof value.after_hash=="string"&&isHistoryPatch(value.patch)}function isCompleteHistoryRecord(entry){return isRetainedHistoryRecordShape(entry)}function hasCompleteRetainedRecordHashEnvelope(evidence){const hasVersion=evidence.record_hash_version!==void 0,hasHash=evidence.record_hash!==void 0;return hasVersion===hasHash}function isHistoryReanchorEvidence(evidence){return!isRecord(evidence)||!hasCompleteRetainedRecordHashEnvelope(evidence)||typeof evidence.before_hash!="string"||typeof evidence.after_hash!="string"||typeof evidence.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(evidence.patch_hash)||evidence.patch!==void 0&&!isHistoryPatch(evidence.patch)||evidence.record_hash_version!==void 0&&typeof evidence.record_hash_version!="number"||evidence.record_hash!==void 0&&(typeof evidence.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(evidence.record_hash))?!1:evidence.record===void 0||isRetainedHistoryRecordShape(evidence.record)}function isHistoryRewriteEvidenceList(evidenceEntries){try{for(const evidence of evidenceEntries){if(!isHistoryReanchorEvidence(evidence))return!1;resolveHistoryHashAlgorithm(evidence.hash_algorithm)}return!0}catch{return!1}}function matchesRetainedHistoryRecord(evidence){const record=evidence.record;return record!==void 0&&record.before_hash===evidence.before_hash&&record.after_hash===evidence.after_hash&&record.item_hash_version===evidence.item_hash_version&&record.hash_algorithm===evidence.hash_algorithm&&record.record_hash_version===evidence.record_hash_version&&record.record_hash===evidence.record_hash&&hashHistoryPatch(record.patch)===evidence.patch_hash}function reconstructPriorHistoryRecord(current,evidence,priorEvidence){if(evidence.patch&&hashHistoryPatch(evidence.patch)!==evidence.patch_hash)return{kind:"patch_hash_mismatch"};if(evidence.record)return matchesRetainedHistoryRecord(evidence)?{kind:"record",entry:evidence.record}:{kind:"record_hash_mismatch"};const priorPatch=evidence.patch??current.patch;if(hashHistoryPatch(priorPatch)!==evidence.patch_hash)return{kind:"digest_only"};const priorRecord={...current,before_hash:evidence.before_hash,after_hash:evidence.after_hash,patch:priorPatch,hash_algorithm:evidence.hash_algorithm,...evidence.item_hash_version===void 0?{}:{item_hash_version:evidence.item_hash_version},...evidence.record_hash_version===void 0?{}:{record_hash_version:evidence.record_hash_version},...evidence.record_hash===void 0?{}:{record_hash:evidence.record_hash},...priorEvidence.length===0?{}:{reanchor_evidence:priorEvidence}};return evidence.hash_algorithm===void 0&&delete priorRecord.hash_algorithm,priorEvidence.length===0&&delete priorRecord.reanchor_evidence,evidence.item_hash_version===void 0&&delete priorRecord.item_hash_version,evidence.record_hash_version===void 0||evidence.record_hash===void 0?{kind:"legacy",entry:priorRecord}:{kind:"record",entry:priorRecord}}function verifyHistoryRewriteEvidence(entry){const evidenceEntries=entry.reanchor_evidence;if(evidenceEntries===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(evidenceEntries)||!isHistoryRewriteEvidenceList(evidenceEntries))return{ok:!1,error:"rewrite_evidence_invalid"};if(evidenceEntries.length===0)return{ok:!0,coverage:"none"};let reconstructed=entry;for(let index=evidenceEntries.length-1;index>=0;index-=1){const evidence=evidenceEntries[index],prior=reconstructPriorHistoryRecord(reconstructed,evidence,evidenceEntries.slice(0,index));if(prior.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(prior.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(prior.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(prior.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!verifyHistoryRecordHash(prior.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};reconstructed=prior.entry}return{ok:!0,coverage:"complete"}}function compareOptionalStrings(left,right){return(left??"").localeCompare(right??"")}function compareOptionalNumbers(left,right){return(left??0)-(right??0)}function compareJsonValues(left,right,fallback){return JSON.stringify(left??fallback).localeCompare(JSON.stringify(right??fallback))}function compareLegacyLinkedTests(left,right){return[left.scope.localeCompare(right.scope),compareOptionalStrings(left.path,right.path),compareOptionalStrings(left.command,right.command),compareOptionalNumbers(left.timeout_seconds,right.timeout_seconds),compareOptionalStrings(left.pm_context_mode,right.pm_context_mode),+!!left.shared_host_safe-+!!right.shared_host_safe,compareJsonValues(left.env_clear,right.env_clear,[]),compareJsonValues(left.env_set,right.env_set,{}),compareJsonValues(left.assert_stdout_contains,right.assert_stdout_contains,[]),compareJsonValues(left.assert_stdout_regex,right.assert_stdout_regex,[]),compareJsonValues(left.assert_stderr_contains,right.assert_stderr_contains,[]),compareJsonValues(left.assert_stderr_regex,right.assert_stderr_regex,[]),compareOptionalNumbers(left.assert_stdout_min_lines,right.assert_stdout_min_lines),compareJsonValues(left.assert_json_field_equals,right.assert_json_field_equals,{}),compareJsonValues(left.assert_json_field_gte,right.assert_json_field_gte,{}),compareOptionalStrings(left.note,right.note)].find(comparison=>comparison!==0)??0}function decodeJsonPointer(path2){return!path2||path2==="/"?[]:path2.startsWith("/")?path2.slice(1).split("/").map(segment=>segment.replaceAll("~1","/").replaceAll("~0","~")):[]}function isDefinedPointerPath(document,path2){const segments=decodeJsonPointer(path2);if(segments.length===0)return!0;let cursor=document;for(const segment of segments){const arrayIndex=/^(0|[1-9]\d*)$/.test(segment)?Number(segment):-1,next=Array.isArray(cursor)?arrayIndex>=0&&arrayIndex<cursor.length?cursor[arrayIndex]:void 0:isRecord(cursor)&&Object.prototype.hasOwnProperty.call(cursor,segment)?cursor[segment]:void 0;if(next===void 0)return!1;cursor=next}return!0}function normalizeHistoryPatchOps(beforeDocument,patch){const normalized=[];let replayCursor=structuredClone(beforeDocument);for(const operation of patch){const normalizedOperation=operation.op==="replace"&&!isDefinedPointerPath(replayCursor,operation.path)?{...operation,op:"add"}:operation;normalized.push(normalizedOperation),replayCursor=jsonPatch.applyPatch(replayCursor,[normalizedOperation],!0,!0).newDocument}return normalized}function canonicalHashDocument(document,version,legacyV2Fields=!1){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{front_matter:{},body:document.body??""};const canonical=canonicalDocument(document),epochMetadata=version===1||version===2&&legacyV2Fields?{...canonical.metadata,...canonical.metadata.dependencies===void 0?{}:{dependencies:canonical.metadata.dependencies.map(dependency=>({...dependency,id:dependency.id.toLowerCase()}))},...canonical.metadata.tests===void 0?{}:{tests:canonical.metadata.tests.map(({workspace_context_mode:_workspaceContextMode,provenance:_provenance,provenance_invalid:_provenanceInvalid,...test})=>test)},...canonical.metadata.test_runs===void 0?{}:{test_runs:canonical.metadata.test_runs.map(({executions:_executions,...testRun})=>testRun)}}:canonical.metadata,metadata=version===1&&epochMetadata.tests?{...epochMetadata,tests:[...epochMetadata.tests].sort(compareLegacyLinkedTests)}:epochMetadata;return{front_matter:orderObject(toItemRecord(metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function canonicalPatchDocument(document){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{metadata:{},body:document.body??""};const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function hashDocument(document){return hashDocumentForVersion(document,CURRENT_HISTORY_ITEM_HASH_VERSION)}function hashDocumentForVersion(document,version,algorithm){if(!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(supportedVersion=>supportedVersion===version))throw new TypeError(`unsupported_item_hash_version:${String(version)}`);return historyDigest(stableStringify(canonicalHashDocument(document,version)),algorithm)}function hashDocumentVerificationCandidates(document,version,algorithm){const canonicalHash=hashDocumentForVersion(document,version,algorithm);return version===2?[canonicalHash,historyDigest(stableStringify(canonicalHashDocument(document,version,!0)),algorithm)]:[canonicalHash]}function hashEmptyDocument(){return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT))}function createHistoryEntry(params){const operation=normalizeHistoryOperationForWrite(params.op),beforeHashCanonical=canonicalHashDocument(params.before,CURRENT_HISTORY_ITEM_HASH_VERSION),afterHashCanonical=canonicalHashDocument(params.after,CURRENT_HISTORY_ITEM_HASH_VERSION),beforePatchCanonical=canonicalPatchDocument(params.before),afterPatchCanonical=canonicalPatchDocument(params.after),rawPatch=jsonPatch.compare(beforePatchCanonical,afterPatchCanonical),patch=normalizeHistoryPatchOps(beforePatchCanonical,rawPatch),agentIdentity=resolveHistoryAgentIdentity(params.author),provenanceOutcomes=agentIdentity.harness?Object.fromEntries(Object.entries(diagnoseAgentIdentity().provenance_outcomes).filter(([dimension,outcome])=>outcome.resolver!==void 0&&(outcome.status!=="resolved"||agentIdentity.provenance?.[dimension]?.source==="probe"))):void 0,context=provenanceOutcomes===void 0||Object.keys(provenanceOutcomes).length===0?params.context:{...params.context,agent_provenance_outcomes:provenanceOutcomes},algorithm=params.hashAlgorithm??CURRENT_HISTORY_HASH_ALGORITHM,entry={hash_algorithm:algorithm,ts:params.nowIso,author:params.author,author_source:params.authorSource??resolveHistoryAuthorSource(params.author),...agentIdentity.harness?{agent_harness:agentIdentity.harness}:{},...agentIdentity.model?{agent_model:agentIdentity.model}:{},...agentIdentity.model_source?{agent_model_source:agentIdentity.model_source}:{},...agentIdentity.instance?{agent_instance:agentIdentity.instance}:{},...agentIdentity.provenance?{agent_provenance:agentIdentity.provenance}:{},...agentIdentity.episode?{agent_episode:agentIdentity.episode}:{},op:operation,patch,before_hash:historyDigest(stableStringify(beforeHashCanonical),algorithm),after_hash:historyDigest(stableStringify(afterHashCanonical),algorithm),item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,message:params.message===void 0?void 0:params.message,...context===void 0?{}:{context}};return sealHistoryRecord({...entry,event_class:classifyHistoryEvent(entry)})}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function invalidHistoryTimestamp(message){return new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function fallbackHistoryTimestamp(entry){const ts=entry.ts.trim();if(ts.length===0)return nowIso();if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(ts!==entry.ts)throw invalidHistoryTimestamp("History timestamp must not contain surrounding whitespace");return entry.ts}function withHistoryTimestamp(value,fallbackTs){const ts=value.ts;if(typeof ts=="string"&&ts.trim().length>0){if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return value}return{...value,ts:fallbackTs}}function serializeHistoryLine(value,fallbackEntry){const fallbackTs=fallbackHistoryTimestamp(fallbackEntry);if(typeof value=="string"){let parsed;try{parsed=JSON.parse(value)}catch{return value}return isRecord(parsed)?JSON.stringify(withHistoryTimestamp(parsed,fallbackTs)):value}return isRecord(value)?JSON.stringify(withHistoryTimestamp(value,fallbackTs)):JSON.stringify(value)}async function applyHistoryAppendOverride(historyPath,entry,result){if(result===!1)return!0;if(typeof result=="string"){const line2=serializeHistoryLine(result,entry);return await appendHistoryLineWithIdentityReservation(historyPath,line2),await invalidateHistoryDriftCacheForPath(historyPath),await removeHistoryEventIndexForHistoryPath(historyPath),!0}if(typeof result!="object"||result===null)return!1;const record=result;if(record.skip===!0)return!0;const nextHistoryPath=typeof record.history_path=="string"?record.history_path:historyPath,line=serializeHistoryLine(typeof record.line=="string"?record.line:record.entry??entry,entry);return await appendHistoryLineWithIdentityReservation(nextHistoryPath,line),await invalidateHistoryDriftCacheForPath(nextHistoryPath),await removeHistoryEventIndexForHistoryPath(nextHistoryPath),!0}async function appendHistoryLineWithIdentityReservation(historyPath,line){let record;try{record=JSON.parse(line)}catch{record=null}if(!isRecord(record)||record.op!=="create"){await appendLineAtomic(historyPath,line);return}await fs.mkdir(path.dirname(historyPath),{recursive:!0});try{await fs.writeFile(historyPath,`${line}
|
|
2
|
+
`,{encoding:"utf8",flag:"wx"})}catch(error){throw error.code!=="EEXIST"?error:new PmCliError("This item identity is reserved by an existing history stream.",EXIT_CODE.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function appendHistoryEntry(historyPath,entry){const override=await runActiveServiceOverride("history_append",{history_path:historyPath,entry});if(override.handled&&await applyHistoryAppendOverride(historyPath,entry,override.result))return;const timestampedEntry=entry.ts.trim().length>0?entry:{...entry,ts:fallbackHistoryTimestamp(entry)},normalizedEntry=sealHistoryRecord({...timestampedEntry,hash_algorithm:resolveHistoryHashAlgorithm(timestampedEntry.hash_algorithm),event_class:classifyHistoryEvent(timestampedEntry)});await appendHistoryEntryWithEventIndex(historyPath,normalizedEntry,async()=>{await appendHistoryLineWithIdentityReservation(historyPath,serializeHistoryLine(normalizedEntry,normalizedEntry))}),await invalidateHistoryDriftCacheForPath(historyPath)}const _testOnly={decodeJsonPointer,isDefinedPointerPath};export{CURRENT_HISTORY_ITEM_HASH_VERSION,CURRENT_HISTORY_RECORD_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS,_testOnly,appendHistoryEntry,createHistoryEntry,hasNewerRecordSealFormat,hashDocument,hashDocumentForVersion,hashDocumentVerificationCandidates,hashEmptyDocument,hashHistoryPatch,hashHistoryRecord,hashHistoryStream,isCompleteHistoryRecord,resealHistoryRewrite,sealHistoryRecord,verifyHistoryRecordHash,verifyHistoryRewriteEvidence};
|
|
3
3
|
//# sourceMappingURL=history.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]="cd7d3a47-d37a-55f4-aa60-4fc3ea08d528")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{historyVersionOffset}from"./version-address.js";import{EMPTY_REPLAY_DOCUMENT,verifyHistoryChain,verifyHistoryChainWithVersion,tryApplyReplayPatch}from"./replay.js";function findHistoryIndexAtTimestamp(history,parsedTarget){let historyIndex=-1;return history.forEach((entry,index)=>{const entryTimestamp=Date.parse(entry.ts);if(!Number.isFinite(entryTimestamp))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);entryTimestamp<=parsedTarget&&(historyIndex=index)}),historyIndex}function buildHistoryTargetGuidance(history,offset){const firstTimestamp=history[0]?.ts??null,lastTimestamp=history.at(-1)?.ts??null,guidance={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:firstTimestamp,last_timestamp:lastTimestamp}};return lastTimestamp!==null&&(guidance.examples=[lastTimestamp],offset!==null&&(guidance.examples.unshift(String(offset+1),String(offset+history.length)),guidance.valid_range.first_version=offset+1,guidance.valid_range.last_version=offset+history.length)),{guidance,lastTimestamp}}function extractPatchFailureContext(patch,error){const failure={};if(error instanceof Error&&error.message.trim().length>0&&(failure.reason=error.message.trim()),typeof error!="object"||error===null)return failure;const candidate=error;if(typeof candidate.index=="number"&&Number.isInteger(candidate.index)&&candidate.index>=0&&(failure.patchIndex=candidate.index),typeof candidate.operation=="object"&&candidate.operation!==null){const operation=candidate.operation;Object.assign(failure,Object.fromEntries(["op","path","from"].flatMap(field=>{const value=operation[field];return typeof value=="string"?[[field,value]]:[]})))}if(failure.patchIndex!==void 0){const fallback=patch[failure.patchIndex];fallback&&(failure.op??=fallback.op,failure.path??=fallback.path,failure.from??=fallback.from)}return failure}function resolveHistoryTarget(target,history,options={}){const trimmed=target.trim(),errorSubject=options.errorSubject??"history",errorSubjectTitle=errorSubject==="restore"?"Restore":"History",{guidance,lastTimestamp}=buildHistoryTargetGuidance(history,historyVersionOffset(history,!0));if(!trimmed)throw new PmCliError(`Missing ${errorSubject} target. Use a timestamp or version number.`,EXIT_CODE.USAGE,guidance);if(/^\d+$/.test(trimmed)){const offset=historyVersionOffset(history),version=Number(trimmed);if(version>=1&&version<=offset)throw new PmCliError(`History version ${version} was pruned by compaction.`,EXIT_CODE.USAGE,{...guidance,code:"history_version_pruned"});if(!Number.isSafeInteger(version)||version<1||version>offset+history.length)throw new PmCliError(`${errorSubjectTitle} version must be between ${offset+1} and ${offset+history.length} for this item.`,EXIT_CODE.USAGE,guidance);return{kind:"version",raw:trimmed,historyIndex:version-offset-1}}const parsedTarget=Date.parse(trimmed);if(!Number.isFinite(parsedTarget))throw new PmCliError(`Invalid ${errorSubject} target "${target}". Use a positive version number or ISO timestamp.`,EXIT_CODE.USAGE,guidance);const historyIndex=findHistoryIndexAtTimestamp(history,parsedTarget);if(historyIndex<0||options.allowFutureTimestamp!==!0&&parsedTarget>Date.parse(lastTimestamp))throw new PmCliError(errorSubject==="restore"?`No history entries exist at or before timestamp ${trimmed}.`:`No history entry exists at timestamp ${trimmed}.`,EXIT_CODE.USAGE,guidance);return{kind:"timestamp",raw:trimmed,historyIndex}}function applyHistoryPatch(current,patch,entryNumber,entryOp){const applied=tryApplyReplayPatch(current,patch);if(applied.ok)return applied.document;const failure=extractPatchFailureContext(patch,applied.error),tokens=[`history_op=${entryOp}`,failure.patchIndex===void 0?null:`patch_index=${failure.patchIndex}`,failure.op?`op=${failure.op}`:null,failure.path?`path=${failure.path}`:null,failure.from?`from=${failure.from}`:null].filter(token=>token!==null);throw new PmCliError(`Failed to apply history patch at entry ${entryNumber} (${tokens.join(", ")}). ${failure.reason??String(applied.error)}`,EXIT_CODE.GENERIC_FAILURE)}function unreconstructableHistoryVersion(targetIndex,liveBridge){return new PmCliError(`History entry ${targetIndex+1} lies between an unrecorded change and the record that repaired it, so its historical state cannot be reconstructed.`,EXIT_CODE.USAGE,{code:"history_version_unreconstructable",required:liveBridge?"Choose a version before the bridged break or from its bridge onward.":"Choose a version whose record is not marked replay_inexact.",nextSteps:[liveBridge?"Run pm history <id> --full to find the bridge record and the versions around it.":"Run pm history <id> --full and pick a version whose record has no replay_inexact marker."]})}function replayHistoryToTarget(history,targetIndex){const first=history[0];if(first&&first.op!=="create"&&first.op!=="history_compact_baseline"){const baseline=tryApplyReplayPatch(EMPTY_REPLAY_DOCUMENT,first.patch);if(!baseline.ok||typeof baseline.document.metadata.id!="string")throw new PmCliError("History starts without a reconstructable item baseline.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}if(history[targetIndex]?.replay_inexact===!0)throw unreconstructableHistoryVersion(targetIndex,!1);const selected=history.slice(0,targetIndex+1),verification=verifyHistoryChain([...selected]);let document=structuredClone(EMPTY_REPLAY_DOCUMENT);for(let index=0;index<=targetIndex;index+=1){const entry=history[index];if(!entry)throw new PmCliError(`History target entry ${index+1} does not exist.`,EXIT_CODE.USAGE);document=applyHistoryPatch(document,entry.patch,index+1,entry.op)}if(!verification.ok){const bridged=verifyHistoryChainWithVersion([...history]);throw bridged.ok&&bridged.bridged_segments?.some(segment=>segment.start<=targetIndex&&targetIndex<segment.end)?unreconstructableHistoryVersion(targetIndex,!0):new PmCliError(`History cannot be replayed: ${verification.errors.join(", ")}.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:verification.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]})}return document}function ensureMaterializedHistoryTarget(replayDocument,target){if(Object.keys(replayDocument.metadata).length>0){if(typeof replayDocument.metadata.id!="string"||!Array.isArray(replayDocument.metadata.tags))throw new PmCliError("History has no complete item baseline for this target.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return replayDocument}throw new PmCliError(`History target ${target.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,EXIT_CODE.USAGE)}export{applyHistoryPatch,ensureMaterializedHistoryTarget,extractPatchFailureContext,replayHistoryToTarget,resolveHistoryTarget};
|
|
2
2
|
//# sourceMappingURL=projection.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type{HistoryEntry}from "../../types/index.js";
|
|
1
|
+
import type{BigIntStats}from "node:fs";import type{HistoryEntry}from "../../types/index.js";
|
|
2
2
|
/** Exact bytes and decoded entries from one read, suitable for optimistic concurrency checks. */
|
|
3
3
|
export interface HistoryStreamSnapshot{
|
|
4
4
|
/** Null means the stream did not exist; an empty string means it existed without entries. */
|
|
@@ -9,5 +9,24 @@ raw_bytes:Uint8Array|null;
|
|
|
9
9
|
entries:HistoryEntry[];}
|
|
10
10
|
/** Read one history stream once so replay input and the concurrency snapshot cannot disagree. */
|
|
11
11
|
export declare function readHistorySnapshot(historyPath:string,itemId:string):Promise<HistoryStreamSnapshot>;
|
|
12
|
+
/** A snapshot plus the identity of the open file that supplied its bytes. */
|
|
13
|
+
export interface IdentifiedHistoryStreamSnapshot extends HistoryStreamSnapshot{
|
|
14
|
+
/** Stat of the open handle the bytes were read from; null when the stream was absent. */
|
|
15
|
+
source:BigIntStats|null;}
|
|
16
|
+
/**
|
|
17
|
+
* Read one history stream through a single open handle and report that
|
|
18
|
+
* handle's stat, so derived state can be bound to the exact file revision
|
|
19
|
+
* that supplied the bytes, whatever happens to the path meanwhile.
|
|
20
|
+
*/
|
|
21
|
+
export declare function readIdentifiedHistorySnapshot(historyPath:string,itemId:string):Promise<IdentifiedHistoryStreamSnapshot>;
|
|
22
|
+
/**
|
|
23
|
+
* Describe why one decoded JSONL value cannot be a history record, or return
|
|
24
|
+
* null for an object. Readers dereference every line as an object, so a JSON
|
|
25
|
+
* null, boolean, number, string or array refuses here with a typed error
|
|
26
|
+
* instead of crashing a reader; objects keep each reader's legacy tolerance.
|
|
27
|
+
*/
|
|
28
|
+
export declare function describeHistoryRecordDefect(value:unknown):string|null;
|
|
29
|
+
/** Whether one decoded JSON value is a scalar that cannot encode or hide a record. */
|
|
30
|
+
export declare function isNonRecordScalar(value:unknown):boolean;
|
|
12
31
|
/** Read and validate one item's JSONL history stream without mutating it. */
|
|
13
32
|
export declare function readHistoryEntries(historyPath:string,itemId:string):Promise<HistoryEntry[]>;
|
|
@@ -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]="2560e353-1428-540b-bf0b-3c157bdb3b3b")}catch{}})();import fs from"node:fs/promises";import{isFileAbsentError}from"../fs/fs-utils.js";import{runActiveOnReadHooks}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";async function readHistorySnapshot(historyPath,itemId){const rawBytes=await fs.readFile(historyPath).catch(error=>{if(isFileAbsentError(error))return null;throw error});return decodeHistorySnapshot(historyPath,itemId,rawBytes)}async function readIdentifiedHistorySnapshot(historyPath,itemId){const handle=await fs.open(historyPath,"r").catch(error=>{if(isFileAbsentError(error))return null;throw error});if(handle===null)return{...await decodeHistorySnapshot(historyPath,itemId,null),source:null};try{const source=await handle.stat({bigint:!0}),rawBytes=await handle.readFile();return{...await decodeHistorySnapshot(historyPath,itemId,rawBytes),source}}finally{await handle.close()}}async function decodeHistorySnapshot(historyPath,itemId,rawBytes){const raw=rawBytes?.toString("utf8")??null;if(raw===null)return{raw,raw_bytes:rawBytes,entries:[]};if(await runActiveOnReadHooks({path:historyPath,scope:"project"}),raw.trim()==="")return{raw,raw_bytes:rawBytes,entries:[]};const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History for ${itemId} contains merge conflict markers at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${itemId}`,`pm restore ${itemId} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(!line)continue;let parsed;try{parsed=JSON.parse(line)}catch{throw new PmCliError(`History for ${itemId} contains invalid JSON at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}const defect=describeHistoryRecordDefect(parsed);if(defect!==null)throw new PmCliError(`History for ${itemId} holds ${defect} at line ${index+1}, which is not a history record. Remove or restore the line and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_record_invalid",item_id:itemId,reason:defect,details:{line:index+1},required:"Every history line must be one JSON object record.",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run: it removes a line that cannot hold a record (a JSON null, boolean or number) and keeps every record.`,"Otherwise recover the line from version control or a backup."]});entries.push(parsed)}return{raw,raw_bytes:rawBytes,entries}}function describeHistoryRecordDefect(value){return value===null?"a JSON null":Array.isArray(value)?"a JSON array":typeof value=="object"?null:`a JSON ${typeof value}`}function isNonRecordScalar(value){return value===null||typeof value=="boolean"||typeof value=="number"}async function readHistoryEntries(historyPath,itemId){return(await readHistorySnapshot(historyPath,itemId)).entries}export{describeHistoryRecordDefect,isNonRecordScalar,readHistoryEntries,readHistorySnapshot,readIdentifiedHistorySnapshot};
|
|
2
2
|
//# sourceMappingURL=read.js.map
|
|
@@ -38,8 +38,22 @@ export declare function normalizeReplayPatchOps(patch:HistoryPatchOp[]|unknown):
|
|
|
38
38
|
export type ReplayApplyResult={ok:true;document:ReplayDocument;}|{ok:false;error:unknown;};
|
|
39
39
|
/** Strictly apply a history patch (front_matter->metadata normalized) to a replay document. Returns a result envelope rather than throwing so each caller can format its own error contract. */
|
|
40
40
|
export declare function tryApplyReplayPatch(current:ReplayDocument,patch:HistoryPatchOp[]):ReplayApplyResult;
|
|
41
|
+
/**
|
|
42
|
+
* Whether one operation can never change state: a test, a move onto its own
|
|
43
|
+
* path, or a copy onto its own path unless that path may be an array element
|
|
44
|
+
* (copying onto an index inserts a second element there).
|
|
45
|
+
*/
|
|
46
|
+
declare function isEffectFreeOperation(operation:HistoryPatchOp):boolean;
|
|
47
|
+
/** Zero-based inclusive range of entries closed by one verified bridge. */
|
|
48
|
+
export interface HistoryBridgedSegment{
|
|
49
|
+
/** First entry after the first named break. */
|
|
50
|
+
start:number;
|
|
51
|
+
/** The bridge record that closes the segment. */
|
|
52
|
+
end:number;}
|
|
41
53
|
/** Verify a chain and report the explicit or auto-detected item hash epoch. */
|
|
42
|
-
export declare function verifyHistoryChainWithVersion(entries:HistoryEntry[]):{ok:boolean;errors:string[];item_hash_version?:HistoryItemHashVersion;
|
|
54
|
+
export declare function verifyHistoryChainWithVersion(entries:HistoryEntry[]):{ok:boolean;errors:string[];item_hash_version?:HistoryItemHashVersion;
|
|
55
|
+
/** Segments closed by an append-only bridge, in stream order; absent when none. */
|
|
56
|
+
bridged_segments?:HistoryBridgedSegment[];};
|
|
43
57
|
/** Deterministically verify a history chain while preserving the legacy result shape. */
|
|
44
58
|
export declare function verifyHistoryChain(entries:HistoryEntry[]):{ok:boolean;errors:string[];};
|
|
45
59
|
/** Documents the lenient apply result payload exchanged by command, SDK, and package integrations. */
|
|
@@ -50,8 +64,8 @@ document:ReplayDocument;
|
|
|
50
64
|
convertedReplaceToAdd:number;
|
|
51
65
|
/** Value that configures or reports skipped ops for this contract. */
|
|
52
66
|
skippedOps:number;}
|
|
53
|
-
/** Apply a legacy patch op-by-op, recovering from drift that strict replay rejects: a `replace` whose path no longer exists is retried as `add`, and any op that still cannot apply against the current replay state is skipped. The resulting document is what the repaired entry's recomputed patch should target. */
|
|
54
|
-
export declare function lenientApplyReplayPatch(current:ReplayDocument,patch:HistoryPatchOp[]):LenientApplyResult;
|
|
67
|
+
/** Apply a legacy patch op-by-op, recovering from drift that strict replay rejects: a `replace` whose path no longer exists is retried as `add`, and any op that still cannot apply against the current replay state is skipped. A patch may pass through a non-object root and restore the item. One that ends without an item root records a deletion when it belongs to a `delete` entry, which replays as the canonical empty document; any other is replayed again without its root transitions, so the ops that did apply are kept and no empty state is invented. The resulting document is what the repaired entry's recomputed patch should target. */
|
|
68
|
+
export declare function lenientApplyReplayPatch(current:ReplayDocument,patch:HistoryPatchOp[],operation?:string):LenientApplyResult;
|
|
55
69
|
/** Documents the reanchor entry detail payload exchanged by command, SDK, and package integrations. */
|
|
56
70
|
export interface ReanchorEntryDetail{
|
|
57
71
|
/** Value that configures or reports index for this contract. */
|
|
@@ -78,6 +92,8 @@ entriesPatchRepaired:number;
|
|
|
78
92
|
convertedReplaceToAdd:number;
|
|
79
93
|
/** Value that configures or reports skipped ops for this contract. */
|
|
80
94
|
skippedOps:number;
|
|
95
|
+
/** Entries resealed to dissolve a bridge or add a replay_inexact marker, or for any reason when the input failed verification; an epoch label alone on a verified input does not count. */
|
|
96
|
+
entriesResealed:number;
|
|
81
97
|
/** Value that configures or reports details for this contract. */
|
|
82
98
|
details:ReanchorEntryDetail[];
|
|
83
99
|
/** Hash epoch retained while rebuilding the stream. */
|
|
@@ -89,7 +105,9 @@ export interface ReanchorHistoryOptions{
|
|
|
89
105
|
/** Keep one semantic hash candidate for the complete rewritten stream so adjacent stored endpoints are identical. */
|
|
90
106
|
continuousHashSurface?:boolean;
|
|
91
107
|
/** Rebase an entry's patch onto its new replay position, retaining the original patch as immutable rewrite evidence. */
|
|
92
|
-
projectPatch?:(entry:HistoryEntry,current:ReplayDocument)=> HistoryPatchOp[];
|
|
108
|
+
projectPatch?:(entry:HistoryEntry,current:ReplayDocument)=> HistoryPatchOp[];
|
|
109
|
+
/** The caller already marked every record a dissolved bridge covers (a merge union marks each original branch before it interleaves them), so re-anchoring adds no markers of its own. */
|
|
110
|
+
callerMarksBridgeCoverage?:boolean;}
|
|
93
111
|
/**
|
|
94
112
|
* Resolve the hash epoch a repair must retain.
|
|
95
113
|
*
|
|
@@ -99,7 +117,30 @@ projectPatch?:(entry:HistoryEntry,current:ReplayDocument)=> HistoryPatchOp[];}
|
|
|
99
117
|
* irreconcilably mixed stream falls forward to the current epoch.
|
|
100
118
|
*/
|
|
101
119
|
export declare function resolveHistoryRepairItemHashVersion(entries:HistoryEntry[]):HistoryItemHashVersion;
|
|
120
|
+
/**
|
|
121
|
+
* Indexes of the entries a bridged segment covers before its bridge, plus the
|
|
122
|
+
* bridge record itself when no intact commitment proved the segment: its
|
|
123
|
+
* recorded state then rests on records that cannot be trusted either.
|
|
124
|
+
*/
|
|
125
|
+
export declare function collectBridgedInteriorIndexes(segments:ReadonlyArray<HistoryBridgedSegment&{exact?:boolean;}>):Set<number>;
|
|
126
|
+
/**
|
|
127
|
+
* Reseal one record with replay_inexact. The evidence keeps only digests of
|
|
128
|
+
* the prior record, never its values: a following provenance normalization
|
|
129
|
+
* or redaction must not find the removed values preserved in this evidence.
|
|
130
|
+
*/
|
|
131
|
+
export declare function markHistoryEntryInexact(entry:HistoryEntry):HistoryEntry;
|
|
132
|
+
/**
|
|
133
|
+
* Write the unreconstructable knowledge a verified bridge carries onto the
|
|
134
|
+
* records it covers, before any rewrite that may dissolve the bridge: each
|
|
135
|
+
* covered entry is resealed with replay_inexact (its prior record kept as
|
|
136
|
+
* rewrite evidence). Rewrites that reseal, interleave or re-anchor entries
|
|
137
|
+
* before they can see the segment (provenance normalization, merge unions)
|
|
138
|
+
* call this first, so the marker survives whatever they do to the bridge.
|
|
139
|
+
*/
|
|
140
|
+
export declare function materializeBridgedSegments(entries:HistoryEntry[]):HistoryEntry[];
|
|
102
141
|
/** Re-anchor a drifted history chain: replay every entry from empty, recompute the before/after hashes, and only rewrite a patch when the original op set no longer strictly applies (legacy drift). Clean entries keep their patch verbatim so the on-disk diff stays minimal. The returned chain verifies via verifyHistoryChain. */
|
|
103
142
|
export declare function reanchorHistoryEntries(entries:HistoryEntry[],itemHashVersion?:HistoryItemHashVersion,options?:ReanchorHistoryOptions):ReanchorResult;
|
|
104
143
|
/** Implements history entries to raw for the public runtime surface of this module. */
|
|
105
|
-
export declare function historyEntriesToRaw(entries:HistoryEntry[]):string;
|
|
144
|
+
export declare function historyEntriesToRaw(entries:HistoryEntry[]):string;
|
|
145
|
+
/** Internal helpers exposed for focused specs only. */
|
|
146
|
+
export declare const _testOnly:{isEffectFreeOperation:typeof isEffectFreeOperation;};export{};
|
|
@@ -1,4 +1,4 @@
|
|
|
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]="0c0cb8c7-4d7d-53f8-8ec2-d6dc98fc6dc5")}catch{}})();import jsonPatch from"fast-json-patch";import{historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,stableStringify}from"../shared/serialization.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates,resealHistoryRewrite,verifyHistoryRecordHash,verifyHistoryRewriteEvidence}from"./history.js";const EMPTY_REPLAY_DOCUMENT={metadata:{},body:""};function cloneEmptyReplayDocument(){return structuredClone(EMPTY_REPLAY_DOCUMENT)}function replayHash(document,version=CURRENT_HISTORY_ITEM_HASH_VERSION,algorithm){return replayHashVerificationCandidates(document,version,algorithm)[0]}function replayHashVerificationCandidates(document,version,algorithm){if(Object.keys(document.metadata).length===0||Array.isArray(document.metadata.tags))try{return hashDocumentVerificationCandidates(replayToItemDocument(document),version,algorithm)}catch{}const fallback=historyDigest(stableStringify({replay_fallback:!0,metadata:document.metadata,body:document.body}),algorithm);return version===2?[fallback,fallback]:[fallback]}function matchReplayHashCandidates(before,after,version,entry,memo){const algorithm=resolveHistoryHashAlgorithm(entry.hash_algorithm),memoKey=`${version}:${algorithm}`,beforeHashes=memo?.before.get(memoKey)??replayHashVerificationCandidates(before,version,algorithm),afterHashes=replayHashVerificationCandidates(after,version,algorithm);return memo?.after.set(memoKey,afterHashes),{beforeHashes,afterHashes,pairIndex:beforeHashes.findIndex((beforeHash,hashIndex)=>beforeHash===entry.before_hash&&afterHashes[hashIndex]===entry.after_hash),beforeIndex:beforeHashes.indexOf(entry.before_hash),afterIndex:afterHashes.indexOf(entry.after_hash)}}function replayToItemDocument(document){return{metadata:document.metadata,body:document.body}}function replayToCanonicalItemDocument(document,options={}){return canonicalDocument(replayToItemDocument(document),options)}function toReplayDocument(document){if(!document.metadata||Object.keys(document.metadata).length===0)return{metadata:{},body:document.body??""};const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function normalizeReplayPatchPath(path){return path==="/front_matter"?"/metadata":path.startsWith("/front_matter/")?`/metadata/${path.slice(14)}`:path}function isHistoryPatchOp(value){return typeof value=="object"&&value!==null&&typeof value.op=="string"&&typeof value.path=="string"}function normalizeReplayPatchOps(patch){return Array.isArray(patch)?patch.filter(isHistoryPatchOp).map(operation=>({...operation,path:normalizeReplayPatchPath(operation.path),from:typeof operation.from=="string"?normalizeReplayPatchPath(operation.from):void 0})):[]}function isReplayDocumentShape(value){return typeof value=="object"&&value!==null&&"metadata"in value&&"body"in value&&typeof value.body=="string"&&typeof value.metadata=="object"&&value.metadata!==null}function tryApplyReplayPatch(current,patch){try{const normalizedPatch=normalizeReplayPatchOps(patch),applied=jsonPatch.applyPatch(structuredClone(current),normalizedPatch,!0,!0).newDocument;return isReplayDocumentShape(applied)?{ok:!0,document:{metadata:applied.metadata,body:applied.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(error){return{ok:!1,error}}}function supportedExplicitHistoryItemHashVersions(entries){return[...new Set(entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)))]}function isUnsupportedExplicitHistoryItemHashVersion(version){return version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)}function historyEntryHashCandidates(explicitVersion,authoritativeVersion){return explicitVersion!==void 0?[explicitVersion]:authoritativeVersion===void 0?[...SUPPORTED_HISTORY_ITEM_HASH_VERSIONS]:[authoritativeVersion]}function historyEntryIntegrityError(entry){const recordVerification=verifyHistoryRecordHash(entry);if(!recordVerification.ok)return recordVerification.error;const rewriteVerification=verifyHistoryRewriteEvidence(entry);return rewriteVerification.ok?void 0:rewriteVerification.error}function verifyHistoryEntryInput(entry,replay){const integrityError=historyEntryIntegrityError(entry);if(integrityError)return{ok:!1,error:integrityError};const applied=tryApplyReplayPatch(replay,entry.patch);return applied.ok?{ok:!0,document:applied.document}:{ok:!1,error:"patch_apply_failed"}}function assertHistoryEntryIntegrity(entry,index){const integrityError=historyEntryIntegrityError(entry);if(integrityError)throw new TypeError(`${integrityError}:entry_${index+1}`)}function matchReplayEpochCandidates(before,after,candidates,entry,memo){const matches=[];for(const version of candidates){const match=matchReplayHashCandidates(before,after,version,entry,memo);if(matches.push({version,match}),match.pairIndex>=0)break}return matches}function verifyHistoryChainWithVersion(entries){let replay=cloneEmptyReplayDocument(),beforeHashMemo=new Map,detectedVersion,authoritativeExplicitVersion;const errors=findHistoryIdentityDiscontinuities(entries).map(finding=>`verify_failed:duplicate_create:entry_${finding.repeated_create_index}:prior_${finding.prior_genesis_index}`);for(let index=0;index<entries.length;index+=1){const entry=entries[index],explicitVersion=entry.item_hash_version,unsupportedVersion=isUnsupportedExplicitHistoryItemHashVersion(explicitVersion);unsupportedVersion&&errors.push(`verify_failed:unsupported_item_hash_version:${String(explicitVersion)}:entry_${index+1}`);const input=verifyHistoryEntryInput(entry,replay);if(!input.ok)return{ok:!1,errors:[...errors,`verify_failed:${input.error}:entry_${index+1}`]};if(unsupportedVersion){replay=input.document,beforeHashMemo=new Map,detectedVersion=void 0,authoritativeExplicitVersion=void 0;continue}const candidates=historyEntryHashCandidates(explicitVersion,authoritativeExplicitVersion),memo={before:beforeHashMemo,after:new Map},candidateMatches=matchReplayEpochCandidates(replay,input.document,candidates,entry,memo),matchingVersion=candidateMatches.find(({match})=>match.pairIndex>=0);if(matchingVersion===void 0){const beforeMatches=candidateMatches.some(({match})=>match.beforeIndex>=0);return{ok:!1,errors:[...errors,`verify_failed:${beforeMatches?"after":"before"}_hash_mismatch:entry_${index+1}`]}}const version=matchingVersion.version;replay=input.document,beforeHashMemo=memo.after,detectedVersion=version,authoritativeExplicitVersion=explicitVersion??authoritativeExplicitVersion}return errors.length>0?{ok:!1,errors,...detectedVersion===void 0?{}:{item_hash_version:detectedVersion}}:{ok:!0,errors:[],...detectedVersion===void 0?{}:{item_hash_version:detectedVersion}}}function verifyHistoryChain(entries){const result=verifyHistoryChainWithVersion(entries);return{ok:result.ok,errors:result.errors}}function tryApplySingleOp(document,op){try{return{ok:!0,document:jsonPatch.applyPatch(structuredClone(document),[op],!0,!1).newDocument}}catch{return{ok:!1}}}function lenientApplyReplayPatch(current,patch){let working=structuredClone(current),convertedReplaceToAdd=0,skippedOps=0;for(const op of normalizeReplayPatchOps(patch)){const direct=tryApplySingleOp(working,op);if(direct.ok){working=direct.document;continue}if(op.op==="replace"){const asAdd=tryApplySingleOp(working,{...op,op:"add"});if(asAdd.ok){working=asAdd.document,convertedReplaceToAdd+=1;continue}}skippedOps+=1}const candidate=working;return{document:{metadata:typeof candidate.metadata=="object"&&candidate.metadata!==null?candidate.metadata:{},body:typeof candidate.body=="string"?candidate.body:current.body},convertedReplaceToAdd,skippedOps}}function resolveHistoryRepairItemHashVersion(entries){const explicitVersions=supportedExplicitHistoryItemHashVersions(entries);if(explicitVersions.length===1)return explicitVersions[0];const verified=verifyHistoryChainWithVersion(entries);return verified.ok&&verified.item_hash_version!==void 0?verified.item_hash_version:explicitVersions.length===0?1:CURRENT_HISTORY_ITEM_HASH_VERSION}function applyReanchorPatch(replay,entry,projectedPatch=entry.patch){const strict=tryApplyReplayPatch(replay,projectedPatch);if(strict.ok)return{next:strict.document,patch:projectedPatch,repaired:stableStringify(projectedPatch)!==stableStringify(entry.patch),converted:0,skipped:0};const lenient=lenientApplyReplayPatch(replay,projectedPatch);return{next:lenient.document,patch:jsonPatch.compare(replay,lenient.document),repaired:!0,converted:lenient.convertedReplaceToAdd,skipped:lenient.skippedOps}}function applyProjectedReanchorPatch(replay,entry,options){return applyReanchorPatch(replay,entry,options.projectPatch?.(entry,replay))}function reanchorHistoryEntries(entries,itemHashVersion=resolveHistoryRepairItemHashVersion(entries),options={}){const unsupportedIndex=entries.findIndex(entry=>isUnsupportedExplicitHistoryItemHashVersion(entry.item_hash_version));if(unsupportedIndex>=0)throw new TypeError(`unsupported_item_hash_version:${String(entries[unsupportedIndex]?.item_hash_version)}:entry_${unsupportedIndex+1}`);let replay=cloneEmptyReplayDocument();const rewritten=[],details=[];let entriesRehashed=0,entriesPatchRepaired=0,convertedReplaceToAdd=0,skippedOps=0,semanticIndex;const explicitItemHashVersion=itemHashVersion!==1||entries.some(entry=>entry.item_hash_version!==void 0);for(let index=0;index<entries.length;index+=1){const entry=entries[index];assertHistoryEntryIntegrity(entry,index);const patchApplication=applyProjectedReanchorPatch(replay,entry,options),{next,patch:outPatch,repaired:patchRepaired,converted:entryConverted,skipped:entrySkipped}=patchApplication;convertedReplaceToAdd+=entryConverted,skippedOps+=entrySkipped,entriesPatchRepaired+=Number(patchRepaired);const hashMatch=matchReplayHashCandidates(replay,next,itemHashVersion,entry);semanticIndex===void 0||options.continuousHashSurface!==!0?semanticIndex=[hashMatch.pairIndex,hashMatch.beforeIndex,hashMatch.afterIndex,Math.min(semanticIndex??0,hashMatch.beforeHashes.length-1)].find(candidate=>candidate>=0):semanticIndex=Math.min(semanticIndex,hashMatch.beforeHashes.length-1);const beforeHash=hashMatch.beforeHashes[semanticIndex],afterHash=hashMatch.afterHashes[semanticIndex],rehashed=beforeHash!==entry.before_hash||afterHash!==entry.after_hash;rehashed&&(entriesRehashed+=1);let rewrittenEntry={...entry,patch:outPatch,before_hash:beforeHash,after_hash:afterHash};explicitItemHashVersion?rewrittenEntry.item_hash_version=itemHashVersion:delete rewrittenEntry.item_hash_version;const versionChanged=rewrittenEntry.item_hash_version!==entry.item_hash_version;(rehashed||patchRepaired||versionChanged)&&(rewrittenEntry=resealHistoryRewrite(entry,rewrittenEntry,{retainOriginalPatch:patchRepaired})),rewritten.push(rewrittenEntry),details.push({index:index+1,rehashed,patch_repaired:patchRepaired,converted_replace_to_add:entryConverted,skipped_ops:entrySkipped}),replay=next}return{entries:rewritten,finalDocument:replay,entriesRehashed,entriesPatchRepaired,convertedReplaceToAdd,skippedOps,details,itemHashVersion,explicitItemHashVersion}}function historyEntriesToRaw(entries){return entries.length===0?"":`${entries.map(entry=>JSON.stringify(entry)).join(`
|
|
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]="b329322c-71f1-57f9-b678-5e1166ecb938")}catch{}})();import jsonPatch from"fast-json-patch";import{historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{digestBridgedSegment,findNextHistoryBridge,locateBridgedSegments,matchesHistoryBreak,readHistoryBridge}from"./bridge.js";import{ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,stableStringify}from"../shared/serialization.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates,isCompleteHistoryRecord,resealHistoryRewrite,verifyHistoryRecordHash,verifyHistoryRewriteEvidence}from"./history.js";const EMPTY_REPLAY_DOCUMENT={metadata:{},body:""};function cloneEmptyReplayDocument(){return structuredClone(EMPTY_REPLAY_DOCUMENT)}function replayHash(document,version=CURRENT_HISTORY_ITEM_HASH_VERSION,algorithm){return replayHashVerificationCandidates(document,version,algorithm)[0]}function replayHashVerificationCandidates(document,version,algorithm){if(Object.keys(document.metadata).length===0||Array.isArray(document.metadata.tags))try{return hashDocumentVerificationCandidates(replayToItemDocument(document),version,algorithm)}catch{}const fallback=historyDigest(stableStringify({replay_fallback:!0,metadata:document.metadata,body:document.body}),algorithm);return version===2?[fallback,fallback]:[fallback]}function matchReplayHashCandidates(before,after,version,entry,memo){const algorithm=resolveHistoryHashAlgorithm(entry.hash_algorithm),memoKey=`${version}:${algorithm}`,beforeHashes=memo?.before.get(memoKey)??replayHashVerificationCandidates(before,version,algorithm),afterHashes=replayHashVerificationCandidates(after,version,algorithm);return memo?.after.set(memoKey,afterHashes),{beforeHashes,afterHashes,pairIndex:beforeHashes.findIndex((beforeHash,hashIndex)=>beforeHash===entry.before_hash&&afterHashes[hashIndex]===entry.after_hash),beforeIndex:beforeHashes.indexOf(entry.before_hash),afterIndex:afterHashes.indexOf(entry.after_hash)}}function replayToItemDocument(document){return{metadata:document.metadata,body:document.body}}function replayToCanonicalItemDocument(document,options={}){return canonicalDocument(replayToItemDocument(document),options)}function toReplayDocument(document){if(!document.metadata||Object.keys(document.metadata).length===0)return{metadata:{},body:document.body??""};const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function normalizeReplayPatchPath(path){return path==="/front_matter"?"/metadata":path.startsWith("/front_matter/")?`/metadata/${path.slice(14)}`:path}function isHistoryPatchOp(value){return typeof value=="object"&&value!==null&&typeof value.op=="string"&&typeof value.path=="string"}function normalizeReplayPatchOps(patch){return Array.isArray(patch)?patch.filter(isHistoryPatchOp).map(operation=>({...operation,...(operation.op==="add"||operation.op==="replace")&&Object.hasOwn(operation,"value")?{value:structuredClone(operation.value)}:{},path:normalizeReplayPatchPath(operation.path),from:typeof operation.from=="string"?normalizeReplayPatchPath(operation.from):void 0})):[]}function isReplayDocumentShape(value){return typeof value=="object"&&value!==null&&"metadata"in value&&"body"in value&&typeof value.body=="string"&&typeof value.metadata=="object"&&value.metadata!==null}function tryApplyReplayPatch(current,patch){try{const normalizedPatch=normalizeReplayPatchOps(patch),applied=jsonPatch.applyPatch(structuredClone(current),normalizedPatch,!0,!0).newDocument;return isReplayDocumentShape(applied)?{ok:!0,document:{metadata:applied.metadata,body:applied.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(error){return{ok:!1,error}}}function supportedExplicitHistoryItemHashVersions(entries){return[...new Set(entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)))]}function isUnsupportedExplicitHistoryItemHashVersion(version){return version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)}function historyEntryHashCandidates(explicitVersion,authoritativeVersion){return explicitVersion!==void 0?[explicitVersion]:authoritativeVersion===void 0?[...SUPPORTED_HISTORY_ITEM_HASH_VERSIONS]:[authoritativeVersion]}function historyEntryIntegrityError(entry){const recordVerification=verifyHistoryRecordHash(entry);if(!recordVerification.ok)return recordVerification.error;const rewriteVerification=verifyHistoryRewriteEvidence(entry);return rewriteVerification.ok?void 0:rewriteVerification.error}function verifyHistoryEntryInput(entry,replay){const integrityError=historyEntryIntegrityError(entry);if(integrityError)return{ok:!1,error:integrityError};const applied=tryApplyReplayPatch(replay,entry.patch);return applied.ok?{ok:!0,document:applied.document}:{ok:!1,error:"patch_apply_failed"}}function assertHistoryEntryIntegrity(entry,index){const integrityError=historyEntryIntegrityError(entry);if(integrityError)throw new TypeError(`${integrityError}:entry_${index+1}`)}function matchReplayEpochCandidates(before,after,candidates,entry,memo){const matches=[];for(const version of candidates){const match=matchReplayHashCandidates(before,after,version,entry,memo);if(matches.push({version,match}),match.pairIndex>=0)break}return matches}function isBridgeableRecord(entry){if(!isCompleteHistoryRecord(entry))return!1;let length;try{length=resolveHistoryHashAlgorithm(entry.hash_algorithm)==="sha512"?128:64}catch{return!1}const digest=new RegExp(`^[a-f0-9]{${length}}$`,"u");return!digest.test(entry.before_hash)||!digest.test(entry.after_hash)?!1:!entry.patch.filter(isHistoryPatchOp).map(operation=>({op:operation.op,path:normalizeReplayPatchPath(operation.path),from:typeof operation.from=="string"?normalizeReplayPatchPath(operation.from):void 0})).every(operation=>isEffectFreeOperation(operation))||entry.before_hash===entry.after_hash||Object.hasOwn(entry,"bridge")}function isEffectFreeOperation(operation){return operation.op==="test"?!0:operation.from!==operation.path?!1:operation.op==="move"||operation.op==="copy"&&!/\/(?:\d+|-)$/u.test(operation.path)}const BRIDGED_SEGMENT_EPOCHS=new WeakMap;function openBridgedSegment(entries,index){if(index===0||!isBridgeableRecord(entries[index]))return;const closer=findNextHistoryBridge(entries,index);if(closer<0)return;const bridge=readHistoryBridge(entries[closer]);if(!(typeof bridge!="object"||!matchesHistoryBreak(bridge.breaks[0],entries[index-1],entries[index])))return{start:index,closer,bridge,next:1}}function verifyBridgedInteriorEntry(entries,index,segment,replay,candidates){const entry=entries[index],previous=entries[index-1];if(!isBridgeableRecord(entry))return{ok:!1,error:"record_incomplete"};const input=verifyHistoryEntryInput(entry,replay);if(!input.ok)return input;const matches=candidates.map(version=>matchReplayHashCandidates(replay,input.document,version,entry));return matches.some(match=>match.beforeIndex>=0)&&!matches.some(match=>match.pairIndex>=0)?{ok:!1,error:"after_hash_mismatch"}:entry.before_hash===previous.after_hash?input:matchesHistoryBreak(segment.bridge.breaks[segment.next],previous,entry)?(segment.next+=1,input):{ok:!1,error:"bridge_unnamed_break"}}function verifyBridgeCloser(entries,index,segment,replay,candidates){const entry=entries[index];if(!isBridgeableRecord(entry))return{ok:!1,error:"record_incomplete"};const input=verifyHistoryEntryInput(entry,replay);if(!input.ok)return input;if(segment.next!==segment.bridge.breaks.length)return{ok:!1,error:"bridge_names_absent_break"};if(entry.before_hash!==entries[index-1].after_hash)return{ok:!1,error:"bridge_link_mismatch"};if(digestBridgedSegment(entries.slice(segment.start,index),entry)!==segment.bridge.segment_digest)return{ok:!1,error:"bridge_segment_mismatch"};const algorithm=resolveHistoryHashAlgorithm(entry.hash_algorithm),version=candidates.find(candidate=>replayHashVerificationCandidates(input.document,candidate,algorithm).includes(entry.after_hash));return version===void 0?{ok:!1,error:"bridge_after_hash_mismatch"}:{ok:!0,document:input.document,version}}function acceptHistoryEpoch(walk,entry,version,document,memo){walk.replay=document,walk.beforeHashMemo=memo,walk.detectedVersion=version,walk.authoritativeExplicitVersion=entry.item_hash_version??walk.authoritativeExplicitVersion}function stepBridgedSegment(entries,index,walk){const segment=walk.segment,entry=entries[index];if(index===segment.closer&&walk.authoritativeExplicitVersion!==void 0&&entry.item_hash_version!==walk.authoritativeExplicitVersion)return"bridge_epoch_mismatch";const bridged=(index<segment.closer?verifyBridgedInteriorEntry:verifyBridgeCloser)(entries,index,segment,walk.replay,historyEntryHashCandidates(entry.item_hash_version,walk.authoritativeExplicitVersion));if(!bridged.ok)return bridged.error;if(bridged.version===void 0){walk.replay=bridged.document,walk.beforeHashMemo=new Map,walk.authoritativeExplicitVersion=entry.item_hash_version??walk.authoritativeExplicitVersion;return}const closed={start:segment.start,end:index};BRIDGED_SEGMENT_EPOCHS.set(closed,bridged.version),walk.bridgedSegments.push(closed),walk.segment=void 0,acceptHistoryEpoch(walk,entry,bridged.version,bridged.document,new Map)}function stepAnchoredEntry(entries,index,walk,unsupportedVersion){const entry=entries[index];if(Object.hasOwn(entry,"bridge"))return"bridge_without_break";const input=verifyHistoryEntryInput(entry,walk.replay);if(!input.ok)return input.error;if(unsupportedVersion){walk.replay=input.document,walk.beforeHashMemo=new Map,walk.detectedVersion=void 0,walk.authoritativeExplicitVersion=void 0;return}const memo={before:walk.beforeHashMemo,after:new Map},candidateMatches=matchReplayEpochCandidates(walk.replay,input.document,historyEntryHashCandidates(entry.item_hash_version,walk.authoritativeExplicitVersion),entry,memo),matching=candidateMatches.find(({match})=>match.pairIndex>=0);if(matching!==void 0){acceptHistoryEpoch(walk,entry,matching.version,input.document,memo.after);return}const beforeMatches=candidateMatches.some(({match})=>match.beforeIndex>=0);if(walk.segment=beforeMatches?void 0:openBridgedSegment(entries,index),walk.segment===void 0)return`${beforeMatches?"after":"before"}_hash_mismatch`;walk.replay=input.document,walk.beforeHashMemo=new Map,walk.authoritativeExplicitVersion=entry.item_hash_version??walk.authoritativeExplicitVersion}function verifyHistoryChainWithVersion(entries){const walk={replay:cloneEmptyReplayDocument(),beforeHashMemo:new Map,bridgedSegments:[]},errors=findHistoryIdentityDiscontinuities(entries).map(finding=>`verify_failed:duplicate_create:entry_${finding.repeated_create_index}:prior_${finding.prior_genesis_index}`),finish=(ok,details)=>({ok,errors:ok?[]:errors,...details,...walk.bridgedSegments.length===0?{}:{bridged_segments:walk.bridgedSegments}}),failure=(error,index)=>(errors.push(`verify_failed:${error}:entry_${index+1}`),finish(!1,{})),invalidBridge=entries.findIndex(entry=>readHistoryBridge(entry)==="invalid");if(invalidBridge>=0)return failure("bridge_invalid",invalidBridge);for(let index=0;index<entries.length;index+=1){const explicitVersion=entries[index].item_hash_version,unsupportedVersion=isUnsupportedExplicitHistoryItemHashVersion(explicitVersion);unsupportedVersion&&errors.push(`verify_failed:unsupported_item_hash_version:${String(explicitVersion)}:entry_${index+1}`);const error=walk.segment===void 0?stepAnchoredEntry(entries,index,walk,unsupportedVersion):stepBridgedSegment(entries,index,walk);if(error!==void 0)return failure(error,index)}return finish(errors.length===0,walk.detectedVersion===void 0?{}:{item_hash_version:walk.detectedVersion})}function verifyHistoryChain(entries){const result=verifyHistoryChainWithVersion(entries);return{ok:result.ok,errors:result.errors}}function isObjectRoot(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function tryApplySingleOp(document,op,requireObjectRoot){try{const applied=jsonPatch.applyPatch(structuredClone(document),[op],!0,!1).newDocument;return requireObjectRoot&&!isObjectRoot(applied)?{ok:!1}:{ok:!0,document:applied}}catch{return{ok:!1}}}function applyPatchLeniently(current,patch,requireObjectRoot){let working=structuredClone(current),convertedReplaceToAdd=0,skippedOps=0;for(const op of normalizeReplayPatchOps(patch)){const direct=tryApplySingleOp(working,op,requireObjectRoot);if(direct.ok){working=direct.document;continue}if(op.op==="replace"){const asAdd=tryApplySingleOp(working,{...op,op:"add"},requireObjectRoot);if(asAdd.ok){working=asAdd.document,convertedReplaceToAdd+=1;continue}}skippedOps+=1}return{working,convertedReplaceToAdd,skippedOps}}function lenientApplyReplayPatch(current,patch,operation){const first=applyPatchLeniently(current,patch,!1);if(!isObjectRoot(first.working)&&operation==="delete")return{document:{metadata:{},body:""},convertedReplaceToAdd:first.convertedReplaceToAdd,skippedOps:first.skippedOps};const{working,convertedReplaceToAdd,skippedOps}=isObjectRoot(first.working)?first:applyPatchLeniently(current,patch,!0),candidate=working;return{document:{metadata:typeof candidate.metadata=="object"&&candidate.metadata!==null?candidate.metadata:{},body:typeof candidate.body=="string"?candidate.body:current.body},convertedReplaceToAdd,skippedOps}}function resolveHistoryRepairItemHashVersion(entries){const explicitVersions=supportedExplicitHistoryItemHashVersions(entries);if(explicitVersions.length===1)return explicitVersions[0];const verified=verifyHistoryChainWithVersion(entries);return verified.ok&&verified.item_hash_version!==void 0?verified.item_hash_version:explicitVersions.length===0?1:CURRENT_HISTORY_ITEM_HASH_VERSION}function applyReanchorPatch(replay,entry,projectedPatch=entry.patch){const strict=tryApplyReplayPatch(replay,projectedPatch);if(strict.ok)return{next:strict.document,patch:projectedPatch,repaired:stableStringify(projectedPatch)!==stableStringify(entry.patch),converted:0,skipped:0};const lenient=lenientApplyReplayPatch(replay,projectedPatch,entry.op);return{next:lenient.document,patch:jsonPatch.compare(replay,lenient.document),repaired:!0,converted:lenient.convertedReplaceToAdd,skipped:lenient.skippedOps}}function applyProjectedReanchorPatch(replay,entry,options){return applyReanchorPatch(replay,entry,options.projectPatch?.(entry,replay))}function indexBridgedSegments(entries,options,itemHashVersion,explicitItemHashVersion){const verification=verifyHistoryChainWithVersion(entries),verified=options.projectPatch===void 0&&options.continuousHashSurface!==!0?(verification.bridged_segments??[]).filter(segment=>BRIDGED_SEGMENT_EPOCHS.get(segment)===itemHashVersion&&(!explicitItemHashVersion||entries[segment.end].item_hash_version===itemHashVersion)&&entries.slice(segment.start,segment.end+1).every(entry=>entry.item_hash_version===void 0||entry.item_hash_version===itemHashVersion)):[];return{inputVerifies:verification.ok,preservable:new Map(verified.map(segment=>[segment.start,segment.end])),inexact:collectBridgedInteriorIndexes(options.callerMarksBridgeCoverage===!0?[]:locateBridgedSegments(entries).segments)}}function collectBridgedInteriorIndexes(segments){const interior=new Set;for(const{start,end,exact}of segments){const last=exact===!1?end:end-1;for(let index=start;index<=last;index+=1)interior.add(index)}return interior}function markHistoryEntryInexact(entry){return resealHistoryRewrite(entry,{...entry,replay_inexact:!0},{retainPriorRecord:!0,retainPriorRecordHash:!1})}function materializeBridgedSegments(entries){const interior=collectBridgedInteriorIndexes(locateBridgedSegments(entries).segments);return entries.map((entry,index)=>interior.has(index)&&entry.replay_inexact!==!0?markHistoryEntryInexact(entry):entry)}function keepBridgedSegment(entries,start,end,replay,rewritten,details){let current=replay;for(let index=start;index<=end;index+=1){const kept=entries[index],applied=tryApplyReplayPatch(current,kept.patch);if(!applied.ok)throw new TypeError(`patch_apply_failed:entry_${index+1}`);current=applied.document,rewritten.push(kept),details.push({index:index+1,rehashed:!1,patch_repaired:!1,converted_replace_to_add:0,skipped_ops:0})}return current}function finalizeReanchoredEntry(entry,rewrittenEntry,flags){flags.itemHashVersion===void 0?delete rewrittenEntry.item_hash_version:rewrittenEntry.item_hash_version=flags.itemHashVersion,flags.inexact&&(rewrittenEntry.replay_inexact=!0);const bridgeDissolved=Object.hasOwn(entry,"bridge");delete rewrittenEntry.bridge;const unbridged=bridgeDissolved||rewrittenEntry.replay_inexact!==entry.replay_inexact,changed=flags.rehashed||flags.patchRepaired||unbridged||rewrittenEntry.item_hash_version!==entry.item_hash_version;return{changed,persist:flags.inputVerifies?unbridged:changed,anchorsChanged:flags.rehashed||flags.patchRepaired,entry:changed?resealHistoryRewrite(entry,rewrittenEntry,{retainOriginalPatch:flags.patchRepaired,retainPriorRecord:bridgeDissolved}):rewrittenEntry}}function reanchorHistoryEntries(entries,itemHashVersion=resolveHistoryRepairItemHashVersion(entries),options={}){const unsupportedIndex=entries.findIndex(entry=>isUnsupportedExplicitHistoryItemHashVersion(entry.item_hash_version));if(unsupportedIndex>=0)throw new TypeError(`unsupported_item_hash_version:${String(entries[unsupportedIndex]?.item_hash_version)}:entry_${unsupportedIndex+1}`);let replay=cloneEmptyReplayDocument();const rewritten=[],details=[];let entriesRehashed=0,entriesPatchRepaired=0,convertedReplaceToAdd=0,skippedOps=0,entriesResealed=0,semanticIndex;const explicitItemHashVersion=itemHashVersion!==1||entries.some(entry=>entry.item_hash_version!==void 0),bridged=indexBridgedSegments(entries,options,itemHashVersion,explicitItemHashVersion);let unchangedPrefix=!0;for(let index=0;index<entries.length;index+=1){const entry=entries[index];assertHistoryEntryIntegrity(entry,index);const preservedEnd=unchangedPrefix?bridged.preservable.get(index):void 0;if(preservedEnd!==void 0){replay=keepBridgedSegment(entries,index,preservedEnd,replay,rewritten,details),index=preservedEnd;continue}const patchApplication=applyProjectedReanchorPatch(replay,entry,options),{next,patch:outPatch,repaired:patchRepaired,converted:entryConverted,skipped:entrySkipped}=patchApplication;convertedReplaceToAdd+=entryConverted,skippedOps+=entrySkipped,entriesPatchRepaired+=Number(patchRepaired);const hashMatch=matchReplayHashCandidates(replay,next,itemHashVersion,entry);semanticIndex===void 0||options.continuousHashSurface!==!0?semanticIndex=[hashMatch.pairIndex,hashMatch.beforeIndex,hashMatch.afterIndex,Math.min(semanticIndex??0,hashMatch.beforeHashes.length-1)].find(candidate=>candidate>=0):semanticIndex=Math.min(semanticIndex,hashMatch.beforeHashes.length-1);const beforeHash=hashMatch.beforeHashes[semanticIndex],afterHash=hashMatch.afterHashes[semanticIndex],rehashed=beforeHash!==entry.before_hash||afterHash!==entry.after_hash;rehashed&&(entriesRehashed+=1);const finalized=finalizeReanchoredEntry(entry,{...entry,patch:outPatch,before_hash:beforeHash,after_hash:afterHash},{itemHashVersion:explicitItemHashVersion?itemHashVersion:void 0,rehashed,patchRepaired,inexact:bridged.inexact.has(index),inputVerifies:bridged.inputVerifies});unchangedPrefix&&=!finalized.anchorsChanged,entriesResealed+=Number(finalized.persist),rewritten.push(finalized.entry),details.push({index:index+1,rehashed,patch_repaired:patchRepaired,converted_replace_to_add:entryConverted,skipped_ops:entrySkipped}),replay=next}return{entries:rewritten,finalDocument:replay,entriesRehashed,entriesPatchRepaired,convertedReplaceToAdd,skippedOps,entriesResealed,details,itemHashVersion,explicitItemHashVersion}}function historyEntriesToRaw(entries){return entries.length===0?"":`${entries.map(entry=>JSON.stringify(entry)).join(`
|
|
2
2
|
`)}
|
|
3
|
-
`}export{EMPTY_REPLAY_DOCUMENT,cloneEmptyReplayDocument,historyEntriesToRaw,lenientApplyReplayPatch,normalizeReplayPatchOps,normalizeReplayPatchPath,reanchorHistoryEntries,replayHash,replayHashVerificationCandidates,replayToCanonicalItemDocument,replayToItemDocument,resolveHistoryRepairItemHashVersion,toReplayDocument,tryApplyReplayPatch,verifyHistoryChain,verifyHistoryChainWithVersion};
|
|
3
|
+
`}const _testOnly={isEffectFreeOperation};export{EMPTY_REPLAY_DOCUMENT,_testOnly,cloneEmptyReplayDocument,collectBridgedInteriorIndexes,historyEntriesToRaw,lenientApplyReplayPatch,markHistoryEntryInexact,materializeBridgedSegments,normalizeReplayPatchOps,normalizeReplayPatchPath,reanchorHistoryEntries,replayHash,replayHashVerificationCandidates,replayToCanonicalItemDocument,replayToItemDocument,resolveHistoryRepairItemHashVersion,toReplayDocument,tryApplyReplayPatch,verifyHistoryChain,verifyHistoryChainWithVersion};
|
|
4
4
|
//# sourceMappingURL=replay.js.map
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import{type FileHandle}from "node:fs/promises";import type{BigIntStats,Stats}from "node:fs";import type{HistoryEntry}from "../../types/index.js";import type{IdentifiedHistoryStreamSnapshot}from "./read.js";
|
|
2
|
+
/** Tracker-relative location of the derived summary, for cleanup registries. */
|
|
3
|
+
export declare const HISTORY_STREAM_SUMMARY_RELATIVE_PATH="runtime/history-stream-summary.json";
|
|
4
|
+
/**
|
|
5
|
+
* Smallest stream count at which bounded readers consult the summary. Below it
|
|
6
|
+
* a full read is already cheap, so no summary file is written; this mirrors
|
|
7
|
+
* the metadata cache's derived-index minimum.
|
|
8
|
+
*/
|
|
9
|
+
export declare const HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS=500;
|
|
10
|
+
/**
|
|
11
|
+
* A fixed-length digest of the reader identity, so every record stays small
|
|
12
|
+
* however many supplementary groups the account has.
|
|
13
|
+
*/
|
|
14
|
+
declare function readerDigest(identity:string|undefined):string|undefined;
|
|
15
|
+
/** The credential sources readerIdentityOf consults; process and os in production. */
|
|
16
|
+
interface ReaderCredentials{geteuid?:()=> number;getegid?:()=> number;getgroups?:()=> number[];}
|
|
17
|
+
/**
|
|
18
|
+
* The credentials this process opens files with: on POSIX the effective user
|
|
19
|
+
* id, effective group id and sorted supplementary groups (sessions of one
|
|
20
|
+
* user can differ in groups), elsewhere (Windows) the account name.
|
|
21
|
+
* Undefined when the platform reports neither, and then no stream earns
|
|
22
|
+
* trust.
|
|
23
|
+
*/
|
|
24
|
+
declare function readerIdentityOf(credentials:ReaderCredentials,userInfo:()=>{username:string;}):string|undefined;
|
|
25
|
+
/** Timestamp bounds of every entry one history stream held when it was read. */
|
|
26
|
+
export interface HistoryStreamBounds{
|
|
27
|
+
/** Number of parsed entries in the stream. */
|
|
28
|
+
count:number;
|
|
29
|
+
/** Oldest canonical entry timestamp; null when no entry has one. */
|
|
30
|
+
oldest:string|null;
|
|
31
|
+
/** Newest canonical entry timestamp; null when no entry has one. */
|
|
32
|
+
newest:string|null;
|
|
33
|
+
/**
|
|
34
|
+
* True when any entry timestamp is not a canonical millisecond UTC string
|
|
35
|
+
* (`YYYY-MM-DDTHH:mm:ss.sssZ`), so the bounds cannot prove the stream is
|
|
36
|
+
* outside a window and readers must read it.
|
|
37
|
+
*/
|
|
38
|
+
irregular:boolean;}
|
|
39
|
+
/** Why a bounded read could not use trusted bounds for a stream population. */
|
|
40
|
+
export type HistoryStreamSummaryFallback="summary_missing"|"summary_invalid"|"summary_stale"|"irregular_timestamps"|"read_hooks_active";
|
|
41
|
+
/** One read's view of the persisted summary, bound to stats taken before any stream read. */
|
|
42
|
+
export interface HistoryStreamSummarySession{
|
|
43
|
+
/** Whether trusted bounds may be used to skip streams. */
|
|
44
|
+
readonly enabled:boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Set when the summary could not serve most of this read: it is absent or
|
|
47
|
+
* unreadable, more than half of the streams lack usable regular bounds, or
|
|
48
|
+
* read hooks require every stream to be read.
|
|
49
|
+
*/
|
|
50
|
+
readonly fallback:HistoryStreamSummaryFallback|undefined;
|
|
51
|
+
/** Streams without current bounds when the session opened (stale or never recorded). */
|
|
52
|
+
readonly staleAtOpen:number;
|
|
53
|
+
/** Bounds recorded for the stream's unchanged signature, or undefined when it must be read. */
|
|
54
|
+
trusted(file:string):HistoryStreamBounds|undefined;
|
|
55
|
+
/**
|
|
56
|
+
* Record the bounds of a stream this read parsed completely, under the
|
|
57
|
+
* identity of the open file that supplied the bytes (`snapshot.source`, the
|
|
58
|
+
* stat of that handle; null when the stream was absent). Bounds are kept
|
|
59
|
+
* only when the bytes read are the whole of that file, so they always
|
|
60
|
+
* describe the exact revision their signature names, whatever happened to
|
|
61
|
+
* the path.
|
|
62
|
+
*/
|
|
63
|
+
record(file:string,snapshot:Pick<IdentifiedHistoryStreamSnapshot,"entries"|"raw_bytes"|"source">):void;
|
|
64
|
+
/**
|
|
65
|
+
* Re-stat streams this read skipped on trusted bounds, just before the read
|
|
66
|
+
* finishes, and return those whose signature changed since the session
|
|
67
|
+
* opened (they are no longer trusted). Reading them keeps a change that
|
|
68
|
+
* completed while the read ran from being dropped; a change after this
|
|
69
|
+
* check is one a complete read could also have missed.
|
|
70
|
+
*/
|
|
71
|
+
revalidate(files:readonly string[]):Promise<string[]>;
|
|
72
|
+
/** Persist changed bounds best-effort; a failure leaves the next read to rebuild. */
|
|
73
|
+
commit():Promise<void>;}
|
|
74
|
+
interface StoredStream{signature:string;bounds:HistoryStreamBounds;}
|
|
75
|
+
interface ObservedStream{signature:string;
|
|
76
|
+
/** Byte size the stat reported; bytes of any other length are not recorded. */
|
|
77
|
+
size:bigint;
|
|
78
|
+
/** Latest of mtime and ctime, in nanoseconds since the epoch. */
|
|
79
|
+
changedAtNs:bigint;}
|
|
80
|
+
/**
|
|
81
|
+
* Whether a value is a canonical millisecond UTC timestamp whose string order
|
|
82
|
+
* is its time order: exactly what `new Date(Date.parse(v)).toISOString() === v`
|
|
83
|
+
* accepts for the fixed `YYYY-MM-DDTHH:mm:ss.sssZ` shape, checked on the
|
|
84
|
+
* calendar fields instead of a Date round trip, which dominated summary
|
|
85
|
+
* rebuilds (about 256 ms per 200,000 entries).
|
|
86
|
+
*/
|
|
87
|
+
export declare function isCanonicalHistoryTimestamp(value:unknown):value is string;
|
|
88
|
+
/** Derive the bounds a full read of one stream observed. */
|
|
89
|
+
export declare function summarizeHistoryStreamBounds(entries:readonly HistoryEntry[]):HistoryStreamBounds;
|
|
90
|
+
/** Lower the engagement threshold for specs that cannot afford 500 streams. */
|
|
91
|
+
declare function setMinimumStreams(value:number):()=> void;
|
|
92
|
+
/** Replace the reader identity so specs can model another user on a shared tracker. */
|
|
93
|
+
declare function setReaderIdentity(identity:()=> string|undefined):()=> void;
|
|
94
|
+
/** Move the racy-window clock so specs can treat just-written streams as settled. */
|
|
95
|
+
declare function setWallClock(clock:()=> number):()=> void;declare function signatureOf(stats:BigIntStats,reader:string|undefined):ObservedStream|undefined;
|
|
96
|
+
/**
|
|
97
|
+
* Whether bounds could have been produced by summarizeHistoryStreamBounds:
|
|
98
|
+
* an empty stream has no timestamps and is regular, a regular non-empty
|
|
99
|
+
* stream has both, timestamps appear together and in order. A record that
|
|
100
|
+
* fails this is damaged, and trusting it could hide a non-empty stream.
|
|
101
|
+
*/
|
|
102
|
+
declare function areConsistentBounds(bounds:HistoryStreamBounds):boolean;declare function parseStoredStream(value:unknown):StoredStream|undefined;
|
|
103
|
+
/** Generous per-record allowance plus envelope; a larger file is not a summary of these streams. */
|
|
104
|
+
declare function summaryByteCap(streamCount:number):number;
|
|
105
|
+
/**
|
|
106
|
+
* Whether an opened summary can be evidence for this reader: an unshared
|
|
107
|
+
* regular file of plausible size and, on POSIX, owned by the effective user
|
|
108
|
+
* and writable by no one else, so another account that can write runtime/
|
|
109
|
+
* cannot author bounds that suppress history it may not alter.
|
|
110
|
+
*/
|
|
111
|
+
declare function isTrustedSummaryFile(stats:Stats,streamCount:number,euid:number|undefined):boolean;
|
|
112
|
+
/**
|
|
113
|
+
* Read the whole file, refusing one that grew past the cap after its stat.
|
|
114
|
+
* The buffer starts at the stat'ed size (plus one byte to notice growth) and
|
|
115
|
+
* doubles only while the file keeps growing, never past the cap, so a warm
|
|
116
|
+
* read allocates what the summary holds rather than the whole allowance.
|
|
117
|
+
*/
|
|
118
|
+
declare function readAtMost(handle:FileHandle,cap:number,expectedSize:number):Promise<string>;declare function serializeSummary(streams:ReadonlyMap<string,StoredStream>):string;
|
|
119
|
+
/** Hash the canonical serialization the writer produced; JSON round-trips it exactly. */
|
|
120
|
+
declare function checksumOf(streams:unknown):string;
|
|
121
|
+
/**
|
|
122
|
+
* Open the summary for one bounded read of `files` (stream file names in
|
|
123
|
+
* `historyDir`). Stats are captured here, before the caller reads any stream,
|
|
124
|
+
* so a stream changed after this call can never be recorded under its new
|
|
125
|
+
* signature.
|
|
126
|
+
*/
|
|
127
|
+
export declare function openHistoryStreamSummary(params:{pmRoot:string;historyDir:string;files:readonly string[];}):Promise<HistoryStreamSummarySession>;
|
|
128
|
+
/** Test-only seams for the engagement threshold and racy window. */
|
|
129
|
+
export declare const _testOnly:{areConsistentBounds:typeof areConsistentBounds;readAtMost:typeof readAtMost;readerDigest:typeof readerDigest;isTrustedSummaryFile:typeof isTrustedSummaryFile;summaryByteCap:typeof summaryByteCap;readerIdentityOf:typeof readerIdentityOf;checksumOf:typeof checksumOf;setMinimumStreams:typeof setMinimumStreams;setReaderIdentity:typeof setReaderIdentity;setWallClock:typeof setWallClock;signatureOf:typeof signatureOf;RACY_WINDOW_NS:bigint;SUMMARY_VERSION:number;serializeSummary:typeof serializeSummary;parseStoredStream:typeof parseStoredStream;};export{};
|
|
@@ -0,0 +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]="0a7f878e-2354-5f40-9217-81b86d7b5423")}catch{}})();import{createHash}from"node:crypto";import fs from"node:fs/promises";import os from"node:os";import path from"node:path";import{hasActiveOnReadHooks}from"../extensions/index.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";const HISTORY_STREAM_SUMMARY_RELATIVE_PATH="runtime/history-stream-summary.json",SUMMARY_VERSION=1,STAT_CONCURRENCY=64,RACY_WINDOW_NS=2000000000n,HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS=500;let minimumStreams=HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS,wallClockMs=()=>Date.now(),readerIdentity=()=>readerDigest(readerIdentityOf(process,os.userInfo));function readerDigest(identity){return identity===void 0?void 0:createHash("sha256").update(identity).digest("hex").slice(0,16)}function readerIdentityOf(credentials,userInfo){try{if(credentials.geteuid&&credentials.getegid&&credentials.getgroups){const groups=[...new Set(credentials.getgroups())].sort((left,right)=>left-right);return`uid:${credentials.geteuid()}:gid:${credentials.getegid()}:groups:${groups.join(",")}`}const{username}=userInfo();return username.length>0?`user:${username}`:void 0}catch{return}}const CANONICAL_TIMESTAMP=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;function daysInMonth(year,month){return month===2?year%4===0&&year%100!==0||year%400===0?29:28:month===4||month===6||month===9||month===11?30:31}function isCanonicalHistoryTimestamp(value){if(typeof value!="string"||!CANONICAL_TIMESTAMP.test(value))return!1;const year=Number(value.slice(0,4)),month=Number(value.slice(5,7)),day=Number(value.slice(8,10));return month>=1&&month<=12&&day>=1&&day<=daysInMonth(year,month)&&Number(value.slice(11,13))<24&&Number(value.slice(14,16))<60&&Number(value.slice(17,19))<60}function summarizeHistoryStreamBounds(entries){let oldest=null,newest=null,irregular=!1;for(const entry of entries){const timestamp=typeof entry=="object"&&entry!==null?entry.ts:void 0;if(!isCanonicalHistoryTimestamp(timestamp)){irregular=!0;continue}(oldest===null||timestamp<oldest)&&(oldest=timestamp),(newest===null||timestamp>newest)&&(newest=timestamp)}return{count:entries.length,oldest,newest,irregular}}function setMinimumStreams(value){const previous=minimumStreams;return minimumStreams=value,()=>{minimumStreams=previous}}function setReaderIdentity(identity){const previous=readerIdentity;return readerIdentity=identity,()=>{readerIdentity=previous}}function setWallClock(clock){const previous=wallClockMs;return wallClockMs=clock,()=>{wallClockMs=previous}}function isFileExistsError(error){return typeof error=="object"&&error!==null&&"code"in error&&error.code==="EEXIST"}function summaryPath(pmRoot){return path.join(pmRoot,...HISTORY_STREAM_SUMMARY_RELATIVE_PATH.split("/"))}function signatureOf(stats,reader){if(!(!stats.isFile()||stats.ino===0n||reader===void 0))return{size:stats.size,signature:[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs,reader].join(":"),changedAtNs:stats.mtimeNs>stats.ctimeNs?stats.mtimeNs:stats.ctimeNs}}async function observeStreams(historyDir,files,reader){const observed=new Map;for(let start=0;start<files.length;start+=STAT_CONCURRENCY){const chunk=files.slice(start,start+STAT_CONCURRENCY);(await Promise.all(chunk.map(file=>fs.stat(path.join(historyDir,file),{bigint:!0}).catch(()=>{})))).forEach((stat,index)=>{const signature=stat===void 0?void 0:signatureOf(stat,reader);signature!==void 0&&observed.set(chunk[index],signature)})}return observed}function isNullableCanonical(value){return value===null||isCanonicalHistoryTimestamp(value)}function areConsistentBounds(bounds){return bounds.oldest===null!=(bounds.newest===null)?!1:bounds.count===0?bounds.oldest===null&&!bounds.irregular:bounds.oldest===null?bounds.irregular:bounds.oldest<=bounds.newest}function parseStoredStream(value){if(!Array.isArray(value)||value.length!==5)return;const[signature,count,oldest,newest,irregular]=value;if(typeof signature!="string"||!Number.isSafeInteger(count)||count<0||!isNullableCanonical(oldest)||!isNullableCanonical(newest)||typeof irregular!="boolean")return;const bounds={count,oldest,newest,irregular};return areConsistentBounds(bounds)?{signature,bounds}:void 0}function summaryByteCap(streamCount){return 4096+streamCount*1024}function isTrustedSummaryFile(stats,streamCount,euid){return!stats.isFile()||stats.nlink!==1||stats.size>summaryByteCap(streamCount)?!1:euid===void 0||stats.uid===euid&&(stats.mode&18)===0}async function hasRealRuntimeDirectory(pmRoot){return(await fs.lstat(path.join(pmRoot,"runtime"))).isDirectory()}async function hasNonRegularSummaryEntry(pmRoot){try{return!(await fs.lstat(summaryPath(pmRoot))).isFile()}catch{return!1}}async function isSummaryUnwritable(pmRoot){try{if(!await hasRealRuntimeDirectory(pmRoot))return!0}catch{return!1}return hasNonRegularSummaryEntry(pmRoot)}async function readSummaryText(pmRoot,streamCount){if(!await hasRealRuntimeDirectory(pmRoot))throw new Error("runtime directory is redirected");if((await fs.lstat(summaryPath(pmRoot))).isSymbolicLink())throw new Error("history stream summary is a link");const handle=await fs.open(summaryPath(pmRoot),fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);try{const stats=await handle.stat();if(!isTrustedSummaryFile(stats,streamCount,process.geteuid?.()))throw new Error("history stream summary is not a trusted file");return await readAtMost(handle,summaryByteCap(streamCount),stats.size)}finally{await handle.close()}}async function readAtMost(handle,cap,expectedSize){let buffer=Buffer.alloc(Math.min(Math.max(expectedSize,0),cap)+1),length=0;for(;;){if(length===buffer.length){const grown=Buffer.alloc(Math.min(buffer.length*2,cap+1));buffer.copy(grown,0,0,length),buffer=grown}const{bytesRead}=await handle.read(buffer,length,buffer.length-length,length);if(bytesRead===0)break;if(length+=bytesRead,length>cap)throw new Error("history stream summary grew past its size cap")}return buffer.subarray(0,length).toString("utf8")}async function readStoredSummary(pmRoot,streamCount){let raw;try{raw=await readSummaryText(pmRoot,streamCount)}catch(error){return{state:isFileMissingError(error)?"missing":"invalid",streams:new Map}}try{const parsed=JSON.parse(raw);if(parsed.version!==SUMMARY_VERSION||typeof parsed.streams!="object"||parsed.streams===null||Array.isArray(parsed.streams)||parsed.checksum!==checksumOf(parsed.streams))return{state:"invalid",streams:new Map};const streams=new Map;for(const[file,value]of Object.entries(parsed.streams)){const stream=parseStoredStream(value);if(stream===void 0)return{state:"invalid",streams:new Map};streams.set(file,stream)}return{state:"loaded",streams}}catch{return{state:"invalid",streams:new Map}}}function serializeSummary(streams){const ordered=[...streams.entries()].sort(([left],[right])=>left<right?-1:1),encoded={};for(const[file,{signature,bounds}]of ordered)encoded[file]=[signature,bounds.count,bounds.oldest,bounds.newest,bounds.irregular];return`${JSON.stringify({version:SUMMARY_VERSION,checksum:checksumOf(encoded),streams:encoded})}
|
|
2
|
+
`}function checksumOf(streams){return createHash("sha256").update(JSON.stringify(streams)).digest("hex")}function summaryFallback(state,current,streamCount){if(state==="missing")return"summary_missing";if(state==="invalid")return"summary_invalid";const stale=streamCount-current.size;let irregular=0;for(const{bounds}of current.values())bounds.irregular&&(irregular+=1);if(!((stale+irregular)*2<=streamCount))return stale>=irregular?"summary_stale":"irregular_timestamps"}function disabledSession(fallback){return{enabled:!1,staleAtOpen:0,fallback,trusted:()=>{},record:()=>{},revalidate:async()=>[],commit:async()=>{}}}async function openHistoryStreamSummary(params){if(params.files.length<minimumStreams)return disabledSession(void 0);if(hasActiveOnReadHooks())return disabledSession("read_hooks_active");if(await isSummaryUnwritable(params.pmRoot))return disabledSession("summary_invalid");const observedAtNs=BigInt(Math.floor(wallClockMs()))*1000000n,reader=readerIdentity(),[stored,observed]=await Promise.all([readStoredSummary(params.pmRoot,params.files.length),observeStreams(params.historyDir,params.files,reader)]);if(hasActiveOnReadHooks())return disabledSession("read_hooks_active");const next=new Map;for(const[file,stream]of stored.streams)observed.get(file)?.signature===stream.signature&&next.set(file,stream);let dirty=!1;return{enabled:!0,staleAtOpen:params.files.length-next.size,fallback:summaryFallback(stored.state,next,params.files.length),trusted:file=>next.get(file)?.bounds,record:(file,{entries,raw_bytes:rawBytes,source})=>{const observation=source===null||rawBytes===null?void 0:signatureOf(source,reader);observation===void 0||BigInt(rawBytes.length)!==observation.size||observation.changedAtNs+RACY_WINDOW_NS>=observedAtNs||next.get(file)?.signature===observation.signature||(next.set(file,{signature:observation.signature,bounds:summarizeHistoryStreamBounds(entries)}),dirty=!0)},revalidate:async files=>{const current=await observeStreams(params.historyDir,files,reader),changed=files.filter(file=>current.get(file)?.signature!==next.get(file)?.signature);for(const file of changed)next.delete(file);return changed},commit:async()=>{dirty&&(dirty=!1,await persistSummary(params.pmRoot,next))}}}async function persistSummary(pmRoot,streams){try{if(await fs.mkdir(path.join(pmRoot,"runtime")).catch(error=>{if(!isFileExistsError(error))throw error}),!await hasRealRuntimeDirectory(pmRoot)||await hasNonRegularSummaryEntry(pmRoot))return;await writeFileAtomic(summaryPath(pmRoot),serializeSummary(streams),{createParentDirectories:!1,mode:384})}catch{}}const _testOnly={areConsistentBounds,readAtMost,readerDigest,isTrustedSummaryFile,summaryByteCap,readerIdentityOf,checksumOf,setMinimumStreams,setReaderIdentity,setWallClock,signatureOf,RACY_WINDOW_NS,SUMMARY_VERSION,serializeSummary,parseStoredStream};export{HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS,HISTORY_STREAM_SUMMARY_RELATIVE_PATH,_testOnly,isCanonicalHistoryTimestamp,openHistoryStreamSummary,summarizeHistoryStreamBounds};
|
|
3
|
+
//# sourceMappingURL=stream-summary.js.map
|
|
@@ -238,6 +238,14 @@ suggested_path?:string;
|
|
|
238
238
|
examples?:string[];
|
|
239
239
|
/** Value that configures or reports next steps for this contract. */
|
|
240
240
|
nextSteps?:string[];
|
|
241
|
+
/**
|
|
242
|
+
* The refusal rejects the URL credentials carried by `source` (an option,
|
|
243
|
+
* environment variable or field name), such as an identity with userinfo,
|
|
244
|
+
* so recovery never advises restoring those redacted credentials: replaying
|
|
245
|
+
* with them reproduces this refusal (GH-1757). `source` is a code-defined
|
|
246
|
+
* label, never caller input: guidance prints it unredacted.
|
|
247
|
+
*/
|
|
248
|
+
url_credentials_rejected?:{source:string;};
|
|
241
249
|
/** Exact selectors that could not be matched by a lossless removal. */
|
|
242
250
|
unmatched?:string[];
|
|
243
251
|
/** Dependency selectors that matched no stored edge. */
|
|
@@ -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]="745f8a29-e1f9-574c-bf67-70f564b0415b")}catch{}})();class PmCliError extends Error{exitCode;code;context;constructor(message,exitCode,context={}){super(message),this.name="PmCliError",this.exitCode=exitCode,this.context=context,this.code=context.code}}export{PmCliError};
|
|
2
2
|
//# sourceMappingURL=errors.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]="a6bebd48-2722-5784-b69b-cf18321ea2c0")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{quoteWindowsCommandArg}from"./command-line.js";import{EXIT_CODE}from"./constants.js";import{PmCliError}from"./errors.js";const URL_CREDENTIAL_PLACEHOLDER="[redacted]";function provablyWithoutUserinfo(token,colon){if(/[\t\n\r]/u.test(token)||!/(?:^|[^A-Za-z0-9+.-])(?:https?|wss?|ftp)$/iu.test(token.slice(0,colon)))return!1;let authority=colon+1;for(;token[authority]==="/"||token[authority]==="\\";)authority+=1;const delimiter=token.indexOf("/",authority)-authority;if(delimiter<0)return!1;const authorityEnd=authority+delimiter;return!/[:@%]/u.test(token.slice(authority,authorityEnd))&&!/[:%]|[/\\][/\\]/u.test(token.slice(authorityEnd))}function userinfoBounds(token){const at=Math.max(token.lastIndexOf("@"),token.toLowerCase().lastIndexOf("%40")),colon=token.indexOf(":");if(at<0||colon<0||colon>at)return;let start=colon+1;for(;start<at&&start<colon+3&&(token[start]==="/"||token[start]==="\\");)start+=1;return start===at||provablyWithoutUserinfo(token,colon)?void 0:[start,at]}function redactUrlCredentialsInToken(token){const bounds=userinfoBounds(token);return bounds?`${token.slice(0,bounds[0])}${URL_CREDENTIAL_PLACEHOLDER}${token.slice(bounds[1])}`:token}function redactIdentityCredentials(identity){return redactUrlCredentialsInToken(identity)}const IDENTITY_FIELDS=["author","assignee","claim_principal"];function redactIdentityFields(values){const redacted={...values};for(const field of IDENTITY_FIELDS)typeof redacted[field]=="string"&&(redacted[field]=redactIdentityCredentials(redacted[field]));return redacted}function assertIdentityWithoutUrlCredentials(identity,source){if(!(typeof identity!="string"||userinfoBounds(identity.trim())===void 0))throw new PmCliError(`${source} must not carry URL credentials: an identity is a name, never a credential.`,EXIT_CODE.USAGE,{code:"invalid_argument_value",field:source,required:`Set ${source} to a plain name such as agent-a, with no URL userinfo (no user, password or token before the host).`,nextSteps:[`Rerun with ${source} set to a plain name.`],url_credentials_rejected:{source}})}function parseIdentityOption(value,source){return assertIdentityWithoutUrlCredentials(value,source),value}const NESTED_IDENTITY_PATHS=[["comments","author"],["notes","author"],["learnings","author"],["dependencies","author"],["plan_decisions","author"],["plan_discoveries","author"],["plan_steps","owner"],["tests","provenance","author"],["tests","updated_by"]],IDENTITY_VALUE_DEPTH=4;function assertIdentityValueWithoutUrlCredentials(value,source,depth=0){if(typeof value=="string"){assertIdentityWithoutUrlCredentials(value,source);return}if(!(depth>=IDENTITY_VALUE_DEPTH||typeof value!="object"||value===null))for(const entry of Object.values(value))assertIdentityValueWithoutUrlCredentials(entry,source,depth+1)}function readEntryPath(entry,path){let node=entry;for(const key of path){if(typeof node!="object"||node===null||Array.isArray(node))return;node=node[key]}return node}function assertIdentityFieldsWithoutUrlCredentials(values){const record=values;for(const field of IDENTITY_FIELDS)assertIdentityValueWithoutUrlCredentials(record[field],field);for(const[collection,...path]of NESTED_IDENTITY_PATHS){const entries=record[collection];Array.isArray(entries)&&entries.forEach((entry,index)=>{assertIdentityValueWithoutUrlCredentials(readEntryPath(entry,path),`${collection}[${index}].${path.join(".")}`)})}}function redactOptionalIdentityCredentials(value){return typeof value=="string"?redactIdentityCredentials(value):value}const MIN_FRAGMENT_LENGTH=6,MAX_REGISTERED_FRAGMENTS=65536,NO_INVOCATION={carried:!1,fragments:new Set,fragmentLength:MIN_FRAGMENT_LENGTH,shortSpellings:[]},invocations=new AsyncLocalStorage;function lowerPreservingLength(text){const lowered=text.toLowerCase();if(lowered.length===text.length)return lowered;let result="";for(const unit of text){const lower=unit.toLowerCase();result+=lower.length===unit.length?lower:unit}return result}function spanSpellings(span){return[span,span.replaceAll(/(["\\$`])/gu,"\\$1"),quoteWindowsCommandArg(`${span}@`).slice(1,-2),JSON.stringify(span).slice(1,-1)]}function userinfoSecret(userinfo){const colon=userinfo.indexOf(":");return colon>=0&&colon<userinfo.length-1?userinfo.slice(colon+1):userinfo}function describeInvocation(argv){const unique=new Set;let carried=!1;for(const token of argv){const bounds=userinfoBounds(token);if(bounds){carried=!0;for(const spelling of spanSpellings(userinfoSecret(token.slice(bounds[0],bounds[1]))))unique.add(lowerPreservingLength(spelling))}}const spellings=[...unique],positions=spellings.reduce((total,spelling)=>total+Math.max(0,spelling.length-MIN_FRAGMENT_LENGTH+1)+1,0),stride=Math.max(1,Math.ceil(positions/MAX_REGISTERED_FRAGMENTS)),fragmentLength=Math.max(MIN_FRAGMENT_LENGTH,stride),fragments=new Set,shortSpellings=new Set;for(const spelling of spellings){if(spelling.length<fragmentLength){(spelling.length>=MIN_FRAGMENT_LENGTH||/\s/u.test(spelling))&&shortSpellings.add(spelling);continue}for(let index=0;index+fragmentLength<=spelling.length;index+=stride)fragments.add(spelling.slice(index,index+fragmentLength));fragments.add(spelling.slice(-fragmentLength))}return{carried,fragments,fragmentLength,shortSpellings:[...shortSpellings]}}function removeRegisteredFragments(text,invocation){const lowered=lowerPreservingLength(text),covered=new Uint8Array(text.length);let found=!1;const width=invocation.fragmentLength;for(let index=0;index+width<=lowered.length;index+=1)invocation.fragments.has(lowered.slice(index,index+width))&&(covered.fill(1,index,index+width),found=!0);for(const spelling of invocation.shortSpellings)for(let index=lowered.indexOf(spelling);index>=0;index=lowered.indexOf(spelling,index+1))covered.fill(1,index,index+spelling.length),found=!0;if(!found)return text;let result="";for(let index=0;index<text.length;index+=1)covered[index]?(index===0||!covered[index-1])&&(result+=URL_CREDENTIAL_PLACEHOLDER):result+=text[index];return result}function runWithUrlCredentialInvocation(argv,run){return invocations.run(describeInvocation(argv),run)}function invocationCarriesUrlCredentials(){return(invocations.getStore()??NO_INVOCATION).carried}function redactUrlCredentialsInText(text){const invocation=invocations.getStore()??NO_INVOCATION,redacted=invocation.carried?removeRegisteredFragments(text,invocation):text;return/@|%40/iu.test(redacted)?redacted.replaceAll(/\S+/gu,redactUrlCredentialsInToken):redacted}export{URL_CREDENTIAL_PLACEHOLDER,assertIdentityFieldsWithoutUrlCredentials,assertIdentityWithoutUrlCredentials,invocationCarriesUrlCredentials,parseIdentityOption,redactIdentityCredentials,redactIdentityFields,redactOptionalIdentityCredentials,redactUrlCredentialsInText,redactUrlCredentialsInToken,runWithUrlCredentialInvocation};
|
|
2
2
|
//# sourceMappingURL=url-credentials.js.map
|