@unbrained/pm-cli 2026.11.21 → 2026.11.23
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/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/after-command-context-usage.js +1 -1
- package/dist/cli/argv-utils.js +1 -1
- package/dist/cli/bootstrap-args.js +1 -1
- package/dist/cli/bundle-integrity.js +2 -2
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/commander-usage.js +11 -11
- package/dist/cli/commands/annotations/comments.js +1 -1
- package/dist/cli/commands/annotations/docs.js +1 -1
- package/dist/cli/commands/annotations/files.js +1 -1
- package/dist/cli/commands/annotations/learnings.js +1 -1
- package/dist/cli/commands/annotations/notes.js +1 -1
- package/dist/cli/commands/extension/describe.js +1 -1
- package/dist/cli/commands/extension/extension.js +1 -1
- package/dist/cli/commands/extension/scaffold.js +1 -1
- package/dist/cli/commands/extension/shared.js +1 -1
- package/dist/cli/commands/governance/gc.js +1 -1
- package/dist/cli/commands/governance/health.js +1 -1
- package/dist/cli/commands/governance/telemetry.js +1 -1
- package/dist/cli/commands/governance/validate.js +1 -1
- package/dist/cli/commands/history/activity.js +1 -1
- package/dist/cli/commands/history/history-compact.js +1 -1
- package/dist/cli/commands/history/history-redact.js +1 -1
- package/dist/cli/commands/history/history-repair.js +1 -1
- package/dist/cli/commands/history/history.js +1 -1
- package/dist/cli/commands/history/restore.js +1 -1
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/claim.js +1 -1
- package/dist/cli/commands/lifecycle/close-many.js +1 -1
- package/dist/cli/commands/lifecycle/close.js +1 -1
- package/dist/cli/commands/lifecycle/copy.js +1 -1
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/delete.js +1 -1
- package/dist/cli/commands/lifecycle/focus.js +1 -1
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.js +1 -1
- package/dist/cli/commands/query/aggregate.js +1 -1
- package/dist/cli/commands/query/context.js +1 -1
- package/dist/cli/commands/query/deps.js +1 -1
- package/dist/cli/commands/query/duplicates.js +1 -1
- package/dist/cli/commands/query/eval.js +1 -1
- package/dist/cli/commands/query/get.js +1 -1
- package/dist/cli/commands/query/graph.js +1 -1
- package/dist/cli/commands/query/list.js +1 -1
- package/dist/cli/commands/query/next.js +1 -1
- package/dist/cli/commands/query/search.js +1 -1
- package/dist/cli/commands/query/stats.js +1 -1
- package/dist/cli/commands/test/test-all.js +1 -1
- package/dist/cli/commands/test/test-runs.js +1 -1
- package/dist/cli/commands/test/test.js +1 -1
- package/dist/cli/commands/workspace/config.js +1 -1
- package/dist/cli/commands/workspace/contracts.js +1 -1
- package/dist/cli/commands/workspace/init.js +1 -1
- package/dist/cli/commands/workspace/merge.js +1 -1
- package/dist/cli/commands/workspace/profile.js +1 -1
- package/dist/cli/commands/workspace/schema.js +1 -1
- package/dist/cli/commands/workspace/upgrade.js +1 -1
- package/dist/cli/context-intent-invocation.js +1 -1
- package/dist/cli/description-stdin.js +1 -1
- package/dist/cli/error-guidance.js +5 -5
- package/dist/cli/expected-revisions.js +1 -1
- package/dist/cli/extension-command-help.js +6 -6
- package/dist/cli/extension-recovery.js +1 -1
- package/dist/cli/help-content.js +5 -5
- package/dist/cli/help-json-payload.js +7 -7
- package/dist/cli/invocation-profile.js +2 -2
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/option-values.js +1 -1
- package/dist/cli/preflight-warnings.js +3 -3
- package/dist/cli/public.js +1 -1
- package/dist/cli/register-annotations.js +1 -1
- package/dist/cli/register-assurance.js +1 -1
- package/dist/cli/register-files-lookup.js +1 -1
- package/dist/cli/register-history-activity.js +1 -1
- package/dist/cli/register-history-author.js +1 -1
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli/register-list-query.js +10 -10
- package/dist/cli/register-mutation-options.js +0 -1
- package/dist/cli/register-mutation.js +6 -6
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli/registration-helpers.js +1 -1
- package/dist/cli/runtime/activation.js +1 -1
- package/dist/cli/runtime/annotation-option-retry.js +1 -1
- package/dist/cli/runtime/close-fields-retry.js +1 -1
- package/dist/cli/runtime/field-route-retry.js +1 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli/runtime/invocation-rewrites.js +1 -1
- package/dist/cli/runtime/projection-retry.js +1 -1
- package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
- package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
- package/dist/cli/runtime/selection.js +1 -1
- package/dist/cli/runtime/telemetry-outcome.js +1 -1
- package/dist/cli/runtime-compatibility-boundary.js +4 -4
- package/dist/cli/schema/registration.js +15 -15
- package/dist/cli/schema-registration-helpers.js +1 -1
- package/dist/cli/search-refresh.js +1 -1
- package/dist/cli/stats-analytics-json.js +1 -1
- package/dist/cli/telemetry-flush.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2UQU7HRR.js +9 -0
- package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
- package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +3 -0
- package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
- package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +2 -0
- package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
- package/dist/cli-bundle/chunks/chunk-AEOHUSUI.js +2289 -0
- package/dist/cli-bundle/chunks/chunk-BSRIVYTM.js +8 -0
- package/dist/cli-bundle/chunks/chunk-CFWLQFJM.js +71 -0
- package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
- package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +31 -0
- package/dist/cli-bundle/chunks/chunk-F2Z6XLZB.js +3 -0
- package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +2 -0
- package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +2 -0
- package/dist/cli-bundle/chunks/chunk-H7JEXRIN.js +6 -0
- package/dist/cli-bundle/chunks/chunk-J2PDAVBC.js +2 -0
- package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +33 -0
- package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +115 -0
- package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +2 -0
- package/dist/cli-bundle/chunks/chunk-O7JHS64G.js +3 -0
- package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +2 -0
- package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +2 -0
- package/dist/cli-bundle/chunks/chunk-OPJF254V.js +9 -0
- package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
- package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +2 -0
- package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +2 -0
- package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
- package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +125 -0
- package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
- package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +8 -0
- package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
- package/dist/cli-bundle/chunks/{item-revision-R5SZPJZ5.js → item-revision-FMD4KWBB.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +2 -0
- package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +2 -0
- package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-SPGPS3OS.js → register-list-query-L4IBU64P.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +21 -0
- package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +2 -0
- package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
- package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
- package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IROZDIDX.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +13 -0
- package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QQIIMMFU.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
- package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +27 -0
- package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +44 -0
- package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y2ESLKCF.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +102 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZHWPCVQL.js +78 -0
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
- package/dist/cli-bundle/focused-chunks/{item-revision-3V3UIP5X.js → item-revision-YDACCDVY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +2 -0
- package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
- package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +2 -0
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +5 -5
- 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 +72 -60
- 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 +13 -13
- package/dist/cli.js +1 -1
- package/dist/core/checkpoint/checkpoint-gc.js +1 -1
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
- package/dist/core/checkpoint/mutation-context.js +1 -1
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/extensions/activation-summary-markdown.js +2 -2
- package/dist/core/extensions/activation-summary.js +1 -1
- package/dist/core/extensions/activation-transaction.js +1 -1
- package/dist/core/extensions/capability-usage.js +1 -1
- package/dist/core/extensions/command-hook-context.js +1 -1
- package/dist/core/extensions/command-metadata-contract.js +1 -1
- package/dist/core/extensions/command-visibility-tier.js +1 -1
- package/dist/core/extensions/contribution-inventory.js +1 -1
- package/dist/core/extensions/exporter-output-contract.js +1 -1
- package/dist/core/extensions/extension-candidate.js +1 -1
- package/dist/core/extensions/extension-capability-aliases.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-policy.js +1 -1
- package/dist/core/extensions/extension-registries.js +1 -1
- package/dist/core/extensions/extension-runtime-helpers.js +1 -1
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/flag-definition-validation.js +1 -1
- package/dist/core/extensions/flag-value-types.js +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/item-field-types.js +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/manifest-parser.js +1 -1
- package/dist/core/extensions/manifest-schema.js +1 -1
- package/dist/core/extensions/module-graph-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor.js +1 -1
- package/dist/core/extensions/preflight-ownership.js +1 -1
- package/dist/core/extensions/read-output-contract.js +1 -1
- package/dist/core/extensions/registration-contracts.js +1 -1
- package/dist/core/extensions/registration-validation.js +1 -1
- package/dist/core/extensions/registration-values.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/extensions/runtime-registrations.js +1 -1
- package/dist/core/extensions/service-ownership.js +1 -1
- package/dist/core/extensions/version-compat.js +1 -1
- package/dist/core/extensions/version-diagnostics.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.js +2 -2
- package/dist/core/fs/host-environment-errors.js +1 -1
- package/dist/core/fs/index.js +1 -1
- package/dist/core/fs/path-utils.js +1 -1
- package/dist/core/governance/content-fields.js +1 -1
- package/dist/core/governance/issue-codes.js +1 -1
- package/dist/core/governance/metadata-coverage.js +1 -1
- package/dist/core/history/bridge.js +2 -0
- package/dist/core/history/digest.js +1 -1
- package/dist/core/history/drift-cache.js +3 -3
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/event-classification.js +1 -1
- package/dist/core/history/event-index.js +11 -11
- package/dist/core/history/history-compact-bulk.js +1 -1
- package/dist/core/history/history-diff.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history-storage-stats.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/identity.js +1 -1
- package/dist/core/history/index.js +1 -1
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.d.ts +9 -0
- 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.js +2 -2
- package/dist/core/history/tombstone.js +1 -1
- package/dist/core/history/version-address.js +1 -1
- package/dist/core/history/workspace-history.js +2 -2
- package/dist/core/io/body-file.js +1 -1
- package/dist/core/io/bulk-ids-input.js +2 -2
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/item/deferred-fields.js +1 -1
- package/dist/core/item/dependency-reference.js +1 -1
- package/dist/core/item/id.js +1 -1
- package/dist/core/item/index.js +1 -1
- package/dist/core/item/item-format-version.js +1 -1
- package/dist/core/item/item-format.js +7 -7
- package/dist/core/item/item-record.js +1 -1
- package/dist/core/item/item-type-definition.js +1 -1
- package/dist/core/item/literal-mutation-input.js +1 -1
- package/dist/core/item/parent-reference-policy.js +1 -1
- package/dist/core/item/parse.js +8 -8
- package/dist/core/item/plan-lifecycle.js +1 -1
- package/dist/core/item/priority.js +1 -1
- package/dist/core/item/sprint-release-format.js +1 -1
- package/dist/core/item/status-filter.js +1 -1
- package/dist/core/item/status.js +1 -1
- package/dist/core/item/toon-decode.js +1 -1
- package/dist/core/item/type-registry.js +1 -1
- package/dist/core/item/type-synonyms.js +1 -1
- package/dist/core/lock/index.js +1 -1
- package/dist/core/lock/lock-confinement.js +1 -1
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.js +1 -1
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/linked-test-projection.js +5 -5
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output-control.js +1 -1
- package/dist/core/output/output.js +19 -19
- package/dist/core/output/query-summary.js +1 -1
- package/dist/core/output/tabular.js +3 -3
- package/dist/core/packages/manifest.js +1 -1
- package/dist/core/packages/root.js +1 -1
- package/dist/core/policy/workflow-policy-schema.js +1 -1
- package/dist/core/policy/workflow-policy-store.js +1 -1
- package/dist/core/policy/workflow-policy.js +1 -1
- package/dist/core/profile/profile-describe.js +1 -1
- package/dist/core/profile/profile-lint.d.ts +1 -1
- package/dist/core/profile/profile-lint.js +1 -1
- package/dist/core/profile/profile-plan.js +1 -1
- package/dist/core/profile/profile-presets.js +4 -4
- package/dist/core/reproducibility/context.js +1 -1
- package/dist/core/schema/fields-file.js +2 -2
- package/dist/core/schema/item-types-file.js +2 -2
- package/dist/core/schema/runtime-field-filters.js +1 -1
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/schema/runtime-schema.js +2 -2
- package/dist/core/schema/status-defs-file.js +2 -2
- package/dist/core/schema/status-token.js +1 -1
- package/dist/core/schema/type-inference.js +1 -1
- package/dist/core/schema/type-presets.js +1 -1
- package/dist/core/schema/type-workflows.js +1 -1
- package/dist/core/search/background-refresh.js +2 -2
- package/dist/core/search/bm25.js +1 -1
- package/dist/core/search/cache.js +2 -2
- package/dist/core/search/corpus.js +1 -1
- package/dist/core/search/embedding-batches.js +1 -1
- package/dist/core/search/eval-thresholds.js +1 -1
- package/dist/core/search/eval.js +1 -1
- package/dist/core/search/http-client.js +1 -1
- package/dist/core/search/providers.js +1 -1
- package/dist/core/search/relevance.js +1 -1
- package/dist/core/search/semantic-defaults.js +1 -1
- package/dist/core/search/staleness.js +1 -1
- package/dist/core/search/vector-stores.js +2 -2
- package/dist/core/search/vectorization-metadata.js +1 -1
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/sentry/sensitive-assignments.js +1 -1
- package/dist/core/session/session-state.js +1 -1
- package/dist/core/shared/agent-session-context.js +1 -1
- package/dist/core/shared/author.js +5 -5
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/command-types.js +0 -1
- package/dist/core/shared/conflict-markers.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/error-details.js +1 -1
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/html-entity-decode.js +1 -1
- package/dist/core/shared/index.js +1 -1
- package/dist/core/shared/item-metadata-contract.js +1 -1
- package/dist/core/shared/lazy-module.js +1 -1
- package/dist/core/shared/levenshtein.js +1 -1
- package/dist/core/shared/memo.js +1 -1
- package/dist/core/shared/numeric-parsers.js +1 -1
- package/dist/core/shared/option-alias-visibility.js +1 -1
- package/dist/core/shared/output-unicode.js +1 -1
- package/dist/core/shared/primitives.js +1 -1
- package/dist/core/shared/process-tree.js +2 -2
- package/dist/core/shared/secret-rules.js +5 -5
- package/dist/core/shared/serial-queue.js +1 -1
- package/dist/core/shared/serialization.js +1 -1
- package/dist/core/shared/split-comma-list.js +1 -1
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/time.js +2 -2
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/core/store/index.js +1 -1
- package/dist/core/store/item-format-migration.js +1 -1
- package/dist/core/store/item-metadata-cache.js +1 -1
- package/dist/core/store/item-metadata-query-index.js +11 -11
- package/dist/core/store/item-metadata-read-work.js +1 -1
- package/dist/core/store/item-mutation-precondition.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/paths.js +1 -1
- package/dist/core/store/settings-concurrency.js +1 -1
- package/dist/core/store/settings-read-cache.js +1 -1
- package/dist/core/store/settings-sections.js +2 -2
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.d.ts +3 -1
- package/dist/core/store/settings.js +6 -6
- package/dist/core/store/sqlite-runtime.js +1 -1
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/core/store/transaction-coordinator-scope.js +1 -1
- package/dist/core/telemetry/consent.js +3 -3
- package/dist/core/telemetry/observability.js +1 -1
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/read-sampling.js +2 -2
- package/dist/core/telemetry/runtime.js +9 -9
- package/dist/core/test/background-runs.js +4 -4
- package/dist/core/test/item-test-run-tracking.js +1 -1
- package/dist/core/test/run-selectors.js +1 -1
- package/dist/core/validate/estimate-defaults.js +1 -1
- package/dist/core/validate/fix-planning.js +1 -1
- package/dist/core/validate/linked-artifact-reference.js +1 -1
- package/dist/core/validate/missing-by-type.js +1 -1
- package/dist/core/validate/missing-link-owners.js +1 -1
- package/dist/core/validate/stale-file-classification.js +1 -1
- package/dist/mcp/http-server.js +5 -5
- package/dist/mcp/legacy-adapter.js +1 -1
- package/dist/mcp/runtime-capabilities.js +1 -1
- package/dist/mcp/server.js +4 -4
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/actionability.js +1 -1
- package/dist/sdk/agent/closed-domain-contracts.js +1 -1
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/agent/create-option-policy.js +1 -1
- package/dist/sdk/agent/identity-config.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent/linked-resource-recovery.js +1 -1
- package/dist/sdk/agent/refusal-closure-census.js +2 -2
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent/subcommand-recovery.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +3 -3
- package/dist/sdk/agent-session-context.js +1 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/author-attribution.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/commander-types.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
- package/dist/sdk/cli-contracts/string-lists.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- 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/cli-contracts/typed-action-inputs.js +0 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/cli-program.js +1 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/compile-cache.js +1 -1
- package/dist/sdk/completion/bash.js +2 -2
- package/dist/sdk/completion/fish.js +74 -73
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +77 -76
- package/dist/sdk/completion.js +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/context/recency.js +1 -1
- package/dist/sdk/context/semantic-session-attribution.js +1 -1
- package/dist/sdk/context/usage-egress.js +1 -1
- package/dist/sdk/context/usage-ledger.js +6 -6
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/context-intent-runtime.js +1 -1
- package/dist/sdk/context-packing.js +1 -1
- package/dist/sdk/context-relevance.js +1 -1
- package/dist/sdk/context-signal-store.js +2 -2
- package/dist/sdk/context-usage.js +1 -1
- package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/dependency-flag-validation.js +1 -1
- package/dist/sdk/dependency-provenance.js +1 -1
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/duplicates.js +1 -1
- package/dist/sdk/environment/host-environment-errors.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
- package/dist/sdk/environment/source-context.js +1 -1
- package/dist/sdk/environment/tracker-preflight.js +1 -1
- package/dist/sdk/error-code-catalog.js +1 -1
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/eval.js +1 -1
- package/dist/sdk/extension/author-manifest.js +1 -1
- package/dist/sdk/extension/bundled-catalog.js +1 -1
- package/dist/sdk/extension/command-options.js +1 -1
- package/dist/sdk/extension/concurrency.js +1 -1
- package/dist/sdk/extension/copy-scope.js +1 -1
- package/dist/sdk/extension/custom-field-collisions.js +1 -1
- package/dist/sdk/extension/describe.js +3 -3
- package/dist/sdk/extension/doctor.js +1 -1
- package/dist/sdk/extension/install-plan.js +1 -1
- package/dist/sdk/extension/install-receipts.js +1 -1
- package/dist/sdk/extension/install-runtime.js +3 -3
- package/dist/sdk/extension/install-snapshot.js +1 -1
- package/dist/sdk/extension/install-sources.js +5 -5
- package/dist/sdk/extension/managed-state.js +2 -2
- package/dist/sdk/extension/managed-update-status.js +1 -1
- package/dist/sdk/extension/migrations.js +2 -2
- package/dist/sdk/extension/native-command-options.js +1 -1
- package/dist/sdk/extension/output-ownership.js +1 -1
- package/dist/sdk/extension/runtime-summary.js +1 -1
- package/dist/sdk/extension/scaffold.js +11 -11
- package/dist/sdk/extension/shared.js +1 -1
- package/dist/sdk/extension/source-resolution.js +1 -1
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/extension/update-check.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/extension-contracts.js +1 -1
- package/dist/sdk/extension.js +1 -1
- package/dist/sdk/files.js +1 -1
- package/dist/sdk/flag-invocation-contracts.js +1 -1
- package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
- 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/generated-error-code-catalog.js +1 -1
- package/dist/sdk/governance/assurance-action-contracts.js +0 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance-limits.js +1 -1
- package/dist/sdk/governance/assurance-mutation-error.js +1 -1
- package/dist/sdk/governance/assurance-presets.js +1 -1
- package/dist/sdk/governance/assurance-runtime.js +1 -1
- package/dist/sdk/governance/assurance.js +4 -4
- package/dist/sdk/governance/boundary-fixtures.js +1 -1
- package/dist/sdk/governance/closure-timestamps.js +1 -1
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
- package/dist/sdk/governance/defect-recurrence.js +2 -2
- package/dist/sdk/governance/extension-host-version.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/projection.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/governance/hierarchy-validation.js +1 -1
- package/dist/sdk/governance/in-progress-work-health.js +1 -1
- package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
- package/dist/sdk/governance/linked-file-report.js +1 -1
- package/dist/sdk/governance/merge-receipt-history.js +1 -1
- package/dist/sdk/governance/provenance-health.js +4 -4
- package/dist/sdk/governance/reindex.js +5 -5
- package/dist/sdk/governance/stale-work.js +1 -1
- package/dist/sdk/governance/status-role-diagnostics.js +1 -1
- package/dist/sdk/governance/storage-integrity.js +1 -1
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
- package/dist/sdk/governance/upgrade.js +2 -2
- package/dist/sdk/governance/validate-deferred-fields.js +1 -1
- package/dist/sdk/governance/validate-history-drift.js +1 -1
- package/dist/sdk/governance/validate-item-reader.js +1 -1
- package/dist/sdk/governance/validate-normalization.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workflow-completeness.js +1 -1
- package/dist/sdk/governance/workflow-policy.js +3 -3
- package/dist/sdk/governance/workspace-position.js +2 -2
- package/dist/sdk/graph/analytics.js +1 -1
- package/dist/sdk/graph/assembly.js +1 -1
- package/dist/sdk/graph/cache.js +1 -1
- package/dist/sdk/graph/cardinality-integrity.js +1 -1
- package/dist/sdk/graph/centrality.js +1 -1
- package/dist/sdk/graph/deadline-scheduling.js +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -1
- package/dist/sdk/graph/governance-contracts.js +1 -1
- package/dist/sdk/graph/governance.js +1 -1
- package/dist/sdk/graph/hierarchy-integrity.js +1 -1
- package/dist/sdk/graph/lifecycle-coverage.js +1 -1
- package/dist/sdk/graph/mutation-advisory.js +1 -1
- package/dist/sdk/graph/query-contracts.js +1 -1
- package/dist/sdk/graph/remediation.js +1 -1
- package/dist/sdk/graph/run.js +1 -1
- package/dist/sdk/graph/scheduling.js +1 -1
- package/dist/sdk/graph/traversal.js +1 -1
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/guide.js +7 -7
- 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/attestation-command.js +2 -2
- package/dist/sdk/history/attestation-contract.js +1 -1
- package/dist/sdk/history/attestation-scan.js +1 -1
- package/dist/sdk/history/attestation.js +1 -1
- 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/subject.js +1 -1
- package/dist/sdk/history-analytics.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-mcp.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/history-read.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/improvement-ledger-validation.js +1 -1
- package/dist/sdk/improvement-ledger.js +2 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/init-agent-guidance.js +10 -10
- package/dist/sdk/init.js +14 -14
- package/dist/sdk/invocation-author.js +1 -1
- package/dist/sdk/item-children.js +1 -1
- package/dist/sdk/item-metadata-index.js +1 -1
- package/dist/sdk/item-schedule.js +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/append.js +3 -3
- package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/cli-input.js +1 -1
- package/dist/sdk/lifecycle/close-many.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/copy.js +1 -1
- package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
- package/dist/sdk/lifecycle/core-item-fields.js +1 -1
- package/dist/sdk/lifecycle/create-deferrals.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/delete.js +1 -1
- package/dist/sdk/lifecycle/dependency-removal.js +1 -1
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
- package/dist/sdk/lifecycle/focus.js +1 -1
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
- package/dist/sdk/lifecycle/item-revision.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
- package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
- package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
- package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
- package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
- package/dist/sdk/lifecycle/release-handoff.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
- package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/start-blockers.js +1 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/lifecycle/workflow-transition.js +1 -1
- package/dist/sdk/lifecycle-completion.js +1 -1
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/linked-artifacts.js +2 -2
- package/dist/sdk/mcp/apps.js +5 -5
- package/dist/sdk/mcp/authorization.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/mcp/executable.js +4 -4
- package/dist/sdk/mcp/interactions.js +1 -1
- package/dist/sdk/mcp/protocol.js +1 -1
- package/dist/sdk/mcp/skills.js +3 -3
- package/dist/sdk/mcp/subscriptions.js +1 -1
- package/dist/sdk/mcp/tasks.js +2 -2
- package/dist/sdk/mcp/transport.js +1 -1
- package/dist/sdk/merge/abandoned-receipts.js +1 -1
- package/dist/sdk/merge/driver.js +7 -7
- package/dist/sdk/merge/history-scalar-rebase.js +1 -1
- package/dist/sdk/merge/ignored-artifacts.js +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
- package/dist/sdk/merge/install.js +6 -6
- package/dist/sdk/merge/receipt-file-boundary.js +1 -1
- package/dist/sdk/merge/receipt-operation.js +1 -1
- package/dist/sdk/merge/receipt-schema.js +1 -1
- package/dist/sdk/merge/receipts.js +4 -4
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/settlement-hook.js +4 -4
- package/dist/sdk/merge/stage.js +1 -1
- package/dist/sdk/merge/three-way.d.ts +22 -3
- package/dist/sdk/merge/three-way.js +9 -3
- package/dist/sdk/merge/worktree-config.js +2 -2
- package/dist/sdk/merge.js +1 -1
- package/dist/sdk/mutation-events.js +1 -1
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/output/fit-envelope.js +1 -1
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output-contracts.js +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/output-token-accounting.js +1 -1
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/package-migrations.js +1 -1
- package/dist/sdk/package-runtime-options.js +1 -1
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/profile.js +5 -5
- package/dist/sdk/provenance.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/aggregate.js +1 -1
- package/dist/sdk/query/calendar.js +4 -4
- package/dist/sdk/query/complete-list.js +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/declared-blockers.js +1 -1
- package/dist/sdk/query/duplicate-candidates.js +1 -1
- package/dist/sdk/query/get-facet-roots.js +1 -1
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/item-filter-options.js +0 -1
- package/dist/sdk/query/light-metadata.js +1 -1
- package/dist/sdk/query/list-filter-shared.js +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/multi-value-filters.js +1 -1
- package/dist/sdk/query/next-ranking-policy.js +1 -1
- package/dist/sdk/query/next-ready-budget.js +1 -1
- package/dist/sdk/query/next.js +2 -2
- package/dist/sdk/query/parsers.js +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/query/search/corpus.js +2 -2
- package/dist/sdk/query/search/filters.js +1 -1
- package/dist/sdk/query/search/input.js +1 -1
- package/dist/sdk/query/search/lexical.js +1 -1
- package/dist/sdk/query/search/response.js +1 -1
- package/dist/sdk/query/search/semantic.js +3 -3
- package/dist/sdk/query/search/types.js +0 -1
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/query/search-pagination.js +1 -1
- package/dist/sdk/query/search-rendering.js +1 -1
- package/dist/sdk/query/search.js +1 -1
- package/dist/sdk/query/window-pagination.js +1 -1
- package/dist/sdk/query/workspace-contracts.js +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/extension.js +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/positional-rows.js +1 -1
- package/dist/sdk/read-output/provenance.js +1 -1
- package/dist/sdk/read-output/session-result.js +0 -1
- package/dist/sdk/read-output/surfaces.js +1 -1
- package/dist/sdk/read-output/tail-retention.js +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.js +1 -1
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-analytics.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/relationship-history.js +6 -6
- package/dist/sdk/relationship-kinds/contract.js +1 -1
- package/dist/sdk/relationships.js +1 -1
- package/dist/sdk/reproducibility/process.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime/context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.js +1 -1
- package/dist/sdk/runtime/mutation-value-validation.js +1 -1
- package/dist/sdk/runtime/schema-preview.js +1 -1
- package/dist/sdk/runtime/schema.js +1 -1
- package/dist/sdk/runtime-action-aliases.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/sdk/runtime-input.d.ts +8 -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-public-contracts.js +0 -1
- package/dist/sdk/runtime-stats-options.js +1 -1
- package/dist/sdk/runtime.d.ts +9 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/scheduling-shortcuts.js +1 -1
- package/dist/sdk/schema/field-option-collisions.js +2 -0
- package/dist/sdk/schema-migration.js +4 -4
- package/dist/sdk/schema.js +7 -7
- package/dist/sdk/search-refresh-worker.js +1 -1
- package/dist/sdk/similarity-scoring.js +1 -1
- package/dist/sdk/similarity.js +1 -1
- package/dist/sdk/start-task-status.js +1 -1
- package/dist/sdk/stats.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +5 -5
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/telemetry-flush.js +1 -1
- package/dist/sdk/telemetry.js +4 -4
- package/dist/sdk/templates.js +3 -3
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/command-args.js +1 -1
- package/dist/sdk/test/command-resolution.js +2 -2
- package/dist/sdk/test/entry.js +2 -2
- package/dist/sdk/test/execution-receipts.js +2 -2
- package/dist/sdk/test/execution.js +5 -5
- package/dist/sdk/test/json-path.js +1 -1
- package/dist/sdk/test/linked-command-detection.js +1 -1
- package/dist/sdk/test/measurements.js +1 -1
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/sdk/test/prerequisites.js +1 -1
- package/dist/sdk/test/receipt-index-snapshot.js +1 -1
- package/dist/sdk/test/run-phases.js +1 -1
- package/dist/sdk/test/runs.js +1 -1
- package/dist/sdk/test/trust.js +2 -2
- package/dist/sdk/test/update.js +1 -1
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
- package/dist/sdk/traceability/source-traceability.js +2 -2
- package/dist/sdk/tracker-root-discovery.js +1 -1
- package/dist/sdk/transactions/item-finalization.js +2 -0
- package/dist/sdk/workspace-contracts-cache.js +1 -1
- package/dist/sdk/workspace-contracts.js +1 -1
- package/dist/sdk/workspace-memory.js +2 -2
- package/dist/sdk/workspace-snapshot.js +5 -5
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/sdk/workspace.js +6 -6
- package/dist/types/index.js +1 -1
- 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 +7 -3
- package/docs/EXTENSIONS.md +1 -1
- package/docs/HISTORY_RECOVERY.md +229 -5
- package/docs/README.md +2 -2
- package/docs/SDK.md +174 -5
- package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
- package/marketplace.json +1 -1
- package/node_modules/tar/package.json +2 -3
- package/package.json +31 -2
- 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/scripts/finalize-build.mjs +63 -24
- package/scripts/prepare-build-cache.mjs +28 -1
- package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +0 -21
- package/dist/cli-bundle/chunks/chunk-5647LU3A.js +0 -2287
- package/dist/cli-bundle/chunks/chunk-6QLEXRUG.js +0 -9
- package/dist/cli-bundle/chunks/chunk-AHQB7W2H.js +0 -3
- package/dist/cli-bundle/chunks/chunk-BKSVHOWI.js +0 -2
- package/dist/cli-bundle/chunks/chunk-CASX6SFI.js +0 -2
- package/dist/cli-bundle/chunks/chunk-CIKGG34F.js +0 -2
- package/dist/cli-bundle/chunks/chunk-D6ILFXZY.js +0 -2
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IUIOTAF6.js +0 -9
- package/dist/cli-bundle/chunks/chunk-JVGRFU5H.js +0 -3
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
- package/dist/cli-bundle/chunks/chunk-KVBIMFUG.js +0 -6
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
- package/dist/cli-bundle/chunks/chunk-NCFCBKIP.js +0 -2
- package/dist/cli-bundle/chunks/chunk-NT5AKFE5.js +0 -31
- package/dist/cli-bundle/chunks/chunk-PJXKA4QU.js +0 -125
- package/dist/cli-bundle/chunks/chunk-RMIRNYRG.js +0 -71
- package/dist/cli-bundle/chunks/chunk-RULHZRFN.js +0 -2
- package/dist/cli-bundle/chunks/chunk-S6HB3WL2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SA4BNP3Q.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SRVTCYAU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-WELSVDPU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XHJ3H5PL.js +0 -3
- package/dist/cli-bundle/chunks/chunk-XWHJIRNV.js +0 -8
- package/dist/cli-bundle/chunks/chunk-YJEBK7HU.js +0 -8
- package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +0 -115
- package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
- package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
- package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
- package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +0 -2
- package/dist/cli-bundle/chunks/mutation-actor-3TG636XG.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-LICSDNNO.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-WWVECKFQ.js +0 -21
- package/dist/cli-bundle/chunks/register-operations-L6HFJNWD.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-K7UFG5TD.js +0 -2
- package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
- package/dist/cli-bundle/chunks/stage-57KH3KAC.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
- package/dist/cli-bundle/focused-chunks/chunk-532WZV65.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-7A4QWNZX.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-CU2BRAOX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CWWKRI5P.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HGFNL5XI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IQK5NPMG.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-J63D6QST.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-JMQJBZQ5.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LNHUE4VV.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-MKM5NKD7.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-NP72ZDXE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-QGKLRXP7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QSJW6NSQ.js +0 -66
- package/dist/cli-bundle/focused-chunks/chunk-RPE6IX26.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-UOC6257J.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-URJ2E6AS.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-WXMI4AV5.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-XCJSHNXK.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-XQQSSKJI.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-YOAYY3HE.js +0 -2
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
- package/dist/cli-bundle/focused-chunks/item-transaction-HLBW7B3J.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-actor-62HKR5IO.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-X4PF2SG3.js +0 -2
- package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
- package/dist/cli-bundle/focused-chunks/stage-O7T7CXBB.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/PERFORMANCE.md +0 -204
|
@@ -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]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{getActiveExtensionRegistrations,hasActiveOnReadHooks,runActiveOnReadHooks}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{parseItemDocument}from"../item/item-format.js";import{evictOldestMemoEntries}from"../shared/memo.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{ITEM_FILE_EXTENSIONS,getItemFormatFromPath}from"./paths.js";import{rebuildItemMetadataQueryIndex,removeItemMetadataQueryIndex,updateItemMetadataQueryIndex}from"./item-metadata-query-index.js";const CACHE_VERSION=8,DEFAULT_DERIVED_INDEX_MINIMUM_ITEMS=500,DERIVED_INDEX_LOCK_ID="metadata-derived-index",CACHE_FILENAME="metadata-cache.json",BODY_CACHE_FILENAME="metadata-cache-bodies.json",COLLECTIONS_CACHE_FILENAME="metadata-cache-collections.json",DELTA_CACHE_FILENAME="metadata-cache-delta.json",MANIFEST_CACHE_FILENAME="metadata-cache-manifest.json",MAX_CACHE_CONTEXTS=4,HEAVY_METADATA_KEYS=["comments","notes","learnings","files","tests","test_runs","docs"];function resolveActiveExtensionFieldNames(){return collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function splitHeavyMetadata(metadata){const light={...metadata},heavy={};for(const key of HEAVY_METADATA_KEYS)key in light&&(heavy[key]=light[key],delete light[key]);return{light,heavy}}function mergeHeavyMetadata(light,heavy){return!heavy||Object.keys(heavy).length===0?light:{...light,...heavy}}function computeContextFingerprint(preferredFormat,typeToFolder,schema,extensionFieldNames){const hash=createHash("sha256");hash.update(`format:${preferredFormat??"default"}`);const sortedTypes=Object.entries(typeToFolder).sort(([a],[b])=>a.localeCompare(b)).map(([type,folder])=>`${type}=${folder}`).join(",");return hash.update(`|types:${sortedTypes}`),schema&&hash.update(`|schema:${JSON.stringify(schema)}`),extensionFieldNames.length>0&&hash.update(`|extension_fields:${extensionFieldNames.join(",")}`),hash.digest("hex").slice(0,16)}function getCachePath(pmRoot){return path.join(pmRoot,"runtime",CACHE_FILENAME)}function getBodyCachePath(pmRoot){return path.join(pmRoot,"runtime",BODY_CACHE_FILENAME)}function getCollectionsCachePath(pmRoot){return path.join(pmRoot,"runtime",COLLECTIONS_CACHE_FILENAME)}function getDeltaCachePath(pmRoot){return path.join(pmRoot,"runtime",DELTA_CACHE_FILENAME)}function getManifestCachePath(pmRoot){return path.join(pmRoot,"runtime",MANIFEST_CACHE_FILENAME)}function getContextCachePath(cachePath,contextFingerprint){const extension=path.extname(cachePath);return`${cachePath.slice(0,-extension.length)}.${contextFingerprint}${extension}`}const ENVELOPE_MEMO_MAX_ENTRIES=24,envelopeMemo=new Map,projectedBaseCursor=new WeakMap;function baseCursorFor(envelope){return projectedBaseCursor.get(envelope)??envelope.source_cursor}function applyMetadataDelta(envelope,delta){const baseCursor=baseCursorFor(envelope);if(!(delta.base_source_cursor!==baseCursor||envelope.source_cursor===delta.source_cursor)){projectedBaseCursor.set(envelope,baseCursor);for(const[relativePath,change]of Object.entries(delta.changes))change.entry?envelope.entries[relativePath]=change.entry:delete envelope.entries[relativePath];envelope.directory_signatures=delta.directory_signatures,envelope.source_cursor=delta.source_cursor}}function applyBodyDelta(envelope,delta){if(!envelope)return;const baseCursor=baseCursorFor(envelope);if(!(delta.base_source_cursor!==baseCursor||envelope.source_cursor===delta.source_cursor)){projectedBaseCursor.set(envelope,baseCursor);for(const[relativePath,change]of Object.entries(delta.changes))change.body?envelope.bodies[relativePath]=change.body:delete envelope.bodies[relativePath];envelope.source_cursor=delta.source_cursor}}function applyCollectionsDelta(envelope,delta){if(!envelope)return;const baseCursor=baseCursorFor(envelope);if(!(delta.base_source_cursor!==baseCursor||envelope.source_cursor===delta.source_cursor)){projectedBaseCursor.set(envelope,baseCursor);for(const[relativePath,change]of Object.entries(delta.changes))change.collections?envelope.collections[relativePath]=change.collections:delete envelope.collections[relativePath];envelope.source_cursor=delta.source_cursor}}function applyDerivedIndexDelta(metadata,bodies,collections,delta){!metadata||!delta||metadata.context_fingerprint!==delta.context_fingerprint||(applyMetadataDelta(metadata,delta),applyBodyDelta(bodies,delta),applyCollectionsDelta(collections,delta))}function memoizeEnvelope(cachePath,entry){envelopeMemo.size>=ENVELOPE_MEMO_MAX_ENTRIES&&!envelopeMemo.has(cachePath)&&evictOldestMemoEntries(envelopeMemo),envelopeMemo.set(cachePath,entry)}async function loadEnvelopeMemoized(cachePath,parse){let stat;try{stat=await fs.stat(cachePath)}catch{return envelopeMemo.delete(cachePath),null}const memoized=envelopeMemo.get(cachePath);if(memoized&&statMatches(memoized.signature,stat.mtimeMs,stat.ctimeMs,stat.size))return envelopeMemo.delete(cachePath),envelopeMemo.set(cachePath,memoized),memoized.envelope;let envelope;try{envelope=parse(await fs.readFile(cachePath,"utf8"))}catch{envelope=null}return memoizeEnvelope(cachePath,{signature:{mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size},envelope}),envelope}function clearItemMetadataEnvelopeMemo(){envelopeMemo.clear()}async function loadCache(pmRoot,contextFingerprint,diagnostics){const parse=raw=>{const parsed=JSON.parse(raw);return parsed.version!==CACHE_VERSION||typeof parsed.source_cursor!="string"||typeof parsed.entries!="object"||parsed.entries===null?null:parsed},cachePath=getCachePath(pmRoot),active=await loadEnvelopeMemoized(cachePath,parse);if(!contextFingerprint||active===null||active.context_fingerprint===contextFingerprint)return active;const retained=await loadEnvelopeMemoized(getContextCachePath(cachePath,contextFingerprint),parse);return retained===null&&appendWarning(diagnostics,`metadata_cache_context_changed:${active.context_fingerprint}->${contextFingerprint}`),retained}async function loadBodyCache(pmRoot,contextFingerprint){const parse=raw=>{const parsed=JSON.parse(raw);return parsed.version!==CACHE_VERSION||typeof parsed.source_cursor!="string"||typeof parsed.bodies!="object"||parsed.bodies===null?null:parsed},cachePath=getBodyCachePath(pmRoot),active=await loadEnvelopeMemoized(cachePath,parse);return contextFingerprint&&active?.context_fingerprint!==contextFingerprint?await loadEnvelopeMemoized(getContextCachePath(cachePath,contextFingerprint),parse):active}async function loadCollectionsCache(pmRoot,contextFingerprint){const parse=raw=>{const parsed=JSON.parse(raw);return parsed.version!==CACHE_VERSION||typeof parsed.source_cursor!="string"||typeof parsed.collections!="object"||parsed.collections===null?null:parsed},cachePath=getCollectionsCachePath(pmRoot),active=await loadEnvelopeMemoized(cachePath,parse);return contextFingerprint&&active?.context_fingerprint!==contextFingerprint?await loadEnvelopeMemoized(getContextCachePath(cachePath,contextFingerprint),parse):active}async function loadDerivedIndexDelta(pmRoot){const deltaPath=getDeltaCachePath(pmRoot),envelope=await loadEnvelopeMemoized(deltaPath,raw=>{const parsed=JSON.parse(raw);return parsed.version!==CACHE_VERSION||typeof parsed.base_source_cursor!="string"||typeof parsed.source_cursor!="string"||typeof parsed.changes!="object"||parsed.changes===null?null:parsed});if(envelope)return{envelope,invalid:!1};try{return await fs.stat(deltaPath),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function loadDerivedIndexManifest(pmRoot){const manifestPath=getManifestCachePath(pmRoot),manifest=await loadEnvelopeMemoized(manifestPath,raw=>{const parsed=JSON.parse(raw);return parsed.version!==CACHE_VERSION||typeof parsed.context_fingerprint!="string"||typeof parsed.source_cursor!="string"||!Number.isInteger(parsed.entry_count)||parsed.entry_count<0||typeof parsed.directory_signatures!="object"||parsed.directory_signatures===null?null:parsed});if(manifest)return manifest;try{await fs.stat(manifestPath),await removeDerivedIndexFiles(pmRoot)}catch{}return null}async function persistCache(cachePath,envelope){await fs.mkdir(path.dirname(cachePath),{recursive:!0}),await writeFileAtomic(cachePath,JSON.stringify(envelope));try{const stat=await fs.stat(cachePath);memoizeEnvelope(cachePath,{signature:{mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size},envelope})}catch{envelopeMemo.delete(cachePath)}const pmRoot=path.dirname(path.dirname(cachePath));if(cachePath===getCachePath(pmRoot)||cachePath===getBodyCachePath(pmRoot)||cachePath===getCollectionsCachePath(pmRoot)){const contextPath=getContextCachePath(cachePath,envelope.context_fingerprint);await writeFileAtomic(contextPath,JSON.stringify(envelope));try{const contextStat=await fs.stat(contextPath);memoizeEnvelope(contextPath,{signature:{mtime_ms:contextStat.mtimeMs,ctime_ms:contextStat.ctimeMs,size:contextStat.size},envelope})}catch{envelopeMemo.delete(contextPath)}const directory=path.dirname(cachePath),extension=path.extname(cachePath),stem=path.basename(cachePath,extension),variants=(await fs.readdir(directory,{withFileTypes:!0}).catch(()=>[])).filter(entry=>entry.isFile()&&entry.name!==path.basename(cachePath)&&entry.name.startsWith(`${stem}.`)&&entry.name.endsWith(extension)).map(entry=>path.join(directory,entry.name));if(variants.length>MAX_CACHE_CONTEXTS){const byAge=(await Promise.all(variants.map(async variantPath=>{try{return{path:variantPath,mtime:(await fs.stat(variantPath)).mtimeMs}}catch{return null}}))).filter(entry=>entry!==null);for(const stale of byAge.sort((left,right)=>left.mtime-right.mtime).slice(0,Math.max(0,byAge.length-MAX_CACHE_CONTEXTS)))await fs.rm(stale.path,{force:!0}),envelopeMemo.delete(stale.path)}}}function shouldReplaceCachedDocumentCandidate(existingFormat,candidateFormat,preferredFormat){return preferredFormat?candidateFormat===preferredFormat&&existingFormat!==preferredFormat:candidateFormat==="toon"&&existingFormat!=="toon"}function shouldRecordCachedDocumentCandidate(existingFormat,candidateFormat,preferredFormat){return existingFormat===void 0||shouldReplaceCachedDocumentCandidate(existingFormat,candidateFormat,preferredFormat)}function appendWarning(warnings,warning){warnings&&!warnings.includes(warning)&&warnings.push(warning)}function statMatches(signature,mtimeMs,ctimeMs,size){return signature.mtime_ms===mtimeMs&&signature.ctime_ms===ctimeMs&&signature.size===size}async function readItemDirectoryFiles(pmRoot,folder,warnings){const dirPath=path.join(pmRoot,folder);try{const files=await fs.readdir(dirPath);return{folder,dirPath,files}}catch(error){return typeof error=="object"&&error!==null&&"code"in error&&!isFileMissingError(error)&&appendWarning(warnings,`item_list_directory_read_failed:${folder}`),{folder,dirPath,files:[]}}}async function readDirectorySignature(pmRoot,folder){try{const stat=await fs.stat(path.join(pmRoot,folder));return[folder,{exists:!0,mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size}]}catch{return[folder,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function readDirectorySignatures(pmRoot,folders){return Object.fromEntries(await Promise.all(folders.map(async folder=>await readDirectorySignature(pmRoot,folder))))}function directorySignaturesMatch(left,right){return!left||Object.keys(left).length!==Object.keys(right).length?!1:Object.entries(right).every(([folder,signature])=>{const previous=left[folder];return previous!==void 0&&previous.exists===signature.exists&&statMatches(previous,signature.mtime_ms,signature.ctime_ms,signature.size)})}function isItemDocumentFile(file){return ITEM_FILE_EXTENSIONS.some(ext=>file.toLowerCase().endsWith(ext))}function markDocumentCacheMisses(misses,includeBody,includeCollections,metadataCached,bodyCached,collectionsCached){metadataCached||(misses.metadata=!0),includeBody&&!bodyCached&&(misses.body=!0),includeCollections&&!collectionsCached&&(misses.collections=!0)}async function dispatchCachedDocumentReadHooks(filePath,warnings,dispatchReadHooks){if(dispatchReadHooks)for(const warning of await runActiveOnReadHooks({path:filePath,scope:"project"}))appendWarning(warnings,warning)}function selectHeavyMetadata(includeCollections,collectionsCached,cachedCollections,parsedCollections){if(includeCollections)return collectionsCached&&cachedCollections?cachedCollections.collections:parsedCollections}async function readCachedDocumentParts(filePath,relativePath,context){const stat=await fs.stat(filePath),mtimeMs=stat.mtimeMs,ctimeMs=stat.ctimeMs,{size}=stat,itemFormat=getItemFormatFromPath(filePath);await dispatchCachedDocumentReadHooks(filePath,context.warnings,context.dispatchReadHooks);const cachedEntry=context.previousEntries[relativePath],metadataCached=!context.forceSourceRead&&cachedEntry!==void 0&&statMatches(cachedEntry,mtimeMs,ctimeMs,size),cachedBody=context.previousBodies[relativePath],bodyCached=!context.forceSourceRead&&cachedBody!==void 0&&statMatches(cachedBody,mtimeMs,ctimeMs,size),cachedCollections=context.previousCollections[relativePath],collectionsCached=!context.forceSourceRead&&cachedCollections!==void 0&&statMatches(cachedCollections,mtimeMs,ctimeMs,size);if(!(!metadataCached||context.includeBody&&!bodyCached||context.includeCollections&&!collectionsCached))return{mtimeMs,ctimeMs,size,itemFormat,lightMetadata:cachedEntry.metadata,heavyMetadata:selectHeavyMetadata(context.includeCollections,collectionsCached,cachedCollections,void 0),bodyLength:cachedEntry.body_length,body:context.includeBody?cachedBody.body:void 0};const raw=await fs.readFile(filePath,"utf8"),parsed=parseItemDocument(raw,{format:itemFormat,schema:context.schema,extensionFieldNames:context.extensionFieldNames,onWarning:warning=>appendWarning(context.warnings,warning)}),split=splitHeavyMetadata(parsed.metadata);return markDocumentCacheMisses(context.state.misses,context.includeBody,context.includeCollections,metadataCached,bodyCached,collectionsCached),{mtimeMs,ctimeMs,size,itemFormat,lightMetadata:metadataCached?cachedEntry.metadata:split.light,heavyMetadata:selectHeavyMetadata(context.includeCollections,collectionsCached,cachedCollections,split.heavy),bodyLength:metadataCached?cachedEntry.body_length:parsed.body.length,body:context.includeBody?parsed.body:void 0}}function recordCachedDocumentCandidate(filePath,relativePath,context,parts){context.state.newEntries[relativePath]={mtime_ms:parts.mtimeMs,ctime_ms:parts.ctimeMs,size:parts.size,metadata:parts.lightMetadata,body_length:parts.bodyLength},context.includeBody&&parts.body!==void 0&&(context.state.newBodies[relativePath]={mtime_ms:parts.mtimeMs,ctime_ms:parts.ctimeMs,size:parts.size,body:parts.body}),context.includeCollections&&parts.heavyMetadata!==void 0&&(context.state.newCollections[relativePath]={mtime_ms:parts.mtimeMs,ctime_ms:parts.ctimeMs,size:parts.size,collections:parts.heavyMetadata});const metadata=context.includeCollections?mergeHeavyMetadata(parts.lightMetadata,parts.heavyMetadata):parts.lightMetadata,existing=context.state.documentsById.get(metadata.id),candidate={metadata,body:parts.body,item_format:parts.itemFormat,item_path:filePath};shouldRecordCachedDocumentCandidate(existing?.itemFormat,parts.itemFormat,context.preferredFormat)&&context.state.documentsById.set(metadata.id,{candidate,itemFormat:parts.itemFormat})}async function processCachedDocumentFile(folder,filePath,relativePath,context){try{const parts=await readCachedDocumentParts(filePath,relativePath,context);recordCachedDocumentCandidate(filePath,relativePath,context,parts)}catch{appendWarning(context.warnings,`item_list_item_read_failed:${folder}/${path.basename(filePath)}`)}}function selectPreviousMetadataEntries(existingCache,contextFingerprint){return existingCache&&existingCache.context_fingerprint===contextFingerprint?existingCache.entries:{}}function selectPreviousBodyEntries(existingBodyCache,contextFingerprint){return existingBodyCache&&existingBodyCache.context_fingerprint===contextFingerprint?existingBodyCache.bodies:{}}function selectPreviousCollectionEntries(existingCollectionsCache,contextFingerprint){return existingCollectionsCache&&existingCollectionsCache.context_fingerprint===contextFingerprint?existingCollectionsCache.collections:{}}function createDocumentCacheMutableState(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function processCachedDocumentFiles(dirResults,context){const parseTasks=[];for(const{folder,dirPath,files}of dirResults)for(const file of files){if(!isItemDocumentFile(file))continue;const filePath=path.join(dirPath,file),relativePath=path.relative(context.pmRoot,filePath);parseTasks.push(processCachedDocumentFile(folder,filePath,relativePath,context)),parseTasks.length===32&&(await Promise.all(parseTasks),parseTasks.length=0)}await Promise.all(parseTasks)}async function persistMetadataCacheIfNeeded(params){if(!(!(params.state.misses.metadata||Object.keys(params.previousEntries).length!==Object.keys(params.state.newEntries).length||!directorySignaturesMatch(params.existingCache?.directory_signatures,params.directorySignatures))&¶ms.existingCache!==null&¶ms.existingCache.context_fingerprint===params.contextFingerprint))try{await persistCache(getCachePath(params.pmRoot),{version:CACHE_VERSION,context_fingerprint:params.contextFingerprint,source_cursor:params.sourceCursor,directory_signatures:params.directorySignatures,entries:params.state.newEntries}),await persistCache(getManifestCachePath(params.pmRoot),{version:CACHE_VERSION,context_fingerprint:params.contextFingerprint,source_cursor:params.sourceCursor,entry_count:Object.keys(params.state.newEntries).length,directory_signatures:params.directorySignatures});const rows=[...params.state.documentsById.values()].map(({candidate})=>({relativePath:path.relative(params.pmRoot,candidate.item_path),metadata:splitHeavyMetadata(candidate.metadata).light,linkedFiles:candidate.metadata.files??[]}));rows.length>=params.minimumIndexedItems?await rebuildItemMetadataQueryIndex({pmRoot:params.pmRoot,contextFingerprint:params.contextFingerprint,sourceCursor:params.sourceCursor,rows}):await removeItemMetadataQueryIndex(params.pmRoot)}catch{}}async function persistBodyCacheIfNeeded(params){!(params.state.misses.body||Object.keys(params.previousBodies).length!==Object.keys(params.state.newBodies).length)&¶ms.existingBodyCache!==null&¶ms.existingBodyCache.context_fingerprint===params.contextFingerprint||await persistCache(getBodyCachePath(params.pmRoot),{version:CACHE_VERSION,context_fingerprint:params.contextFingerprint,source_cursor:params.sourceCursor,bodies:params.state.newBodies}).catch(()=>{})}async function persistCollectionsCacheIfNeeded(params){!(params.state.misses.collections||Object.keys(params.previousCollections).length!==Object.keys(params.state.newCollections).length)&¶ms.existingCollectionsCache!==null&¶ms.existingCollectionsCache.context_fingerprint===params.contextFingerprint||await persistCache(getCollectionsCachePath(params.pmRoot),{version:CACHE_VERSION,context_fingerprint:params.contextFingerprint,source_cursor:params.sourceCursor,collections:params.state.newCollections}).catch(()=>{})}async function acquireItemMetadataDerivedIndexLock(pmRoot,author,options={}){const cache=await loadDerivedIndexManifest(pmRoot);return options.required!==!0&&(cache===null||cache.entry_count<DEFAULT_DERIVED_INDEX_MINIMUM_ITEMS)?async()=>{}:acquireLock(pmRoot,DERIVED_INDEX_LOCK_ID,30,author,!1,!1,3e3)}async function readItemMetadataDerivedIndexState(pmRoot,folders){const manifest=await loadDerivedIndexManifest(pmRoot);if(manifest===null)return null;const delta=await loadDerivedIndexDelta(pmRoot);if(delta.invalid)return await removeDerivedIndexFiles(pmRoot),null;const effectiveCursor=delta.envelope?.context_fingerprint===manifest.context_fingerprint&&delta.envelope.base_source_cursor===manifest.source_cursor?delta.envelope.source_cursor:manifest.source_cursor,effectiveDirectorySignatures=delta.envelope?.context_fingerprint===manifest.context_fingerprint&&delta.envelope.base_source_cursor===manifest.source_cursor?delta.envelope.directory_signatures:manifest.directory_signatures;return folders&&!directorySignaturesMatch(effectiveDirectorySignatures,await readDirectorySignatures(pmRoot,folders))?null:{source_cursor:effectiveCursor,entry_count:manifest.entry_count}}function relativeIndexPath(pmRoot,itemPath){const relative=path.relative(pmRoot,itemPath);return relative===""||relative===".."||relative.startsWith(`..${path.sep}`)||path.isAbsolute(relative)?null:relative}async function removeDerivedIndexFiles(pmRoot){await Promise.all([getCachePath(pmRoot),getBodyCachePath(pmRoot),getCollectionsCachePath(pmRoot),getDeltaCachePath(pmRoot),getManifestCachePath(pmRoot)].map(async cachePath=>{await fs.rm(cachePath,{force:!0}),envelopeMemo.delete(cachePath)})),await removeItemMetadataQueryIndex(pmRoot)}async function createDerivedIndexDeltaChange(params){if(params.mutation.document===null)return{entry:null,body:null,collections:null};const stat=await fs.stat(params.mutation.itemPath),split=splitHeavyMetadata(params.mutation.document.metadata),signature={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size};return{entry:{...signature,metadata:split.light,body_length:params.mutation.document.body.length},body:{...signature,body:params.mutation.document.body},collections:{...signature,collections:split.heavy}}}function selectDerivedIndexDeltaChanges(delta,contextFingerprint,baseSourceCursor){return delta?.context_fingerprint===contextFingerprint&&delta.base_source_cursor===baseSourceCursor?structuredClone(delta.changes):{}}async function refreshItemMetadataDerivedIndex(mutation){const relativePath=relativeIndexPath(mutation.pmRoot,mutation.itemPath),previousRelativePath=mutation.previousItemPath?relativeIndexPath(mutation.pmRoot,mutation.previousItemPath):void 0;if(relativePath===null||previousRelativePath===null)return await removeDerivedIndexFiles(mutation.pmRoot),["metadata_derived_index_path_invalidated"];try{const contextFingerprint=computeContextFingerprint(mutation.preferredFormat,mutation.typeToFolder,mutation.schema,resolveActiveExtensionFieldNames()),existingCache=await loadDerivedIndexManifest(mutation.pmRoot);if(existingCache===null||existingCache.context_fingerprint!==contextFingerprint)return[];const baseSourceCursor=existingCache.source_cursor,delta=await loadDerivedIndexDelta(mutation.pmRoot);if(delta.invalid)return await removeDerivedIndexFiles(mutation.pmRoot),["metadata_derived_index_refresh_failed"];const changes=selectDerivedIndexDeltaChanges(delta.envelope,contextFingerprint,baseSourceCursor),expectedSourceCursor=delta.envelope?.context_fingerprint===contextFingerprint&&delta.envelope.base_source_cursor===baseSourceCursor?delta.envelope.source_cursor:baseSourceCursor;previousRelativePath!==void 0&&(changes[previousRelativePath]={entry:null,body:null,collections:null}),changes[relativePath]=await createDerivedIndexDeltaChange({mutation});const sourceCursor=randomUUID();return await persistCache(getDeltaCachePath(mutation.pmRoot),{version:CACHE_VERSION,context_fingerprint:contextFingerprint,base_source_cursor:baseSourceCursor,source_cursor:sourceCursor,directory_signatures:await readDirectorySignatures(mutation.pmRoot,[...new Set(Object.values(mutation.typeToFolder))]),changes}),await updateItemMetadataQueryIndex({pmRoot:mutation.pmRoot,contextFingerprint,expectedSourceCursor,sourceCursor,row:mutation.document===null?null:{relativePath,metadata:splitHeavyMetadata(mutation.document.metadata).light,linkedFiles:mutation.document.metadata.files},deletedRelativePaths:[...previousRelativePath===void 0?[]:[previousRelativePath],...mutation.document===null?[relativePath]:[]]})||await removeItemMetadataQueryIndex(mutation.pmRoot),[]}catch{return await removeDerivedIndexFiles(mutation.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function sortedCachedDocumentCandidates(state){return[...state.documentsById.values()].sort((left,right)=>left.candidate.metadata.id.localeCompare(right.candidate.metadata.id)).map(entry=>entry.candidate)}function cacheTierMatchesContext(envelope,contextFingerprint,sourceCursor){return envelope?.context_fingerprint===contextFingerprint&&envelope.source_cursor===sourceCursor}function hasEveryDerivedIndexPart(keys,includeBody,includeCollections,previousBodies,previousCollections){return keys.every(key=>(!includeBody||previousBodies[key]!==void 0)&&(!includeCollections||previousCollections[key]!==void 0))}function candidatesFromDerivedIndex(params){const candidatesById=new Map;for(const[relativePath,entry]of Object.entries(params.previousEntries)){const itemFormat=getItemFormatFromPath(relativePath);if(!itemFormat)continue;const metadata=params.includeCollections?mergeHeavyMetadata(entry.metadata,params.previousCollections[relativePath]?.collections):entry.metadata,existing=candidatesById.get(metadata.id);shouldRecordCachedDocumentCandidate(existing?.itemFormat,itemFormat,params.preferredFormat)&&candidatesById.set(metadata.id,{itemFormat,candidate:{metadata,body:params.includeBody?params.previousBodies[relativePath]?.body:void 0,item_format:itemFormat,item_path:path.join(params.pmRoot,relativePath)}})}return[...candidatesById.values()].sort((left,right)=>left.candidate.metadata.id.localeCompare(right.candidate.metadata.id)).map(entry=>entry.candidate)}function canUseDerivedIndex(params){return params.forceSourceScan||hasActiveOnReadHooks()||params.existingCache?.context_fingerprint!==params.contextFingerprint||params.entryKeys.length<params.minimumIndexedItems||!directorySignaturesMatch(params.existingCache?.directory_signatures,params.directorySignatures)?!1:[!params.includeBody||cacheTierMatchesContext(params.existingBodyCache,params.contextFingerprint,params.existingCache.source_cursor),!params.includeCollections||cacheTierMatchesContext(params.existingCollectionsCache,params.contextFingerprint,params.existingCache.source_cursor)].every(Boolean)&&hasEveryDerivedIndexPart(params.entryKeys,params.includeBody,params.includeCollections,params.previousBodies,params.previousCollections)}async function listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,options={}){const includeBody=options.includeBody!==!1,includeCollections=options.includeCollections!==!1,extensionFieldNames=resolveActiveExtensionFieldNames(),contextFingerprint=computeContextFingerprint(preferredFormat,typeToFolder,schema,extensionFieldNames),delta=await loadDerivedIndexDelta(pmRoot);delta.invalid&&await removeDerivedIndexFiles(pmRoot);const existingCache=await loadCache(pmRoot,contextFingerprint,options.cacheDiagnostics),existingBodyCache=includeBody?await loadBodyCache(pmRoot,contextFingerprint):null,existingCollectionsCache=includeCollections?await loadCollectionsCache(pmRoot,contextFingerprint):null;applyDerivedIndexDelta(existingCache,existingBodyCache,existingCollectionsCache,delta.envelope);const previousEntries=selectPreviousMetadataEntries(existingCache,contextFingerprint),previousBodies=selectPreviousBodyEntries(existingBodyCache,contextFingerprint),previousCollections=selectPreviousCollectionEntries(existingCollectionsCache,contextFingerprint),folders=[...new Set(Object.values(typeToFolder))],directorySignaturesBefore=await readDirectorySignatures(pmRoot,folders),entryKeys=Object.keys(previousEntries),minimumIndexedItems=Math.max(1,Math.floor(options.derivedIndexMinimumItems??DEFAULT_DERIVED_INDEX_MINIMUM_ITEMS));if(canUseDerivedIndex({forceSourceScan:options.forceSourceScan===!0,contextFingerprint,existingCache,existingBodyCache,existingCollectionsCache,directorySignatures:directorySignaturesBefore,entryKeys,minimumIndexedItems,includeBody,includeCollections,previousBodies,previousCollections}))return candidatesFromDerivedIndex({pmRoot,preferredFormat,includeBody,includeCollections,previousEntries,previousBodies,previousCollections});const dirResults=await Promise.all(folders.map(folder=>readItemDirectoryFiles(pmRoot,folder,warnings))),dispatchReadHooks=hasActiveOnReadHooks(),state=createDocumentCacheMutableState(),context={pmRoot,preferredFormat,warnings,schema,extensionFieldNames,includeBody,includeCollections,forceSourceRead:options.forceSourceScan===!0,dispatchReadHooks,previousEntries,previousBodies,previousCollections,state};await processCachedDocumentFiles(dirResults,context);const directorySignaturesAfter=await readDirectorySignatures(pmRoot,folders),stableDirectorySignatures=directorySignaturesMatch(directorySignaturesBefore,directorySignaturesAfter)?directorySignaturesAfter:{},sourceCursor=state.misses.metadata||Object.keys(previousEntries).length!==Object.keys(state.newEntries).length||!directorySignaturesMatch(existingCache?.directory_signatures,stableDirectorySignatures)||existingCache===null?randomUUID():existingCache.source_cursor;return await persistMetadataCacheIfNeeded({pmRoot,contextFingerprint,sourceCursor,existingCache,previousEntries,directorySignatures:stableDirectorySignatures,state,minimumIndexedItems}),includeBody&&await persistBodyCacheIfNeeded({pmRoot,contextFingerprint,sourceCursor,existingBodyCache,previousBodies,state}),includeCollections&&await persistCollectionsCacheIfNeeded({pmRoot,contextFingerprint,sourceCursor,existingCollectionsCache,previousCollections,state}),sortedCachedDocumentCandidates(state)}async function listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema){return(await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!1})).map(candidate=>({metadata:candidate.metadata,body:candidate.body??""}))}async function listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema){return(await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!1,includeCollections:!1})).map(candidate=>({metadata:candidate.metadata,body:candidate.body??""}))}export{DEFAULT_DERIVED_INDEX_MINIMUM_ITEMS,HEAVY_METADATA_KEYS,acquireItemMetadataDerivedIndexLock,clearItemMetadataEnvelopeMemo,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,readItemMetadataDerivedIndexState,refreshItemMetadataDerivedIndex,shouldRecordCachedDocumentCandidate,shouldReplaceCachedDocumentCandidate};
|
|
1
|
+
import l from"node:fs/promises";import d from"node:path";import{createHash as me,randomUUID as K}from"node:crypto";import{getActiveExtensionRegistrations as ye,hasActiveOnReadHooks as V,runActiveOnReadHooks as _e}from"../extensions/index.js";import{collectRegisteredItemFieldNames as ge}from"../extensions/item-fields.js";import{parseItemDocument as he}from"../item/item-format.js";import{evictOldestMemoEntries as Ce}from"../shared/memo.js";import{isFileMissingError as we,writeFileAtomic as Q}from"../fs/fs-utils.js";import{acquireLock as be}from"../lock/lock.js";import{ITEM_FILE_EXTENSIONS as ve,getItemFormatFromPath as Y}from"./paths.js";import{rebuildItemMetadataQueryIndex as Me,removeItemMetadataQueryIndex as L,updateItemMetadataQueryIndex as xe}from"./item-metadata-query-index.js";const y=8,G=500,pe="metadata-derived-index",Ie="metadata-cache.json",Ee="metadata-cache-bodies.json",De="metadata-cache-collections.json",Se="metadata-cache-delta.json",je="metadata-cache-manifest.json",Z=4,Fe=["comments","notes","learnings","files","tests","test_runs","docs"];function ee(){return ge(ye())}function F(e){const n={...e},t={};for(const i of Fe)i in n&&(t[i]=n[i],delete n[i]);return{light:n,heavy:t}}function te(e,n){return!n||Object.keys(n).length===0?e:{...e,...n}}function ne(e,n,t,i){const o=me("sha256");o.update(`format:${e??"default"}`);const s=Object.entries(n).sort(([r],[u])=>r.localeCompare(u)).map(([r,u])=>`${r}=${u}`).join(",");return o.update(`|types:${s}`),t&&o.update(`|schema:${JSON.stringify(t)}`),i.length>0&&o.update(`|extension_fields:${i.join(",")}`),o.digest("hex").slice(0,16)}function O(e){return d.join(e,"runtime",Ie)}function B(e){return d.join(e,"runtime",Ee)}function A(e){return d.join(e,"runtime",De)}function T(e){return d.join(e,"runtime",Se)}function H(e){return d.join(e,"runtime",je)}function N(e,n){const t=d.extname(e);return`${e.slice(0,-t.length)}.${n}${t}`}const Oe=24,f=new Map,k=new WeakMap;function $(e){return k.get(e)??e.source_cursor}function Be(e,n){const t=$(e);if(!(n.base_source_cursor!==t||e.source_cursor===n.source_cursor)){k.set(e,t);for(const[i,o]of Object.entries(n.changes))o.entry?e.entries[i]=o.entry:delete e.entries[i];e.directory_signatures=n.directory_signatures,e.source_cursor=n.source_cursor}}function Ae(e,n){if(!e)return;const t=$(e);if(!(n.base_source_cursor!==t||e.source_cursor===n.source_cursor)){k.set(e,t);for(const[i,o]of Object.entries(n.changes))o.body?e.bodies[i]=o.body:delete e.bodies[i];e.source_cursor=n.source_cursor}}function Ne(e,n){if(!e)return;const t=$(e);if(!(n.base_source_cursor!==t||e.source_cursor===n.source_cursor)){k.set(e,t);for(const[i,o]of Object.entries(n.changes))o.collections?e.collections[i]=o.collections:delete e.collections[i];e.source_cursor=n.source_cursor}}function ke(e,n,t,i){!e||!i||e.context_fingerprint!==i.context_fingerprint||(Be(e,i),Ae(n,i),Ne(t,i))}function P(e,n){f.size>=Oe&&!f.has(e)&&Ce(f),f.set(e,n)}async function w(e,n){let t;try{t=await l.stat(e)}catch{return f.delete(e),null}const i=f.get(e);if(i&&D(i.signature,t.mtimeMs,t.ctimeMs,t.size))return f.delete(e),f.set(e,i),i.envelope;let o;try{o=n(await l.readFile(e,"utf8"))}catch{o=null}return P(e,{signature:{mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size},envelope:o}),o}function bt(){f.clear()}async function ze(e,n,t){const i=u=>{const c=JSON.parse(u);return c.version!==y||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=O(e),s=await w(o,i);if(!n||s===null||s.context_fingerprint===n)return s;const r=await w(N(o,n),i);return r===null&&E(t,`metadata_cache_context_changed:${s.context_fingerprint}->${n}`),r}async function Re(e,n){const t=s=>{const r=JSON.parse(s);return r.version!==y||typeof r.source_cursor!="string"||typeof r.bodies!="object"||r.bodies===null?null:r},i=B(e),o=await w(i,t);return n&&o?.context_fingerprint!==n?await w(N(i,n),t):o}async function Le(e,n){const t=s=>{const r=JSON.parse(s);return r.version!==y||typeof r.source_cursor!="string"||typeof r.collections!="object"||r.collections===null?null:r},i=A(e),o=await w(i,t);return n&&o?.context_fingerprint!==n?await w(N(i,n),t):o}async function J(e){const n=T(e),t=await w(n,i=>{const o=JSON.parse(i);return o.version!==y||typeof o.base_source_cursor!="string"||typeof o.source_cursor!="string"||typeof o.changes!="object"||o.changes===null?null:o});if(t)return{envelope:t,invalid:!1};try{return await l.stat(n),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function q(e){const n=H(e),t=await w(n,i=>{const o=JSON.parse(i);return o.version!==y||typeof o.context_fingerprint!="string"||typeof o.source_cursor!="string"||!Number.isInteger(o.entry_count)||o.entry_count<0||typeof o.directory_signatures!="object"||o.directory_signatures===null?null:o});if(t)return t;try{await l.stat(n),await p(e)}catch{}return null}async function I(e,n){await l.mkdir(d.dirname(e),{recursive:!0}),await Q(e,JSON.stringify(n));try{const i=await l.stat(e);P(e,{signature:{mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size},envelope:n})}catch{f.delete(e)}const t=d.dirname(d.dirname(e));if(e===O(t)||e===B(t)||e===A(t)){const i=N(e,n.context_fingerprint);await Q(i,JSON.stringify(n));try{const c=await l.stat(i);P(i,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:n})}catch{f.delete(i)}const o=d.dirname(e),s=d.extname(e),r=d.basename(e,s),u=(await l.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==d.basename(e)&&c.name.startsWith(`${r}.`)&&c.name.endsWith(s)).map(c=>d.join(o,c.name));if(u.length>Z){const c=(await Promise.all(u.map(async a=>{try{return{path:a,mtime:(await l.stat(a)).mtimeMs}}catch{return null}}))).filter(a=>a!==null);for(const a of c.sort((_,m)=>_.mtime-m.mtime).slice(0,Math.max(0,c.length-Z)))await l.rm(a.path,{force:!0}),f.delete(a.path)}}}function Te(e,n,t){return t?n===t&&e!==t:n==="toon"&&e!=="toon"}function ie(e,n,t){return e===void 0||Te(e,n,t)}function E(e,n){e&&!e.includes(n)&&e.push(n)}function D(e,n,t,i){return e.mtime_ms===n&&e.ctime_ms===t&&e.size===i}async function He(e,n,t){const i=d.join(e,n);try{const o=await l.readdir(i);return{folder:n,dirPath:i,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!we(o)&&E(t,`item_list_directory_read_failed:${n}`),{folder:n,dirPath:i,files:[]}}}async function $e(e,n){try{const t=await l.stat(d.join(e,n));return[n,{exists:!0,mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size}]}catch{return[n,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function z(e,n){return Object.fromEntries(await Promise.all(n.map(async t=>await $e(e,t))))}function S(e,n){return!e||Object.keys(e).length!==Object.keys(n).length?!1:Object.entries(n).every(([t,i])=>{const o=e[t];return o!==void 0&&o.exists===i.exists&&D(o,i.mtime_ms,i.ctime_ms,i.size)})}function Pe(e){return ve.some(n=>e.toLowerCase().endsWith(n))}function Je(e,n,t,i,o,s){i||(e.metadata=!0),n&&!o&&(e.body=!0),t&&!s&&(e.collections=!0)}async function qe(e,n,t){if(t)for(const i of await _e({path:e,scope:"project"}))E(n,i)}function oe(e,n,t,i){if(e)return n&&t?t.collections:i}async function Ue(e,n,t){const i=await l.stat(e),o=i.mtimeMs,s=i.ctimeMs,{size:r}=i,u=Y(e);await qe(e,t.warnings,t.dispatchReadHooks);const c=t.previousEntries[n],a=!t.forceSourceRead&&c!==void 0&&D(c,o,s,r),_=t.previousBodies[n],m=!t.forceSourceRead&&_!==void 0&&D(_,o,s,r),g=t.previousCollections[n],h=!t.forceSourceRead&&g!==void 0&&D(g,o,s,r);if(!(!a||t.includeBody&&!m||t.includeCollections&&!h))return{mtimeMs:o,ctimeMs:s,size:r,itemFormat:u,lightMetadata:c.metadata,heavyMetadata:oe(t.includeCollections,h,g,void 0),bodyLength:c.body_length,body:t.includeBody?_.body:void 0};const M=await l.readFile(e,"utf8"),C=he(M,{format:u,schema:t.schema,extensionFieldNames:t.extensionFieldNames,onWarning:j=>E(t.warnings,j)}),x=F(C.metadata);return Je(t.state.misses,t.includeBody,t.includeCollections,a,m,h),{mtimeMs:o,ctimeMs:s,size:r,itemFormat:u,lightMetadata:a?c.metadata:x.light,heavyMetadata:oe(t.includeCollections,h,g,x.heavy),bodyLength:a?c.body_length:C.body.length,body:t.includeBody?C.body:void 0}}function We(e,n,t,i){t.state.newEntries[n]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,metadata:i.lightMetadata,body_length:i.bodyLength},t.includeBody&&i.body!==void 0&&(t.state.newBodies[n]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,body:i.body}),t.includeCollections&&i.heavyMetadata!==void 0&&(t.state.newCollections[n]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,collections:i.heavyMetadata});const o=t.includeCollections?te(i.lightMetadata,i.heavyMetadata):i.lightMetadata,s=t.state.documentsById.get(o.id),r={metadata:o,body:i.body,item_format:i.itemFormat,item_path:e};ie(s?.itemFormat,i.itemFormat,t.preferredFormat)&&t.state.documentsById.set(o.id,{candidate:r,itemFormat:i.itemFormat})}async function Xe(e,n,t,i){try{const o=await Ue(n,t,i);We(n,t,i,o)}catch{E(i.warnings,`item_list_item_read_failed:${e}/${d.basename(n)}`)}}function Ke(e,n){return e&&e.context_fingerprint===n?e.entries:{}}function Ve(e,n){return e&&e.context_fingerprint===n?e.bodies:{}}function Qe(e,n){return e&&e.context_fingerprint===n?e.collections:{}}function Ye(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function Ge(e,n){const t=[];for(const{folder:i,dirPath:o,files:s}of e)for(const r of s){if(!Pe(r))continue;const u=d.join(o,r),c=d.relative(n.pmRoot,u);t.push(Xe(i,u,c,n)),t.length===32&&(await Promise.all(t),t.length=0)}await Promise.all(t)}async function Ze(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!S(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await I(O(e.pmRoot),{version:y,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await I(H(e.pmRoot),{version:y,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});const t=[...e.state.documentsById.values()].map(({candidate:i})=>({relativePath:d.relative(e.pmRoot,i.item_path),metadata:F(i.metadata).light,linkedFiles:i.metadata.files??[]}));t.length>=e.minimumIndexedItems?await Me({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:t}):await L(e.pmRoot)}catch{}}async function et(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await I(B(e.pmRoot),{version:y,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function tt(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await I(A(e.pmRoot),{version:y,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function vt(e,n,t={}){const i=await q(e);return t.required!==!0&&(i===null||i.entry_count<G)?async()=>{}:be(e,pe,30,n,!1,!1,3e3)}async function Mt(e,n){const t=await q(e);if(t===null)return null;const i=await J(e);if(i.invalid)return await p(e),null;const o=i.envelope?.context_fingerprint===t.context_fingerprint&&i.envelope.base_source_cursor===t.source_cursor?i.envelope.source_cursor:t.source_cursor,s=i.envelope?.context_fingerprint===t.context_fingerprint&&i.envelope.base_source_cursor===t.source_cursor?i.envelope.directory_signatures:t.directory_signatures;return n&&!S(s,await z(e,n))?null:{source_cursor:o,entry_count:t.entry_count}}function re(e,n){const t=d.relative(e,n);return t===""||t===".."||t.startsWith(`..${d.sep}`)||d.isAbsolute(t)?null:t}async function p(e){await Promise.all([O(e),B(e),A(e),T(e),H(e)].map(async n=>{await l.rm(n,{force:!0}),f.delete(n)})),await L(e)}async function nt(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};const n=await l.stat(e.mutation.itemPath),t=F(e.mutation.document.metadata),i={mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size};return{entry:{...i,metadata:t.light,body_length:e.mutation.document.body.length},body:{...i,body:e.mutation.document.body},collections:{...i,collections:t.heavy}}}function it(e,n,t){return e?.context_fingerprint===n&&e.base_source_cursor===t?structuredClone(e.changes):{}}async function xt(e){const n=re(e.pmRoot,e.itemPath),t=e.previousItemPath?re(e.pmRoot,e.previousItemPath):void 0;if(n===null||t===null)return await p(e.pmRoot),["metadata_derived_index_path_invalidated"];try{const i=ne(e.preferredFormat,e.typeToFolder,e.schema,ee()),o=await q(e.pmRoot);if(o===null||o.context_fingerprint!==i)return[];const s=o.source_cursor,r=await J(e.pmRoot);if(r.invalid)return await p(e.pmRoot),["metadata_derived_index_refresh_failed"];const u=it(r.envelope,i,s),c=r.envelope?.context_fingerprint===i&&r.envelope.base_source_cursor===s?r.envelope.source_cursor:s;t!==void 0&&(u[t]={entry:null,body:null,collections:null}),u[n]=await nt({mutation:e});const a=K();return await I(T(e.pmRoot),{version:y,context_fingerprint:i,base_source_cursor:s,source_cursor:a,directory_signatures:await z(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:u}),await xe({pmRoot:e.pmRoot,contextFingerprint:i,expectedSourceCursor:c,sourceCursor:a,row:e.document===null?null:{relativePath:n,metadata:F(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...t===void 0?[]:[t],...e.document===null?[n]:[]]})||await L(e.pmRoot),[]}catch{return await p(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function ot(e){return[...e.documentsById.values()].sort((n,t)=>n.candidate.metadata.id.localeCompare(t.candidate.metadata.id)).map(n=>n.candidate)}function se(e,n,t){return e?.context_fingerprint===n&&e.source_cursor===t}function rt(e,n,t,i,o){return e.every(s=>(!n||i[s]!==void 0)&&(!t||o[s]!==void 0))}function st(e){const n=new Map;for(const[t,i]of Object.entries(e.previousEntries)){const o=Y(t);if(!o)continue;const s=e.includeCollections?te(i.metadata,e.previousCollections[t]?.collections):i.metadata,r=n.get(s.id);ie(r?.itemFormat,o,e.preferredFormat)&&n.set(s.id,{itemFormat:o,candidate:{metadata:s,body:e.includeBody?e.previousBodies[t]?.body:void 0,item_format:o,item_path:d.join(e.pmRoot,t)}})}return[...n.values()].sort((t,i)=>t.candidate.metadata.id.localeCompare(i.candidate.metadata.id)).map(t=>t.candidate)}function ct(e){return e.forceSourceScan||V()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!S(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||se(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||se(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&rt(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function ce(e,n,t,i,o,s={}){const r=s.includeBody!==!1,u=s.includeCollections!==!1,c=ee(),a=ne(n,t,o,c),_=await J(e);_.invalid&&await p(e);const m=await ze(e,a,s.cacheDiagnostics),g=r?await Re(e,a):null,h=u?await Le(e,a):null;ke(m,g,h,_.envelope);const v=Ke(m,a),M=Ve(g,a),C=Qe(h,a),x=[...new Set(Object.values(t))],j=await z(e,x),ae=Object.keys(v),U=Math.max(1,Math.floor(s.derivedIndexMinimumItems??G));if(ct({forceSourceScan:s.forceSourceScan===!0,contextFingerprint:a,existingCache:m,existingBodyCache:g,existingCollectionsCache:h,directorySignatures:j,entryKeys:ae,minimumIndexedItems:U,includeBody:r,includeCollections:u,previousBodies:M,previousCollections:C}))return st({pmRoot:e,preferredFormat:n,includeBody:r,includeCollections:u,previousEntries:v,previousBodies:M,previousCollections:C});const ue=await Promise.all(x.map(fe=>He(e,fe,i))),de=V(),b=Ye(),le={pmRoot:e,preferredFormat:n,warnings:i,schema:o,extensionFieldNames:c,includeBody:r,includeCollections:u,forceSourceRead:s.forceSourceScan===!0,dispatchReadHooks:de,previousEntries:v,previousBodies:M,previousCollections:C,state:b};await Ge(ue,le);const W=await z(e,x),X=S(j,W)?W:{},R=b.misses.metadata||Object.keys(v).length!==Object.keys(b.newEntries).length||!S(m?.directory_signatures,X)||m===null?K():m.source_cursor;return await Ze({pmRoot:e,contextFingerprint:a,sourceCursor:R,existingCache:m,previousEntries:v,directorySignatures:X,state:b,minimumIndexedItems:U}),r&&await et({pmRoot:e,contextFingerprint:a,sourceCursor:R,existingBodyCache:g,previousBodies:M,state:b}),u&&await tt({pmRoot:e,contextFingerprint:a,sourceCursor:R,existingCollectionsCache:h,previousCollections:C,state:b}),ot(b)}async function pt(e,n,t,i,o){return(await ce(e,n,t,i,o,{includeBody:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}async function It(e,n,t,i,o){return(await ce(e,n,t,i,o,{includeBody:!1,includeCollections:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}export{G as DEFAULT_DERIVED_INDEX_MINIMUM_ITEMS,Fe as HEAVY_METADATA_KEYS,vt as acquireItemMetadataDerivedIndexLock,bt as clearItemMetadataEnvelopeMemo,ce as listAllDocumentCandidatesCached,pt as listAllDocumentsCached,It as listAllDocumentsCachedLight,Mt as readItemMetadataDerivedIndexState,xt as refreshItemMetadataDerivedIndex,ie as shouldRecordCachedDocumentCandidate,Te as shouldReplaceCachedDocumentCandidate};
|
|
2
2
|
//# sourceMappingURL=item-metadata-cache.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import E from"node:fs/promises";import C from"node:path";import{randomUUID as w}from"node:crypto";import{createRequire as g}from"node:module";import{loadDatabaseSync as k,loadStableDatabaseSync as A}from"./sqlite-runtime.js";const F="metadata-query-index.sqlite",_="5";let m;function f(){return m!==void 0||(m=A(process.versions.node,g(import.meta.url))),m}function M(e,r){return Math.max(0,Math.floor(e===void 0?r:e))}function p(e){return C.join(e,"runtime",F)}function U(e){e.exec(`
|
|
2
2
|
PRAGMA foreign_keys = ON;
|
|
3
3
|
PRAGMA journal_mode = OFF;
|
|
4
4
|
PRAGMA synchronous = OFF;
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
tags,
|
|
54
54
|
tokenize = 'unicode61'
|
|
55
55
|
);
|
|
56
|
-
`)}function
|
|
56
|
+
`)}function S(e,r,t){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r,t)}function x(e,r){const t=r.metadata;e.prepare(`INSERT INTO items(
|
|
57
57
|
id, relative_path, metadata_json, status, type, priority,
|
|
58
58
|
updated_at, created_at, parent, assignee, sprint, release
|
|
59
59
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -68,24 +68,24 @@
|
|
|
68
68
|
parent = excluded.parent,
|
|
69
69
|
assignee = excluded.assignee,
|
|
70
70
|
sprint = excluded.sprint,
|
|
71
|
-
release = excluded.release`).run(
|
|
72
|
-
ORDER BY ${
|
|
71
|
+
release = excluded.release`).run(t.id,r.relativePath,JSON.stringify(t),t.status,t.type,t.priority,t.updated_at,t.created_at,t.parent??null,t.assignee??null,t.sprint??null,t.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(t.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(t.id),e.prepare("DELETE FROM item_search WHERE rowid = (SELECT rowid FROM items WHERE id = ?)").run(t.id),e.prepare("INSERT INTO item_search(rowid, id, title, description, tags) SELECT rowid, ?, ?, ?, ? FROM items WHERE id = ?").run(t.id,t.title,t.description,t.tags.join(" "),t.id);const a=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(const s of Object.keys(t))a.run(t.id,s);const i=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(const s of r.linkedFiles??[])i.run(t.id,s.path,s.scope,s.note??null)}async function b(e){const r=p(e.pmRoot),t=f();if(!t){await E.rm(r,{force:!0});return}await E.mkdir(C.dirname(r),{recursive:!0});const a=`${r}.${w()}.tmp`;let i;try{i=new t(a),U(i),i.exec("BEGIN IMMEDIATE"),S(i,"version",_),S(i,"context_fingerprint",e.contextFingerprint),S(i,"source_cursor",e.sourceCursor);for(const s of e.rows)x(i,s);i.exec("COMMIT"),i.close(),i=void 0,await E.rm(r,{force:!0}),await E.rename(a,r)}catch(s){throw i?.close(),await Promise.allSettled([E.rm(a,{force:!0})]),s}}function h(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(r=>[String(r.key),String(r.value)]))}async function W(e){const r=f();if(!r)return!1;const t=p(e.pmRoot);let a;try{await E.access(t),a=new r(t),a.exec("PRAGMA foreign_keys = ON");const i=h(a);if(i.version!==_||i.context_fingerprint!==e.contextFingerprint||i.source_cursor!==e.expectedSourceCursor)return a.close(),!1;a.exec("BEGIN IMMEDIATE");const s=a.prepare("DELETE FROM items WHERE relative_path = ?"),o=a.prepare("SELECT rowid FROM items WHERE relative_path = ?"),u=a.prepare("DELETE FROM item_search WHERE rowid = ?");for(const d of e.deletedRelativePaths??[]){const c=o.get(d);s.run(d),c&&u.run(c.rowid)}return e.row&&x(a,e.row),S(a,"source_cursor",e.sourceCursor),a.exec("COMMIT"),a.close(),!0}catch{try{a?.exec("ROLLBACK")}catch{}return a?.close(),!1}}function I(e,r,t,a,i){!a||a.length===0||(e.push(`${t} ${i} (${a.map(()=>"?").join(", ")})`),r.push(...a))}function X(e){const r=[],t=[];I(r,t,"status",e.statuses,"IN"),I(r,t,"status",e.excludeStatuses,"NOT IN"),I(r,t,"type",e.types,"IN"),I(r,t,"id",e.ids,"IN");for(const a of e.metadataKeys??[])r.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),t.push(a);for(const[a,i]of[["parent",e.parent],["assignee",e.assignee],["sprint",e.sprint],["release",e.release]])i!==void 0&&(r.push(`${a} = ?`),t.push(i));return e.priority!==void 0&&(r.push("priority = ?"),t.push(e.priority)),{where:r.length===0?"":` WHERE ${r.join(" AND ")}`,parameters:t}}async function B(e){const r=f();if(!r)return null;const t=e.query??{},{where:a,parameters:i}=X(t);let s;try{s=new r(p(e.pmRoot),{readOnly:!0});const o=h(s);if(o.version!==_||o.source_cursor!==e.expectedSourceCursor)return s.close(),null;const u=s.prepare(`SELECT COUNT(*) AS count FROM items${a}`).get(...i),d=[];let c="";t.limit!==void 0?(c+=" LIMIT ?",d.push(Math.max(0,Math.floor(t.limit))),t.offset!==void 0&&(c+=" OFFSET ?",d.push(Math.max(0,Math.floor(t.offset))))):t.offset!==void 0&&(c+=" LIMIT -1 OFFSET ?",d.push(Math.max(0,Math.floor(t.offset))));const T=s.prepare(`SELECT metadata_json FROM items${a}
|
|
72
|
+
ORDER BY ${t.terminalStatuses&&t.terminalStatuses.length>0?`CASE WHEN status IN (${t.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${c}`).all(...i,...t.terminalStatuses??[],...d).map(R=>{const l=JSON.parse(String(R.metadata_json));if(!l.id)throw new TypeError("Indexed metadata row has no id");return l});return s.close(),{source_cursor:o.source_cursor,total:Number(u.count),items:T}}catch{return s?.close(),null}}async function Y(e){const r=f();if(!r||e.paths.length===0)return null;let t;try{t=new r(p(e.pmRoot),{readOnly:!0});const a=h(t);if(a.version!==_||a.source_cursor!==e.expectedSourceCursor)return t.close(),null;const i=e.paths.map(()=>"?").join(", "),s=e.scope===void 0?"":" AND scope = ?",o=[...e.paths,...e.scope===void 0?[]:[e.scope]],u=`path IN (${i})${s}`,d=t.prepare(`SELECT COUNT(DISTINCT item_id) AS count
|
|
73
73
|
FROM item_linked_files
|
|
74
|
-
WHERE ${
|
|
74
|
+
WHERE ${u}`).get(...o),c=M(e.limit,50),O=M(e.offset,0),T=t.prepare(`SELECT items.id, items.metadata_json
|
|
75
75
|
FROM items
|
|
76
76
|
WHERE EXISTS (
|
|
77
77
|
SELECT 1 FROM item_linked_files
|
|
78
|
-
WHERE item_linked_files.item_id = items.id AND ${
|
|
78
|
+
WHERE item_linked_files.item_id = items.id AND ${u}
|
|
79
79
|
)
|
|
80
80
|
ORDER BY items.priority ASC, items.updated_at DESC, items.id ASC
|
|
81
|
-
LIMIT ? OFFSET ?`).all(...
|
|
81
|
+
LIMIT ? OFFSET ?`).all(...o,c,O),R=[];if(T.length>0){const l=T.map(n=>String(n.id)),D=t.prepare(`SELECT item_id, path, scope, note
|
|
82
82
|
FROM item_linked_files
|
|
83
|
-
WHERE item_id IN (${
|
|
84
|
-
AND ${
|
|
85
|
-
ORDER BY path ASC, scope ASC`).all(...
|
|
83
|
+
WHERE item_id IN (${l.map(()=>"?").join(", ")})
|
|
84
|
+
AND ${u}
|
|
85
|
+
ORDER BY path ASC, scope ASC`).all(...l,...o),y=new Map(l.map(n=>[n,[]]));for(const n of D){const N=String(n.item_id),L=y.get(N);L.push({path:String(n.path),scope:String(n.scope),...n.note===null?{}:{note:String(n.note)}}),y.set(N,L)}for(const n of T){const N=JSON.parse(String(n.metadata_json));R.push({item:N,files:y.get(String(n.id))})}}return t.close(),{source_cursor:a.source_cursor,total:Number(d.count),matches:R}}catch{return t?.close(),null}}async function G(e){const r=f();if(!r)return null;let t;try{t=new r(p(e.pmRoot),{readOnly:!0});const a=h(t);if(a.version!==_||a.source_cursor!==e.expectedSourceCursor)return t.close(),null;const s=t.prepare(`SELECT items.metadata_json
|
|
86
86
|
FROM item_search
|
|
87
87
|
JOIN items ON items.id = item_search.id
|
|
88
88
|
WHERE item_search MATCH ?
|
|
89
89
|
ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
|
|
90
|
-
LIMIT ?`).all(
|
|
90
|
+
LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(o=>JSON.parse(String(o.metadata_json)));return t.close(),{source_cursor:a.source_cursor,items:s}}catch{return t?.close(),null}}async function K(e){await E.rm(p(e),{force:!0})}const Q={loadDatabaseSync:k,loadStableDatabaseSync:A,setDatabaseSync(e){const r=m;return m=e,()=>{m=r}}};export{Q as _testOnly,B as queryItemMetadataIndex,Y as queryLinkedFileMetadataIndex,G as querySimilarItemMetadataIndex,b as rebuildItemMetadataQueryIndex,K as removeItemMetadataQueryIndex,W as updateItemMetadataQueryIndex};
|
|
91
91
|
//# sourceMappingURL=item-metadata-query-index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{AsyncLocalStorage as s}from"node:async_hooks";import{channel as i}from"node:diagnostics_channel";const r=new s,a=i("@unbrained/pm-cli/item-metadata-enumeration/v1");function m(t){a.publish(t)}async function l(t){const e={enumeration_calls:0,metadata_rows:0},n=o=>{r.getStore()?.includes(e)&&(e.enumeration_calls+=1,e.metadata_rows+=o)};a.subscribe(n);try{return{result:await r.run([...r.getStore()??[],e],t),work:{...e}}}finally{a.unsubscribe(n)}}export{l as measureItemMetadataReadWork,m as recordItemMetadataEnumeration};
|
|
2
2
|
//# sourceMappingURL=item-metadata-read-work.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{AsyncLocalStorage as _}from"node:async_hooks";import{realpathSync as g}from"node:fs";import u from"node:path";import{hashDocument as S}from"../history/history.js";import{sha256Hex as k}from"../shared/serialization.js";import{renderPmCommand as d}from"../shared/command-line.js";import{EXIT_CODE as p}from"../shared/constants.js";import{PmCliError as m}from"../shared/errors.js";const l=new _;function z(t,e){return l.run([...l.getStore()??[],{...t,pmRoot:u.resolve(t.pmRoot)}],e)}const C=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),b=globalThis,a=b[C]??=new _;function c(t){const e=u.resolve(t);try{return g.native(e)}catch{return e}}function B(){return{entries:new Map}}function X(t,e){return a.run([...a.getStore()??[],t],e)}function J(t,e,n){const o=c(e);if(t.pmRoot!==void 0&&t.pmRoot!==o)throw new m("An expected-revision scope is already bound to another tracker.",p.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});t.pmRoot=o;for(const{id:i,itemHash:r}of n){const s=t.entries.get(i);if(s!==void 0&&s.declared!==r)throw new m(`Item ${i} has two different expected revisions.`,p.USAGE,{code:"expected_revision_duplicate",item_id:i,required:"Declare at most one expected revision per item."});t.entries.set(i,s??{declared:r,expected:r,checked:!1,committed:!1})}}function Q(t){const e=[...t.entries.entries()];return{checked:e.filter(([,n])=>n.checked).map(([n])=>n),unchecked:e.filter(([,n])=>!n.checked).map(([n])=>n)}}function h(t,e){const n=a.getStore()??[];if(n.length===0)return[];const o=c(t),i=new Set(e.filter(r=>typeof r=="string"));return[...new Set(n.flatMap(r=>r.pmRoot===o?[...i].flatMap(s=>r.entries.get(s)??[]):[]))]}function Z(t){const e=a.getStore()??[];if(e.length===0)return[];const n=c(t),o=new Map;for(const i of e)if(i.pmRoot===n)for(const[r,s]of i.entries){if(s.expected!==s.declared)return;o.set(r,(o.get(r)??new Set).add(s.expected))}if(![...o.values()].some(i=>i.size>1))return[...o].map(([i,r])=>`${i}=${[...r][0]}`)}function ee(t){const e=c(t);return(a.getStore()??[]).some(n=>n.pmRoot===e&&n.entries.size>0)}function T(t,e,n){const o=h(t,[n,e.metadata.id]);o.length>0&&y(o,n,S(e),!1,t)}function te(t,e,n){const o=h(t,[e]);o.length>0&&y(o,e,k(n),!0,t)}const A="revision_changed",I="document_unreadable";function O(t,e,n={}){const o=[...n.scopeArgs??[]],i=[...n.outputArgs??["--json"]],r=d([...o,"get",t,...i]),s=d([...o,"history",t,"--limit","5",...i]);return{required:e?`Recover ${t} without --expect-hash (${d([...o,"restore",t,"<version>"])}), since no declared revision describes an unreadable document.`:`Re-read ${t} (${r} reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,examples:[d([...o,"get",t,"--fields","item_hash",...i]),s],nextSteps:[r,s]}}const M=Symbol.for("@unbrained/pm-cli/item-revision-refusal-trackers"),N=globalThis,v=N[M]??=new WeakMap,$=8;function E(t){for(const e of w(t)){const n=v.get(e);if(n!==void 0)return n}}function*w(t){let e=t;for(let n=0;n<$&&typeof e=="object"&&e!==null;n+=1){yield e;try{e=e.cause}catch{return}}}function y(t,e,n,o,i){for(const r of t)if(r.checked=!0,!(!o&&r.expected===n))throw U(i,new m(`Item ${e} is no longer at the expected revision ${r.expected.slice(0,12)}${o?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${r.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,p.CONFLICT,{code:"item_revision_conflict",item_id:e,expected_revision:r.expected,current_revision:n,reason:o?I:A,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",...O(e,o)}))}function ne(t,e){const n=E(t);return n===void 0||n===c(e)}const P=Symbol.for("@unbrained/pm-cli/item-revision-scoped-refusals"),F=globalThis,R=F[P]??=new WeakSet;function L(t){for(const e of w(t))if(R.has(e))return!0;return!1}function oe(t){return R.add(t),t}function ie(t,e){const n=E(t);return n!==void 0&&v.set(e,n),L(t)&&R.add(e),e}function U(t,e){return v.set(e,c(t)),e}function re(t,e,n=e.metadata.id){T(t,e,n);for(const o of f(t,[n,e.metadata.id]))o.validate(e),o.compensation!==void 0&&n===o.id&&(o.compensation.validated_storage_id=n)}function f(t,e){const n=u.resolve(t);return(l.getStore()??[]).filter(o=>o.pmRoot===n&&e.includes(o.id))}function se(t,e,n=e.metadata.id,o=[],i){const r=h(t,[n,e.metadata.id,...o]);if(r.length>0){const s=i??S(e);for(const x of r)x.expected=s,x.committed=!0}for(const s of f(t,[n,e.metadata.id,...o]))s.committed?.(e)}function D(t,e,n){const o=e.filter(i=>i!==void 0);if(!o.some(i=>i!==o[0]))return f(t,[o[0]]).find(i=>i.compensation?.operations.includes(n)===!0&&i.compensation.validated_storage_id===i.id)?.compensation}function ce(t,e,n){const o=D(t,e,n);return o===void 0||o.overrides.length===0?{}:{transaction_compensation:{transaction_id:o.transaction_id,step_id:o.step_id,overridden:structuredClone(o.overrides)}}}function ae(t,e){return Object.assign({},...f(t,e).map(n=>n.historyContext))}export{A as ITEM_REVISION_CONFLICT_CHANGED_REASON,I as ITEM_REVISION_CONFLICT_UNREADABLE_REASON,Z as activeItemRevisionExpectations,se as advanceItemMutationPreconditions,re as assertItemMutationPreconditions,te as assertItemRevisionExpectationsOnUnreadable,J as bindItemRevisionScope,B as createItemRevisionScope,ee as hasActiveItemRevisionScope,ne as isItemRevisionRefusalFrom,L as isItemRevisionRefusalScoped,ae as itemMutationPreconditionHistoryContext,O as itemRevisionConflictGuidance,E as itemRevisionRefusalTracker,Q as itemRevisionScopeReceipt,oe as markItemRevisionRefusalScoped,D as ownedTransactionCompensation,ie as retainItemRevisionRefusalTracker,z as runWithItemMutationPrecondition,X as runWithItemRevisionScope,ce as transactionCompensationHistoryContext};
|
|
2
2
|
//# sourceMappingURL=item-mutation-precondition.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]="2fda779c-a87f-517c-b71a-626c4fef98e5")}catch{}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,itemMutationPreconditionHistoryContext,transactionCompensationHistoryContext}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext}from"../checkpoint/mutation-context.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{effectiveItemFormatVersion,requiredItemFormatVersion}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease}from"../lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS,resolveWorkspaceRoot}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{pruneResolvedDeferredFields}from"../item/deferred-fields.js";import{nowIso}from"../shared/time.js";import{redactOptionalIdentityCredentials}from"../shared/url-credentials.js";async function fileExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){warnings&&(warnings.includes(warning)||warnings.push(warning))}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){return preferredFormat==="toon"?["toon","json_markdown"]:preferredFormat==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim(),exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0)return null;const normalizedId=normalizeItemId(rawId,idPrefix),rawNormalizedId=normalizeRawItemId(rawId),candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0),entries=Object.entries(typeToFolder),searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries)for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);await fileExists(itemPath)&&matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes))throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:!1});const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,requireSupportedFormat:!0,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_format_version_unsupported")throw new PmCliError(`Item ${item.id}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath});if(error instanceof PmCliError&&error.code==="item_document_invalid")return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})};throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!0,forceSourceScan:options.forceSourceScan});return recordItemMetadataEnumeration(candidates.length),candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder)),allIds=[];return await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries)for(const ext of ITEM_FILE_EXTENSIONS)if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}catch{}})),allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix),ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));return ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id)}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder),nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return suggestions.length>0&&nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`),new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{code:"item_not_found",id:badId,nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===!0&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder);const lease=await acquireLockLease(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const warnings=[],{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings}),storedAssignee=document.metadata.assignee?.trim(),assigned=redactOptionalIdentityCredentials(storedAssignee),assignedPrincipal=document.metadata.claim_principal?.trim()||storedAssignee,callerPrincipal=resolveClaimPrincipal(params.author),governance=resolveGovernanceKnobs(params.settings);if(assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict)){if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);governance.ownership_enforcement==="warn"&&warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}return{typeToFolder,located,originalRaw,document,warnings,releaseLock,lease}}catch(error){throw await releaseLock(),error}}function historyContextOrUndefined(context){return Object.keys(context).length===0?void 0:context}async function commitLockedItemWrite(lease,located,originalRaw,commit){return lease.fence(async()=>{let currentRaw;try{currentRaw=await fs.readFile(located.itemPath,"utf8")}catch(error){if(!isFileMissingError(error))throw error;currentRaw=null}if(currentRaw!==originalRaw)throw new PmCliError(`Item ${located.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,EXIT_CODE.CONFLICT,{code:"stale_revision",item_id:located.id,reason:currentRaw===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return commit()})}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!="object"||serviceWriteOverride.result===null)return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:!1};const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path=="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents=="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===!0}}async function readOverriddenCommitRevision(params){try{const located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return{document:EMPTY_CANONICAL_DOCUMENT};const document=parseItemDocument(await fs.readFile(located.itemPath,"utf8"),{format:located.item_format,requireSupportedFormat:!0,schema:params.settings.schema,extensionFieldNames:resolveActiveExtensionFieldNames(params.extensionFieldNames)});return document.metadata.id===params.embeddedId?{document}:{document:params.fallback,revision:UNREADABLE_COMMIT_REVISION}}catch{return{document:params.fallback,revision:UNREADABLE_COMMIT_REVISION}}}const UNREADABLE_COMMIT_REVISION="unreadable-after-storage-override";async function resolveItemStoreDeleteOverride(payload){const override=await runActiveServiceOverride("item_store_delete",payload),record=override.handled&&typeof override.result=="object"&&override.result!==null?override.result:{};return{effectiveItemPath:typeof record.item_path=="string"&&record.item_path.trim().length>0?record.item_path:payload.item_path,skipDelete:record.skip_delete===!0,warnings:override.warnings}}async function rollbackMutatedItemWrite(params){if(!params.skipItemWrite){if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw),await fs.rm(params.effectiveTargetItemPath,{force:!0});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}}function recordResolvedDeferrals(document,changedFields){pruneResolvedDeferredFields(document.metadata)&&changedFields.push("deferred_fields")}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder}),{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document,located.id);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutation=await params.mutate(mutableDocument,{storageId:located.id});if(recordResolvedDeferrals(mutableDocument,mutation.changedFields),params.skipNoop===!0&&mutation.changedFields.length===0)return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]};const historyContext={...params.resolveHistoryContext?.(),...checkpointMutationHistoryContext(params.pmRoot,located.id),...itemMutationPreconditionHistoryContext(params.pmRoot,[located.id,document.metadata.id])},requiredFormat=Math.max(requiredItemFormatVersion(beforeDocument.metadata),requiredItemFormatVersion(mutableDocument.metadata));assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(params.pmRoot),requiredFormat),requiredFormat>effectiveItemFormatVersion(mutableDocument.metadata)&&(mutableDocument.metadata.pm_format_version=requiredFormat,mutation.changedFields.push("pm_format_version")),mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,author:params.author,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op}),targetItemFormat="toon",serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder),historyPath=getHistoryPath(params.pmRoot,located.id),committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter}),{effectiveTargetItemPath:effectiveTargetItemPath2,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipItemWrite||await writeFileAtomic(effectiveTargetItemPath2,effectiveSerializedAfter),!skipItemWrite&&effectiveTargetItemPath2!==located.itemPath&&await fs.rm(located.itemPath);const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:historyContextOrUndefined({...historyContext,...workflowPolicy.decisions.length===0?{}:{workflow_policies:workflowPolicy.decisions},...transactionCompensationHistoryContext(params.pmRoot,[located.id,document.metadata.id],params.op)})});try{await appendHistoryEntry(historyPath,entry)}catch(error){throw await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath:effectiveTargetItemPath2,originalItemPath:located.itemPath,originalRaw}),error}skipItemWrite||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath2,previousItemPath:located.itemPath,document:afterDocument}))}finally{await releaseDerivedIndexLock()}const overridden=skipItemWrite||effectiveTargetItemPath2!==targetItemPath||effectiveSerializedAfter!==serializedAfter;return{derivedIndexWarnings:derivedIndexWarnings2,effectiveTargetItemPath:effectiveTargetItemPath2,overrideWarnings:serviceWriteOverride.warnings,stored:overridden?await readOverriddenCommitRevision({pmRoot:params.pmRoot,settings:params.settings,id:located.id,typeToFolder,extensionFieldNames:params.extensionFieldNames,fallback:afterDocument,embeddedId:afterDocument.metadata.id}):{document:afterDocument}}}),{derivedIndexWarnings,effectiveTargetItemPath,stored}=committed;advanceItemMutationPreconditions(params.pmRoot,stored.document,located.id,[afterDocument.metadata.id],stored.revision);const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];return recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields}),{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force}),{located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document,located.id);const extensionFieldNames=resolveActiveExtensionFieldNames(void 0),beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],author:params.author,dry_run:params.dryRun===!0,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"}),deletionTimestamp=nowIso(),tombstoneDocument=EMPTY_CANONICAL_DOCUMENT,historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:historyContextOrUndefined({...workflowPolicy.decisions.length===0?{}:{workflow_policies:workflowPolicy.decisions},...transactionCompensationHistoryContext(params.pmRoot,[located.id,document.metadata.id],"delete")})}),historyPath=getHistoryPath(params.pmRoot,located.id),runDeleteOverride=()=>resolveItemStoreDeleteOverride({op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});if(params.dryRun===!0){const preview=await runDeleteOverride();return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:preview.effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...preview.warnings]}}const committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const{effectiveItemPath:effectiveItemPath2,skipDelete,warnings}=await runDeleteOverride(),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipDelete||await fs.rm(effectiveItemPath2);try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw skipDelete||await writeFileAtomic(effectiveItemPath2,originalRaw),error}skipDelete||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath2,document:null}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveItemPath:effectiveItemPath2,overrideWarnings:warnings,stored:skipDelete||effectiveItemPath2!==located.itemPath?await readOverriddenCommitRevision({pmRoot:params.pmRoot,settings:params.settings,id:located.id,typeToFolder:prepared.typeToFolder,fallback:tombstoneDocument,embeddedId:document.metadata.id}):{document:tombstoneDocument}}}),{derivedIndexWarnings,effectiveItemPath,stored}=committed;advanceItemMutationPreconditions(params.pmRoot,stored.document,located.id,[document.metadata.id],stored.revision);const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];return recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]}),{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
|
|
1
|
+
import I from"node:fs/promises";import{buildDeletedItemError as bt}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite as Pt}from"../history/operation-contract.js";import{enforceWorkflowMutation as B}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration as L}from"./item-metadata-read-work.js";import{advanceItemMutationPreconditions as G,assertItemMutationPreconditions as V,itemMutationPreconditionHistoryContext as kt,transactionCompensationHistoryContext as Y}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext as Ct}from"../checkpoint/mutation-context.js";import M from"node:path";import{getActiveExtensionRegistrations as K,projectAfterCommandItemSnapshot as E,recordAfterCommandAffectedItem as X,runActiveOnReadHooks as Nt,runActiveBeforeMutationHooks as J,runActiveOnWriteHooks as D,runActiveServiceOverride as Q}from"../extensions/index.js";import{collectRegisteredItemFieldNames as Tt}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT as Z,EXIT_CODE as C,TYPE_TO_FOLDER as O}from"../shared/constants.js";import{PmCliError as y}from"../shared/errors.js";import{levenshteinDistanceWithinLimit as Dt}from"../shared/levenshtein.js";import{appendHistoryEntry as tt,createHistoryEntry as et}from"../history/history.js";import{enforceHistoryStreamPolicyForItem as ot}from"../history/history-stream-policy.js";import{canonicalDocument as W,parseItemDocument as it,serializeItemDocument as Ot}from"../item/item-format.js";import{resolveItemTypeRegistry as Wt}from"../item/type-registry.js";import{effectiveItemFormatVersion as At,requiredItemFormatVersion as nt}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard as St}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease as Lt}from"../lock/lock.js";import{isFileMissingError as Mt,writeFileAtomic as A}from"../fs/fs-utils.js";import{isUtf8 as Et}from"node:buffer";import{normalizeItemId as rt,normalizeRawItemId as jt}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock as at,listAllDocumentCandidatesCached as $t,listAllDocumentsCached as Ht,listAllDocumentsCachedLight as zt,refreshItemMetadataDerivedIndex as st}from"./item-metadata-cache.js";import{getHistoryPath as dt,getItemPath as ct,ITEM_FILE_EXTENSIONS as qt,resolveWorkspaceRoot as Ut}from"./paths.js";import{resolveGovernanceKnobs as Bt}from"./settings.js";import{assertReadableTrackerRoot as j}from"./tracker-preflight.js";import{resolveClaimPrincipal as Gt}from"../shared/author.js";import{pruneResolvedDeferredFields as Vt}from"../item/deferred-fields.js";import{nowIso as mt}from"../shared/time.js";import{redactOptionalIdentityCredentials as Yt}from"../shared/url-credentials.js";async function Kt(t){try{return await I.access(t),!0}catch{return!1}}function Xt(t,o){return typeof t=="object"&&t!==null&&"code"in t&&t.code===o}function lt(t,o){t&&(t.includes(o)||t.push(o))}function $(t){return t??Tt(K())}function Jt(t){return t==="toon"?["toon","json_markdown"]:t==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function H(t,o,e="pm-",i,a=O){const n=o.trim(),d=n.startsWith("#")?n.slice(1):n;if(d.length===0)return null;const l=rt(o,e),m=jt(o),r=[...new Set([d,l,m])].filter(h=>h.length>0),f=Object.entries(a),c=Jt(i);for(const h of r){const u=new Map;for(const[s]of f)for(const g of c){const p=ct(t,s,h,g,a);await Kt(p)&&u.set(p,u.get(p)??{id:h,type:s,itemPath:p,item_format:g})}if(u.size>1){const s=[...u.keys()].map(g=>M.relative(t,g).split(M.sep).join("/")).sort();throw new y(`Item ${h} has ambiguous identity across ${s.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,C.CONFLICT,{code:"item_identity_ambiguous",item_id:h,paths:s})}for(const s of u.values())return s}return null}async function ft(t,o={}){const e=await Qt(t,o);if(e.error!==null)throw e.error;return{raw:e.raw,document:e.document}}async function Qt(t,o={}){const e=await I.readFile(t.itemPath);if(!Et(e))throw new y("Item contains invalid UTF-8; preserve a binary backup before recovering it.",C.CONFLICT,{code:"item_document_encoding_invalid",item_id:t.id,item_path:t.itemPath,byte_length:e.length,empty:!1});const i=e.toString("utf8");await Nt({path:t.itemPath,scope:"project"});let a;try{a=it(i,{format:t.item_format,requireSupportedFormat:!0,schema:o.schema,extensionFieldNames:$(o.extensionFieldNames),onWarning:n=>lt(o.warnings,n)})}catch(n){if(n instanceof y&&n.code==="item_format_version_unsupported")throw new y(`Item ${t.id}: ${n.message}`,n.exitCode,{...n.context,item_id:t.id,item_path:t.itemPath});if(n instanceof y&&n.code==="item_document_invalid")return{raw:i,document:null,error:new y(`Cannot read ${t.id} at ${t.itemPath}${e.length===0?" (zero-length file)":""}: ${n.message}`,n.exitCode,{...n.context,item_id:t.id,item_path:t.itemPath,byte_length:e.length,empty:e.length===0,nextSteps:[`Run pm history ${t.id} --full, then pm restore ${t.id} <version> to recover a recorded state.`]})};throw n}return{raw:i,document:a,error:null}}async function Zt(t,o,e=O,i,a){await j(t);const n=await Ht(t,o,e,i,a);return L(n.length),n.map(d=>d.metadata)}async function Me(t,o,e=O,i,a){await j(t);const n=await zt(t,o,e,i,a);return L(n.length),n.map(d=>d.metadata)}async function Ee(t,o,e=O,i,a,n={}){await j(t);const d=await $t(t,o,e,i,a,{includeBody:!0,forceSourceScan:n.forceSourceScan});return L(d.length),d.map(l=>({...l.metadata,body:l.body}))}function ut(t){return{async get(o){const e=await H(t.pmRoot,o,t.settings.id_prefix,t.settings.item_format,t.typeToFolder);if(!e)return null;const{document:i}=await ft(e,{schema:t.settings.schema});return{item:i.metadata,body:i.body}},list:()=>Zt(t.pmRoot,t.settings.item_format,t.typeToFolder,void 0,t.settings.schema)}}async function te(t,o){const e=new Set(Object.values(o)),i=[];return await Promise.all([...e].map(async a=>{try{const n=await I.readdir(M.join(t,a));for(const d of n)for(const l of qt)if(d.toLowerCase().endsWith(l)){i.push(d.slice(0,-l.length));break}}catch{}})),i}async function ht(t,o,e,i){const a=rt(o,e),n=await te(t,i);if(n.length===0)return[];const d=Math.max(3,Math.floor(a.length/2));return n.map(m=>({id:m,distance:Dt(m,a,d)})).filter(m=>m.distance!==null).sort((m,r)=>m.distance-r.distance).slice(0,3).map(m=>m.id)}async function ee(t,o,e,i){const a=await bt(t,o,e);if(a)return a;const n=await ht(t,o,e,i),d=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return n.length>0&&d.unshift(`Did you mean one of: ${n.join(", ")}?`),new y(`Item ${o} not found`,C.NOT_FOUND,{code:"item_not_found",id:o,nextSteps:d})}function gt(t,o){return t==="claim"||o===!0&&(t==="comment_add"||t==="comment_edit"||t==="comment_delete"||t==="note_add"||t==="learning_add"||t==="release"||t==="update"||t==="update_ownership_bypass"||t==="update_audit")}async function wt(t){const o=t.typeToFolder??Wt(t.settings,K()).type_to_folder,e=await H(t.pmRoot,t.id,t.settings.id_prefix,t.settings.item_format,o);if(!e)throw await ee(t.pmRoot,t.id,t.settings.id_prefix,o);const i=await Lt(t.pmRoot,e.id,t.settings.locks.ttl_seconds,t.author,!!t.force,t.settings.governance.force_required_for_stale_lock,t.settings.locks.wait_ms,{waitPolicy:"progress"}),a=i.release;try{const n=[],{raw:d,document:l}=await ft(e,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames,warnings:n}),m=l.metadata.assignee?.trim(),r=Yt(m),f=l.metadata.claim_principal?.trim()||m,c=Gt(t.author),h=Bt(t.settings);if(r&&f!==c&&!t.force&&!gt(t.op,t.bypassAssigneeConflict)){if(h.ownership_enforcement==="strict")throw new y(`Item ${e.id} is assigned to ${r}. Use --force to override.`,C.CONFLICT);h.ownership_enforcement==="warn"&&n.push(`ownership_warning:assignee_conflict:${e.id}:${r}`)}return{typeToFolder:o,located:e,originalRaw:d,document:l,warnings:n,releaseLock:a,lease:i}}catch(n){throw await a(),n}}function pt(t){return Object.keys(t).length===0?void 0:t}async function yt(t,o,e,i){return t.fence(async()=>{let a;try{a=await I.readFile(o.itemPath,"utf8")}catch(n){if(!Mt(n))throw n;a=null}if(a!==e)throw new y(`Item ${o.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,C.CONFLICT,{code:"stale_revision",item_id:o.id,reason:a===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return i()})}function oe(t,o,e){if(!t.handled||typeof t.result!="object"||t.result===null)return{effectiveTargetItemPath:o,effectiveSerializedAfter:e,skipItemWrite:!1};const i=t.result;return{effectiveTargetItemPath:typeof i.target_item_path=="string"&&i.target_item_path.trim().length>0?i.target_item_path:o,effectiveSerializedAfter:typeof i.contents=="string"?i.contents:e,skipItemWrite:i.skip_write===!0}}async function _t(t){try{const o=await H(t.pmRoot,t.id,t.settings.id_prefix,t.settings.item_format,t.typeToFolder);if(!o)return{document:Z};const e=it(await I.readFile(o.itemPath,"utf8"),{format:o.item_format,requireSupportedFormat:!0,schema:t.settings.schema,extensionFieldNames:$(t.extensionFieldNames)});return e.metadata.id===t.embeddedId?{document:e}:{document:t.fallback,revision:It}}catch{return{document:t.fallback,revision:It}}}const It="unreadable-after-storage-override";async function ie(t){const o=await Q("item_store_delete",t),e=o.handled&&typeof o.result=="object"&&o.result!==null?o.result:{};return{effectiveItemPath:typeof e.item_path=="string"&&e.item_path.trim().length>0?e.item_path:t.item_path,skipDelete:e.skip_delete===!0,warnings:o.warnings}}async function ne(t){if(!t.skipItemWrite){if(t.effectiveTargetItemPath!==t.originalItemPath){await A(t.originalItemPath,t.originalRaw),await I.rm(t.effectiveTargetItemPath,{force:!0});return}await A(t.originalItemPath,t.originalRaw)}}function re(t,o){Vt(t.metadata)&&o.push("deferred_fields")}async function z(t){Pt(t.op);const o=await wt({pmRoot:t.pmRoot,settings:t.settings,id:t.id,op:t.op,author:t.author,force:t.force,bypassAssigneeConflict:t.bypassAssigneeConflict,extensionFieldNames:t.extensionFieldNames,typeToFolder:t.typeToFolder}),{typeToFolder:e,located:i,originalRaw:a,document:n,warnings:d,releaseLock:l,lease:m}=o;try{V(t.pmRoot,n,i.id);const r=W(n,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),f=W(structuredClone(n),{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),c=await t.mutate(f,{storageId:i.id});if(re(f,c.changedFields),t.skipNoop===!0&&c.changedFields.length===0)return{item:r.metadata,body:r.body,changedFields:[],warnings:[...d,...c.warnings??[]]};const h={...t.resolveHistoryContext?.(),...Ct(t.pmRoot,i.id),...kt(t.pmRoot,[i.id,n.metadata.id])},u=Math.max(nt(r.metadata),nt(f.metadata));St(Ut(t.pmRoot),u),u>At(f.metadata)&&(f.metadata.pm_format_version=u,c.changedFields.push("pm_format_version")),f.metadata.updated_at=mt();const s=W(f,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),g=await B({pmRoot:t.pmRoot,settings:t.settings,operation:t.op,author:t.author,before:r,after:s});await J({pm_root:t.pmRoot,operation:t.op,before:r,after:s,changed_fields:c.changedFields,author:t.author,sdk:ut({pmRoot:t.pmRoot,settings:t.settings,typeToFolder:e})});const p=await ot({pmRoot:t.pmRoot,settings:t.settings,itemId:i.id,commandLabel:t.op}),v="toon",x=Ot(s,{format:v,schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),b=ct(t.pmRoot,s.metadata.type,i.id,v,e),F=dt(t.pmRoot,i.id),N=await yt(m,i,a,async()=>{const P=await Q("item_store_write",{op:t.op,pm_root:t.pmRoot,item_id:i.id,source_item_path:i.itemPath,target_item_path:b,history_path:F,item_format:v,before:r,after:s,contents:x}),{effectiveTargetItemPath:_,effectiveSerializedAfter:q,skipItemWrite:k}=oe(P,b,x),vt=await at(t.pmRoot,t.author);let U=[];try{k||await A(_,q),!k&&_!==i.itemPath&&await I.rm(i.itemPath);const Rt=et({nowIso:s.metadata.updated_at,author:t.author,op:t.op,before:r,after:s,message:t.message,context:pt({...h,...g.decisions.length===0?{}:{workflow_policies:g.decisions},...Y(t.pmRoot,[i.id,n.metadata.id],t.op)})});try{await tt(F,Rt)}catch(xt){throw await ne({skipItemWrite:k,effectiveTargetItemPath:_,originalItemPath:i.itemPath,originalRaw:a}),xt}k||(U=await st({pmRoot:t.pmRoot,preferredFormat:t.settings.item_format,typeToFolder:e,schema:t.settings.schema,itemPath:_,previousItemPath:i.itemPath,document:s}))}finally{await vt()}const Ft=k||_!==b||q!==x;return{derivedIndexWarnings:U,effectiveTargetItemPath:_,overrideWarnings:P.warnings,stored:Ft?await _t({pmRoot:t.pmRoot,settings:t.settings,id:i.id,typeToFolder:e,extensionFieldNames:t.extensionFieldNames,fallback:s,embeddedId:s.metadata.id}):{document:s}}}),{derivedIndexWarnings:w,effectiveTargetItemPath:R,stored:T}=N;G(t.pmRoot,T.document,i.id,[s.metadata.id],T.revision);const S=[...await D({path:R,scope:"project",op:t.op,item_id:s.metadata.id,item_type:s.metadata.type,before:r,after:s,changed_fields:c.changedFields}),...await D({path:F,scope:"project",op:`${t.op}:history`,item_id:s.metadata.id,item_type:s.metadata.type,before:r,after:s,changed_fields:c.changedFields})];return X({id:s.metadata.id,op:t.op,item_type:s.metadata.type,previous_status:r.metadata.status,status:s.metadata.status,previous:E(r.metadata,c.changedFields),current:E(s.metadata,c.changedFields),changed_fields:c.changedFields}),{item:s.metadata,body:s.body,changedFields:c.changedFields,warnings:[...d,...c.warnings??[],...g.warnings,...p.warnings,...N.overrideWarnings,...w,...S]}}finally{await l()}}async function je(t){const{historyContext:o,...e}=t;return z({...e,resolveHistoryContext:()=>o})}async function $e(t){return z(t)}async function He(t){return z(t)}const ze={appendWarning:lt,bypassesAssigneeConflict:gt,buildDidYouMeanSuggestions:ht,isErrno:Xt};async function qe(t){const o=await wt({pmRoot:t.pmRoot,settings:t.settings,id:t.id,op:"delete",author:t.author,force:t.force}),{located:e,originalRaw:i,document:a,warnings:n,releaseLock:d,lease:l}=o;try{V(t.pmRoot,a,e.id);const m=$(void 0),r=W(a,{schema:t.settings.schema,extensionFieldNames:m}),f=await B({pmRoot:t.pmRoot,settings:t.settings,operation:"delete",author:t.author,before:r,after:null,dryRun:t.dryRun});await J({pm_root:t.pmRoot,operation:"delete",before:r,after:null,changed_fields:["deleted"],author:t.author,dry_run:t.dryRun===!0,sdk:ut({pmRoot:t.pmRoot,settings:t.settings,typeToFolder:o.typeToFolder})});const c=await ot({pmRoot:t.pmRoot,settings:t.settings,itemId:e.id,commandLabel:"delete"}),h=mt(),u=Z,s=et({nowIso:h,author:t.author,op:"delete",before:r,after:u,message:t.message,context:pt({...f.decisions.length===0?{}:{workflow_policies:f.decisions},...Y(t.pmRoot,[e.id,a.metadata.id],"delete")})}),g=dt(t.pmRoot,e.id),p=()=>ie({op:"delete",pm_root:t.pmRoot,item_id:e.id,item_path:e.itemPath,history_path:g,before:r});if(t.dryRun===!0){const w=await p();return{item:r.metadata,changedFields:["deleted"],targetPath:w.effectiveItemPath,warnings:[...n,...f.warnings,...c.warnings,...w.warnings]}}const v=await yt(l,e,i,async()=>{const{effectiveItemPath:w,skipDelete:R,warnings:T}=await p(),S=await at(t.pmRoot,t.author);let P=[];try{R||await I.rm(w);try{await tt(g,s)}catch(_){throw R||await A(w,i),_}R||(P=await st({pmRoot:t.pmRoot,preferredFormat:t.settings.item_format,typeToFolder:o.typeToFolder,schema:t.settings.schema,itemPath:w,document:null}))}finally{await S()}return{derivedIndexWarnings:P,effectiveItemPath:w,overrideWarnings:T,stored:R||w!==e.itemPath?await _t({pmRoot:t.pmRoot,settings:t.settings,id:e.id,typeToFolder:o.typeToFolder,fallback:u,embeddedId:a.metadata.id}):{document:u}}}),{derivedIndexWarnings:x,effectiveItemPath:b,stored:F}=v;G(t.pmRoot,F.document,e.id,[a.metadata.id],F.revision);const N=[...await D({path:b,scope:"project",op:"delete",item_id:r.metadata.id,item_type:r.metadata.type,before:r,after:u,changed_fields:["deleted"]}),...await D({path:g,scope:"project",op:"delete:history",item_id:r.metadata.id,item_type:r.metadata.type,before:r,after:u,changed_fields:["deleted"]})];return X({id:r.metadata.id,op:"delete",item_type:r.metadata.type,previous_status:r.metadata.status,previous:E(r.metadata,Object.keys(r.metadata)),changed_fields:["deleted"]}),{item:r.metadata,changedFields:["deleted"],warnings:[...n,...f.warnings,...c.warnings,...v.overrideWarnings,...x,...N]}}finally{await d()}}export{ee as buildItemNotFoundError,ut as createMutationGuardSdk,qe as deleteItem,ze as itemStoreTestOnly,Zt as listAllItemMetadata,Me as listAllItemMetadataLight,Ee as listAllItemMetadataWithBody,H as locateItem,He as mutateItem,je as mutateItemWithHistoryContext,$e as mutateItemWithHistoryContextResolver,ft as readLocatedItem,Qt as readLocatedItemSnapshot};
|
|
2
2
|
//# sourceMappingURL=item-store.js.map
|
package/dist/core/store/paths.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{readFileSync as R,readdirSync as x,realpathSync as m,statSync as p}from"node:fs";import j from"node:os";import r from"node:path";import{PM_DIRNAME as l,EXIT_CODE as E,SETTINGS_FILENAME as f,TYPE_TO_FOLDER as d}from"../shared/constants.js";import{PmCliError as g}from"../shared/errors.js";import{isFileAbsentError as h}from"../fs/fs-utils.js";import{toDefaultFolder as T}from"../item/type-registry.js";const _={json_markdown:".md",toon:".toon"},S={".md":"json_markdown",".toon":"toon"},v=new Set([".git","coverage","dist","node_modules"]),Y=[".md",".toon"];function u(e){try{return p(e),!0}catch{return!1}}function y(e){let t=r.resolve(e);const o=[];for(;r.dirname(t)!==t;)try{return r.join(m(t),...o)}catch(n){if(!h(n))throw n;o.unshift(r.basename(t)),t=r.dirname(t)}return r.join(m(t),...o)}function I(e){try{return p(e),!0}catch(t){if(h(t))return!1;throw t}}function P(e){try{const t=JSON.parse(R(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function A(e){let t=y(e);for(;;){const o=r.join(t,l),n=r.join(o,f);if(u(n))return o;const i=r.join(t,f);if(u(i)&&P(i))return t;if(I(r.join(t,".git")))return o;const s=r.dirname(t);if(s===t)return;t=s}}function F(e){return A(e)??r.resolve(e,l)}function z(e,t){const o=t?r.resolve(t):void 0;try{return x(r.resolve(e),{withFileTypes:!0}).filter(n=>n.isDirectory()&&!v.has(n.name)).map(n=>r.join(r.resolve(e),n.name)).filter(n=>n!==o).filter(n=>u(a(n))).filter(n=>P(a(n))).sort((n,i)=>n.localeCompare(i))[0]}catch{return}}function H(e,t){const o=process.env.PM_PATH,n=t?.trim()||o?.trim();if(n){const i=r.resolve(e,n);if(!u(a(i))){const s=r.join(i,l);if(u(a(s)))return s}return i}return F(e)}function J(e){const t=r.resolve(e),o=r.dirname(t);return r.basename(t)==="pm"&&r.basename(o)===".agents"?r.dirname(o):t}function K(e){const t=process.env.PM_GLOBAL_PATH?.trim(),o=t&&t.length>0?t:r.join(j.homedir(),".pm-cli");return r.resolve(e,o)}function a(e){return r.join(e,f)}function N(e,t,o=d){const n=o[t]??T(t);return r.join(e,n)}function U(e,t,o,n="toon",i=d){return r.join(N(e,t,i),`${o}${_[n]}`)}function W(e){const t=e.replaceAll("\\","/"),o=r.posix.extname(t).toLowerCase();return S[o]??null}function q(e,t){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(t))throw new g("Invalid history item id: expected a single filename.",E.USAGE);return r.join(e,"history",`${t}.jsonl`)}function Q(e,t){return r.join(e,"locks",`${t}.lock`)}function O(e){return r.join(e,"runtime")}function c(e){return r.join(O(e),"test-runs")}function M(e){return r.join(c(e),"runs")}function V(e,t){return r.join(M(e),`${t}.json`)}function $(e){return r.join(c(e),"stdout")}function D(e){return r.join(c(e),"stderr")}function Z(e,t){return r.join($(e),`${t}.log`)}function tt(e,t){return r.join(D(e),`${t}.log`)}function L(e){return r.join(c(e),"results")}function et(e,t){return r.join(L(e),`${t}.json`)}export{Y as ITEM_FILE_EXTENSIONS,_ as ITEM_FILE_EXTENSION_BY_FORMAT,z as discoverNearbyPmRoot,q as getHistoryPath,W as getItemFormatFromPath,U as getItemPath,Q as getLockPath,O as getRuntimePath,a as getSettingsPath,V as getTestRunRecordPath,et as getTestRunResultPath,tt as getTestRunStderrPath,Z as getTestRunStdoutPath,c as getTestRunsPath,M as getTestRunsRecordsPath,L as getTestRunsResultsPath,D as getTestRunsStderrPath,$ as getTestRunsStdoutPath,N as getTypeDirPath,K as resolveGlobalPmRoot,F as resolveImplicitPmRoot,H as resolvePmRoot,J as resolveWorkspaceRoot};
|
|
2
2
|
//# sourceMappingURL=paths.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{EXIT_CODE as c}from"../shared/constants.js";import{PmCliError as d}from"../shared/errors.js";import{stableValueEquals as o}from"../shared/serialization.js";function i(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function g(t,r,e,a=[]){if(o(t,r)&&(a.length>0||i(e)))return e;if(o(t,e)||o(r,e))return r;if((t===void 0||i(t))&&i(r)&&i(e)){const s=t??{},f=new Set([...Object.keys(s),...Object.keys(r),...Object.keys(e)]);return Object.fromEntries([...f].flatMap(n=>{const h=g(Object.hasOwn(s,n)?s[n]:void 0,Object.hasOwn(r,n)?r[n]:void 0,Object.hasOwn(e,n)?e[n]:void 0,[...a,n]);return h===void 0?[]:[[n,h]]}))}throw new d(`Settings changed concurrently at ${a.join(".")||"<root>"}; read the latest settings and reapply the intended change.`,c.CONFLICT,{reason:"stale_settings_snapshot",required:"Read a fresh settings snapshot and reapply the intended change.",why:"Another writer changed the same setting after this snapshot was read.",examples:["pm config project export --json"],nextSteps:["Read the current settings, then retry the original config operation."]})}export{g as reconcileSettingsSnapshot};
|
|
2
2
|
//# sourceMappingURL=settings-concurrency.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{stat as c}from"node:fs/promises";const s=new Map;function i(t){return[...new Set(t.map(e=>e.trim()).filter(e=>e.length>0))].sort((e,a)=>e.localeCompare(a))}async function m(t){try{const e=await c(t);return{path:t,mtime_ms:e.mtimeMs,size:e.size}}catch{return{path:t,mtime_ms:null,size:null}}}async function u(t){const e=i(t),a=await Promise.all(e.map(r=>m(r)));return a.sort((r,n)=>r.path.localeCompare(n.path)),a}function h(t,e){if(t.length!==e.length)return!1;for(let a=0;a<t.length;a+=1){const r=t[a],n=e[a];if(r.path!==n.path||r.mtime_ms!==n.mtime_ms||r.size!==n.size)return!1}return!0}function p(t){return s.get(t)}function d(t,e){const a=i(e.tracked_paths),r=[...e.signatures].map(n=>({path:n.path,mtime_ms:n.mtime_ms,size:n.size})).sort((n,o)=>n.path.localeCompare(o.path));s.set(t,{tracked_paths:a,signatures:r,value:e.value})}function g(t){if(t){s.delete(t);return}s.clear()}export{g as clearSettingsReadCache,u as collectSettingsReadCacheSignatures,p as getSettingsReadCacheEntry,d as setSettingsReadCacheEntry,h as settingsReadCacheSignaturesEqual};
|
|
2
2
|
//# sourceMappingURL=settings-read-cache.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
`,result:{...
|
|
1
|
+
import{createHash as P}from"node:crypto";import{readFileIfExists as T}from"../fs/fs-utils.js";import{runActiveOnReadHooks as k,runActiveOnWriteHooks as x}from"../extensions/index.js";import{mutateWorkspaceJsonWithHistory as I}from"../history/workspace-history.js";import{resolveAuthor as R}from"../shared/author.js";import{EXIT_CODE as c}from"../shared/constants.js";import{PmCliError as a}from"../shared/errors.js";import{toErrorMessage as C}from"../shared/primitives.js";import{stableValueEquals as D}from"../shared/serialization.js";import{getSettingsPath as O}from"./paths.js";import{readSettings as G}from"./settings.js";import{clearSettingsReadCache as V}from"./settings-read-cache.js";import{CORE_SETTINGS_SECTION_KEYS as q}from"./settings-validator.js";const H=/^[a-z][a-z0-9_-]{0,63}$/u,M=new Set(["constructor","prototype"]),w="settings:section:write",U=240;function h(e){return`sha256:${P("sha256").update(g(e)).digest("hex")}`}function g(e){return Array.isArray(e)?`[${e.map(t=>g(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${g(Object.getOwnPropertyDescriptor(e,n)?.value)}`).join(",")}}`:String(JSON.stringify(e))}function _(e){if(!H.test(e)||M.has(e))throw new a(`Invalid settings section name "${e.slice(0,80)}". Use 1-64 lowercase letters, digits, underscores or hyphens, starting with a letter.`,c.USAGE,{code:"settings_section_name_invalid",field:"section",required:"Name the section after the package, for example lint or jev."});if(q.includes(e))throw new a(`Settings section "${e}" is owned by core settings; extension sections must use another name.`,c.USAGE,{code:"settings_section_reserved",field:"section",value:e,required:"Read core settings with readSettings and change them with writeSettings or pm config."})}function b(e){let t;try{t=JSON.parse(e)}catch{t=void 0}if(typeof t!="object"||t===null||Array.isArray(t))throw new a("settings.json is not a JSON object, so no settings section can be read or written.",c.USAGE,{code:"settings_section_document_malformed",reason:t===void 0?"settings_json_malformed":"settings_json_not_object",nextSteps:["Repair .agents/pm/settings.json so it is a JSON object, then retry.","Run pm health to confirm the settings warning has cleared."]});return t}function y(e,t,n){let r;try{r=n===void 0?t:n(t)}catch(i){throw new a(`Settings section "${e}" is invalid: ${C(i).slice(0,U)}`,c.USAGE,{code:"settings_section_invalid",field:e,required:`Fix the "${e}" section of .agents/pm/settings.json so the owning package accepts it, then retry.`})}return r}function j(e){return typeof Reflect.get(e,"toJSON")=="function"}function S(e){return e.length===0?"the value":e.join(".")}function E(e,t){return Object.values(Object.getOwnPropertyDescriptors(e)).every(n=>"value"in n&&(!t||n.enumerable===!0))}function F(e){if(Object.getPrototypeOf(e)!==Array.prototype||!E(e,!1))return!1;const t=Object.keys(e);return t.length===e.length&&t.every((n,r)=>n===String(r))&&Object.getOwnPropertyNames(e).length===e.length+1&&Object.getOwnPropertySymbols(e).length===0&&!j(e)}function W(e){const t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&E(e,!0)&&Object.getOwnPropertySymbols(e).length===0&&!j(e)}function z(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return null;const n=S(t);return typeof e=="number"?Number.isFinite(e)?null:{detail:`${n} is a non-finite number`,representable:!0}:{detail:`${n} is ${typeof e}`,representable:typeof e!="bigint"&&t.length>0}}function N(e,t=[],n=new Set){if(typeof e!="object"||e===null)return z(e,t);const r=S(t);if(n.has(e))return{detail:`${r} is a circular reference`,representable:!1};if(!(Array.isArray(e)?F(e):W(e)))return{detail:`${r} is not a plain JSON ${Array.isArray(e)?"array":"object"}`,representable:!0};n.add(e);for(const[o,s]of Object.entries(e)){const f=N(s,[...t,o],n);if(f!==null)return f}return n.delete(e),null}function A(e,t=[]){if(typeof e!="object"||e===null)return null;for(const[n,r]of Object.entries(e)){const i=[...t,n];if(n==="__proto__"||n==="prototype"&&t.at(-1)==="constructor")return S(i);const o=A(r,i);if(o!==null)return o}return null}function $(e,t,n){return y(e,t,()=>{throw new Error(n)})}function L(e,t){const n=N(t);if(n!==null){const i=n.representable?`the value would change when stored as JSON: ${n.detail}`:`the value is not representable as JSON: ${n.detail}`;return $(e,t,i)}const r=A(t);return r!==null?$(e,t,`${r} is a reserved key that settings history cannot record`):JSON.parse(JSON.stringify(t))}function J(e,t){return Object.hasOwn(e,t)?e[t]:void 0}async function se(e,t,n={}){_(t);const r=O(e);await k({path:r,scope:"project"});const i=await T(r),o=i===null?void 0:J(b(i),t);if(o===void 0)return{section:t,source:"default",value:n.defaultValue,revision:null};const s=h(o);return{section:t,source:"stored",value:y(t,structuredClone(o),n.validate),revision:s}}async function ce(e,t,n,r={}){_(t);const i=n===void 0?void 0:L(t,y(t,n,r.validate)),o=O(e),s=await G(e);try{const f=await I({pmRoot:e,filePath:o,op:w,author:R(r.author,s.author_default),lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms,recordCreation:!1,mutate:d=>{if(d===null)throw new a("settings.json does not exist, so no settings section can be written.",c.NOT_FOUND,{code:"settings_section_document_missing",required:"Initialize the tracker with pm init, then retry."});const u=b(d),l=J(u,t),p=l===void 0?null:h(l);if(r.expectedRevision!==void 0&&r.expectedRevision!==p)throw new a(`Settings section "${t}" changed since it was read; read it again and reapply the change.`,c.CONFLICT,{code:"settings_section_revision_conflict",field:t,expected_revision:r.expectedRevision,current_revision:p,required:"Read the section again with readSettingsSection, then retry with its current revision."});const m={section:t,changed:!1,previous_revision:p,revision:i===void 0?null:h(i)};return D(l,i)?{raw:d,result:m}:(i===void 0?delete u[t]:u[t]=i,{raw:`${JSON.stringify(u,null,2)}
|
|
2
|
+
`,result:{...m,changed:!0}})}});return f.changed&&await x({path:o,scope:"project",op:w}),f.result}finally{V(e)}}export{se as readSettingsSection,h as settingsSectionRevision,ce as writeSettingsSection};
|
|
3
3
|
//# sourceMappingURL=settings-sections.js.map
|