@unbrained/pm-cli 2026.10.4 → 2026.10.5
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/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +11 -0
- 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.d.ts +1 -1
- package/dist/cli/commander-usage.js +7 -4
- 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 +3 -1
- package/dist/cli/extension-command-help.js +5 -3
- package/dist/cli/extension-command-options.js +1 -1
- package/dist/cli/extension-recovery.js +1 -1
- package/dist/cli/help-content.js +5 -2
- package/dist/cli/help-json-payload.js +6 -3
- 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/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 +1 -1
- package/dist/cli/register-mutation.js +2 -2
- 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/invocation-options.js +1 -1
- package/dist/cli/runtime/projection-retry.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 +2 -2
- 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 +163 -163
- package/dist/cli-bundle/chunks/chunk-3CYOBJUK.js +3 -0
- package/dist/cli-bundle/chunks/chunk-5MNOWZPN.js +3 -0
- package/dist/cli-bundle/chunks/chunk-AJ7H6XUF.js +20 -0
- package/dist/cli-bundle/chunks/chunk-D332RXZ7.js +80 -0
- package/dist/cli-bundle/chunks/chunk-HRJ6G6ZG.js +31 -0
- package/dist/cli-bundle/chunks/chunk-KRVI56QE.js +6 -0
- package/dist/cli-bundle/chunks/chunk-N4YGSG6F.js +238 -0
- package/dist/cli-bundle/chunks/{chunk-7CE2DJMA.js → chunk-OOLYASYJ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-R7CG2DB7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TGMONGWX.js +2 -0
- package/dist/cli-bundle/chunks/chunk-UZ7BIUCI.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-GZMWISWW.js → chunk-VZ63DEVJ.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-WFZ4UEOB.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YVBRASXO.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-SMKHR6BM.js → chunk-Z66DWDAU.js} +87 -87
- package/dist/cli-bundle/chunks/{register-list-query-QBGXO5JJ.js → register-list-query-75QXHIFH.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-YS54SCHG.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-6KHZQSYJ.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-RTATEN2M.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-Q6DJ5DFQ.js → chunk-2CVX3KR3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5C3IDDW7.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-467EW5RL.js → chunk-ABV67XCC.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-B5RSLVE6.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-C224METM.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-CLDPTMQY.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-DDRN42PB.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7O4NUJVO.js → chunk-DOVTUKJQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ECBOPEJE.js +75 -0
- package/dist/cli-bundle/focused-chunks/chunk-GITOYRUW.js +165 -0
- package/dist/cli-bundle/focused-chunks/chunk-GUIF3WVC.js +30 -0
- package/dist/cli-bundle/focused-chunks/chunk-LE4JUCRR.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HFAW3FJQ.js → chunk-PSXFFQFT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-RHIH6XIW.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-UDYRVBOZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-XV5RV4ZT.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JCVMOSWQ.js → chunk-YMU42COG.js} +2 -2
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +32 -32
- 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 +55 -55
- 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 +10 -10
- 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/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 -1
- 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/preflight-ownership.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/fs/atomic-create.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/digest.js +1 -1
- package/dist/core/history/drift-cache.js +3 -3
- package/dist/core/history/drift-scan.d.ts +4 -0
- 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 +8 -7
- 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.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.js +1 -1
- package/dist/core/history/replay.js +2 -1
- 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 -1
- package/dist/core/item/actionability.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 +6 -4
- package/dist/core/item/item-record.js +1 -1
- package/dist/core/item/item-type-definition.js +1 -1
- package/dist/core/item/parent-reference-policy.js +1 -1
- package/dist/core/item/parse.js +8 -2
- 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-gc.js +1 -1
- package/dist/core/lock/lock.js +3 -3
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output-control.js +1 -1
- package/dist/core/output/output.js +22 -10
- package/dist/core/output/query-summary.js +1 -1
- package/dist/core/output/tabular.js +3 -1
- 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.js +1 -1
- package/dist/core/profile/profile-plan.js +1 -1
- package/dist/core/profile/profile-presets.js +25 -1
- 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/session/session-state.js +1 -1
- package/dist/core/shared/agent-session-context.js +1 -1
- package/dist/core/shared/author.js +5 -1
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/command-types.js +1 -1
- package/dist/core/shared/conflict-markers.js +1 -1
- package/dist/core/shared/constants.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/primitives.js +1 -1
- package/dist/core/shared/secret-rules.js +1 -1
- 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 -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 +7 -7
- package/dist/core/store/item-metadata-read-work.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-validator.js +1 -1
- package/dist/core/store/settings.js +3 -3
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/core/telemetry/consent.js +2 -2
- 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 -5
- package/dist/core/test/background-runs.js +3 -3
- 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 +6 -4
- 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/refusal-closure-census.js +2 -1
- package/dist/sdk/agent/refusal-closure.js +1 -1
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent/refusal-reachability.js +3 -1
- package/dist/sdk/agent/subcommand-recovery.js +1 -1
- package/dist/sdk/agent/task-transcript-contracts.js +1 -1
- package/dist/sdk/agent/tracker-preflight-contracts.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +3 -1
- 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/authoring.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -3
- 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 -1
- 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.js +1 -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 -1
- package/dist/sdk/completion/fish.js +13 -7
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +14 -8
- package/dist/sdk/completion.js +1 -1
- package/dist/sdk/compose.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 -3
- 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/contracts.js +1 -1
- package/dist/sdk/core-governance.js +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/corpus-shape.js +1 -1
- package/dist/sdk/define.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/agent-environment.js +1 -1
- package/dist/sdk/environment/host-environment-errors.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -1
- 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/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 +4 -2
- 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/migrations.js +2 -2
- 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 -4
- 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 +1 -1
- 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/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 +1 -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/coverage-assurance.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 +1 -1
- package/dist/sdk/governance/extension-host-version.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -1
- package/dist/sdk/governance/hierarchy-validation.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 -1
- package/dist/sdk/governance/reindex.js +5 -4
- 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-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 -1
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/graph/adapter.js +1 -1
- 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/centrality.js +1 -1
- package/dist/sdk/graph/conformance.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/index.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/graph.js +1 -1
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/guide.js +8 -1
- package/dist/sdk/history/attestation-command.js +1 -1
- 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.js +1 -1
- package/dist/sdk/history/salvage.js +3 -2
- 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.js +1 -1
- package/dist/sdk/improvement-ledger-validation.js +1 -1
- package/dist/sdk/improvement-ledger.js +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init-agent-guidance.js +16 -2
- package/dist/sdk/init.js +16 -2
- 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.js +1 -1
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/append.js +4 -2
- package/dist/sdk/lifecycle/claim.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/create.js +1 -1
- package/dist/sdk/lifecycle/delete.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/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 +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/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/shared-unset-fields.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 -1
- package/dist/sdk/lifecycle-completion.js +1 -1
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/linked-artifacts.js +2 -1
- package/dist/sdk/mcp/apps.js +1 -1
- package/dist/sdk/mcp/authorization.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/mcp/interactions.js +1 -1
- package/dist/sdk/mcp/protocol.js +1 -1
- package/dist/sdk/mcp/skills.js +3 -1
- 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 +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/install.js +4 -2
- 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/three-way.js +3 -2
- package/dist/sdk/merge/worktree-config.js +1 -1
- 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-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 -1
- 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 -1
- 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 -1
- package/dist/sdk/query/complete-list.js +1 -1
- package/dist/sdk/query/context.js +2 -1
- package/dist/sdk/query/duplicate-candidates.js +1 -1
- package/dist/sdk/query/get.d.ts +14 -2
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/item-filter-options.js +1 -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-ready-budget.js +1 -1
- package/dist/sdk/query/next.js +2 -1
- 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 -1
- 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 -2
- package/dist/sdk/query/search/types.js +1 -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/workspace-contracts.js +1 -1
- package/dist/sdk/query.js +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/provenance.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 +7 -4
- package/dist/sdk/relationship-kinds/contract.js +1 -1
- package/dist/sdk/relationship-migration.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/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.js +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.js +1 -1
- package/dist/sdk/runtime-stats-options.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/scheduling-shortcuts.js +1 -1
- package/dist/sdk/schema-migration.js +4 -3
- package/dist/sdk/schema.js +7 -1
- 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.js +1 -1
- package/dist/sdk/telemetry-flush.js +1 -1
- package/dist/sdk/telemetry.js +4 -3
- package/dist/sdk/templates.js +26 -2
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/entry.js +1 -1
- package/dist/sdk/test/execution.js +6 -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/runs.js +1 -1
- package/dist/sdk/test/trust.js +2 -2
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/dist/sdk/testing.js +7 -4
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
- package/dist/sdk/traceability/source-traceability.js +2 -1
- package/dist/sdk/tracker-root-discovery.js +1 -1
- 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-recipe.js +1 -1
- package/dist/sdk/workspace-snapshot.js +5 -4
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/sdk/workspace.js +3 -2
- package/dist/types/index.js +1 -1
- package/dist/types.js +1 -1
- package/docs/AGENT_EVIDENCE_CONSISTENCY.md +88 -0
- package/docs/GET_READ_EVIDENCE.md +68 -0
- package/docs/README.md +2 -0
- package/marketplace.json +2 -2
- package/package.json +1 -1
- 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/extensions/vcs/index.ts +4 -2
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +2 -2
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +2 -2
- package/plugins/pm-codex/plugin.json +1 -1
- package/scripts/finalize-build.mjs +3 -2
- package/dist/cli-bundle/chunks/chunk-7UVXKI7K.js +0 -2
- package/dist/cli-bundle/chunks/chunk-D7Z2ZMJL.js +0 -3
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-J52QIRRZ.js +0 -80
- package/dist/cli-bundle/chunks/chunk-JDKD3WGG.js +0 -6
- package/dist/cli-bundle/chunks/chunk-JQ7DW663.js +0 -2
- package/dist/cli-bundle/chunks/chunk-QXIDOOWT.js +0 -20
- package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-V3U77H3V.js +0 -31
- package/dist/cli-bundle/chunks/chunk-XZDWAYJC.js +0 -3
- package/dist/cli-bundle/chunks/chunk-Y6VRBTP3.js +0 -238
- package/dist/cli-bundle/chunks/chunk-YAAFYFS4.js +0 -8
- package/dist/cli-bundle/chunks/register-mutation-53ZLT4RX.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-OBK2FXUU.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-HM3OCBH2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2JFYR56O.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-32EVUSS4.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-5GUSO2P4.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-6XBRADQQ.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-CURTIIQT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IJUWEEEB.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-JMJK2L4Z.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-KG3H4UZZ.js +0 -30
- package/dist/cli-bundle/focused-chunks/chunk-MHQ2XICU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-RJV6QVJE.js +0 -75
- package/dist/cli-bundle/focused-chunks/chunk-ZE2JZ7R6.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-ZLEN4HZD.js +0 -165
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import{$h as Jo,$i as as,A as ge,Ae as Yt,Ag as Ge,Ai as dn,Am as pn,Bj as cs,C as W,Ch as on,D as uo,Dc as D,Dg as So,Dh as Bo,Eg as To,Eh as Ho,Fg as Ro,Fl as un,Gh as Go,Ha as je,Hd as ko,Id as Eo,Ih as sn,Jh as Ko,Kd as yr,Kh as zo,Lf as wr,M as K,Ma as gr,Mc as zt,Mg as xo,Mh as Ir,Na as Gt,Ng as Do,Oa as mo,Oc as Vt,Og as Ao,Oi as rs,Pc as _o,Pg as Oo,Pi as is,Qf as U,Qg as Lo,Qh as Ve,Rh as Vo,Sh as qo,Tb as I,Th as Wo,Ti as os,Ua as L,Uc as yo,Ug as Ke,Uh as Yo,Va as Kt,Vb as re,Vh as Ce,Vi as qe,Vk as ds,Wa as po,Wh as Cr,Xh as Xo,Yh as an,Yi as de,Zf as Co,Zh as xe,Zi as Se,_h as Z,_i as ss,_l as fn,ab as O,ag as ye,ai as Qo,aj as le,be as br,bh as Fo,bj as ln,ca as hr,cd as bo,ff as x,gb as Ue,hf as vr,id as qt,if as Xt,ih as be,ij as ve,jc as go,jf as C,jh as Mo,jm as us,kd as vo,kf as Io,kg as J,kh as nn,km as fs,ko as ue,lf as _e,li as Zo,lo as fe,ma as fo,mf as He,mg as tn,na as g,od as _r,oh as No,om as Tr,p as ne,pa as _,pd as Wt,pf as Jt,ph as $o,qd as Ie,qh as Po,qi as F,rd as ce,rf as Qt,rh as kr,sh as jo,si as es,tf as Zt,th as Uo,u as Bt,ud as wo,uh as Er,ui as ts,vb as ho,vd as Be,vh as rn,w as pr,wh as ze,wi as cn,x as Ht,xf as en,xg as Q,xi as ns,y as Pe,yg as R,yl as ls,z as ae,zg as $,zi as Sr,zm as mn}from"./chunk-N4YGSG6F.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59842825-3a81-53f4-845d-db2257ec6286")}catch{}})();async function Rr(e){let t=O(process.cwd(),e);await U(t);let n=await F(t),r=L(n,D());return{pmRoot:t,settings:n,typeRegistry:r}}async function hn(e,t,n,r){Ue(e,Sr(t));let i=await de(e,t,n.id_prefix,n.item_format,r);if(i)return{id:i.id,historyPath:Ue(e,i.id),located:i};let o=dn(t,n.id_prefix),s=Sr(t),a=o===s?[o]:[o,s];for(let c of a){let d=Ue(e,c);if(await Ht(d))return{id:c,historyPath:d,located:null}}throw new _(`Item ${t} not found`,g.NOT_FOUND)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb2e6046-156c-56ee-a03a-ecaa1cccfb45")}catch{}})();function zv(e,t){let n=Ce(e),r=e.length>0?e[e.length-1].after_hash:Ko(),i=t===void 0||n.item_hash_version===void 0?void 0:sn(t,n.item_hash_version,ye(e.at(-1)?.hash_algorithm)),o=t===void 0?void 0:i===void 0?Go(t):i[Math.max(0,i.indexOf(r))],s=o===void 0?void 0:o===r,a=[...n.errors];return s===!1&&a.push("verify_failed:current_item_hash_mismatch"),{ok:a.length===0,entries:e.length,errors:a,latest_after_hash:e.length>0?e[e.length-1].after_hash:void 0,current_item_hash:o,current_matches_latest:s}}async function Vv(e,t,n={}){let r=O(n.cwd??process.cwd(),n.pmRoot);await U(r);let i=await F(r),o=L(i,D()),s=await hn(r,e,i,o.type_to_folder),a=await nn(s.historyPath,s.id);if(a.length===0)throw new _(`No history exists for ${s.id}; point-in-time reads are unavailable.`,g.NOT_FOUND);let c=ts(t,a),d=ns(cn(a,c.historyIndex),c),l=qo(d,{schema:i.schema});if(l.metadata.id!==s.id)throw new _(`History target resolved to item ${l.metadata.id}, expected ${s.id}.`,g.GENERIC_FAILURE);let u=a[c.historyIndex],f=es(a,!0);return{document:l,reconstructed:!0,as_of_version:f===null?null:f+c.historyIndex+1,as_of_timestamp:u.ts,target:c,history_length:a.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="403706c5-987d-5db1-95d2-b0eaded98e92")}catch{}})();function Qd(e,t,n,r,i,o){if(e.seen.has(t))return"skip";if(e.cursorFound&&e.affected.length>=o)return"truncate";e.seen.add(t),e.parents.set(t,n.id);let s=n.depth+1;return e.queue.push({id:t,depth:s}),e.cursorFound?(e.affected.push({id:t,distance:s,path:ol(r,t,e.parents)}),"continue"):(e.cursorFound=t===i,"skip")}function ps(e,t,n,r){let i=Ie("graph impact",{root:e,direction:n,kinds:[...t.kinds??[]].sort(),max_depth:Number.isFinite(r)?r:"unbounded"});return{fingerprint:i,after:t.after===void 0?void 0:wo(t.after,i)}}function We(e,t,n){e.get(t).add(n)}function ut(e){return new Map(e.map(t=>[t,new Set]))}function hs(e){for(let t of e)t.sort();return e.sort((t,n)=>n.length-t.length||t[0].localeCompare(n[0]))}function gn(e){if(Array.isArray(e))return e.map(n=>gn(n));if(e===null||typeof e!="object")return e;let t=e.toJSON;return typeof t=="function"?gn(t.call(e)):Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,gn(r)]))}function ms(e){return JSON.stringify(gn(e))}function Zd(e,t,n,r){let i=[{id:e,expanded:!1}];for(;i.length>0;){let o=i.pop();if(o.expanded){r.push(o.id);continue}if(n.has(o.id))continue;n.add(o.id),i.push({id:o.id,expanded:!0});let s=[...t.get(o.id)].sort().reverse();for(let a of s)n.has(a)||i.push({id:a,expanded:!1})}}function el(e,t){let n=new Set,r=[];for(let i of e)n.has(i)||Zd(i,t,n,r);return r}function tl(e,t){let n=new Set,r=[];for(let i of[...e].reverse()){if(n.has(i))continue;let o=[],s=[i];for(n.add(i);s.length>0;){let a=s.pop();o.push(a);for(let c of t.get(a))n.has(c)||(n.add(c),s.push(c))}r.push(o)}return hs(r)}function gs(e,t){let n=ut(e);for(let[r,i]of t)for(let o of i)We(n,o,r);return tl(el(e,t),n)}function nl(e,t){let n=ut(e.nodes());for(let r of e.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let o=(i.precedence??"source_before_target")==="source_before_target";We(n,o?r.source:r.target,o?r.target:r.source)}return n}function rl(e,t){let n=new Map(e.map(o=>[o,0]));for(let o of t.values())for(let s of o)n.set(s,n.get(s)+1);let r=e.filter(o=>n.get(o)===0).sort(),i=[];for(;r.length>0;){i.push(r);let o=[];for(let s of r)for(let a of t.get(s)){let c=n.get(a)-1;n.set(a,c),c===0&&o.push(a)}r=o.sort()}return i}function il(e,t){let n=new Map(e.map(s=>[s,0])),r=new Map;for(let s of e)for(let a of t.get(s)){if(!n.has(a))continue;let c=n.get(s)+1,d=r.get(a);(c>n.get(a)||c===n.get(a)&&(d===void 0||s.localeCompare(d)<0))&&(n.set(a,c),r.set(a,s))}let i=[...e].sort((s,a)=>n.get(a)-n.get(s)||s.localeCompare(a))[0],o=i===void 0?[]:[i];for(;o[0]!==void 0&&r.has(o[0]);)o.unshift(r.get(o[0]));return{depth:Object.fromEntries(n),path:o}}function ol(e,t,n){let r=[t],i=t;for(;i!==e;)i=n.get(i),r.push(i);return r.reverse()}function yn(e,t={}){let n=t.registry??ne(),r=[...e.nodes()],i=nl(e,n),o=rl(r,i),s=o.flat(),a=s.length===r.length,c=a?[]:gs(r,i).filter(l=>l.length>1||i.get(l[0]).has(l[0])),d=il(s,i);return{exact:!0,acyclic:a,order:s,layers:o,frontier:o[0]??[],depth:d.depth,criticalPath:d.path,criticalPathLength:Math.max(0,d.path.length-1),cycles:c,provenance:{algorithm:"kahn-longest-path",edgeFamily:"ordering"}}}function sl(e,t,n){let r=ut(e.nodes()),i=n===void 0?void 0:new Set(n.map(s=>e.registry().require(s).kind)),o=e.edges();for(let s of o){let a=e.registry().require(s.kind);i!==void 0&&!i.has(s.kind)&&(a.inverse===void 0||!i.has(a.inverse))||We(r,t==="incoming"?s.target:s.source,t==="incoming"?s.source:s.target)}return{adjacency:r,inspectedEdges:o.length}}function al(e,t,n,r,i,o){let s=_n(e,t,{...n,after:void 0,direction:"incoming",limit:void 0}),a=_n(e,t,{...n,after:void 0,direction:"outgoing",limit:void 0}),c=new Map,d=[...s.affected,...a.affected].sort((m,h)=>m.distance-h.distance||m.id.localeCompare(h.id)||m.path.join("\0").localeCompare(h.path.join("\0")));for(let m of d)c.has(m.id)||c.set(m.id,m);let l=[...c.values()].sort((m,h)=>m.distance-h.distance||m.id.localeCompare(h.id)),u=r===void 0||r===t?-1:l.findIndex(m=>m.id===r);if(r!==void 0&&r!==t&&u<0)throw new TypeError(`Unknown impact cursor item: ${r}`);let f=l.slice(u+1,u+1+i),p=u+1+f.length<l.length;return{root:t,affected:f,exact:!0,truncated:s.truncated||a.truncated||p,...p?{nextCursor:ce(o,f.at(-1)?.id??t)}:{},cost:{visitedNodes:s.cost.visitedNodes+a.cost.visitedNodes,inspectedEdges:s.cost.inspectedEdges+a.cost.inspectedEdges}}}function cl(e,t,n){let r=n.direction,i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=ps(t,n,r,i),{adjacency:c,inspectedEdges:d}=sl(e,r,n.kinds),l={queue:[{id:t,depth:0}],seen:new Set([t]),parents:new Map,affected:[],cursorFound:a===void 0||a===t},u=0,f=!1,p=!1;e:for(let m=0;m<l.queue.length;m+=1){n.signal?.throwIfAborted();let h=l.queue[m];u+=1;let y=[...c.get(h.id)].sort();if(h.depth>=i){y.some(v=>!l.seen.has(v))&&(f=!0);continue}for(let v of y)if(Qd(l,v,h,t,a,o)==="truncate"){f=!0,p=!0;break e}}if(!l.cursorFound)throw new TypeError(`Unknown impact cursor item: ${a}`);return{root:t,affected:l.affected,exact:!0,truncated:f,...p?{nextCursor:ce(s,l.affected.at(-1)?.id??t)}:{},cost:{visitedNodes:u,inspectedEdges:d}}}function _n(e,t,n={}){let r=n.direction??"outgoing";if(r!=="both")return cl(e,t,{...n,direction:r});let i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=ps(t,n,r,i);return al(e,t,n,a,o,s)}function _s(e){let t=[...e.nodes()],n=ut(t),r=ut(t);for(let c of e.edges())We(n,c.source,c.target),We(n,c.target,c.source),We(r,c.source,c.target);let i=[],o=new Set;for(let c of t){if(o.has(c))continue;let d=[],l=[c];for(o.add(c);l.length>0;){let u=l.pop();d.push(u);for(let f of n.get(u))o.has(f)||(o.add(f),l.push(f))}i.push(d)}let s=t.map(c=>({id:c,degree:n.get(c).size})),a=Math.max(0,...s.map(({degree:c})=>c));return{components:hs(i),stronglyConnected:gs(t,r),orphans:s.filter(({degree:c})=>c===0).map(({id:c})=>c),hubs:s.filter(({degree:c})=>c>0&&c===a),exact:!0,provenance:{algorithm:"component-degree",edgeFamily:"all"}}}function Xv(e,t){let n=new Map(e.edges.map(i=>[ms(i),i])),r=new Map(t.edges.map(i=>[ms(i),i]));return{fromVersion:e.version,toVersion:t.version,added:[...r].filter(([i])=>!n.has(i)).map(([,i])=>i),removed:[...n].filter(([i])=>!r.has(i)).map(([,i])=>i),unchangedCount:[...n.keys()].filter(i=>r.has(i)).length,exact:!0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1745a409-0f91-5f5a-8d2a-e5e61ff667a0")}catch{}})();function Te(e,t){return(t===void 0?void 0:po(e,t))?.execution_role??mo[e.trim().toLowerCase()]??"agent"}var Dr="blocked_by",ys="blocks",dl=Object.freeze([Dr,ys]),xr="no-active-blocker";function A(e){return e.trim().toLowerCase()}function bn(e,t){return t?`external:${e}`:`local:${A(e)}`}function De(e){let t=new Map,n=typeof e.blocked_by=="string"?e.blocked_by.trim():"";if(n.length>0&&A(n)!==xr){let r=ue(n);t.set(bn(n,r),r?n:A(n))}for(let r of e.dependencies??[]){let i=typeof r.id=="string"?r.id.trim():"";if(r.kind===Dr&&i.length>0&&A(i)!==xr){let o=ue(i)||fe(r.source_kind);t.set(bn(i,o),o?i:A(i))}}return[...t.values()].sort((r,i)=>r.localeCompare(i))}function vn(e){let t=new Map;for(let n of e){let r=A(n.id);r.length!==0&&t.set(r,new Set(De(n)))}for(let n of e){let r=A(n.id);if(r.length!==0)for(let i of n.dependencies??[]){let o=i.kind===ys&&typeof i.id=="string"?A(i.id):"";if(o.length===0||o===xr)continue;let s=t.get(o)??new Set;s.add(r),t.set(o,s)}}return new Map([...t].map(([n,r])=>[n,[...r].sort((i,o)=>i.localeCompare(o))]))}function bs(e,t){let n=A(e.id);return n.length>0?vn(t).get(n)??De(e):De(e)}function Ar(e,t,n,r){let i=e,o=typeof i.id=="string"?r?.get(A(i.id))??bs(i,[...t.values()]):De(e),s=new Set((e.dependencies??[]).filter(a=>a.kind===Dr&&fe(a.source_kind)&&typeof a.id=="string"&&a.id.trim().length>0).map(a=>bn(a.id.trim(),!0)));return o.map(a=>{if(ue(a)||s.has(bn(a,!0)))return{id:a,title:null,status:null,resolved:!1,external:!0,...typeof e.updated_at=="string"?{blocked_since:e.updated_at}:{},resolver:null};let c=t.get(A(a));return c?{id:a,title:c.title,status:c.status,resolved:$(c.status,n)}:{id:a,title:null,status:null,resolved:!1}})}function wn(e,t,n){return Ar(e,t,n)}function ft(e,t){let n=new Map(e.map(s=>[A(s.id),s])),r=vn(e),i=new Set([...vs(t),...t.blocked_statuses]),o=new Set;for(let s of e){let a=R(s.status,t);i.has(a)&&(t.blocked_statuses.has(a)||Ar(s,n,t,r).some(c=>!c.resolved))&&o.add(A(s.id))}return o}function Or(e,t,n={},r){let i=[...e.ready,...e.decisions,...e.gates];n.includeContainers===!0&&i.push(...e.containers.filter(s=>s.open_blockers.length===0&&!t.blocked_statuses.has(R(s.item.status,t))));let o={ready:[],decisions:[],gates:[]};for(let s of i){let a=Te(s.item.type,r);a==="human"&&n.includeDecisions!==!0?o.decisions.push(s):a==="gate"&&n.includeGates!==!0?o.gates.push(s):o.ready.push(s)}return o}function vs(e){return e.active_statuses.size>0?e.active_statuses:new Set([e.open_status])}function ll(e,t,n){let r=[A(e)],i=new Set;for(;r.length>0;){let o=r.pop();if(!i.has(o)){i.add(o);for(let s of t.get(o)??[]){if(!$(s.status,n))return!0;r.push(A(s.id))}}}return!1}function ul(e){let t=new Map,n=new Map,r=new Map,i=vn(e);for(let o of e){t.set(A(o.id),o);let s=typeof o.parent=="string"?o.parent.trim():"";if(s.length>0){let a=A(s),c=n.get(a)??[];c.push(o),n.set(a,c)}for(let a of i.get(A(o.id))){let c=A(a),d=r.get(c)??[];d.push(o.id),r.set(c,d)}}return{itemsById:t,childrenByParent:n,blockedByReverse:r,blockerIdsByItem:i}}function mt(e,t,n,r){let{itemsById:i,childrenByParent:o,blockedByReverse:s,blockerIdsByItem:a}=ul(t),c=new Set([...vs(n),...n.blocked_statuses]),d=new Set(t.filter(y=>!$(y.status,n)).map(y=>A(y.id))),l=[],u=[],f=[],p=[],m=[],h=0;for(let y of e){if(!c.has(R(y.status,n)))continue;h+=1;let v=Ar(y,i,n,a).filter(S=>!S.resolved),b=(s.get(A(y.id))??[]).filter(S=>d.has(A(S))).sort((S,P)=>S.localeCompare(P)),w={item:y,open_blockers:v,unblocks:b};if(ll(y.id,o,n)){f.push(w);continue}let k=n.blocked_statuses.has(R(y.status,n));if(v.length===0&&!k){let S=Te(y.type,r);S==="human"?p.push(w):S==="gate"?m.push(w):l.push(w)}else u.push(w)}return{ready:l,blocked:u,containers:f,decisions:p,gates:m,active_count:h,container_count:f.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ae1c56b3-148d-502d-9450-e807fdfab4da")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="738a98bc-eaf0-578d-88e3-1c5f83c8894b")}catch{}})();function ie(e,t="--limit"){if(e===void 0)return;let n=String(e).trim(),r=n.length===0?Number.NaN:Number(n);if(!Number.isInteger(r)||r<0)throw new _(`${t} must be a non-negative integer`,g.USAGE);return r}function kn(e,t="--priority"){if(e===void 0)return;let n=String(e).trim(),r=n.length===0?Number.NaN:Number(n);if(!Number.isInteger(r)||r<0||r>4)throw new _(`${t} filter must be 0..4`,g.USAGE);return r}function ws(e,t,n="--type"){if(e===void 0)return;let r=Kt(e,t);if(!r)throw new _(`${n} filter must be one of ${t.types.join("|")}`,g.USAGE);return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="75ecca0c-fac8-5a9b-9043-c65731daad4a")}catch{}})();function Lr(e,t){if(e===void 0)return;let n=[],r="";for(let s=0;s<e.length;s+=1){let a=e[s];if(a==="\\"){let c=e[s+1];if(c===","||c==="\\"){r+=c,s+=1;continue}r+=a;continue}if(a===","){n.push(r),r="";continue}r+=a}n.push(r);let i=n.map(s=>s.trim());if(i.some(s=>s.length===0))throw new _(`${t.label} requires at least one non-empty value`,g.USAGE);let o=i.map(s=>t.normalize?.(s)??s);return[...new Set(o)]}function pt(e,t){let n=Lr(e,t);return n===void 0?void 0:new Set(n)}function ks(e,t,n="--type"){let r=Lr(e,{label:n});if(r===void 0)return;let i=r.map(o=>{let s=Kt(o,t);if(!s)throw new _(`${n} filter token "${o}" must be one of ${t.types.join("|")}`,g.USAGE);return s});return new Set(i)}function Es(e,t="--priority"){let n=Lr(e,{label:t});if(n!==void 0)return new Set(n.map(r=>kn(r,t)))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6c580b70-76eb-51db-8587-99b73dd20875")}catch{}})();var fl="global",_w="external",ml=["open","closed","unknown"],ht=new Map,pl=240,hl=2048;function Is(e,t,n){return(e?.trim()||t).slice(0,n)}function gl(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return typeof t.status=="string"&&(t.title==null||typeof t.title=="string")&&(t.source==null||typeof t.source=="string")&&(t.checkedAt==null||typeof t.checkedAt=="string")}function yw(e){let t=e.name.trim();if(t.length===0)throw new Error("External dependency resolver name must not be empty");if(ht.has(t))throw new Error(`External dependency resolver already registered: ${t}`);let n={name:t,supports:r=>e.supports(r),resolve:r=>e.resolve(r)};return ht.set(t,n),()=>{ht.get(t)===n&&ht.delete(t)}}async function bw(e,t={}){let n=e.trim();if(!ue(n))return null;let r=[...ht.values()].filter(o=>{try{return o.supports(n)}catch{return!1}}),i=await Promise.allSettled(r.map(o=>Promise.resolve().then(()=>o.resolve(n))));for(let[o,s]of i.entries()){if(s.status!=="fulfilled"||!gl(s.value))continue;let a=r[o],c=s.value,d=ml.includes(c.status)?c.status:"unknown",l=Is(c.title,"",pl),u=Is(c.source,n,hl),f=Date.parse(c.checkedAt?.trim()??""),p=Number.isFinite(f)?new Date(f).toISOString():t.now?.()??new Date().toISOString();return{id:n,status:d,resolved:d==="closed",title:l.length>0?l:null,source:u,checked_at:p,resolver:a.name}}return null}function vw(e){let t=e?.trim();if(t)return fe(t)?fl:t}function ww(e,t,n){return _l(e,t,n)}function _l(e,t,n){let r=e.trim();return fe(n)||ue(r)?r:dn(r,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="283dfa35-9a8e-524c-b6e2-d433d51215ca")}catch{}})();function z(){let e=ne();for(let t of D()?.relationship_kinds??[])for(let n of t.definitions)e.register(n);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b57e560-4ac4-53b6-9fb1-eebb1f30562a")}catch{}})();function gt(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function En(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function yl(e,t){let n=new Set,r=[];for(let i of[...e].sort()){if(n.has(i))continue;n.add(i);let o=[{nodeId:i,children:[...t.get(i)??[]].sort(),nextChild:0}];for(;o.length>0;){let s=o.at(-1),a=s.children[s.nextChild];a===void 0?(r.push(s.nodeId),o.pop()):(s.nextChild+=1,n.has(a)||(n.add(a),o.push({nodeId:a,children:[...t.get(a)??[]].sort(),nextChild:0})))}}return r}function bl(e,t){let n=[...e].sort(),r=yl(n,t),i=new Set,o=vl(n,t),s=[];for(let a of r.reverse()){if(i.has(a))continue;let c=wl(a,o,i);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((a,c)=>a.join("\0").localeCompare(c.join("\0")))}function vl(e,t){let n=new Map(e.map(r=>[r,new Set]));for(let[r,i]of t)for(let o of i)n.get(o)?.add(r);return n}function wl(e,t,n){let r=[],i=[e];for(n.add(e);i.length>0;){let o=i.pop();r.push(o);for(let s of[...t.get(o)].sort())n.has(s)||(n.add(s),i.push(s))}return r.sort()}function Cs(e){let t=new Map;for(let n of e){let r=gt(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function kl(e,t,n){let r=gt(t.parent);if(!(!r||!n.has(r)))return{parent_id:r,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function El(e,t,n,r){let i=gt(t?.id),o=r.resolve(t?.kind);if(!i||!n.has(i)||!o?.hierarchy)return;let s=o.hierarchyDirection==="source_parent";return{parent_id:s?e:i,child_id:s?i:e,source:"dependency",kind:o.kind,holder_id:e,target_id:i,child_cardinality:s?o.incoming:o.outgoing}}function Ss(e,t){let n=new Map;for(let[r,i]of e){let o=kl(r,i,e);o&&n.set(En(o),o);for(let s of i.dependencies??[]){let a=El(r,s,e,t);a&&n.set(En(a),a)}}return[...n.values()].sort((r,i)=>En(r).localeCompare(En(i)))}function Ts(e,t=z()){return Ss(Cs(e),t)}function Il(e,t,n){let r=new Set(e.filter(i=>i.child_cardinality==="one").map(i=>i.child_id));return[...t].filter(([i,o])=>o.length>1&&r.has(i)).map(([i,o])=>({child_id:i,parent_ids:[...o],legacy_terminal:n.has(i)&&o.every(s=>n.has(s))})).sort((i,o)=>i.child_id.localeCompare(o.child_id))}function Cl(e,t,n){let r=new Map;for(let o of t){if(o.source!=="dependency")continue;let s=r.get(o.child_id)??new Set;s.add(o.parent_id),r.set(o.child_id,s)}let i=[];for(let[o,s]of e){let a=gt(s.parent);if(!a||!e.has(a))continue;let c=[...r.get(o)??[]].filter(d=>d!==a).sort();c.length!==0&&i.push({child_id:o,scalar_parent_id:a,dependency_parent_ids:c,legacy_terminal:n.has(o)&&n.has(a)&&c.every(d=>n.has(d))})}return i.sort((o,s)=>o.child_id.localeCompare(s.child_id))}function In(e,t=r=>r==="closed"||r==="canceled",n=z()){let r=Cs(e),i=Ss(r,n),o=Mr(i),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=bl([...r.keys()],new Map([...o.children_by_parent].map(([c,d])=>[c,new Set(d)]))).map(c=>({item_ids:c,legacy_terminal:c.every(d=>s.has(d))}));return{relations:i,cycles:a,cardinality_violations:Il(i,o.parents_by_child,s),divergences:Cl(r,i,s)}}function xw(e){return e.source==="scalar_parent"?`${e.parent_id} -> ${e.child_id} (scalar parent on ${e.holder_id})`:`${e.parent_id} -> ${e.child_id} (${e.kind} dependency on ${e.holder_id})`}function Mr(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.child_id)??new Set;i.add(r.parent_id),t.set(r.child_id,i);let o=n.get(r.parent_id)??new Set;o.add(r.child_id),n.set(r.parent_id,o)}return{parents_by_child:new Map([...t].map(([r,i])=>[r,[...i].sort()])),children_by_parent:new Map([...n].map(([r,i])=>[r,[...i].sort()]))}}function Fr(e,t){let n=new Set(t);return e.every(r=>n.has(r))}function Dw(e,t,n,r,i){let o=gt(n);if(!o)return;let s=In(e,r,i),a=In(t,r,i),c=a.divergences.find(u=>!s.divergences.some(f=>f.child_id===u.child_id&&f.scalar_parent_id===u.scalar_parent_id&&Fr(u.dependency_parent_ids,f.dependency_parent_ids)));if(c){let u=[c.scalar_parent_id,...c.dependency_parent_ids].sort();throw new _(`Hierarchy mutation would assign ${c.child_id} to multiple parents: ${u.join(", ")}.`,g.CONFLICT,{code:"hierarchy_parent_divergence_created",source_id:o,target_id:c.child_id,verification_errors:u})}let d=a.cardinality_violations.find(u=>(u.child_id===o||u.parent_ids.includes(o))&&!s.cardinality_violations.some(f=>f.child_id===u.child_id&&Fr(u.parent_ids,f.parent_ids)));if(d)throw new _(`Hierarchy mutation would assign ${d.child_id} to multiple parents: ${d.parent_ids.join(", ")}.`,g.CONFLICT,{code:"hierarchy_cardinality_created",source_id:o,target_id:d.child_id,verification_errors:d.parent_ids});let l=a.cycles.find(u=>u.item_ids.includes(o)&&!s.cycles.some(f=>Fr(u.item_ids,f.item_ids)));if(l)throw new _(`Hierarchy mutation would create a cycle: ${l.item_ids.join(" -> ")}.`,g.CONFLICT,{code:"hierarchy_cycle_created",source_id:o,verification_errors:l.item_ids})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41f814be-ee87-5cae-b674-69c2e7f42655")}catch{}})();function Xe(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function _t(e){let t=Xe(e);return t?.toLowerCase()==="no-active-blocker"?void 0:t}function yt(e,t,n=!0){let r=Xe(e);return n&&(fe(t)||r!==void 0&&ue(r))}function Nr(e,t){return yt(e,t)?`external\0${e}`:`local\0${e.toLowerCase()}`}function Rs(e,t,n,r){return yt(e,t)?r.get(e):n.get(e.toLowerCase())}function Ye(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n!==r?n<r?-1:1:e!==t?e<t?-1:1:0}function Sl(e){let t=new Map;for(let n of e.dependencies??[]){if(typeof n!="object"||n===null)continue;let r=n,i=Xe(r.id);if(!i)continue;let o=typeof r.kind=="string"?r.kind:"related",s=`${o}\0${Nr(i,r.source_kind)}`,a=t.get(s);a?a.count+=1:t.set(s,{target_id:i,kind:o,count:1})}return t}function Tl(e,t=n=>n==="closed"||n==="canceled"){let n=[];for(let r of e)if(!(typeof r?.id!="string"||r.id.trim().length===0))for(let i of Sl(r).values())i.count<2||n.push({holder_id:r.id.trim(),target_id:i.target_id,kind:i.kind,occurrences:i.count,holder_status:r.status,legacy_terminal:t(r.status)});return n.sort((r,i)=>{let o=Ye(r.holder_id,i.holder_id);if(o!==0)return o;let s=Ye(r.target_id,i.target_id);return s!==0?s:Ye(r.kind,i.kind)})}function Rl(e,t,n,r,i){if(typeof n!="object"||n===null)return;let o=Xe(n.id);if(!o||Nr(o,n.source_kind)!==Nr(t))return;let s=i.resolve(typeof n.kind=="string"?n.kind:"related");if(!(s?.ordering!==!0||(s.precedence??"source_before_target")!=="source_before_target"))return{holder_id:e.id.trim(),target_id:o,dependency_kind:s.kind,holder_status:e.status,legacy_terminal:r(e.status)}}function xl(e,t=r=>r==="closed"||r==="canceled",n=z()){let r=new Map;for(let i of e){if(typeof i?.id!="string"||i.id.trim().length===0)continue;let o=Xe(i.blocked_by);if(o)for(let s of i.dependencies??[]){let a=Rl(i,o,s,t,n);a&&r.set(`${a.holder_id.toLowerCase()}\0${a.target_id.toLowerCase()}\0${a.dependency_kind}`,a)}}return[...r.values()].sort((i,o)=>{let s=Ye(i.holder_id,o.holder_id);if(s!==0)return s;let a=Ye(i.target_id,o.target_id);return a!==0?a:Ye(i.dependency_kind,o.dependency_kind)})}function $r(e,t=n=>n==="closed"||n==="canceled"){let n=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),r=new Set(n.map(c=>c.id.trim().toLowerCase())),i=new Map,o=(c,d,l,u,f)=>{let p=Xe(d);if(!p||r.has(p.toLowerCase())||yt(p,void 0,f))return;let m={holder_id:c.id.trim(),target_id:p,kind:l,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:p.toLowerCase()==="no-active-blocker"};i.set(`${m.holder_id}::${m.target_id}::${m.kind}::${m.source}`,m)};for(let c of n){o(c,c.parent,"parent","parent",!1),o(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let d of c.dependencies??[]){if(typeof d!="object"||d===null)continue;let l=d;fe(l.source_kind)||o(c,l.id,typeof l.kind=="string"?l.kind:"related","dependency",!0)}}let s=[...i.values()].sort((c,d)=>c.holder_id.localeCompare(d.holder_id)||c.target_id.localeCompare(d.target_id)||c.kind.localeCompare(d.kind)||c.source.localeCompare(d.source)),a=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:a,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}function Dl(e){let t=new Map;for(let n of[...e.active,...e.legacy_terminal]){if(n.no_active_blocker_sentinel)continue;let r=n.target_id.trim(),i=r.toLowerCase();t.has(i)||t.set(i,r)}return[...t.values()].sort((n,r)=>n.localeCompare(r))}function Al(e){let t=new Map;for(let n of e){let r=_t(n.blocked_by);r&&yt(r)&&!t.has(r)&&t.set(r,r);for(let i of n.dependencies??[]){if(typeof i!="object"||i===null||!yt(i.id,i.source_kind))continue;let o=_t(i.id);o&&!t.has(o)&&t.set(o,o)}}return[...t.values()].sort((n,r)=>n.localeCompare(r))}var xs=new WeakMap;function Cn(e){return e.hierarchyIntegrity??xs.get(e)}function Ol(e,t=z()){let n={};for(let r of e)for(let i of r.dependencies??[]){if(typeof i!="object"||i===null)continue;let o=i.kind;if(typeof o!="string")continue;let s=o.trim().toLowerCase().replaceAll("-","_"),a=t.resolve(o);a&&s!==a.kind&&(n[s]=(n[s]??0)+1)}return Object.fromEntries(Object.entries(n).sort(([r],[i])=>r.localeCompare(i)))}function Je(e,t,n){let r=n??z(),i=e.filter(m=>typeof m?.id=="string"&&m.id.trim().length>0),o=new Map(i.map(m=>[m.id.trim().toLowerCase(),m.id.trim()])),s=$r(i,t),a=Dl(s);for(let m of a)o.set(m.toLowerCase(),m);let c=Al(i),d=new Set(o.keys()),l=new Map;for(let m of c){let h=m;for(;d.has(h.toLowerCase());)h=`external:${h}`;l.set(m,h),d.add(h.toLowerCase())}let u=i.map(m=>{let h=_t(m.parent),y=_t(m.blocked_by),v=(m.dependencies??[]).flatMap(b=>{if(typeof b!="object"||b===null)return[];let w=b,k=_t(w.id);return k?[{id:Rs(k,w.source_kind,o,l),kind:typeof w.kind=="string"?w.kind:"related"}]:[]});return{id:m.id.trim(),...h?{parent:o.get(h.toLowerCase())}:{},...y?{blocked_by:Rs(y,void 0,o,l)}:{},dependencies:v}}),f=In(i,t,r),p={graph:Bt.fromItems([...u,...a.map(m=>({id:m})),...c.map(m=>({id:l.get(m)}))],r),details:[...i.map(m=>({id:m.id.trim(),title:m.title,status:m.status,...typeof m.type=="string"&&m.type.trim().length>0?{type:m.type.trim()}:{}})),...a.map(m=>({id:m,title:`[missing] ${m}`,status:"missing"})),...c.map(m=>({id:l.get(m),title:`[external] ${m}`,status:"external"}))],missingIdSet:new Set(a.map(m=>m.toLowerCase())),dangling:s,duplicateRows:Tl(i,t),orderingContradictions:xl(i,t,r),legacyAliasCounts:Ol(i,r),hierarchyIntegrity:f};return xs.set(p,f),p}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19d6f507-d3b1-5ccc-aba5-594983776618")}catch{}})();var Pr=["id","title","status","type","priority","parent","updated_at"],jr=["id","status","type","title"],Ll={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"brief","list-canceled":"full"},Fl=["tree_depth","tree_parent","tree_children","tree_title"];function Ur(e=[]){return[...new Set([...hr,"body",...Fl,...e])].flatMap(t=>[t,`item.${t}`]).sort()}var jw=["brief","standard","deep"],Ml=["body","linked","claim_state","children","schedule","blockers"],Nl=["linked.files","linked.tests","linked.docs"],$l=["claim_state.claimed","claim_state.assignee","claim_state.last_claim","claim_state.last_release"],Pl=["schedule.deadline","schedule.start_at","schedule.end_at","schedule.location","schedule.reminders","schedule.events"];function Uw(e=[]){return[...[...new Set([...hr,...e,"notes_count","tests_count","collection_counts"])].flatMap(t=>[t,`item.${t}`]),...Ml,...Nl,...$l,...Pl].sort()}var Bw=["id","title","status","type","priority","updated_at","score","matched_fields"],jl=["score","matched_fields","highlights"],Ds=["id","title","description","type","status","priority","tags","created_at","updated_at","deadline","assignee","author","estimated_minutes","acceptance_criteria","dependencies","comments","notes","learnings","reminders","events","files","tests","docs","close_reason","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result","affected_version","fixed_version","component","regression","customer_impact","definition_of_ready","order","rank","goal","objective","value","impact","outcome","why_now","plan"];function Hw(e=[]){let t=[...new Set(e)];return[...jl,...Ds,...Ds.map(n=>`item.${n}`),...t,...t.map(n=>`item.${n}`)].sort()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9d73d74-7c4e-5ea9-b34c-c984b4c15ab3")}catch{}})();function As(e,t){let n=e.trim().toLowerCase();return t.alias_to_id.get(n)??n}function Ms(e){return{isTerminal(t){return e.terminal_statuses.has(As(t,e))},classify(t){let n=As(t,e);return e.terminal_canceled_statuses.has(n)?"canceled":e.terminal_statuses.has(n)?"closed":e.blocked_statuses.has(n)?"blocked":e.draft_statuses.has(n)?"draft":n===e.open_status?"open":e.active_statuses.has(n)?"in_progress":"other"}}}function Br(e){return K(e.acceptance_criteria)===void 0}function Hr(e){return!Number.isFinite(e.estimated_minutes)}function Ns(e,t){return t.isTerminal(e.status)?K(e.resolution)===void 0:!1}function Ul(e){return K(e.reviewer)===void 0}function Bl(e){return K(e.risk)===void 0}function Hl(e){return typeof e.confidence=="number"?!Number.isFinite(e.confidence):K(e.confidence)===void 0}function Gl(e){return K(e.sprint)===void 0}function Kl(e){return K(e.release)===void 0}function Gr(e){return!!(e.acMissing||e.estimatesMissing||e.resolutionMissing||e.reviewerMissing||e.riskMissing||e.confidenceMissing||e.sprintMissing||e.releaseMissing||e.metadataMissing)}function zl(e,t,n){return[[t.acMissing,Br(e)],[t.estimatesMissing,Hr(e)],[t.resolutionMissing,Ns(e,n)],[t.reviewerMissing,Ul(e)],[t.riskMissing,Bl(e)],[t.confidenceMissing,Hl(e)],[t.sprintMissing,Gl(e)],[t.releaseMissing,Kl(e)]].every(([r,i])=>r!==!0||i)}function Vl(e,t){return Br(e)||Hr(e)||Ns(e,t)}function $s(e,t,n){return Gr(t)?!(!zl(e,t,n)||t.metadataMissing&&!Vl(e,n)):!0}var Kr=["acceptance_criteria","estimated_minutes","resolution","tags","parent"];function ql(e,t){switch(t){case"acceptance_criteria":return!Br(e);case"estimated_minutes":return!Hr(e);case"resolution":return K(e.resolution)!==void 0;case"tags":return Array.isArray(e.tags)&&e.tags.length>0;default:return K(e.parent)!==void 0}}function Wl(e,t,n){return t==="resolution"?n.isTerminal(e.status):!0}function Yl(e,t){return t===0?100:Math.round(e/t*1e3)/10}function Os(){let e={};for(let t of Kr)e[t]={present:0,applicable:0,percent:100};return e}function Ls(e,t,n){for(let r of Kr){if(!Wl(t,r,n))continue;let i=e[r];i.applicable+=1,ql(t,r)&&(i.present+=1)}}function Fs(e){for(let t of Kr){let n=e[t];n.percent=Yl(n.present,n.applicable)}}function zw(e,t){let n=Os(),r={};for(let i of e){Ls(n,i,t);let o=r[i.type]??(r[i.type]=Os());Ls(o,i,t)}Fs(n);for(let i of Object.values(r))Fs(i);return{overall:n,by_type:r}}var Xl={assignee:"(unassigned)",priority:"(no priority)",tag:"(untagged)",parent:"(unparented)",type:"(untyped)",status:"(no status)"};function Jl(e){return Xl[e]}function Ql(){return{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}function Zl(e,t,n){switch(t){case"assignee":return[K(e.assignee)??null];case"parent":return[K(e.parent)??null];case"type":return[K(e.type)??null];case"status":return[K(e.status)??null];case"priority":return[typeof e.priority=="number"?`P${e.priority}`:null];default:{let r=n.tagPrefix?.trim(),i=(Array.isArray(e.tags)?e.tags:[]).filter(o=>typeof o=="string"&&o.length>0&&(!r||o.startsWith(r)));return i.length>0?i:[null]}}}function Vw(e,t,n,r={}){let i=new Map,o=0;for(let a of e){o+=1;let c=n.classify(a.status);for(let d of Zl(a,t,r)){let l=d??"\0empty",u=i.get(l);u||(u={label:d??Jl(t),key:d,buckets:Ql(),total:0},i.set(l,u)),u.buckets[c]+=1,u.total+=1}}let s=[...i.values()].sort((a,c)=>c.total!==a.total?c.total-a.total:a.key===null?1:c.key===null?-1:a.label.localeCompare(c.label));return{dimension:t,rows:s,total_items:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67f9184e-08b6-5f21-9f92-e60974adbf1e")}catch{}})();var Qe=["notes","learnings","files","docs","tests","comments","deps","body","linked_command"];function Ae(e){return Array.isArray(e)&&e.length>0}function eu(e){return typeof e=="string"&&e.trim().length>0}function tu(e){return Array.isArray(e)?e.some(t=>{if(typeof t!="object"||t===null)return!1;let n=t.command;return typeof n=="string"&&n.trim().length>0}):!1}function js(e,t){switch(t){case"notes":return Ae(e.notes);case"learnings":return Ae(e.learnings);case"files":return Ae(e.files);case"docs":return Ae(e.docs);case"tests":return Ae(e.tests);case"comments":return Ae(e.comments);case"deps":return Ae(e.dependencies);case"body":return eu(e.body);case"linked_command":return tu(e.tests)}}function Us(e){return Qe.some(t=>e[t]!==void 0)}function Bs(e,t){for(let n of Qe){let r=t[n];if(r===void 0)continue;let i=js(e,n);if(r==="present"&&!i||r==="absent"&&i)return!1}return!0}function Hs(e){return Qe.some(t=>t!=="body"&&e[t]!==void 0)}function Gs(e){return e.body!==void 0}function Ps(e,t){return t===0?100:Math.round(e/t*1e3)/10}function nu(){let e={};for(let t of Qe)e[t]={present:0,total:0,percent:100};return e}function Ww(e){let t=nu(),n=e.length;for(let s of e)for(let a of Qe)js(s,a)&&(t[a].present+=1);for(let s of Qe)t[s].total=n,t[s].percent=Ps(t[s].present,n);let r=t.body,i=n-r.present,o={present:i,total:n,percent:Ps(i,n)};return{total_items:n,fields:t,body_populated:r,empty_body:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d638f294-7d4b-5fdc-9a86-d70c2cbdd9f4")}catch{}})();var ru=e=>({acMissing:e.filterAcMissing===!0,estimatesMissing:e.filterEstimatesMissing===!0,resolutionMissing:e.filterResolutionMissing===!0,metadataMissing:e.filterMetadataMissing===!0,reviewerMissing:e.filterReviewerMissing===!0,riskMissing:e.filterRiskMissing===!0,confidenceMissing:e.filterConfidenceMissing===!0,sprintMissing:e.filterSprintMissing===!0,releaseMissing:e.filterReleaseMissing===!0}),Ks=[{field:"notes",presentKey:"hasNotes",absentKey:"noNotes",presentFlag:"--has-notes",absentFlag:"--no-notes"},{field:"learnings",presentKey:"hasLearnings",absentKey:"noLearnings",presentFlag:"--has-learnings",absentFlag:"--no-learnings"},{field:"files",presentKey:"hasFiles",absentKey:"noFiles",presentFlag:"--has-files",absentFlag:"--no-files"},{field:"docs",presentKey:"hasDocs",absentKey:"noDocs",presentFlag:"--has-docs",absentFlag:"--no-docs"},{field:"tests",presentKey:"hasTests",absentKey:"noTests",presentFlag:"--has-tests",absentFlag:"--no-tests"},{field:"comments",presentKey:"hasComments",absentKey:"noComments",presentFlag:"--has-comments",absentFlag:"--no-comments"},{field:"deps",presentKey:"hasDeps",absentKey:"noDeps",presentFlag:"--has-deps",absentFlag:"--no-deps"},{field:"body",presentKey:"hasBody",absentKey:"emptyBody",presentFlag:"--has-body",absentFlag:"--empty-body"},{field:"linked_command",presentKey:"hasLinkedCommand",absentKey:"noLinkedCommand",presentFlag:"--has-linked-command",absentFlag:"--no-linked-command"}],Xs=e=>{let t=Ks.find(n=>e[n.presentKey]===!0&&e[n.absentKey]===!0);if(t)throw new _(`Cannot combine ${t.presentFlag} with ${t.absentFlag} for the same field.`,g.USAGE);return Object.fromEntries(Ks.flatMap(n=>e[n.presentKey]===!0?[[n.field,"present"]]:e[n.absentKey]===!0?[[n.field,"absent"]]:[]))},zs=["priority","deadline","updated_at","created_at","title","parent"],Vs=["asc","desc"],Js=new Set(os);function iu(e,t,n){let r=e.filter(s=>s.startsWith("item_list_item_read_failed:")).length,i=e.filter(s=>s.startsWith("item_list_directory_read_failed:")).length,o={status:t?"unchecked":r+i>0?"partial":"complete",unreadable_item_count:r,unreadable_directory_count:i};if(n&&o.status==="partial")throw new _(`List source is incomplete: ${r} item document(s) and ${i} item directory/directories could not be read.`,g.GENERIC_FAILURE,{code:"list_source_incomplete",why:"Strict list reads fail closed so agents and SDK consumers never treat an omitted item as a complete workspace.",nextSteps:["Run pm validate --check-storage-integrity to locate unreadable tracker artifacts.","Repair the reported files or align the installed decoder version, then retry."]});return o}function ou(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0}var su=[{key:"hasNotes",summaryKey:"has_notes"},{key:"hasLearnings",summaryKey:"has_learnings"},{key:"hasFiles",summaryKey:"has_files"},{key:"hasDocs",summaryKey:"has_docs"},{key:"hasTests",summaryKey:"has_tests"},{key:"hasComments",summaryKey:"has_comments"},{key:"hasDeps",summaryKey:"has_deps"},{key:"hasBody",summaryKey:"has_body"},{key:"hasLinkedCommand",summaryKey:"has_linked_command"},{key:"noNotes",summaryKey:"no_notes"},{key:"noLearnings",summaryKey:"no_learnings"},{key:"noFiles",summaryKey:"no_files"},{key:"noDocs",summaryKey:"no_docs"},{key:"noTests",summaryKey:"no_tests"},{key:"noComments",summaryKey:"no_comments"},{key:"noDeps",summaryKey:"no_deps"},{key:"emptyBody",summaryKey:"empty_body"},{key:"noLinkedCommand",summaryKey:"no_linked_command"}],au=[{key:"filterReviewerMissing",summaryKey:"filter_reviewer_missing"},{key:"filterRiskMissing",summaryKey:"filter_risk_missing"},{key:"filterConfidenceMissing",summaryKey:"filter_confidence_missing"},{key:"filterSprintMissing",summaryKey:"filter_sprint_missing"},{key:"filterReleaseMissing",summaryKey:"filter_release_missing"}];function Qs(e,t){for(let n of su)t[n.key]===!0&&(e[n.summaryKey]=!0)}function Zs(e,t){for(let n of au)t[n.key]===!0&&(e[n.summaryKey]=!0)}function cu(e,t,n){for(let r of n){let i=t[r.optionKey];i!==void 0&&(e[r.summaryKey]=r.normalize?r.normalize(i):i)}}function du(e){let t={};return Qs(t,e),t}function lu(e){let t={};return Zs(t,e),t}var uu=[{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"ids",summaryKey:"ids"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"assigneeFilter",summaryKey:"assignee_filter"},{optionKey:"parent",summaryKey:"parent"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"}],fu=[{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"ids",summaryKey:"ids"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"assigneeFilter",summaryKey:"assignee_filter"},{optionKey:"parent",summaryKey:"parent"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"},{optionKey:"limit",summaryKey:"limit"},{optionKey:"offset",summaryKey:"offset"},{optionKey:"includeBody",summaryKey:"include_body"},{optionKey:"compact",summaryKey:"compact"},{optionKey:"fields",summaryKey:"fields"}],mu=[{key:"filterAcMissing",summaryKey:"filter_ac_missing"},{key:"filterEstimatesMissing",summaryKey:"filter_estimates_missing"},{key:"filterResolutionMissing",summaryKey:"filter_resolution_missing"},{key:"filterMetadataMissing",summaryKey:"filter_metadata_missing"}],pu="-7d";function hu(e){let{filtersStatus:t,options:n,treeEnabled:r,treeDepth:i,sortField:o,sortOrder:s,runtimeFieldFilters:a}=e,c={};return t!==null&&(c.status=t),n.dependencyBlocked===!0&&(c.blocked_semantics="status_or_dependency"),cu(c,n,uu),ta(c,n),n.filterAcMissing===!0&&(c.filter_ac_missing=!0),n.filterEstimatesMissing===!0&&(c.filter_estimates_missing=!0),n.filterResolutionMissing===!0&&(c.filter_resolution_missing=!0),n.filterMetadataMissing===!0&&(c.filter_metadata_missing=!0),Zs(c,n),Qs(c,n),n.limit!==void 0&&(c.limit=n.limit),n.offset!==void 0&&(c.offset=n.offset),n.includeBody===!0&&(c.include_body=!0),n.fields!==void 0&&(c.fields=n.fields),r&&(c.tree=!0,i!==void 0&&(c.tree_depth=i)),o!==void 0&&(c.sort=o,c.order=s),ou(a)&&(c.runtime_filters=a),c}function ea(e,t,n){let r=$(e.status,n),i=$(t.status,n);if(r!==i)return r?1:-1;let o=e.priority-t.priority;if(o!==0)return o;let s=C(t.updated_at,e.updated_at);return s!==0?s:(e.id??"").localeCompare(t.id??"")}function gu(e,t){return[...e].sort((n,r)=>ea(n,r,t))}function qs(e,t){if(e!==void 0)return _e(e,new Date,t)}function bt(e,t){if(e==null)return;let n=String(e).trim();if(n.length!==0)return _e(n,new Date,t)}function _u(e){let t=e.updatedAfter!=null&&String(e.updatedAfter).trim().length>0;if([e.today===!0,e.recent===!0,t].filter(n=>n).length>1)throw new _("Choose only one updated_at window: --today, --recent, or --updated-after.",g.USAGE);if(e.today===!0){let n=new Date;return n.setHours(0,0,0,0),n.toISOString()}return e.recent===!0?bt(pu,"recent"):bt(e.updatedAfter,"updated-after")}function ta(e,t){t.today===!0&&(e.today=!0),t.recent===!0&&(e.recent=!0)}function yu(e){if(e==null)return;let t=String(e).trim();if(t.length===0)throw new _("--ids requires at least one non-empty item ID",g.USAGE);let n=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new _("--ids requires at least one non-empty item ID",g.USAGE);return new Set(n)}function na(e){if(e===void 0)return;let t=String(e).trim(),n=t.length===0?Number.NaN:Number(t);if(!Number.isInteger(n)||n<0)throw new _("Offset filter must be a non-negative integer",g.USAGE);return n}function bu(e){if(e===void 0)return;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new _("List --fields requires a comma-separated list of field names",g.USAGE);return[...new Set(t)]}function vu(e,t=e.projectionCommand??"list"){let n=e.compact===!0,r=e.brief===!0,i=e.full===!0,o=bu(e.fields);if(Number(n)+Number(r)+Number(i)+ +(o!==void 0)>1)throw new _("List projection options are mutually exclusive. Use one of --compact, --brief, --full, or --fields.",g.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:`pm ${t} --brief`,suggested_retry_args:[t,"--brief"]}});return i?{mode:"full",fields:[]}:r?{mode:"brief",fields:[...jr]}:n?{mode:"compact",fields:[...Pr]}:o?{mode:"fields",fields:[...new Set(o.map(s=>Oe(s)))]}:{mode:"full",fields:[]}}function Oe(e){return e.startsWith("item.")?e.slice(5):e}function wu(e,t,n){if(e.mode!=="fields")return;let r=Ur(t),i=new Set(r.map(s=>Oe(s))),o=e.fields.filter(s=>!i.has(Oe(s)));if(o.length>0){let s=[n,"--fields",e.fields.filter(a=>!o.includes(a)).join(",")||"id,title,status"];throw new _(`Unknown list --fields value(s): ${o.join(", ")}`,g.USAGE,{code:"unknown_field_projection",examples:["pm list-open --fields id,title,status,type,updated_at","pm list --fields id,title,parent,priority --limit 10","pm list-all --fields id,title,body --limit 5"],recovery:{allowed_values:r,suggested_retry:bo(s),suggested_retry_args:s}})}}var ku=new Map([["updated","updated_at"],["update","updated_at"],["modified","updated_at"],["created","created_at"],["create","created_at"]]);function Eu(e){if(e===void 0)return;let t=e.trim().toLowerCase(),n=ku.get(t);if(n)return n;if(!zs.includes(t))throw new _(`Sort field must be one of ${zs.join("|")} (aliases: updated->updated_at, created->created_at)`,g.USAGE);return t}function Iu(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!Vs.includes(t))throw new _(`Sort order must be one of ${Vs.join("|")}`,g.USAGE);return t}function Cu(e){return ie(e,"--tree-depth")}function Su(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!t)throw new _("Assignee filter must be one of assigned|unassigned",g.USAGE);if(t!=="assigned"&&t!=="unassigned")throw new _(`Invalid assignee filter "${e}". Allowed: assigned|unassigned`,g.USAGE);return t}function Ws(e,t){return fs(e,t,{strict:!0})}function ra(e){return pt(e,{label:"--tag",normalize:t=>t.toLowerCase()})}function Tu(e,t,n){let r=ra(t);if(r===void 0)return;let i=new Set(e.flatMap(s=>s.tags.map(a=>a.trim().toLowerCase()))),o=[...r].filter(s=>!i.has(s));o.length>0&&n.push(`unknown_tags:${o.join(",")}`)}function Ru(e,t){if(e&&[...e].some(n=>n.toLowerCase()==="none"||n.toLowerCase()==="null"))throw new _('--assignee no longer accepts "none" or "null". Use --assignee-filter unassigned.',g.USAGE);if(e!==void 0&&t==="unassigned")throw new _("Cannot combine --assignee with --assignee-filter unassigned",g.USAGE)}function xu(e,t,n,r){let i=pt(t.assignee,{label:"--assignee"}),o=Su(t.assigneeFilter);Ru(i,o);let s=ru(t),a=Xs(t);return{idsFilter:yu(t.ids),statusSet:e&&e.length>0?new Set(e):void 0,excludeTerminal:t.excludeTerminal===!0,typeFilter:ks(t.type,n),tagFilters:ra(t.tag),priorityFilter:Es(t.priority),deadlineBefore:qs(t.deadlineBefore,"deadline-before"),deadlineAfter:qs(t.deadlineAfter,"deadline-after"),updatedAfter:_u(t),updatedBefore:bt(t.updatedBefore,"updated-before"),createdAfter:bt(t.createdAfter,"created-after"),createdBefore:bt(t.createdBefore,"created-before"),assigneeFilter:i,assigneeModeFilter:o,parentFilter:t.parent?.trim(),treeEnabled:t.tree===!0,sprintFilter:pt(t.sprint,{label:"--sprint"}),releaseFilter:pt(t.release,{label:"--release"}),missingMetadataFilters:s,missingMetadataActive:Gr(s),lifecycleClassifier:Ms(r),contentFieldFilters:a,contentFiltersActive:Us(a)}}function Du(e,t,n){return t.idsFilter&&!t.idsFilter.has(e.id)||t.statusSet&&!t.statusSet.has(e.status)||t.excludeTerminal&&$(e.status,n)||t.typeFilter&&!t.typeFilter.has(e.type)||t.tagFilters&&![...t.tagFilters].some(r=>(e.tags??[]).some(i=>i.trim().toLowerCase()===r))?!1:t.priorityFilter===void 0||t.priorityFilter.has(e.priority)}function Au(e,t){return Io(e,t)}function Ou(e,t){return t.assigneeModeFilter==="assigned"&&!e.assignee||t.assigneeModeFilter==="unassigned"&&e.assignee?!1:t.assigneeFilter===void 0||e.assignee!==void 0&&t.assigneeFilter.has(e.assignee)}function Lu(e,t,n){let r=e.parent?.trim().toLowerCase(),i=[...new Set([...n?.get(e.id.trim().toLowerCase())??[],...r?[r]:[]])];return t.parentFilter!==void 0&&!t.treeEnabled&&!i.includes(t.parentFilter.trim().toLowerCase())||t.sprintFilter!==void 0&&(e.sprint===void 0||!t.sprintFilter.has(e.sprint))?!1:t.releaseFilter===void 0||e.release!==void 0&&t.releaseFilter.has(e.release)}function Fu(e,t,n,r,i){return!(!Du(e,t,n)||!Au(e,t)||!Ou(e,t)||!Lu(e,t,i)||t.missingMetadataActive&&!$s(e,t.missingMetadataFilters,t.lifecycleClassifier)||t.contentFiltersActive&&!Bs(e,t.contentFieldFilters)||!pn(e,r))}function Mu(e,t,n,r,i,o,s){let a=xu(t,n,r,i);return e.filter(c=>Fu(c,a,i,o,s))}function vt(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Ys(e,t,n,r){let i=e,o=typeof i.title=="string"?i.title:"",s=r??vt(typeof i.parent=="string"?i.parent:void 0)??null;return{...e,tree_depth:t,tree_parent:s,tree_children:n,tree_title:`${" ".repeat(t)}${o}`}}function Nu(e,t){let n=new Map,r=new Map;for(let i of e){let o=i.id.trim().toLowerCase();n.set(o,i);let s=t?t.parents_by_child.get(o)??[]:[vt(i.parent)?.toLowerCase()].filter(a=>a!==void 0);for(let a of s){let c=r.get(a)??[];c.push(i),r.set(a,c)}}return{byId:n,childrenByParent:r}}function $u(e,t,n,r,i){return t?[...r.get(t.toLowerCase())??[]]:e.filter(o=>(i?i.parents_by_child.get(o.id.trim().toLowerCase())??[]:[vt(o.parent)?.toLowerCase()].filter(s=>s!==void 0)).every(s=>!n.has(s)))}function Pu(e,t,n,r,i=e){let{byId:o,childrenByParent:s}=Nu(e,r),a=$u(e,t,o,s,r),c=[],d=new Set,l=new Map(i.map(f=>[f.id.trim().toLowerCase(),f.id.trim()])),u=[...a].reverse().map(f=>({node:f,depth:0,parentId:t===void 0?void 0:l.get(t.trim().toLowerCase())??t.trim()}));for(;u.length>0;){let{node:f,depth:p,parentId:m}=u.pop(),h=f.id.trim().toLowerCase();if(d.has(h))continue;d.add(h);let y=s.get(h)??[];if(c.push(Ys(f,p,y.length,m)),!(n!==void 0&&p>=n))for(let v of[...y].reverse())u.push({node:v,depth:p+1,parentId:l.get(h)})}if(t===void 0&&n===void 0)for(let f of e){let p=f.id.trim().toLowerCase();d.has(p)||(d.add(p),c.push(Ys(f,0,s.get(p)?.length??0)))}return c}function ju(e,t){return e===t?0:e===null?1:t===null?-1:e.localeCompare(t)}function Uu(e,t){return e===t?0:e===null?1:t===null?-1:C(e,t)}function Bu(e,t,n){switch(n){case"priority":return e.priority-t.priority;case"deadline":return Uu(e.deadline??null,t.deadline??null);case"updated_at":return C(e.updated_at,t.updated_at);case"created_at":return C(e.created_at,t.created_at);case"title":return(e.title??"").localeCompare(t.title??"");case"parent":return ju(e.parent??null,t.parent??null);default:return 0}}function Hu(e,t,n,r){return t?[...e].sort((i,o)=>{let s=Bu(i,o,t);if(s!==0)return n==="desc"?-s:s;let a=ea(i,o,r);return n==="desc"?-a:a}):gu(e,r)}function Gu(e,t,n=!1){let r=Oe(t.trim());if(r.length===0)return null;let i=e;return n&&r==="title"&&typeof i.tree_title=="string"?i.tree_title:Object.prototype.hasOwnProperty.call(i,r)?i[r]??null:null}function ia(e,t,n=!1){return t.mode==="full"?e:e.map(r=>{let i={};for(let o of t.fields)i[o]=Gu(r,o,n);return i})}function Ku(e){let t=[];for(let n of e)t.push(n.metadata_key);return t}function zu(e,t){if(e.noTruncate!==!0)return ie(e.limit)??(t>=1e4?20:void 0)}function Vu(e,t,n){return t.after===void 0?na(t.offset)??0:Be(e,t.after,n,r=>r.id)}function oa(e,t,n){return{...e!==void 0?{applied_limit:e}:{},has_more:t,truncated:t,next_cursor:n??null}}async function qu(e,t){let n=O(process.cwd(),t.path);await U(n);let r=await F(n),i=J(r.schema),o=tn(r.schema),s=e.projectionCommand??"list",a=vu(e,s);return wu(a,Ku(o.definitions),s),{pmRoot:n,settings:r,statusRegistry:i,runtimeFieldFilters:mn(e,o,"list"),typeRegistry:L(r,D()),projection:a}}async function Wu(e,t,n){let r=t.projection.fields.some(c=>Oe(c)==="body"),i=t.projection.mode==="full"||t.projection.fields.some(c=>Js.has(Oe(c))),o=Xs(e),s=Hs(o),a=Gs(o);return e.includeBody||r||a?await ln(t.pmRoot,t.settings.item_format,t.typeRegistry.type_to_folder,n,t.settings.schema):i||s?await as(t.pmRoot,t.settings.item_format,t.typeRegistry.type_to_folder,n,t.settings.schema):await le(t.pmRoot,t.settings.item_format,t.typeRegistry.type_to_folder,n,t.settings.schema)}function Yu(e){let t=Eu(e.sort),n=Iu(e.order)??"asc",r=e.tree===!0;if(!r&&e.treeDepth!==void 0)throw new _("List --tree-depth requires --tree",g.USAGE);if(!t&&e.order!==void 0)throw new _("List --order requires --sort",g.USAGE);return{sortField:t,sortOrder:n,treeEnabled:r,treeDepth:r?Cu(e.treeDepth):void 0,parentRoot:r?vt(e.parent):void 0}}function Xu(e,t,n){let r=Ws(t.status,n),i;t.lifecycleBucket==="in_progress"?i=[n.in_progress_status]:t.lifecycleBucket==="open"&&(i=[...n.active_statuses].filter(d=>d!==n.in_progress_status).sort((d,l)=>d.localeCompare(l)));let o=r??i??Ws(e,n),s=us(t.status),a=r||s?{...t,excludeTerminal:!1}:t,c="all";return s?c="all":r!==void 0?c=r.length===1?r[0]:r:t.lifecycleBucket!==void 0?c=t.lifecycleBucket:o!==void 0?c=o.length===1?o[0]:o:a.excludeTerminal===!0&&(c=null),{resolvedStatus:o,explicitAllStatuses:s,effectiveOptions:a,filtersStatus:c}}function Ju(e,t,n,r,i){if(t.after!==void 0&&t.offset!==void 0)throw new _("List --after cannot be combined with --offset.",g.USAGE);let o=zu(t,e.length),s=Vu(e,t,i),a=o===void 0?e.slice(s):e.slice(s,s+o),c=ia(a,n,r),d=e.length,l=a.length>0&&s+a.length<d,u=l&&a.length>0?ce(i,a[a.length-1].id,s+a.length-1):void 0;return{projected:c,totalMatched:d,pageExtras:oa(o,l,u)}}function sa(e,t,n,r){return Ie("list",{pmRoot:r,status:e,options:Wt(t,cs),sort:n.sortField??"default",order:n.sortOrder,tree:n.treeEnabled,tree_depth:n.treeDepth??null})}async function Qu(e){let{options:t,runtime:n,statusSelection:r,ordering:i}=e,o=new Set(["status","limit","offset","compact","brief","full","fields","format","stream","includeBody","excludeTerminal","dependencyBlocked","lifecycleBucket","noTruncate","projectionCommand","truncate","notes","learnings","files","docs","tests","comments","deps","linkedCommand"]),s=[n.projection.mode==="full",n.projection.fields.some(p=>{let m=Oe(p);return m==="body"||Js.has(m)})].includes(!0);if([t.limit===void 0,t.after!==void 0,t.noTruncate===!0,t.includeBody===!0,t.dependencyBlocked===!0,t.strictRead===!0,i.treeEnabled,i.sortField!==void 0,s,_o(),Object.keys(n.runtimeFieldFilters).length>0,Object.entries(t).some(([p,m])=>m!==void 0&&!o.has(p))].includes(!0))return null;let a=await qe(n.pmRoot,[...new Set(Object.values(n.typeRegistry.type_to_folder))]);if(!a)return null;let c=ie(t.limit),d=na(t.offset)??0,l=await is({pmRoot:n.pmRoot,expectedSourceCursor:a.source_cursor,query:{statuses:r.resolvedStatus,excludeStatuses:r.resolvedStatus===void 0&&r.effectiveOptions.excludeTerminal===!0?[...n.statusRegistry.terminal_statuses]:void 0,terminalStatuses:[...n.statusRegistry.terminal_statuses],limit:c,offset:d}});if(!l)return null;let u=l.items.length>0&&d+l.items.length<l.total,f=u?ce(sa(r.filtersStatus,t,i,n.pmRoot),l.items.at(-1).id,d+l.items.length-1):void 0;return{projected:ia(l.items,n.projection,!1),totalMatched:l.total,pageExtras:oa(c,u,f)}}function Zu(e){let{filtersStatus:t,options:n,noTruncate:r,treeEnabled:i,treeDepth:o,sortField:s,sortOrder:a,runtimeFieldFilters:c}=e,d={};t!==null&&(d.status=t),n.dependencyBlocked===!0&&(d.blocked_semantics="status_or_dependency");let l=n;for(let u of fu){let f=l[u.optionKey];f!=null&&(d[u.summaryKey]=f)}for(let u of mu)l[u.key]===!0&&(d[u.summaryKey]=!0);return Object.assign(d,lu(n),du(n)),ta(d,n),r&&(d.no_truncate=!0),n.strictRead===!0&&(d.strict_read=!0),i&&(d.tree=!0,o!==void 0&&(d.tree_depth=o)),s!==void 0&&(d.sort=s,d.order=a),d.runtime_filters=c,d}async function wt(e,t,n){let r=await qu(t,n),i=[],o=Yu(t),s=Xu(e,t,r.statusRegistry),a=t.noTruncate===!0,c=await Qu({options:t,runtime:r,statusSelection:s,ordering:o}),d=c;if(!d){let m=await Wu(t,r,i),h=o.treeEnabled||vt(t.parent)!==void 0?Mr(Ts(m,z())):void 0;Tu(m,t.tag,i);let y=Mu(m,s.resolvedStatus,s.effectiveOptions,r.typeRegistry,r.statusRegistry,r.runtimeFieldFilters,h?.parents_by_child),v=t.dependencyBlocked===!0?(()=>{let k=ft(m,r.statusRegistry);return y.filter(S=>k.has(S.id.trim().toLowerCase()))})():y,b=Hu(v,o.sortField,o.sortOrder,r.statusRegistry),w=o.treeEnabled?Pu(b,o.parentRoot,o.treeDepth,h,m):b;d=Ju(w,t,r.projection,o.treeEnabled,sa(s.filtersStatus,t,o,r.pmRoot))}let l=x(),u=[...new Set(i)].sort((m,h)=>m.localeCompare(h)),f=iu(u,c!==null,t.strictRead===!0),p=r.projection.mode==="full"?null:[...r.projection.fields];if(r.projection.mode==="compact"&&t.compact===!0){let m=hu({filtersStatus:s.filtersStatus,options:t,treeEnabled:o.treeEnabled,treeDepth:o.treeDepth,sortField:o.sortField,sortOrder:o.sortOrder,runtimeFieldFilters:r.runtimeFieldFilters});return{items:d.projected,count:d.projected.length,total:d.totalMatched,...d.pageExtras,completeness:f,filters:m,projection:{mode:"compact",fields:p},...u.length>0?{warnings:u}:{}}}return{items:d.projected,count:d.projected.length,total:d.totalMatched,...d.pageExtras,completeness:f,filters:Zu({filtersStatus:s.filtersStatus,options:t,noTruncate:a,treeEnabled:o.treeEnabled,treeDepth:o.treeDepth,sortField:o.sortField,sortOrder:o.sortOrder,runtimeFieldFilters:r.runtimeFieldFilters}),projection:{mode:r.projection.mode,fields:p},sorting:{sort:o.sortField??"default",order:o.sortField?o.sortOrder:"asc"},now:l,...u.length>0?{warnings:u}:{}}}import{createHash as ef}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e31ef0fb-e803-500b-b1e5-db9edfc880c4")}catch{}})();var tf=64,nf=8;function rf(e,t){let n=(e.dependencies??[]).map(r=>{if(typeof r!="object"||r===null)return"";let i=r;return`${typeof i.kind=="string"?i.kind:"related"}:${typeof i.id=="string"?i.id:""}`}).sort().join(",");return[e.id,e.title,e.status,t(e.status)?"1":"0",typeof e.type=="string"?e.type.trim():"",e.parent??"",e.blocked_by??"",n].join("\0")}function Sn(e,t=r=>r==="closed"||r==="canceled",n=ne()){let r=e.filter(o=>typeof o?.id=="string"&&o.id.trim().length>0).map(o=>rf(o,t)).sort(),i=n.list().map(o=>I(o)).sort();return ef("sha256").update(r.join("")).update("").update(i.join("")).digest("hex")}function aa(e,t,n){let r=t??n;if(!Number.isInteger(r)||r<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`);return r}var zr=class{#e=new Map;#t;#n;constructor(t={}){this.#t=aa("maxResultsPerWorkspace",t.maxResultsPerWorkspace,tf),this.#n=aa("maxWorkspaces",t.maxWorkspaces,nf)}lookup(t,n,r){let i=this.#e.get(t),o=!0;(i===void 0||i.fingerprint!==n)&&(i={fingerprint:n,assembly:r(),results:new Map},o=!1,!this.#e.has(t)&&this.#e.size>=this.#n&&this.#e.delete(this.#e.keys().next().value)),this.#e.delete(t),this.#e.set(t,i);let s=i,a=this.#t;return{assembly:s.assembly,assemblyReused:o,fingerprint:n,memoize(c,d){let l=s.results.get(c);if(l!==void 0||s.results.has(c))return s.results.delete(c),s.results.set(c,l),{value:structuredClone(l),reused:!0};let u=d();return s.results.size>=a&&s.results.delete(s.results.keys().next().value),s.results.set(c,structuredClone(u)),{value:u,reused:!1}}}}clear(){this.#e.clear()}},ca=new zr;function Tn(){return ca}function x0(){ca.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c67d6023-2fb2-541f-9541-8aa317368dcf")}catch{}})();var of=["prerequisite","dependent","ancestor","descendant","provenance","related"],sf=new TextEncoder;function Vr(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<1)throw new TypeError(`Relationship context ${n} must be positive`);return r}function Rn(e){return Math.max(1,Math.ceil(sf.encode(JSON.stringify(e)).byteLength/4))}function qr(e,t,n){let r=n.resolve(e.kind);if(r?.ordering){let i=(r.precedence??"source_before_target")==="source_before_target"?e.source:e.target;return t===i?"prerequisite":"dependent"}if(r?.hierarchy){let i=r.hierarchyDirection==="source_parent"?e.source:e.target;return t===i?"ancestor":"descendant"}return e.kind==="discovered_from"||e.kind==="incident_from"?"provenance":"related"}function af(e,t,n,r){let i=e.filter(o=>o.source===t&&o.target===n||o.target===t&&o.source===n).map(o=>qr(o,n,r));return[...new Set(i)].sort()}function cf(e){return of.find(t=>e.includes(t))}function df(e,t,n,r){let i=r.direction??"both",o=r.maxDepth??3;if(!Number.isInteger(o)||o<0)throw new TypeError("Relationship context maxDepth must be non-negative");let s=new Set([t]),a=[{id:t,distance:0}],c=[],d=0,l=!1;for(let u=0;u<a.length;u+=1){r.signal?.throwIfAborted();let f=a[u];if(f.distance>=o&&l)continue;let p=e.neighborEdges(f.id,{direction:i,kinds:r.kinds,signal:r.signal});if(d+=p.meta.inspectedEdges,f.distance>=o){p.value.some(m=>!s.has(m.id))&&(l=!0);continue}for(let{id:m,edge:h}of p.value){if(s.has(m))continue;s.add(m);let y={id:m,distance:f.distance+1,via:f.id,role:qr(h,m,n)};c.push(y),a.push(y)}}return c.sort((u,f)=>u.distance-f.distance||u.id.localeCompare(f.id)),{rows:c,visitedNodes:a.length,inspectedEdges:d,depthTruncated:l}}function lf(e,t,n,r){let i={prerequisite:0,dependent:0,ancestor:0,descendant:0,provenance:0,related:0},o=e.neighborEdges(t,{direction:r.direction??"both",kinds:r.kinds,signal:r.signal}).value;for(let{id:s,edge:a}of o)i[qr(a,s,n)]+=1;return{directEdges:i,directTotal:o.length,rootEdges:o.map(({edge:s})=>s)}}function uf(e){let t=[],n=e.initialTokens;for(let r of e.candidates){if(t.length>=e.nodeLimit)break;let i=r.distance===1?af(e.rootEdges,e.rootId,r.id,e.registry):[],o={...e.details.get(r.id)??{id:r.id},distance:r.distance,role:i.length>0?cf(i):r.role,via:r.via,reasons:i.length>0?i:[`${r.role} via ${r.via} (depth ${r.distance})`]},s=Rn(o);if(n+s>e.tokenBudget)break;t.push(o),n+=s}if(e.candidates.length>0&&t.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes:t,usedTokens:n}}function ff(e){let t=e.options.kinds?new Set(e.options.kinds.map(o=>e.registry.require(o).kind)):void 0,n=e.graph.edges().filter(o=>{if(!e.included.has(o.source)||!e.included.has(o.target))return!1;if(t===void 0||t.has(o.kind))return!0;let s=e.registry.resolve(o.kind)?.inverse;return s!==void 0&&t.has(s)}),r=[],i=e.initialTokens;for(let o of n){if(r.length>=e.edgeLimit)break;let s=Rn(o);if(i+s>e.tokenBudget)break;r.push(o),i+=s}return{edges:r,usedTokens:i,candidateCount:n.length}}function da(e,t,n,r={}){if(!e.nodes().includes(t))throw new TypeError(`Relationship node not found: ${t}`);let i=Vr(r.nodeLimit,20,"nodeLimit"),o=Vr(r.edgeLimit,40,"edgeLimit"),s=Vr(r.tokenBudget,1200,"tokenBudget"),a=r.registry??ne(),c=new Map(n.map(V=>[V.id,V])),d=c.get(t)??{id:t},{evidence:l=[],...u}=d,f=[...l],p=df(e,t,a,r),{rootEdges:m,...h}=lf(e,t,a,r),y=Ie("relationship-context",{rootId:t,direction:r.direction??"both",kinds:[...r.kinds??[]].sort(),maxDepth:r.maxDepth??3}),v=Be(p.rows,r.cursor,y,({id:V})=>V),b=p.rows.slice(v),w=Rn(u)+Rn(f);if(w>s)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");let k=uf({candidates:b,details:c,rootEdges:m,rootId:t,registry:a,nodeLimit:i,tokenBudget:s,initialTokens:w}),{nodes:S}=k,P=new Set([t,...S.map(({id:V})=>V)]),j=ff({graph:e,included:P,options:r,registry:a,edgeLimit:o,tokenBudget:s,initialTokens:k.usedTokens}),{edges:M,usedTokens:Ee}=j,N=v+S.length,B=N<p.rows.length,Y=S.at(-1),X=j.candidateCount-M.length,te=p.depthTruncated||B||X>0,se={rootId:t,...u.status===void 0?{}:{rootStatus:u.status},...h,discoveredNodes:p.rows.length,returnedNodes:S.length,returnedEdges:M.length,omittedNodes:p.rows.length-N,omittedEdges:X,evidenceCount:f.length,hasMore:B};return{root:u,summary:se,nodes:S,edges:M,evidence:f,meta:{exact:!0,truncated:te,completeness:te?"truncated":"complete",nodeLimit:i,edgeLimit:o,tokenBudget:s,usedTokens:Ee,visitedNodes:p.visitedNodes,inspectedEdges:p.inspectedEdges,omittedNodes:p.rows.length-N,omittedEdges:X,...B&&Y?{nextCursor:ce(y,Y.id,N-1)}:{}}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="620bf4e4-e6d1-5520-89e4-0859f57c7afe")}catch{}})();var mf=["tree","graph","context"],pf=["none","repeated"],hf=["outgoing","incoming","both"],gf=32,_f=200,yf=400,bf=16e3;function vf(e){let t=e?.trim().toLowerCase()??"tree";if(mf.includes(t))return t;throw new _(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,g.USAGE)}function me(e,t){if(e===void 0)return;let n=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(n)||n<1)throw new _(`Invalid --${t} value "${e}". Use a positive integer.`,g.USAGE);return n}function xn(e){if(e===void 0)return;let t=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(t)||t<0)throw new _(`Invalid --max-depth value "${e}". Use a non-negative integer.`,g.USAGE);return t}function wf(e){let t=e?.trim().toLowerCase()??"none";if(pf.includes(t))return t;throw new _(`Invalid --collapse value "${e}". Use "none" or "repeated".`,g.USAGE)}function Yr(e){let t=e?.trim().toLowerCase()??"both";if(hf.includes(t))return t;throw new _(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,g.USAGE)}function Xr(e,t=ne()){if(e===void 0)return;let n=(Array.isArray(e)?e:[e]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)return;let r=new Set;for(let i of n){let o=t.resolve(i);if(!o){let s=t.list().map(a=>a.kind).join(", ");throw new _(`Invalid --kind value "${i}". Registered kinds: ${s}.`,g.USAGE)}r.add(o.kind)}return[...r].sort()}function kf(e){if(!e||e.length===0)return[];let t=e.map(({id:r,kind:i})=>({id:r.trim(),kind:i.trim().toLowerCase()})).sort((r,i)=>{let o=r.kind.localeCompare(i.kind);return o!==0?o:r.id.localeCompare(i.id)}),n=new Map;for(let r of t){let i=`${r.kind.toLowerCase()}::${r.id.toLowerCase()}`;n.has(i)||n.set(i,{id:r.id,kind:r.kind})}return[...n.values()]}function Ef(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:kf(e.dependencies)}}function If(e){return Yt(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function Cf(e,t,n,r,i,o,s,a,c){for(let d of t.dependencies){let l=Math.max(1,Math.ceil(JSON.stringify({from:e.id,to:d.id,kind:d.kind}).length/3));if(a.nodes>=a.nodeLimit){e.truncated=!0,a.reasons.add("node_limit");break}if(a.edges>=a.edgeLimit){e.truncated=!0,a.reasons.add("edge_limit");break}if(a.estimatedTokens+l>=a.tokenBudget){e.truncated=!0,a.reasons.add("token_budget");break}a.edges+=1,a.estimatedTokens+=l,e.dependencies.push(ua(d.id,n,r,i,o,s,a,c+1,d.kind))}}function Sf(e,t,n,r,i,o,s,a){return s.estimatedTokens>=s.tokenBudget&&t?.dependencies.length?(e.truncated=!0,s.reasons.add("token_budget"),!0):!t||e.cycle?!0:r!==void 0&&a>=r?(t.dependencies.length>0&&(e.truncated=!0,s.reasons.add("max_depth")),!0):i==="repeated"&&o.has(n)?(e.collapsed=!0,!0):!1}function ua(e,t,n,r,i,o,s,a=0,c){let d=e.trim().toLowerCase(),l=t.get(d),u={id:l?.id??e,title:l?.title,type:l?.type,status:l?.status,via:c,missing:!l,cycle:n.has(d),dependencies:[]};if(s.nodes+=1,s.estimatedTokens+=If(u),Sf(u,l,d,r,i,o,s,a))return u;i==="repeated"&&o.add(d);let f=new Set(n);return f.add(d),Cf(u,l,t,f,r,i,o,s,a),u}function la(e,t){return!e||e.missing&&!t.missing?t:{...e,title:e.title??t.title,type:e.type??t.type,status:e.status??t.status}}function Tf(e){let t=new Map,n=new Map,r=[e];for(;r.length>0;){let a=r.pop();t.set(a.id,la(t.get(a.id),{id:a.id,title:a.title,type:a.type,status:a.status,missing:a.missing}));for(let c of a.dependencies){t.set(c.id,la(t.get(c.id),{id:c.id,title:c.title,type:c.type,status:c.status,missing:c.missing}));let d=c.via??"related",l=`${a.id}::${c.id}::${d}`;n.has(l)||n.set(l,{from:a.id,to:c.id,kind:d}),c.cycle||r.push(c)}}let i=[...t.values()].sort((a,c)=>a.id.localeCompare(c.id)),o=[...n.values()].sort((a,c)=>{let d=a.from.localeCompare(c.from);if(d!==0)return d;let l=a.to.localeCompare(c.to);return l!==0?l:a.kind.localeCompare(c.kind)}),s=i.filter(a=>a.missing).map(a=>a.id);return{root_id:e.id,nodes:i,edges:o,missing_ids:s}}function fa(e,t,n){let r=new Set,i=new Set,o=new Set,s=new Set,a=[{id:e,depth:0}],c=0;for(;c<a.length;){let d=a[c++],l=d.id.trim().toLowerCase();r.add(l);let u=t.get(l);if(!u){o.add(l);continue}if(!(n!==void 0&&d.depth>=n)&&!s.has(l)){s.add(l);for(let f of u.dependencies)i.add(`${l}::${f.id.trim().toLowerCase()}::${f.kind}`),a.push({id:f.id,depth:d.depth+1})}}return{node_count:r.size,edge_count:i.size,edge_basis:"deduplicated_directed",missing_count:o.size}}function Rf(e,t=ne()){let n=xn(e.maxDepth),r=me(e.nodeLimit,"node-limit"),i=me(e.edgeLimit,"edge-limit"),o=me(e.tokenBudget,"token-budget"),s=Xr(e.kind,t);return{direction:Yr(e.direction),...s===void 0?{}:{kinds:s},...n===void 0?{}:{maxDepth:n},...r===void 0?{}:{nodeLimit:r},...i===void 0?{}:{edgeLimit:i},...o===void 0?{}:{tokenBudget:o},...e.cursor?.trim()?{cursor:e.cursor.trim()}:{}}}function xf(e,t,n,r){return da(e.graph,t,e.details.map(i=>i.id===t&&r.length>0?{...i,evidence:r}:i),n)}function Wr(e,t,n,r){for(let i of n.slice(0,r)){let o=i?.trim();o&&e.push(`${t}:${o}`)}}async function Df(e,t,n,r){let i=await de(e,t,n.id_prefix,n.item_format,r);if(!i)return[];let{document:o}=await Se(i,{schema:n.schema}),s=o.metadata,a=s.files??[],c=s.tests??[],d=s.docs??[],l=[["files",a.length],["tests",c.length],["docs",d.length],["comments",(s.comments??[]).length],["notes",(s.notes??[]).length],["learnings",(s.learnings??[]).length]];if(l.every(([,f])=>f===0))return[];let u=[`linked:${l.map(([f,p])=>`${f}=${p}`).join(",")}`];return Wr(u,"file",a.map(f=>f.path),3),Wr(u,"test",c.map(f=>f.command??f.path),2),Wr(u,"doc",d.map(f=>f.path),2),u}function Af(e){let{canonicalId:t,context:n,missingCount:r,missingReferences:i,referenceLimit:o,summaryOnly:s}=e;return{id:t,format:"context",node_count:n.nodes.length+1,edge_count:n.edges.length,edge_basis:"deduplicated_directed",missing_count:r,missing_scope:"traversal",missing_reference_count:i.length,...s?{}:{missing_references:i.slice(0,o),context:n}}}function Of(e){let{row:t,missingReachableSet:n,packetIds:r,filteredKinds:i,registry:o}=e;if(t.no_active_blocker_sentinel||!n.has(t.target_id.trim().toLowerCase())||!r.has(t.holder_id))return!1;if(i===void 0)return!0;let s=o.resolve(t.kind);return s!==void 0&&(i.has(s.kind)||s.inverse!==void 0&&i.has(s.inverse))}function ma(e,t,n){let r;for(;;){let i=Yt(new TextEncoder().encode(wr(_r("deps",e),t)).byteLength);if(i===r)return i;n(i),r=i}}function Lf(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function Ff(e){try{return xf(e.assembly,e.canonicalId,{...e.contextOptions,...e.internalTokenBudget===void 0?{}:{tokenBudget:e.internalTokenBudget}},e.rootEvidence)}catch(t){if(e.smallestResult!==void 0&&Lf(t))return e.smallestResult;throw t}}function Mf(e){let{assembly:t,canonicalId:n,contextOptions:r,rootEvidence:i,summaryOnly:o,outputFormat:s,missingCount:a,missingReferences:c}=e,d=r.edgeLimit??40,l=r.tokenBudget,u,f;for(;;){let p=Ff({assembly:t,canonicalId:n,contextOptions:r,internalTokenBudget:l,rootEvidence:i,smallestResult:f});if("format"in p)return p;let m=p;u??=m.meta.tokenBudget,l??=u;let h=Af({canonicalId:n,context:m,missingCount:a,missingReferences:c,referenceLimit:d,summaryOnly:o});if(f=h,o||(m.meta.tokenBudget=u,m.meta.usedTokens=ma(Ze(h,!1),s,b=>{m.meta.usedTokens=b}),m.meta.usedTokens<=u))return h;if(d>0){d-=1;continue}let y=l,v=y*u/m.meta.usedTokens;l=Math.min(y-1,Math.max(1,Math.floor(v*.9)))}}function Nf(e){let{assembly:t,canonicalId:n,options:r,rootEvidence:i,summaryOnly:o,outputFormat:s}=e,a=Rf(r,t.graph.registry()),c=t.graph.closure(n,{direction:a.direction,...a.kinds===void 0?{}:{kinds:a.kinds},maxDepth:a.maxDepth??3}),d=c.value.filter(h=>t.missingIdSet.has(h.toLowerCase())),l=new Set(d.map(h=>h.toLowerCase())),u=t.graph.registry(),f=a.kinds?new Set(a.kinds.map(h=>u.require(h).kind)):void 0,p=new Set([n,...c.value]),m=[...t.dangling.active,...t.dangling.legacy_terminal].filter(h=>Of({row:h,missingReachableSet:l,packetIds:p,filteredKinds:f,registry:u}));return Mf({assembly:t,canonicalId:n,contextOptions:a,rootEvidence:i,summaryOnly:o,outputFormat:s,missingCount:d.length,missingReferences:m})}function $f(e){let t=[e],n;for(;t.length>0;){let r=t.pop();r.dependencies.length>0&&(n=r,t.push(...r.dependencies))}return n?(n.dependencies.pop(),n.truncated=!0,!0):!1}function Pf(e,t,n,r,i,o,s){let a=i??gf,c=me(n.nodeLimit,"node-limit")??_f,d=me(n.edgeLimit,"edge-limit")??yf,l=me(n.tokenBudget,"token-budget")??bf,u={nodeLimit:c,edgeLimit:d,tokenBudget:l,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},f=ua(e,r,new Set,a,t==="graph"?"repeated":o,new Set,u),p=fa(e,r,void 0),m;for(;;){let h=Tf(f),y=u.reasons.size===0?void 0:{reasons:[...u.reasons].sort(),limits:{max_depth:a,node_limit:c,edge_limit:d,token_budget:l},estimated_tokens:0,total_node_count:p.node_count,total_edge_count:p.edge_count,omitted_node_count:Math.max(0,p.node_count-h.nodes.length),omitted_edge_count:Math.max(0,p.edge_count-h.edges.length)},v={id:e,format:t,node_count:h.nodes.length,edge_count:h.edges.length,edge_basis:"deduplicated_directed",missing_count:h.missing_ids.length,...y?{truncation:y}:{}};if(m=t==="tree"?{...v,tree:f}:{...v,graph:h},(m.truncation===void 0?Yt(new TextEncoder().encode(wr(_r("deps",Ze(m,!1)),s)).byteLength):ma(Ze(m,!1),s,b=>{m.truncation.estimated_tokens=b}))<=l)return m;if(!$f(f))return u.reasons.add("token_budget"),m;u.reasons.add("token_budget")}}function Ze(e,t,n={}){let r={name:e.format==="tree"?"dependency_tree":e.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"};return{...e,legacy_alias_counts:n,projection:{mode:t?"summary":"full",declared_field_groups:[r],included_field_groups:t?[]:[r.name]}}}async function J0(e,t,n){let r=O(process.cwd(),n.path);await U(r);let i=vf(t.format),o=xn(t.maxDepth),s=wf(t.collapse);qt(t.summary===!0,t.full===!0,"--summary");let a=t.summary===!0,c=await F(r),d=L(c,D()),l=await le(r,c.item_format,d.type_to_folder,void 0,c.schema),u=J(c.schema),f=new Map(l.map(m=>[m.id.trim().toLowerCase(),Ef(m)])),p=$r(l,m=>$(m,u));for(let m of[...p.active,...p.legacy_terminal]){let h=f.get(m.holder_id.trim().toLowerCase()),y=m.kind.trim().toLowerCase();h&&!h.dependencies.some(v=>v.id.trim().toLowerCase()===m.target_id.trim().toLowerCase()&&v.kind===y)&&h.dependencies.push({id:m.target_id,kind:y})}if(!f.has(e.trim().toLowerCase()))throw new _(`Item ${e} not found`,g.NOT_FOUND);if(i==="context"){let m=f.get(e.trim().toLowerCase()).id,h=a?[]:await Df(r,m,c,d.type_to_folder),y=w=>$(w,u),v=z(),b=Tn().lookup(r,Sn(l,y,v),()=>Je(l,y,v));return Ze(Nf({assembly:b.assembly,canonicalId:m,options:t,rootEvidence:h,summaryOnly:a,outputFormat:n.json===!0?"json":"toon"}),a,b.assembly.legacyAliasCounts)}return a?Ze({id:e,format:i,...fa(e,f,o)},!0,Object.fromEntries(Object.entries(Je(l,m=>$(m,u)).legacyAliasCounts))):Ze(Pf(e,i,t,f,o,s,n.json===!0?"json":"toon"),!1,Object.fromEntries(Object.entries(Je(l,m=>$(m,u)).legacyAliasCounts)))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f60c628a-2e42-5770-a001-39cce5f92595")}catch{}})();var jf=ve.paths,Uf=ve.visited_paths,Bf=ve.path_depth;function Jr(e,t){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new TypeError(`Invalid path ${e} bound: ${String(t)}`)}function Dn(e,t){return t.hierarchyDirection==="target_parent"?e.target:e.source}function kt(e,t){return(t.precedence??"source_before_target")==="target_before_source"?e.target:e.source}function et(e,t){let n=kt(e,t);return{predecessor:n,successor:n===e.source?e.target:e.source}}function Hf(e,t,n){if(t===void 0)return;let r=e.registry(),i=new Set;for(let o of t){let s=r.require(o),a=s.traversal;if(a==="association")throw new TypeError(`Relationship kind ${s.kind} uses association traversal; use graph impact --direction both`);if(a!==n&&a!=="semantic"){let c=a==="hierarchy"?"graph ancestors or graph descendants":"graph predecessors or graph successors";throw new TypeError(`Relationship kind ${s.kind} uses ${a} traversal; use ${c}`)}i.add(s.kind)}return i}function Gf(e,t,n,r,i){let o=e.registry(),s=e.neighborEdges(t,{direction:"both",...n===void 0?{}:{kinds:[...n]}}),a=[],c=new Set;for(let d of s.value){let l=o.require(d.edge.kind);n===void 0&&!l[r]||i(d,l,t)&&(c.has(d.id)||(c.add(d.id),a.push(d.id)))}return{neighbors:a,inspectedEdges:s.meta.inspectedEdges}}function Kf(e,t,n,r,i,o){if(t>=n)return e.neighbors.some(s=>!o.seen.has(s))&&(o.truncated=!0),!1;for(let s of e.neighbors)if(!o.seen.has(s)){if(o.seen.add(s),o.queue.push({id:s,depth:t+1}),!o.resumed){s===i&&(o.resumed=!0);continue}if(o.value.length>=r)return o.truncated=!0,!0;o.value.push(s)}return!1}function An(e,t,n,r,i){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);let o=Hf(e,n.kinds,r),s=n.limit??Number.POSITIVE_INFINITY,a=n.maxDepth??Number.POSITIVE_INFINITY,c=n.after,d={seen:new Set([t]),value:[],queue:[{id:t,depth:0}],resumed:c===void 0,truncated:!1},l=0,u=0;for(let f=0;f<d.queue.length;f+=1){n.signal?.throwIfAborted();let p=d.queue[f];l+=1;let m=Gf(e,p.id,o,r,i);if(u+=m.inspectedEdges,Kf(m,p.depth,a,s,c,d))break}if(!d.resumed)throw new TypeError(`Traversal cursor not found in sequence: ${c}`);return{value:d.value,meta:{visitedNodes:l,inspectedEdges:u,truncated:d.truncated,nextCursor:d.value.at(-1)}}}function pa(e,t){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`)}function ha(e,t,n,r,i){let o=e.neighborEdges(t.nodes.at(-1),{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});return i.inspectedEdges+=o.meta.inspectedEdges,o.value.filter(s=>!t.nodeSet.has(s.id))}function zf(e,t,n,r,i,o,s){for(let a of ha(e,t,r,i,s)){let c=[...t.nodes,a.id],d=new Set(t.nodeSet).add(a.id),l=[...t.edges,a.edge];if(a.id===n){if(s.value.push({nodes:c,edges:l,length:l.length}),s.value.length>=o)return!0}else s.queue.push({nodes:c,nodeSet:d,edges:l})}return!1}function ga(e,t,n={}){return An(e,t,n,"hierarchy",(r,i)=>Dn(r.edge,i)===r.id)}function _a(e,t,n={}){return An(e,t,n,"hierarchy",(r,i,o)=>Dn(r.edge,i)===o)}function ya(e,t,n={}){return An(e,t,n,"ordering",(r,i)=>kt(r.edge,i)===r.id)}function ba(e,t,n={}){return An(e,t,n,"ordering",(r,i,o)=>kt(r.edge,i)===o)}function Vf(e,t,n,r,i,o,s,a){let c={value:[],queue:[{nodes:[t],nodeSet:new Set([t]),edges:[]}],inspectedEdges:0},d=0,l=!1,u=i+1;for(let f=0;f<c.queue.length;f+=1){if(r.signal?.throwIfAborted(),c.value.length>=u||d>=o){l=!0;break}let p=c.queue[f];if(d+=1,p.edges.length>=s){ha(e,p,r,a,c).length>0&&(l=!0);continue}if(zf(e,p,n,r,a,u,c)){l=!0;break}}return{value:c.value.slice(0,i),meta:{visitedNodes:d,inspectedEdges:c.inspectedEdges,truncated:l}}}function va(e,t,n,r={}){pa(e,t),pa(e,n);let i=r.maxPaths??jf,o=r.maxVisitedPaths??Uf,s=r.maxDepth??Bf;Jr("maxPaths",i),Jr("maxVisitedPaths",o),Jr("maxDepth",s);let a=r.direction??"outgoing";r.signal?.throwIfAborted();for(let c of r.kinds??[])e.registry().require(c);return t===n?i===0?{value:[],meta:{visitedNodes:1,inspectedEdges:0,truncated:!0}}:{value:[{nodes:[t],edges:[],length:0}],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}}:Vf(e,t,n,r,i,o,s,a)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="789f7451-ceb1-5e5c-b2b6-45eec49580ce")}catch{}})();var qf=16,Wf=2,Yf=8;function On(e,t){if(!Number.isInteger(t)||t<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`)}function Ln(e,t,n){let r=e.registry(),i=t===void 0?void 0:new Set(t.map(o=>r.require(o).kind));for(let o of e.edges()){if(o.source===o.target)continue;let s=r.require(o.kind);i!==void 0&&!(i.has(s.kind)||s.inverse!==void 0&&i.has(s.inverse))||n(o,s)}}function Xf(e,t){let n=new Map;Ln(e,t,r=>{wa(n,r.source,r.target),wa(n,r.target,r.source)});for(let r of n.values())r.sort();return n}function wa(e,t,n){let r=e.get(t);r===void 0?e.set(t,[n]):r.push(n)}function Jf(e,t){let n=new Map;for(let o of e){let s=t.get(o);n.set(s,(n.get(s)??0)+1)}let r,i=0;for(let[o,s]of n)(s>i||s===i&&o<r)&&(r=o,i=s);return r}function Qf(e,t){let n=new Map;for(let[i,o]of e){let s=n.get(o);s===void 0?n.set(o,[i]):s.push(i)}let r=[];for(let i of n.values())i.length<t||(i.sort(),r.push({representative:i[0],size:i.length,members:i}));return r.sort((i,o)=>o.size-i.size||i.representative.localeCompare(o.representative))}function ka(e,t={}){let n=t.maxIterations??qf,r=t.minSize??Wf;On("maxIterations",n),On("minSize",r);let i=Xf(e,t.kinds),o=e.nodes(),s=new Map(o.map(u=>[u,u])),a=0,c=!1,d=0,l=0;for(;a<n&&!c;){t.signal?.throwIfAborted(),a+=1,c=!0;for(let u of o){d+=1;let f=i.get(u);if(f===void 0)continue;l+=f.length;let p=Jf(f,s);p!==s.get(u)&&(s.set(u,p),c=!1)}}return{value:{communities:Qf(s,r),iterations:a,converged:c},meta:{visitedNodes:d,inspectedEdges:l,truncated:!c}}}function Fn(e){return e.direction==="directed"&&(e.ordering||e.hierarchy)}function Mn(e){return e.inverse!==void 0&&e.inverse<e.kind?e.inverse:e.kind}function Qr(e,t){return(t.hierarchy?Dn(e,t):e.source===kt(e,t)?e.target:e.source)===e.target?{from:e.source,to:e.target}:{from:e.target,to:e.source}}function Zf(e,t){if(t===void 0)return;let n=e.registry(),r=new Set;for(let i of t){let o=n.require(i);if(!Fn(o))throw new TypeError(`Relationship kind ${o.kind} is not a directed ordering or hierarchy kind`);r.add(Mn(o))}return r}function em(e,t){let n=e.registry(),r=new Map;for(let i of e.edges()){let o=n.require(i.kind);if(!Fn(o))continue;let s=Mn(o);if(t!==void 0&&!t.has(s))continue;let a=Qr(i,o);if(a.from===a.to)continue;let c=r.get(s);c===void 0&&(c={adjacency:new Map,records:[]},r.set(s,c));let d=c.adjacency.get(a.from);d===void 0?c.adjacency.set(a.from,new Set([a.to])):d.add(a.to),c.records.push({...a,edge:i})}return r}function tm(e){let t=new Map;for(let[n,r]of e.adjacency)t.set(n,[...r].sort());return t}function nm(e,t,n,r){let i=[r];for(let o=n;o!==t;o=e.get(o))i.push(o);return i.push(t),i.reverse()}function rm(e,t,n,r,i,o){for(let s of e.get(n.id)??[])if(o.inspectedEdges+=1,!(n.depth===0&&s===t.to)&&!r.has(s)){if(r.set(s,n.id),s===t.to)return nm(r,t.from,n.id,s);i.push({id:s,depth:n.depth+1})}}function im(e,t,n,r){let i=new Map([[t.from,t.from]]),o=[{id:t.from,depth:0}];for(let s=0;s<o.length;s+=1){let a=o[s];if(r.visitedNodes+=1,a.depth>=n)continue;let c=rm(e,t,a,i,o,r);if(c!==void 0)return c}}function tt(e,t={}){let n=t.maxDepth??Yf;On("maxDepth",n),t.limit!==void 0&&On("limit",t.limit);let r=t.limit??Number.POSITIVE_INFINITY,i=Zf(e,t.kinds),o=em(e,i),s=[],a={visitedNodes:0,inspectedEdges:0},c=!1;e:for(let d of[...o.keys()].sort()){let l=o.get(d),u=tm(l);for(let f of l.records){t.signal?.throwIfAborted();let p=im(u,f,n,a);if(p!==void 0){if(s.length>=r){c=!0;break e}s.push({edge:f.edge,witness:p})}}}return{value:s,meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:c}}}function om(e,t,n,r,i){let o=new Set,s=[];for(let a of n){if(a.id===e||o.has(a.id))continue;if(!i.seen.has(a.id)){if(t>=r){i.truncated=!0;continue}i.seen.add(a.id),i.queue.push({id:a.id,depth:t+1})}o.add(a.id),s.push(a.id);let c=i.predecessors.get(a.id);c===void 0&&(c=new Set,i.predecessors.set(a.id,c)),c.add(e)}return s}function sm(e,t,n){let r=n.direction??"outgoing",i=n.maxDepth??Number.POSITIVE_INFINITY,o=[],s=new Map,a={seen:new Set([t]),queue:[{id:t,depth:0}],predecessors:new Map,truncated:!1},c=0;for(let d=0;d<a.queue.length;d+=1){n.signal?.throwIfAborted();let{id:l,depth:u}=a.queue[d];o.push(l);let f=e.neighborEdges(l,{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});c+=f.meta.inspectedEdges,s.set(l,om(l,u,f.value,i,a))}return{order:o,successors:s,predecessors:a.predecessors,inspectedEdges:c,truncated:a.truncated}}function am(e,t){let n=[],r=new Set([t]),i=[{id:t,index:0}];for(;i.length>0;){let o=i.at(-1),s=e.successors.get(o.id);if(o.index<s.length){let a=s[o.index];o.index+=1,r.has(a)||(r.add(a),i.push({id:a,index:0}))}else n.push(o.id),i.pop()}return n.reverse()}function cm(e,t,n,r){let i=e,o=t;for(;i!==o;){for(;r.get(i)>r.get(o);)i=n.get(i);for(;r.get(o)>r.get(i);)o=n.get(o)}return i}function dm(e,t,n){let r;for(let i of[...e].sort())t.has(i)&&(r=r===void 0?i:cm(r,i,t,n));return r}function lm(e,t,n,r,i){let o=new Map([[t,t]]),s=!0;for(;s;){s=!1;for(let a of n){if(i?.throwIfAborted(),a===t)continue;let c=dm(e.predecessors.get(a),o,r);c!==void 0&&o.get(a)!==c&&(o.set(a,c),s=!0)}}return o}function Ea(e,t,n={}){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);if(n.maxDepth!==void 0&&(!Number.isInteger(n.maxDepth)||n.maxDepth<0))throw new TypeError(`Invalid maxDepth bound: ${String(n.maxDepth)}`);let r=sm(e,t,n),i=am(r,t),o=new Map(i.map((d,l)=>[d,l])),s=lm(r,t,i,o,n.signal),a=new Map(i.map(d=>[d,1]));for(let d=i.length-1;d>=0;d-=1){let l=i[d];if(l===t)continue;let u=s.get(l);a.set(u,a.get(u)+a.get(l))}let c=i.filter(d=>d!==t).map(d=>({id:d,idom:s.get(d),dominatedCount:a.get(d)-1})).sort((d,l)=>l.dominatedCount-d.dominatedCount||d.id.localeCompare(l.id));return{value:{root:t,reachableCount:r.order.length,rows:c},meta:{visitedNodes:r.order.length,inspectedEdges:r.inspectedEdges,truncated:r.truncated}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3cef3a97-fda4-5811-9e69-04ff722e40a1")}catch{}})();function Ia(e){return Math.round(e*1e6)/1e6}function Ca(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Sa(e,t){let n=new Map(e.nodes().map(i=>[i,new Set]));Ln(e,t,i=>{n.get(i.source).add(i.target),n.get(i.target).add(i.source)});let r=new Map;for(let[i,o]of n)r.set(i,[...o].sort());return r}function um(e,t){let n=new Map,r=new Map;return Ln(e,t,(i,o)=>{if(!o.ordering)return;let{predecessor:s,successor:a}=et(i,o);Ca(r,s,a),Ca(n,a,s)}),{incoming:n,outgoing:r}}function fm(e,t,n){let r=new Map([[e,0]]),i=new Map([[e,1]]),o=new Map,s=[],a=[e],c=0,d=0;for(let l=0;l<a.length;l+=1){let u=a[l];n.visitedNodes+=1,s.push(u);let f=r.get(u);u!==e&&(c+=1,d+=f);for(let p of t.get(u))if(n.inspectedEdges+=1,r.has(p)||(r.set(p,f+1),a.push(p)),r.get(p)===f+1){i.set(p,(i.get(p)??0)+i.get(u));let m=o.get(p);m===void 0?o.set(p,[u]):m.push(u)}}return{stack:s,sigma:i,predecessors:o,reachableCount:c,distanceSum:d}}function mm(e,t,n){let r=new Map;for(let i=e.stack.length-1;i>=0;i-=1){let o=e.stack[i],s=(1+(r.get(o)??0))/e.sigma.get(o);for(let a of e.predecessors.get(o)??[])r.set(a,(r.get(a)??0)+e.sigma.get(a)*s);o!==t&&n.set(o,(n.get(o)??0)+(r.get(o)??0))}}function pm(e,t){return t<=1||e.reachableCount===0?0:e.reachableCount/(t-1)*(e.reachableCount/e.distanceSum)}function hm(e,t,n,r,i){return{id:e,degree:t.get(e).length,inDegree:n.incoming.get(e)?.size??0,outDegree:n.outgoing.get(e)?.size??0,betweenness:Ia((r.get(e)??0)/2),closeness:Ia(i.get(e))}}function Ta(e,t={}){let n=Sa(e,t.kinds),r=um(e,t.kinds),i=e.nodes(),o=new Map,s=new Map,a={visitedNodes:0,inspectedEdges:0};for(let l of i){t.signal?.throwIfAborted();let u=fm(l,n,a);s.set(l,pm(u,i.length)),mm(u,l,o)}let c=0;for(let l of n.values())c+=l.length;let d=i.map(l=>hm(l,n,r,o,s)).sort((l,u)=>u.betweenness-l.betweenness||u.degree-l.degree||l.id.localeCompare(u.id));return{value:{nodeCount:i.length,edgeCount:c/2,rows:d},meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:!1}}}function gm(e,t){return e<=t?{source:e,target:t}:{source:t,target:e}}function _m(e,t,n){let r=t.get(e.node)[e.neighborIndex];if(e.neighborIndex+=1,n.inspectedEdges+=1,r!==e.parent){if(n.discovery.has(r)){n.low.set(e.node,Math.min(n.low.get(e.node),n.discovery.get(r)));return}return e.children+=1,n.discovery.set(r,n.timer),n.low.set(r,n.timer),n.timer+=1,{node:r,parent:e.node,neighborIndex:0,children:0}}}function ym(e,t,n){if(e.parent===null){e.children>1&&n.articulation.add(e.node);return}let r=e.parent,i=n.low.get(e.node);n.low.set(r,Math.min(n.low.get(r),i)),r!==t&&i>=n.discovery.get(r)&&n.articulation.add(r),i>n.discovery.get(r)&&n.bridges.push(gm(r,e.node))}function bm(e,t,n,r){n.discovery.set(e,n.timer),n.low.set(e,n.timer),n.timer+=1;let i=[{node:e,parent:null,neighborIndex:0,children:0}];for(;i.length>0;){r?.throwIfAborted();let o=i.at(-1);if(o.neighborIndex<t.get(o.node).length){let s=_m(o,t,n);s!==void 0&&i.push(s)}else ym(o,e,n),i.pop()}}function Nn(e,t={}){let n=Sa(e,t.kinds),r={discovery:new Map,low:new Map,timer:0,articulation:new Set,bridges:[],inspectedEdges:0};for(let i of e.nodes())r.discovery.has(i)||bm(i,n,r,t.signal);return{value:{articulationPoints:[...r.articulation].sort(),bridges:r.bridges.sort((i,o)=>i.source.localeCompare(o.source)||i.target.localeCompare(o.target))},meta:{visitedNodes:r.discovery.size,inspectedEdges:r.inspectedEdges,truncated:!1}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32f3ce0d-64ac-5ad4-b27a-2a279718de22")}catch{}})();function vm(e){let t=e.registry(),n=new Map,r=new Set;for(let i of e.edges()){let o=t.require(i.kind);if(!o.ordering)continue;let{predecessor:s,successor:a}=et(i,o);if(r.add(s),r.add(a),s===a)continue;let c=n.get(s);c===void 0?n.set(s,new Set([a])):c.add(a)}return{forward:n,participants:r}}function wm(e,t,n,r){if(e===void 0)return r;let i=r;for(let o of e)t.has(o)&&(i=Math.min(i,n.get(o)));return i}function km(e,t,n){let r=n-t;return{id:e,earliestStart:t,earliestFinish:t+1,latestStart:n,latestFinish:n+1,slack:r,critical:r===0}}function Em(e,t,n,r,i){let o=new Map;for(let s=e.length-1;s>=0;s-=1){let a=e[s],c=wm(t.forward.get(a),r,o,i);o.set(a,c-1)}return e.map(s=>km(s,n[s],o.get(s))).sort((s,a)=>s.slack-a.slack||s.earliestStart-a.earliestStart||s.id.localeCompare(a.id))}function Ra(e,t={}){t.signal?.throwIfAborted();let n=yn(e,{registry:e.registry()}),r=vm(e),i=new Set(n.order),o=n.order.filter(d=>r.participants.has(d)),s=o.reduce((d,l)=>Math.max(d,n.depth[l]+1),0),a=Em(o,r,n.depth,i,s),c=a.length>0;return{exact:!0,acyclic:n.acyclic,makespan:s,scheduledCount:a.length,criticalPath:c?n.criticalPath:[],criticalPathLength:c?n.criticalPathLength:0,cycles:n.cycles,rows:a,provenance:{algorithm:"critical-path-method",edgeFamily:"ordering",weighting:"unit"}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fa17672a-97a2-5f94-bdfe-9df970cc038b")}catch{}})();function Im(e,t,n){for(let r=e.length-1;r>=0;r-=1){n?.throwIfAborted();let i=t.get(e[r]);for(let o of i.successors){n?.throwIfAborted();let s=t.get(o);if(s.latest===void 0||s.duration===void 0)continue;let a=s.latest-s.duration;(i.latest===void 0||a<i.latest)&&(i.latest=a,i.anchor=s.anchor)}}}function Cm(e,t,n,r){let i=[],o=e;for(;o!==void 0&&i.length<n;)r?.throwIfAborted(),i.push(o),o=t.get(o).predecessor;return i.reverse(),{path:i,path_truncated:o!==void 0}}function Sm(e,t,n,r,i){let o=new Map(t.map(a=>[a.id,a])),s=new Map;for(let a of e){i?.throwIfAborted();let c=o.get(a),d=c?.estimated_minutes,l=typeof d=="number"&&Number.isFinite(d)&&d>=0?d:void 0,u={item:c,duration:l,pending:0,successors:new Set,earliest:0};if(c?.deadline!==void 0){let f=Date.parse(c.deadline);Number.isFinite(f)?(u.deadline=(f-n)/6e4,u.latest=u.deadline,u.anchor=a):r(a,"invalid_deadline")}s.set(a,u)}return s}function Tm(e,t,n){for(let r of e.edges()){n?.throwIfAborted();let i=e.registry().require(r.kind);if(!i.ordering)continue;let{predecessor:o,successor:s}=et(r,i),a=t.get(o);a.successors.has(s)||(a.successors.add(s),t.get(s).pending+=1)}}function Rm(e,t,n){let r=e.filter(i=>t.get(i).pending===0);for(let i=0;i<r.length;i+=1){n?.throwIfAborted();let o=r[i],s=t.get(o),a=s.earliest===null||s.duration===void 0?null:s.earliest+s.duration;for(let c of s.successors){n?.throwIfAborted();let d=t.get(c);a===null?d.earliest=null:d.earliest!==null&&(a>d.earliest||a===d.earliest&&(d.predecessor===void 0||o<d.predecessor))&&(d.earliest=a,d.predecessor=o),d.pending-=1,d.pending===0&&r.push(c)}}return r}function xm(e,t,n,r,i,o,s,a){let c=t.duration;if(t.latest!==void 0){r.scheduled_count+=1;let d=t.latest-c;r.rows.length<o?r.rows.push({id:e,deadline_id:t.anchor,latest_start:new Date(i+d*6e4).toISOString(),slack_minutes:t.earliest===null?null:d-t.earliest}):r.truncated=!0}if(t.deadline!==void 0&&t.earliest!==null&&t.earliest+c>t.deadline)if(r.overcommitted_count+=1,r.overcommitted.length<o){let d=Cm(e,n,Math.min(o,s.remaining),a);s.remaining-=d.path.length,d.path_truncated&&(r.truncated=!0),r.overcommitted.push({deadline_id:e,deadline:t.item.deadline,shortfall_minutes:t.earliest+c-t.deadline,...d})}else r.truncated=!0}function Dm(e,t,n,r,i,o,s,a){let c={remaining:o};for(let d of e){a?.throwIfAborted();let l=t.get(d);if(l.pending>0){s(d,"cycle_or_gated_by_cycle");continue}if(l.duration===void 0){s(d,"unknown_estimate");continue}if(l.latest!==void 0&&!Number.isFinite(new Date(r+(l.latest-l.duration)*6e4).getTime())){s(d,"date_range_exceeded");continue}l.earliest===null&&s(d,"unknown_predecessor_estimate"),xm(d,l,t,n,r,i,c,a)}}function xa(e,t,n={}){n.signal?.throwIfAborted();let r=Date.parse(n.now??new Date().toISOString());if(!Number.isFinite(r))throw new TypeError("Invalid scheduling clock");let i=n.maxWork??1e5,o=n.limit??10;for(let[f,p]of[["maxWork",i],["limit",o]])if(!Number.isSafeInteger(p)||p<1)throw new TypeError(`Invalid scheduling ${f}`);let s={as_of:new Date(r).toISOString(),basis:"derived_elapsed_minutes",complete:!0,truncated:!1,work_limit_exceeded:!1,scheduled_count:0,residual_count:0,overcommitted_count:0,rows:[],residuals:[],overcommitted:[]},a=e.nodes(),c=e.edges();if(a.length+c.length+t.length>i)return{...s,complete:!1,work_limit_exceeded:!0};let d=(f,p)=>{s.complete=!1,s.residual_count+=1,s.residuals.length<o?s.residuals.push({id:f,reason:p}):s.truncated=!0},l=Sm(a,t,r,d,n.signal);Tm(e,l,n.signal);let u=Rm(a,l,n.signal);return Im(u,l,n.signal),Dm(a,l,s,r,o,i,d,n.signal),s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ccb7d865-8baa-5379-a810-7be494eadcb1")}catch{}})();function nt(){return{nodes:0,isolated:0,degree_leq_one:0,semantic_nodes:0,without_semantic_edges:0,degree_histogram:{}}}function Oa(e,t,n,r){let i={all:nt(),active:nt(),terminal:nt()},o=new Map;for(let s of e.details){if(r?.throwIfAborted(),e.missingIdSet.has(s.id.toLowerCase())||s.status==="external")continue;let a=o.get(s.status)??nt();o.set(s.status,a);let c=e.graph.incidentEdges(s.id),d=c.some(l=>n(l.kind));for(let l of[i.all,i[t(s.status)?"terminal":"active"],a]){l.nodes+=1,l.isolated+=+(c.length===0),c.length<=1&&(l.degree_leq_one+=1),d?l.semantic_nodes+=1:l.without_semantic_edges+=1;let u=String(c.length);l.degree_histogram[u]=(l.degree_histogram[u]??0)+1}}return{coverage_by_lifecycle:i,coverage_by_status:Object.fromEntries([...o].sort(([s],[a])=>s.localeCompare(a)))}}function Da(e){if(!$n(e))return!1;let t=e;if(!["nodes","isolated","degree_leq_one","semantic_nodes","without_semantic_edges"].every(r=>Number.isSafeInteger(t[r])&&Number(t[r])>=0)||!$n(t.degree_histogram))return!1;let n=Object.entries(t.degree_histogram);return n.every(([r,i])=>/^(0|[1-9]\d*)$/.test(r)&&Number.isSafeInteger(i)&&Number(i)>=0)&&n.reduce((r,[,i])=>r+Number(i),0)===t.nodes&&Number(t.isolated)<=Number(t.degree_leq_one)&&Number(t.degree_leq_one)<=Number(t.nodes)&&Number(t.semantic_nodes)+Number(t.without_semantic_edges)===t.nodes}function $n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function La(e){for(let r of["ordering_acyclic","active_ordering_acyclic"])if(e[r]!==void 0&&typeof e[r]!="boolean")return!1;let t=e.coverage_by_lifecycle,n=e.coverage_by_status;return t===void 0&&n===void 0?!0:!$n(t)||!$n(n)?!1:["all","active","terminal"].every(r=>Da(t[r]))&&Object.values(n).every(Da)}function Aa(e,t){return Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].sort().map(n=>{let r=Object.hasOwn(e,n)?e[n]:nt(),i=Object.hasOwn(t,n)?t[n]:nt(),o=Object.fromEntries([...new Set([...Object.keys(r.degree_histogram),...Object.keys(i.degree_histogram)])].sort().map(s=>[s,(i.degree_histogram[s]??0)-(r.degree_histogram[s]??0)]));return[n,{nodes:i.nodes-r.nodes,isolated:i.isolated-r.isolated,degree_leq_one:i.degree_leq_one-r.degree_leq_one,semantic_nodes:i.semantic_nodes-r.semantic_nodes,without_semantic_edges:i.without_semantic_edges-r.without_semantic_edges,degree_histogram:o}]}))}function Fa(e,t){return!e.coverage_by_lifecycle||!t.coverage_by_lifecycle||!e.coverage_by_status||!t.coverage_by_status?{lifecycle_comparable:!1}:{lifecycle_comparable:!0,coverage_by_lifecycle:Aa(e.coverage_by_lifecycle,t.coverage_by_lifecycle),coverage_by_status:Aa(e.coverage_by_status,t.coverage_by_status)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="896e1553-b127-532f-ac39-e0d47f29eebc")}catch{}})();var rt=["missing_reference_active","missing_reference_terminal","legacy_no_blocker_sentinel","ordering_cycle","legacy_ordering_cycle","ordering_storage_contradiction","legacy_ordering_storage_contradiction","hierarchy_cycle","legacy_hierarchy_cycle","hierarchy_cardinality_violation","legacy_hierarchy_cardinality_violation","hierarchy_direction_violation","legacy_hierarchy_direction_violation","duplicate_edge","legacy_duplicate_edge","duplicate_dependency_row","legacy_duplicate_dependency_row","stale_lifecycle_block","isolated_active_node","sparse_active_node"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34b2e83e-f6a1-57e7-84ee-4ad83acb2e19")}catch{}})();var Am=25,Om="milestone",Lm="outcome milestone:",Fm=new Set(["discovered_from","incident_from","recurs_from","supersedes","verifies"]);function Pn(e){return Fm.has(e)}var Ma={error:0,warning:1,info:2};function Na(e){return new Set((e??[]).filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()))}function it(e,t,n,r,i,o,s,a){let c=[...i].sort((d,l)=>d.localeCompare(l));return{code:e,severity:t,policy:n,message:r(c.length),count:c.length,sample:c.slice(0,o),sample_truncated:c.length>o,remediation:s,...a===void 0?{}:{evidence:[...a].sort((d,l)=>d.localeCompare(l)).slice(0,o)}}}function Mm(e,t){return e.cycles.map(n=>it(n.legacy_terminal?"legacy_hierarchy_cycle":"hierarchy_cycle",n.legacy_terminal?"info":"error","Structural hierarchy must be acyclic across scalar and registered dependency relationships.",r=>`${r} items participate in one hierarchy cycle.`,n.item_ids,t,n.legacy_terminal?"Preserve historical rows unless an explicit legacy repair is approved.":"Remove or retype one exact hierarchy relation before continuing mutation."))}function $a(e,t,n){let r=e.cardinality_violations.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[it(n?"legacy_hierarchy_cardinality_violation":"hierarchy_cardinality_violation",n?"info":"error","Every structural child must resolve to at most one logical parent across all hierarchy spellings.",i=>`${i} child item${i===1?"":"s"} resolve to multiple hierarchy parents.`,r.map(i=>i.child_id),t,n?"Preserve historical rows unless an explicit legacy repair is approved.":"Remove the exact surplus hierarchy rows so each child has one parent.",r.map(i=>`${i.child_id} <- ${i.parent_ids.join(", ")}`))]}function Pa(e,t,n){let r=e.divergences.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[it(n?"legacy_hierarchy_direction_violation":"hierarchy_direction_violation",n?"info":"error","Scalar parent metadata and dependency-backed hierarchy rows must resolve to the same logical parent.",i=>`${i} child item${i===1?"":"s"} have divergent hierarchy storage surfaces.`,r.map(i=>i.child_id),t,n?"Preserve historical rows unless an explicit legacy repair is approved.":"Align the scalar parent and exact dependency rows to one canonical parent.",r.map(i=>`${i.child_id}: scalar=${i.scalar_parent_id} dependencies=${i.dependency_parent_ids.join(",")}`))]}function Nm(e,t){let n=Cn(e);return n?[...Mm(n,t),...$a(n,t,!1),...$a(n,t,!0),...Pa(n,t,!1),...Pa(n,t,!0)]:[]}function $m(e){let t=e.graph.registry(),n=new Map;for(let r of e.graph.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let[o,s]=(i.precedence??"source_before_target")==="target_before_source"?[r.target,r.source]:[r.source,r.target],a=n.get(o);a?a.push(s):n.set(o,[s])}for(let r of n.values())r.sort((i,o)=>i.localeCompare(o));return n}function Ua(e,t){t.indexes.set(e,t.nextIndex),t.lowLinks.set(e,t.nextIndex),t.nextIndex+=1,t.stack.push(e),t.onStack.add(e)}function Pm(e,t,n,r){let i=n.get(e.node)??[];if(e.neighborIndex>=i.length)return!1;let o=i[e.neighborIndex];return e.neighborIndex+=1,r.indexes.has(o)?r.onStack.has(o)&&r.lowLinks.set(e.node,Math.min(r.lowLinks.get(e.node),r.indexes.get(o))):(Ua(o,r),t.push({node:o,neighborIndex:0})),!0}function jm(e,t,n,r){t.pop();let i=t.at(-1);if(i&&r.lowLinks.set(i.node,Math.min(r.lowLinks.get(i.node),r.lowLinks.get(e.node))),r.lowLinks.get(e.node)!==r.indexes.get(e.node))return;let o=[];for(;;){let s=r.stack.pop();if(r.onStack.delete(s),o.push(s),s===e.node)break}(o.length>1||o.length===1&&n.get(o[0])?.includes(o[0]))&&r.components.push(o.sort((s,a)=>s.localeCompare(a)))}function Um(e){let t={indexes:new Map,lowLinks:new Map,onStack:new Set,stack:[],components:[],nextIndex:0},n=[...e.keys()].sort((r,i)=>r.localeCompare(i));for(let r of n){if(t.indexes.has(r))continue;let i=[{node:r,neighborIndex:0}];for(Ua(r,t);i.length>0;){let o=i.at(-1);Pm(o,i,e,t)||jm(o,i,e,t)}}return t.components.sort((r,i)=>r[0].localeCompare(i[0]))}function Zr(e){return`${e.holder_id} -> ${e.target_id} (${e.kind})`}function ee(e,t,n,r,i,o,s,a){t.length!==0&&e.push(it(r,i,o,s,t,n,a))}function Bm(e,t,n){let r=[],i=[...e.dangling.active,...e.dangling.legacy_terminal].filter(o=>!o.no_active_blocker_sentinel);return ee(r,i.filter(o=>!t(o.holder_status)).map(Zr),n,"missing_reference_active","error","Active items must not reference absent targets; missing prerequisites distort scheduling.",o=>`${o} active dangling reference(s) to absent items`,"Restore or re-create the referenced item, or remove/retype the reference on the holder."),ee(r,i.filter(o=>t(o.holder_status)).map(Zr),n,"missing_reference_terminal","info","Terminal items may retain historical references, but absent targets remain unexplainable context.",o=>`${o} terminal dangling reference(s) to absent items`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),ee(r,e.dangling.no_active_blocker_sentinels.map(Zr),n,"legacy_no_blocker_sentinel","info","The pre-structured-dependency no-active-blocker sentinel is retired; real edges carry blocker state.",o=>`${o} legacy no-active-blocker sentinel reference(s)`,"Delete the sentinel reference; blocker state is derived from blocked_by edges."),r}function ti(e,t){let n=t.get(e);return n?!n.terminal:!0}function Ba(e){return`${e.holder_id} -> ${e.target_id} (blocked_by scalar + ${e.dependency_kind} dependency)`}function Hm(e,t){let n=[],r=[];for(let o of e.orderingContradictions??[])(o.legacy_terminal?r:n).push(Ba(o));let i=[];return ee(i,n,t,"ordering_storage_contradiction","error","A scalar blocker and same-target structured ordering row must not assert opposite precedence.",o=>`${o} active scalar-versus-structured ordering contradiction(s)`,"Remove the structured dependency row that points the holder before its scalar blocker, or replace both representations with one unambiguous ordering edge."),ee(i,r,t,"legacy_ordering_storage_contradiction","info","Terminal scalar-versus-structured ordering contradictions are exact historical storage defects with no live scheduling effect.",o=>`${o} terminal scalar-versus-structured ordering contradiction(s)`,"Remove the contradictory blocks dependency row in a dedicated changelog-safe closed-item batch; preserve the scalar blocker as the historical precedence record."),i}function Gm(e,t,n,r){let i=[],o=$m(e);for(let c of Um(o)){let d=c.some(f=>ti(f,t)),l=new Set(c.map(f=>f.toLowerCase())),u=(e.orderingContradictions??[]).filter(f=>l.has(f.holder_id.toLowerCase())&&l.has(f.target_id.toLowerCase())).map(Ba);i.push(d?it("ordering_cycle","error","Order-bearing relationship kinds must stay acyclic; a cycle makes every member unschedulable.",f=>`execution-order cycle across ${f} item(s)`,c,r,"Remove or retype one ordering edge inside the cycle, or split the work so precedence is linear.",u.length===0?void 0:u):it("legacy_ordering_cycle","info","Ordering cycles between exclusively terminal items are historical contradictions with no scheduling effect.",f=>`terminal-only execution-order cycle across ${f} item(s)`,c,r,"Leave as history debt, or clean up in a dedicated changelog-safe closed-item batch; never repair closed items ad hoc.",u.length===0?void 0:u))}let s=new Map;for(let[c,d]of o)for(let l of d){let u=s.get(l);u?u.push(c):s.set(l,[c])}let a=[...t.values()].filter(c=>!c.missing&&!c.terminal&&n(c.status)&&!(s.get(c.id)??[]).some(d=>{let l=t.get(d);return l===void 0||!l.terminal})).map(c=>c.id);return ee(i,a,r,"stale_lifecycle_block","warning","A blocked lifecycle status must be backed by at least one open ordering predecessor.",c=>`${c} status-blocked item(s) with no open blocker edge`,'Add a local blocker edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status.'),i}function jn(e){let t=e.edges.map(n=>n.kind).sort((n,r)=>n.localeCompare(r));return`${e.from} -> ${e.to} (${t.join(" + ")})`}function ni(e){let t=e.graph.registry(),n=new Map;for(let i of e.graph.edges()){let o=t.require(i.kind);if(!Fn(o))continue;let s=Qr(i,o);if(s.from===s.to)continue;let a=`${Mn(o)}::${s.from}::${s.to}`,c=n.get(a);c?c.edges.push(i):n.set(a,{...s,edges:[i]})}let r=[...n.values()].filter(i=>i.edges.length>=2);for(let i of r)i.edges.sort((o,s)=>o.kind.localeCompare(s.kind));return r.sort((i,o)=>i.from.localeCompare(o.from)||i.to.localeCompare(o.to))}function Km(e,t,n){let r=[],i=[];for(let s of ni(e))(ti(s.from,t)||ti(s.to,t)?r:i).push(jn(s));let o=[];return ee(o,r,n,"duplicate_edge","info","One semantic relationship should be stored once; parallel same-family spellings (reciprocal inverse pairs included) add no information and skew degree metrics.",s=>`${s} duplicated relationship(s) between active endpoints`,"Remove all but one stored spelling of the relationship; keep the canonical direction the holder declared first."),ee(o,i,n,"legacy_duplicate_edge","info","Duplicated spellings between exclusively terminal items are historical noise with no scheduling effect.",s=>`${s} duplicated relationship(s) between terminal endpoints`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),o}function zm(e,t){let n=[],r=[];for(let o of e.duplicateRows??[])(o.legacy_terminal?r:n).push(`${o.holder_id} -> ${o.target_id} (${o.kind} x${o.occurrences})`);let i=[];return ee(i,n,t,"duplicate_dependency_row","warning","One dependency row must be stored once per holder; identical repeated rows are a storage-layer defect invisible to the assembled graph.",o=>`${o} exactly duplicated stored dependency row(s) on active holder(s)`,"Remove the repeated rows so the dependency is stored exactly once; graph semantics are unchanged."),ee(i,r,t,"legacy_duplicate_dependency_row","info","Identical repeated dependency rows on terminal holders are historical storage noise with no scheduling effect.",o=>`${o} exactly duplicated stored dependency row(s) on terminal holder(s)`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),i}function Vm(e,t){let n=new Map,r={source_to_target:[],target_to_source:[],both:[]};for(let s of e.graph.registry().list())s.outcomeTraversal!==void 0&&r[s.outcomeTraversal].push(s.kind);let i={source_to_target:r.source_to_target.join(","),target_to_source:r.target_to_source.join(","),both:r.both.join(",")},o=(s,a)=>{let c=n.get(a)??new Set;c.add(s),n.set(a,c)};for(let s of e.graph.edges()){t?.throwIfAborted();let a=e.graph.registry().require(s.kind);(a.outcomeTraversal==="source_to_target"||a.outcomeTraversal==="both")&&o(s.source,s.target),(a.outcomeTraversal==="target_to_source"||a.outcomeTraversal==="both")&&o(s.target,s.source)}return{basis:i,reverse:n}}function qm(e,t,n){let r=new Set(e),i=[...e].sort();for(let o=0;o<i.length;o+=1){n?.throwIfAborted();for(let s of[...t.get(i[o])??[]].sort())r.has(s)||(r.add(s),i.push(s))}return r}function Wm(e,t,n,r){let i=0,o=0,s=0,a=0;for(let p of e.values())if(r?.throwIfAborted(),!t.has(p.id)&&!(p.missing||p.status==="external")){if(p.terminal){s+=1,n.has(p.id)&&(a+=1);continue}n.has(p.id)?i+=1:o+=1}let c=i+o,d=s-a,l=i+a,u=o+d,f=l+u;return{active_outcome_reachable_nodes:i,active_outcome_unreachable_nodes:o,active_outcome_reachability_basis_points:c===0?0:Math.floor(i*1e4/c),terminal_nodes:s,terminal_outcome_reachable_nodes:a,terminal_outcome_unreachable_nodes:d,terminal_outcome_reachability_basis_points:s===0?0:Math.floor(a*1e4/s),outcome_reachable_nodes:l,outcome_unreachable_nodes:u,outcome_reachability_basis_points:f===0?0:Math.floor(l*1e4/f)}}function Ym(e,t,n){let r=new Set(e.details.filter(a=>a.type?.toLowerCase()===Om&&a.title.trim().toLowerCase().startsWith(Lm)).map(a=>a.id)),{basis:i,reverse:o}=Vm(e,n),s=qm(r,o,n);return{outcome_nodes:r.size,outcome_reachability_basis:i,...Wm(t,r,s,n)}}function Xm(e,t,n,r,i){e.active+=1;let o=t.type??"(untyped)",s=e.byType.get(o);s||(s={active:0,isolated:0,degree_leq_one:0},e.byType.set(o,s)),s.active+=1,!(n>1)&&(e.degreeLeqOne+=1,s.degree_leq_one+=1,n===0&&(e.isolated+=1,s.isolated+=1),!(r.has(t.id.toLowerCase())||i.has(o.toLowerCase()))&&(n===0?e.isolates.push(t.id):e.sparse.push(t.id)))}function Jm(e,t,n,r,i,o,s){let a={active:0,missing:0,isolated:0,degreeLeqOne:0,isolates:[],sparse:[],byType:new Map};for(let b of e.graph.nodes()){s?.throwIfAborted();let w=t.get(b);if(w){if(w.missing){a.missing+=1;continue}w.terminal||Xm(a,w,e.graph.incidentEdges(b).length,n,r)}}let{isolates:c,sparse:d}=a,l=[];ee(l,c,i,"isolated_active_node","warning","Active work should be reachable from the graph unless explicitly declared a valid isolate.",b=>`${b} active item(s) with no relationships`,"Link the item to its parent, prerequisite, or origin \u2014 or register it as an exempt isolate."),ee(l,d,i,"sparse_active_node","info","Active items with a single edge often miss an honest semantic partner; sparse is not automatically defective.",b=>`${b} active item(s) with exactly one relationship`,"Investigate for an honest second edge (story->task, defect family, cross-epic complement); do not fabricate one.");let u=e.graph.edges().length,f=tt(e.graph,{signal:s}).value,p=new Set(f.map(({edge:b})=>`${b.source.toLowerCase()}\0${b.target.toLowerCase()}\0${b.kind}`));for(let b of e.orderingContradictions??[])p.add(`${b.holder_id.toLowerCase()}\0${b.target_id.toLowerCase()}\0${b.dependency_kind}`);let m=Object.fromEntries(Object.entries(o).sort(([b],[w])=>b.localeCompare(w))),h=Object.entries(m).reduce((b,[w,k])=>b+(Pn(w)?k:0),0),y=Nn(e.graph,{signal:s}).value,v=Ym(e,t,s);return{findings:l,profile:{nodes:e.graph.nodes().length,recorded_nodes:e.details.filter(b=>b.status!=="missing"&&b.status!=="external").length,edges:u,informative_edges:u-p.size,redundant_edges:f.length,ordering_contradiction_edges:e.orderingContradictions?.length??0,edge_basis:"deduplicated_directed",edges_by_kind:m,edge_share_by_kind:Object.fromEntries(Object.entries(m).map(([b,w])=>[b,w/u])),semantic_edges:h,semantic_edge_share:u===0?0:h/u,active_nodes:a.active,missing_nodes:a.missing,isolated_active_nodes:a.isolated,degree_leq_one_active_nodes:a.degreeLeqOne,coverage_by_type:Object.fromEntries([...a.byType.entries()].sort(([b],[w])=>b<w?-1:1)),articulation_points:y.articulationPoints.length,bridge_edges:y.bridges.length,...v,finding_subjects_by_code:Object.fromEntries(rt.map(b=>[b,0]))}}}function Un(e,t={}){let n=t.isTerminal??(f=>f==="closed"||f==="canceled"),r=t.isBlocked??(f=>f==="blocked"),i=t.maxSampleSize??Am;if(!Number.isInteger(i)||i<1)throw new TypeError(`Invalid audit sample bound: ${String(t.maxSampleSize)}`);let o=Na(t.exemptIsolates),s=Na(t.isolateExemptTypes),a=new Map(e.details.map(f=>[f.id,{id:f.id,status:f.status,missing:e.missingIdSet.has(f.id.toLowerCase()),terminal:n(f.status),...f.type===void 0?{}:{type:f.type}}]));t.signal?.throwIfAborted();let c={};for(let f of e.graph.edges())c[f.kind]=(c[f.kind]??0)+1;let d=Bm(e,n,i);d.push(...Nm(e,i)),t.signal?.throwIfAborted(),d.push(...Hm(e,i)),t.signal?.throwIfAborted(),d.push(...Gm(e,a,r,i)),t.signal?.throwIfAborted(),d.push(...Km(e,a,i),...zm(e,i)),t.signal?.throwIfAborted();let l=Jm(e,a,o,s,i,c,t.signal);d.push(...l.findings),d.sort((f,p)=>Ma[f.severity]-Ma[p.severity]||f.code.localeCompare(p.code)||f.sample[0].localeCompare(p.sample[0]));let u=l.profile.finding_subjects_by_code;for(let f of d)u[f.code]+=f.count;return{findings:d,profile:{...l.profile,...Oa(e,n,Pn,t.signal),ordering_acyclic:!d.some(f=>f.code==="ordering_cycle"||f.code==="legacy_ordering_cycle"),active_ordering_acyclic:!d.some(f=>f.code==="ordering_cycle"),finding_subjects_by_code:u}}}function ei(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),r={};for(let i of n){let o=(t[i]??0)-(e[i]??0);o!==0&&(r[i]=o)}return r}function ja(e){return e.profile.coverage_by_type??{}}function Qm(e,t){let n={},r=ja(e),i=ja(t),o=[...new Set([...Object.keys(r),...Object.keys(i)])].sort();for(let s of o){let a=Object.assign({active:0,isolated:0,degree_leq_one:0},r[s]),c=Object.assign({active:0,isolated:0,degree_leq_one:0},i[s]),d={active:c.active-a.active,isolated:c.isolated-a.isolated,degree_leq_one:c.degree_leq_one-a.degree_leq_one};Object.values(d).some(l=>l!==0)&&(n[s]=d)}return n}function Ha(e,t){let n=Qm(e,t),{edge_share_by_kind:r={},semantic_edges:i=0,semantic_edge_share:o=0}=e.profile,{edge_share_by_kind:s={},semantic_edges:a=0,semantic_edge_share:c=0}=t.profile,d=e.profile.recorded_nodes??e.profile.nodes,l=t.profile.recorded_nodes??t.profile.nodes,u=e.profile.informative_edges??e.profile.edges,f=t.profile.informative_edges??t.profile.edges,p=e.profile.redundant_edges??0,m=t.profile.redundant_edges??0,h=e.profile.ordering_contradiction_edges??0,y=t.profile.ordering_contradiction_edges??0;return{baseline_saved_at:e.saved_at,same_snapshot:e.fingerprint===t.fingerprint,affected_subjects_by_code:ei(e.affected_subjects_by_code,t.affected_subjects_by_code),profile:{nodes:t.profile.nodes-e.profile.nodes,recorded_nodes:l-d,edges:t.profile.edges-e.profile.edges,informative_edges:f-u,redundant_edges:m-p,ordering_contradiction_edges:y-h,active_nodes:t.profile.active_nodes-e.profile.active_nodes,missing_nodes:t.profile.missing_nodes-e.profile.missing_nodes,isolated_active_nodes:t.profile.isolated_active_nodes-e.profile.isolated_active_nodes,degree_leq_one_active_nodes:t.profile.degree_leq_one_active_nodes-e.profile.degree_leq_one_active_nodes,edges_by_kind:ei(e.profile.edges_by_kind,t.profile.edges_by_kind),edge_share_by_kind:ei(r,s),semantic_edges:a-i,semantic_edge_share:c-o,coverage_by_type:n,...Fa(e.profile,t.profile)}}}import Ga from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5089f2d-3fc5-5843-95ab-ba3dd2ab9582")}catch{}})();var Ka=2,ri=500,Zm=64,ep="graph-durable-cache";function za(e){return He(e,ep,30,`graph-cache:${process.pid}`,!1,!1,3e3)}function It(e){return Ga.join(e,"runtime","graph-cache.json")}function Va(e){return Ga.join(e,"runtime","graph-audit-baseline.json")}function ii(e){if(e!==null)try{let t=JSON.parse(e);return typeof t!="object"||t===null||t.version!==Ka||typeof t.fingerprint!="string"||typeof t.saved_at!="string"||typeof t.results!="object"||t.results===null||Array.isArray(t.results)?void 0:t}catch{return}}async function oi(e,t){let n=await ge(It(e)),r=ii(n),i=r?.fingerprint===t;return{exists:n!==null,fresh:i,results:i?r.results:{}}}async function si(e,t,n,r,i){let o=await za(e);try{let s=ii(await ge(It(e))),a=s?.fingerprint===t?s.results:{};delete a[r],a[r]=i;let c=Object.keys(a);for(let d of c.slice(0,Math.max(0,c.length-Zm)))delete a[d];await W(It(e),JSON.stringify({version:Ka,fingerprint:t,saved_at:new Date().toISOString(),results:a})),n.results=a}finally{await o()}}async function ai(e){let t=await za(e);try{await uo(It(e))}finally{await t()}}async function qa(e,t){let n=It(e),r=await ge(n),i=ii(r);return i===void 0?{exists:r!==null,fresh:!1,entry_count:0}:{exists:!0,fresh:i.fingerprint===t,entry_count:Object.keys(i.results).length,fingerprint:i.fingerprint.slice(0,12),saved_at:i.saved_at,bytes:Buffer.byteLength(r,"utf8")}}function ci(e,t){return t||e>=ri}function Bn(e){return ot(e)&&Object.values(e).every(Le)}function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Le(e){return Number.isInteger(e)&&Number(e)>=0}function Wa(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function Et(e,t){return e===void 0||t(e)}function tp(e){return ot(e)&&Object.values(e).every(Wa)}function np(e){return ot(e)?Object.values(e).every(t=>ot(t)&&[t.active,t.isolated,t.degree_leq_one].every(Le)):!1}function rp(e,t,n){let r=["recorded_nodes","informative_edges","redundant_edges","ordering_contradiction_edges"],i=r.filter(s=>e[s]!==void 0).length;if(i!==0&&i!==r.length||!r.every(s=>Et(e[s],Le)))return;let o={recorded_nodes:e.recorded_nodes??t,informative_edges:e.informative_edges??n,redundant_edges:e.redundant_edges??0,ordering_contradiction_edges:e.ordering_contradiction_edges??0};return o.recorded_nodes<=t&&o.informative_edges<=n&&o.redundant_edges<=n&&o.ordering_contradiction_edges<=n?o:void 0}function ip(e,t,n){let r=[...t,...n,"finding_subjects_by_code"],i=r.filter(o=>e[o]!==void 0).length;return i!==0&&i!==r.length?!1:t.every(o=>Et(e[o],Le))&&n.every(o=>Et(e[o],Le)&&(e[o]===void 0||Number(e[o])<=1e4))&&Et(e.finding_subjects_by_code,Bn)}function op(e,t,n,r){let i=rp(e,n,r);if(i===void 0)return;let o=["articulation_points","bridge_edges","outcome_nodes","active_outcome_reachable_nodes","active_outcome_unreachable_nodes","terminal_nodes","terminal_outcome_reachable_nodes","terminal_outcome_unreachable_nodes","outcome_reachable_nodes","outcome_unreachable_nodes"],s=["active_outcome_reachability_basis_points","terminal_outcome_reachability_basis_points","outcome_reachability_basis_points"];if(!ip(e,o,s)||e.edge_basis!==void 0&&e.edge_basis!=="deduplicated_directed")return;let a=Bn(e.finding_subjects_by_code)?e.finding_subjects_by_code:{};return{edge_basis:"deduplicated_directed",...i,...Object.fromEntries(o.map(c=>[c,e[c]??0])),...Object.fromEntries(s.map(c=>[c,e[c]??0])),finding_subjects_by_code:Object.fromEntries(rt.map(c=>[c,a[c]??t[c]??0]))}}function sp(e,t,n,r,i){let o=[n,r,i],s=o.filter(d=>d!==void 0).length;if(s===0)return{edge_share_by_kind:{},semantic_edges:0,semantic_edge_share:0};if(s!==o.length||!tp(n)||!Le(r)||!Wa(i))return;let a=Object.entries(t);if(a.reduce((d,[,l])=>d+l,0)!==e||Object.keys(n).length!==a.length||a.some(([d,l])=>n[d]!==(e===0?0:l/e)))return;let c=a.reduce((d,[l,u])=>d+(Pn(l)?u:0),0);if(!(r!==c||i!==(e===0?0:c/e)))return{edge_share_by_kind:n,semantic_edges:r,semantic_edge_share:i}}function ap(e){if(e!==null)try{let t=JSON.parse(e);if(!ot(t))return;let n=t,r=n.profile;if(typeof n.saved_at!="string"||typeof n.fingerprint!="string")return;let i=n.affected_subjects_by_code;if(!Bn(i)||!ot(r)||!La(r)||![r.nodes,r.edges,r.active_nodes,r.missing_nodes,r.isolated_active_nodes,r.degree_leq_one_active_nodes].every(Le)||!Bn(r.edges_by_kind)||!Et(r.coverage_by_type,np))return;let o=sp(r.edges,r.edges_by_kind,r.edge_share_by_kind,r.semantic_edges,r.semantic_edge_share);if(o===void 0)return;let s=op(r,i,r.nodes,r.edges);if(s===void 0)return;let{coverage_by_type:a={}}=r;return{...n,profile:{...r,...o,...s,coverage_by_type:a}}}catch{return}}async function Ya(e){return ap(await ge(Va(e)))}async function Xa(e,t){await W(Va(e),JSON.stringify(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="253f392d-4e91-57ec-b656-6134583d57e5")}catch{}})();var cp={missing_reference_active:{op:"investigate",confidence:"medium",rationale:"Restore or re-create the referenced item, or remove/retype the reference on the active holder; the correct fix depends on why the target is absent."},missing_reference_terminal:{op:"waive",confidence:"high",rationale:"Terminal-holder reference to an absent item is historical debt; waive it or clean it up only in a dedicated changelog-safe closed-item batch."},legacy_no_blocker_sentinel:{op:"remove",confidence:"high",rationale:"The pre-structured-dependency no-active-blocker sentinel is retired and carries no information; blocker state derives from blocked_by edges."},ordering_cycle:{op:"investigate",confidence:"low",rationale:"Every cycle member is unschedulable until one ordering edge is removed or retyped; the planner never chooses which edge to cut."},legacy_ordering_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only ordering cycles have no scheduling effect; repairing them would mutate closed history (changelog drag)."},ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The structured ordering row asserts the opposite precedence from the same-target scalar blocker; remove that exact dependency row or replace both representations with one unambiguous edge."},legacy_ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The terminal holder contains a proven contradictory structured ordering row; remove it in a dedicated changelog-safe batch while preserving the scalar blocker as history."},hierarchy_cycle:{op:"investigate",confidence:"low",rationale:"Cut or retype one exact structural relation in the cycle; the planner preserves every evidence row because intent determines the correct parent."},legacy_hierarchy_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only hierarchy cycles are historical debt; waive them unless an explicit closed-history repair is approved."},hierarchy_cardinality_violation:{op:"investigate",confidence:"medium",rationale:"Choose the canonical parent and remove or retype the exact surplus hierarchy rows; the planner cannot infer ownership intent."},legacy_hierarchy_cardinality_violation:{op:"waive",confidence:"high",rationale:"Multiple parents confined to terminal items are historical debt; waive them unless a dedicated history repair is approved."},hierarchy_direction_violation:{op:"investigate",confidence:"medium",rationale:"Align the scalar parent and dependency-backed hierarchy rows to the intended canonical parent."},legacy_hierarchy_direction_violation:{op:"waive",confidence:"high",rationale:"Divergent hierarchy storage confined to terminal items is historical debt; waive it unless a dedicated history repair is approved."},duplicate_edge:{op:"remove",confidence:"high",rationale:"Parallel same-family spellings state one relationship twice; remove all but one stored spelling, keeping the holder's canonical direction."},legacy_duplicate_edge:{op:"waive",confidence:"high",rationale:"Duplicated spellings between terminal items are historical noise; waive or batch changelog-safe cleanup."},duplicate_dependency_row:{op:"remove",confidence:"high",rationale:"The identical dependency row is stored more than once on the holder; drop the repeats so the row exists exactly once \u2014 graph semantics are unchanged."},legacy_duplicate_dependency_row:{op:"waive",confidence:"high",rationale:"Repeated identical rows on terminal holders are storage noise; waive or clean up only in a changelog-safe closed-item batch."},stale_lifecycle_block:{op:"investigate",confidence:"medium",rationale:`Add a local ordering edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status; only the holder's owner knows which is true.`},isolated_active_node:{op:"investigate",confidence:"medium",rationale:"Link the item to its parent, prerequisite, or origin \u2014 or register it as an explicitly exempt isolate; the audit never fabricates an edge."},sparse_active_node:{op:"investigate",confidence:"low",rationale:"Investigate for an honest second edge (story-to-task, defect family, cross-epic complement); sparse is not automatically defective."}};function Ja(e){return`${e.source} -${e.kind}-> ${e.target}`}function dp(e){let[t,...n]=e.edges;return n.map(r=>({op:"remove",code:"duplicate_edge",subject:Ja(r),rationale:"This stored spelling restates the kept canonical edge of the same semantic family; removing it leaves the relationship stated exactly once.",evidence:[`keep: ${Ja(t)}`,`group: ${jn(e)}`],confidence:"high"}))}function lp(e,t){if(e.code==="duplicate_edge")return e.sample.flatMap(r=>dp(t.get(r)));let n=cp[e.code];return e.sample.map(r=>({op:n.op,code:e.code,subject:r,rationale:n.rationale,evidence:[e.policy],confidence:n.confidence}))}function Qa(e,t={}){let{redundancyLimit:n,...r}=t,i=Un(e,r),o=new Map(ni(e).map(d=>[jn(d),d])),s=i.findings.flatMap(d=>lp(d,o)),a=i.findings.some(d=>d.sample_truncated);t.signal?.throwIfAborted();let c=tt(e.graph,{limit:n??t.maxSampleSize??25,...t.signal===void 0?{}:{signal:t.signal}});for(let d of c.value)s.push({op:"remove",code:"redundant_edge",subject:`${d.edge.source} -> ${d.edge.target} (${d.edge.kind})`,rationale:"The stored edge is implied by a longer same-family witness path; shortcut edges are sometimes deliberate emphasis, so confirm intent before removing.",evidence:[`witness: ${d.witness.join(" -> ")}`],confidence:"medium"});return a=a||c.meta.truncated,{steps:s,report:i,truncated:a,cost:{visitedNodes:c.meta.visitedNodes,inspectedEdges:c.meta.inspectedEdges}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66df3949-0caf-5f01-8cec-3bba3d1e6111")}catch{}})();var nc=new Set(["ancestors","descendants","predecessors","successors","paths","impact","dominators"]);function Za(e,t,n){let r=e;if(t&&e.subcommand==="audit"){let{nodes:i,recorded_nodes:o,edges:s,active_nodes:a,terminal_nodes:c,missing_nodes:d,ordering_acyclic:l,active_ordering_acyclic:u,coverage_by_lifecycle:f}=e.profile,p=Object.fromEntries(Object.entries(f).map(([m,h])=>{let{degree_histogram:y,...v}=h;return[m,v]}));r={...e,profile:{nodes:i,recorded_nodes:o,edges:s,active_nodes:a,terminal_nodes:c,missing_nodes:d,ordering_acyclic:l,active_ordering_acyclic:u,coverage_by_lifecycle:p}}}return{...r,projection:{mode:t?"summary":"full",declared_field_groups:n===void 0?[]:[{name:n,restore_with:"--full"}],included_field_groups:n===void 0||t?[]:[n]}}}function up(e,t,n,r){return{assembly:t,...n===void 0?{}:{kinds:n},maxDepth:xn(r.maxDepth),limit:e==="impact"&&Number(r.limit)===0?0:me(r.limit,"limit")??(r.full===!0?Number.MAX_SAFE_INTEGER:ve.rows),after:r.after?.trim()||void 0,direction:Yr(r.direction),maxPaths:me(r.maxPaths,"max-paths"),sample:me(r.sample,"sample")??ve.samples,exemptIsolates:ec(r.exemptIsolate),exemptIsolateTypes:ec(r.exemptIsolateType),saveBaseline:r.saveBaseline===!0,summary:r.summary===!0,unbounded:r.full===!0}}function ec(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function fp(e,t,n){let r=e.trim().toLowerCase();if(!br.includes(r))throw ls({command_path:"graph",token:r||"<empty>",allowed:br});let i=r;if(nc.has(i)&&!t?.trim())throw new _(`graph ${i} requires an item id.`,g.USAGE);if(i==="paths"&&!n?.trim())throw new _("graph paths requires a source and a target item id.",g.USAGE);return i}function di(e){throw e instanceof TypeError?new _(e.message,g.USAGE):e}function li(e){return{truncated:e.truncated,cost:{visited_nodes:e.visitedNodes,inspected_edges:e.inspectedEdges}}}function tc(e,t){let n=t.trim().toLowerCase();for(let r of e.details)if(r.id.trim().toLowerCase()===n&&!e.missingIdSet.has(r.id.toLowerCase()))return r.id;throw new _(`Item ${t} not found`,g.NOT_FOUND)}function mp(e,t,n){let r={ancestors:ga,descendants:_a,predecessors:ya,successors:ba}[e],i;try{i=r(n.assembly.graph,t,{...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},limit:n.limit,...n.after===void 0?{}:{after:n.after}})}catch(s){di(s)}let o=li(i.meta);return{subcommand:e,root:t,count:i.value.length,...o,...i.meta.nextCursor===void 0?{}:{next_cursor:i.meta.nextCursor},...n.summary?{}:{ids:i.value}}}function pp(e,t,n){let r=va(n.assembly.graph,e,t,{direction:n.direction,...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},...n.maxPaths===void 0?{}:{maxPaths:n.maxPaths}});return{subcommand:"paths",root:e,target:t,direction:n.direction,count:r.value.length,...li(r.meta),...n.summary?{}:{paths:r.value.map(i=>({nodes:i.nodes,kinds:i.edges.map(o=>o.kind),length:i.length}))}}}function hp(e,t){let n;try{n=_n(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth},...t.unbounded?{}:{limit:t.limit},...t.after===void 0?{}:{after:t.after}})}catch(r){di(r)}return{subcommand:"impact",root:e,direction:t.direction,count:n.affected.length,truncated:n.truncated,...n.nextCursor===void 0?{}:{next_cursor:n.nextCursor},cost:{visited_nodes:n.cost.visitedNodes,inspected_edges:n.cost.inspectedEdges},...t.summary?{}:{affected:n.affected}}}function gp(e,t,n){return{acyclic:e.acyclic,ordered_node_count:e.order.length,layer_count:e.layers.length,frontier_count:e.frontier.length,critical_path_length:e.criticalPathLength,cycle_count:e.cycles.length,...t?{}:{frontier:e.frontier.slice(0,n),critical_path:e.criticalPath.slice(0,n),cycles:e.cycles.slice(0,n)}}}function _p(e,t,n){return{component_count:e.components.length,largest_component_size:e.components[0]?.length??0,orphan_count:e.orphans.length,...t?{}:{orphans:e.orphans.slice(0,n),hubs:e.hubs.slice(0,n)}}}function yp(e,t,n){let r=0,i=0,o=0;for(let s of e.cycles)r+=Number(s.legacy_terminal);for(let s of e.cardinality_violations)i+=Number(s.legacy_terminal);for(let s of e.divergences)o+=Number(s.legacy_terminal);return{acyclic:e.cycles.length===0,relation_count:e.relations.length,cycle_count:e.cycles.length,active_cycle_count:e.cycles.length-r,legacy_cycle_count:r,cardinality_violation_count:e.cardinality_violations.length,active_cardinality_violation_count:e.cardinality_violations.length-i,legacy_cardinality_violation_count:i,parent_divergence_count:e.divergences.length,active_parent_divergence_count:e.divergences.length-o,legacy_parent_divergence_count:o,...t?{}:{cycles:e.cycles.slice(0,n).map(s=>s.item_ids)}}}function bp(e){let t=e.assembly.graph,n=e.limit,r=yn(t,{registry:t.registry()}),i=_s(t);return{subcommand:"analyze",node_count:t.nodes().length,edge_count:t.edges().length,edge_basis:"deduplicated_directed",sample_limit:n,execution:gp(r,e.summary,n),knowledge:_p(i,e.summary,n),hierarchy:yp(Cn(e.assembly),e.summary,n)}}function vp(e,t){let n=Un(e.assembly,{isTerminal:t,maxSampleSize:e.sample,...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),r={},i={},o={},s={};for(let d of n.findings)r[d.severity]=(r[d.severity]??0)+1,i[d.code]=(i[d.code]??0)+1,o[d.severity]=(o[d.severity]??0)+d.count,s[d.code]=(s[d.code]??0)+d.count;let{finding_subjects_by_code:a,...c}=n.profile;return{subcommand:"audit",truncated:n.findings.length>e.limit,finding_count:n.findings.length,findings_by_severity:r,findings_by_code:i,affected_subjects_by_severity:o,affected_subjects_by_code:s,profile:e.summary?c:n.profile,legacy_alias_counts:e.assembly.legacyAliasCounts,...e.summary?{}:{findings:n.findings.slice(0,e.limit)}}}function wp(e){let t=e.limit,n={};e.kinds!==void 0&&(n.kinds=e.kinds);let r=ka(e.assembly.graph,n),i=r.value;return{subcommand:"communities",community_count:i.communities.length,largest_community_size:i.communities[0]?.size??0,iterations:i.iterations,converged:i.converged,truncated:!i.converged||i.communities.length>t,cost:{visited_nodes:r.meta.visitedNodes,inspected_edges:r.meta.inspectedEdges},...e.summary?{}:{communities:i.communities.slice(0,t).map(o=>({representative:o.representative,size:o.size,members:o.members.slice(0,t)}))}}}function kp(e){let t;try{t=tt(e.assembly.graph,{...e.kinds===void 0?{}:{kinds:e.kinds},...e.maxDepth===void 0?{}:{maxDepth:e.maxDepth},limit:e.limit})}catch(n){di(n)}return{subcommand:"redundancy",redundant_count:t.value.length,...li(t.meta),...e.summary?{}:{redundant:t.value.map(n=>({source:n.edge.source,target:n.edge.target,kind:n.edge.kind,witness:n.witness}))}}}function Ep(e,t){let n=t.limit,r=Ea(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth}}),i=r.value.rows.filter(o=>o.dominatedCount>0);return{subcommand:"dominators",root:e,direction:t.direction,reachable_count:r.value.reachableCount,bottleneck_count:i.length,truncated:r.meta.truncated||i.length>n,cost:{visited_nodes:r.meta.visitedNodes,inspected_edges:r.meta.inspectedEdges},...t.summary?{}:{bottlenecks:i.slice(0,n).map(o=>({id:o.id,idom:o.idom,dominated_count:o.dominatedCount}))}}}function Ip(e){let t=e.limit,n=Ra(e.assembly.graph),r=n.rows.filter(i=>i.critical).length;return{subcommand:"slack",acyclic:n.acyclic,makespan:n.makespan,scheduled_count:n.scheduledCount,critical_count:r,critical_path_length:n.criticalPathLength,cycle_count:n.cycles.length,truncated:n.rows.length>t,...e.summary?{}:{critical_path:n.criticalPath.slice(0,t),rows:n.rows.slice(0,t).map(i=>({id:i.id,earliest_start:i.earliestStart,latest_start:i.latestStart,slack:i.slack,critical:i.critical}))}}}function Cp(e){let t=e.limit,n=Ta(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),r=n.value;return{subcommand:"centrality",node_count:r.nodeCount,edge_count:r.edgeCount,edge_basis:"simple_undirected",truncated:r.rows.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{rows:r.rows.slice(0,t).map(i=>({id:i.id,degree:i.degree,in_degree:i.inDegree,out_degree:i.outDegree,betweenness:i.betweenness,closeness:i.closeness}))}}}function Sp(e){let t=e.limit,n=Nn(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),{articulationPoints:r,bridges:i}=n.value;return{subcommand:"articulation",articulation_count:r.length,bridge_count:i.length,truncated:r.length>t||i.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{articulation_points:r.slice(0,t),bridges:i.slice(0,t)}}}function Tp(e,t){let n=e.limit,r=Qa(e.assembly,{isTerminal:t,redundancyLimit:n,maxSampleSize:e.sample,...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),i={},o={};for(let s of r.steps)i[s.op]=(i[s.op]??0)+1,o[s.code]=(o[s.code]??0)+1;return{subcommand:"plan",step_count:r.steps.length,steps_by_op:i,steps_by_code:o,finding_count:r.report.findings.length,truncated:r.truncated||r.steps.length>n,cost:{visited_nodes:r.cost.visitedNodes,inspected_edges:r.cost.inspectedEdges},...e.summary?{}:{steps:r.steps.slice(0,n)}}}function rc(e,t,n,r){return JSON.stringify({projection_version:2,subcommand:e,root:t??null,target:n??null,kinds:r.kinds??null,maxDepth:r.maxDepth??null,limit:r.limit,after:r.after??null,direction:r.direction,maxPaths:r.maxPaths??null,sample:r.sample,exemptIsolates:[...new Set(r.exemptIsolates.map(i=>i.toLowerCase()))].sort(),exemptIsolateTypes:[...new Set(r.exemptIsolateTypes.map(i=>i.toLowerCase()))].sort(),summary:r.summary,unbounded:r.unbounded})}function ic(e,t,n,r,i){return e==="analyze"?bp(r):e==="audit"?vp(r,i):e==="plan"?Tp(r,i):e==="communities"?wp(r):e==="redundancy"?kp(r):e==="dominators"?Ep(t,r):e==="slack"?Ip(r):e==="centrality"?Cp(r):e==="articulation"?Sp(r):e==="paths"?pp(t,n,r):e==="impact"?hp(t,r):mp(e,t,r)}function Rp(e,t){if(e!=="index"&&(t.rebuild===!0||t.clear===!0))throw new _("--rebuild and --clear apply only to graph index.",g.USAGE);if(e!=="audit"&&t.saveBaseline===!0)throw new _("--save-baseline applies only to graph audit.",g.USAGE);if(e==="slack"&&t.kind!==void 0)throw new _("graph slack analyzes every ordering kind; --kind is not supported.",g.USAGE);if(t.rebuild===!0&&t.clear===!0)throw new _("graph index accepts either --rebuild or --clear, not both.",g.USAGE);if(t.full===!0&&t.limit!==void 0)throw new _(`graph ${e} accepts either --full or --limit, not both.`,g.USAGE)}async function xp(e,t,n,r,i,o){let s="status";if(o.clear===!0&&(await ai(e),s="cleared"),o.rebuild===!0){await ai(e);let c=await oi(e,t),d={assembly:n.assembly,direction:"both",exemptIsolates:[],exemptIsolateTypes:[],saveBaseline:!1,summary:!0,limit:ve.rows,sample:ve.samples,unbounded:!1};for(let l of["analyze","audit"])await si(e,t,c,rc(l,void 0,void 0,d),ic(l,void 0,void 0,d,i));s="rebuilt"}let a=await qa(e,t);return{subcommand:"index",action:s,state:a.exists?a.fresh?"fresh":"stale":"absent",entry_count:a.entry_count,item_count:r,min_items_threshold:ri,persist_enabled:ci(r,a.exists),current_fingerprint:t.slice(0,12),...a.saved_at===void 0?{}:{saved_at:a.saved_at},...a.bytes===void 0?{}:{bytes:a.bytes}}}async function Dp(e,t,n,r){let i={saved_at:new Date().toISOString(),fingerprint:t,affected_subjects_by_code:n.affected_subjects_by_code,profile:{...n.profile,finding_subjects_by_code:Object.fromEntries(rt.map(s=>[s,n.affected_subjects_by_code[s]??0]))}},o=await Ya(e);return r&&await Xa(e,i),o===void 0?n:{...n,baseline:Ha(o,i)}}async function Ap(e,t,n,r,i){try{await si(e,t,n,r,i)}catch{}}function Op(e,t,n,r){if(e.subcommand!=="slack")return;let i=new Set(t.assembly.details.filter(f=>r(f.status)).map(f=>f.id)),o=t.assembly.graph,s=new Bt(o.nodes().filter(f=>!i.has(f)),o.edges().filter(f=>!i.has(f.source)&&!i.has(f.target)),o.registry()),a=xa(s,n.filter(f=>!i.has(f.id)),{now:x(),limit:t.limit}),{rows:c,residuals:d,overcommitted:l,...u}=a;e.deadline_schedule={population:"active",...u,...t.summary?{}:{rows:c,residuals:d,overcommitted:l}}}async function iE(e,t,n,r,i){let o=fp(e,t,n);qt(r.summary===!0,r.full===!0,"--summary");let s=O(process.cwd(),i.path);await U(s);let a=await F(s),c=L(a,D()),d=await le(s,a.item_format,c.type_to_folder,void 0,a.schema),l=J(a.schema),u=M=>$(M,l);Rp(o,r);let f=z(),p=Xr(r.kind,f),m=Tn().lookup(s,Sn(d,u,f),()=>Je(d,u,f)),h=up(o,m.assembly,p,r);if(o==="index")return Za(await xp(s,m.fingerprint,h,d.length,u,r),!1);let y=nc.has(o)?tc(h.assembly,t):void 0,v=o==="paths"?tc(h.assembly,n):void 0,b=rc(o,y,v,h),w=await oi(s,m.fingerprint),k=w.results[b],S=m.memoize(b,()=>k!==void 0?structuredClone(k):ic(o,y,v,h,u)),P=ci(d.length,w.exists);!S.reused&&k===void 0&&P&&await Ap(s,m.fingerprint,w,b,S.value);let j=S.value.subcommand==="audit"?await Dp(s,m.fingerprint,S.value,h.saveBaseline):S.value;return j.cache={fingerprint:m.fingerprint.slice(0,12),assembly:m.assemblyReused?"hit":"miss",result:S.reused?"hit":"miss",durable:k!==void 0?"hit":P?"miss":"off"},Op(j,h,d,u),Za(j,h.summary,"result_rows")}import ui from"node:fs/promises";import fi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="069e2e60-11d9-5a37-a966-9073944d32a2")}catch{}})();var oc=8388608,Lp=new Set(["resolved","failed"]),Fp=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function pe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mi(e){return Fp.find(t=>t.matches(e))?.kind}function sc(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let o=pe(i.agent_provenance)?i.agent_provenance:void 0;if(o===void 0||!Bo(i).ok)return i;let s={},a=!1;for(let[d,l]of Object.entries(o)){let u=pe(l)?mi(l.value):void 0;if(u===void 0){s[d]=l;continue}a=!0,r+=1;let f=i.agent_harness??"unknown",p=`${f}\0${d}\0${u}`,m=t.get(p)??{harness:f,dimension:d,kind:u,count:0};m.count+=1,t.set(p,m)}if(!a)return i;n+=1;let c={...i};return Object.keys(s).length===0?delete c.agent_provenance:c.agent_provenance=s,Ho(i,c,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((i,o)=>i.harness.localeCompare(o.harness)||i.dimension.localeCompare(o.dimension)||i.kind.localeCompare(o.kind))}}}async function ac(e){let t=[];for(let n of await cc(e)??[])try{let r=await ui.readFile(fi.join(e,"history",n),"utf8");for(let i of r.split(`
|
|
2
|
+
`)){if(i.trim().length===0)continue;let o=dc(i);if(!(o===null||!pe(o.agent_provenance))&&Object.values(o.agent_provenance).some(s=>pe(s)&&mi(s.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function cc(e){try{return(await ui.readdir(fi.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function Mp(e,t,n){let r;try{r=await ui.open(fi.join(e,"history",t),"r");let i=(await r.stat()).size,o=Math.min(i,Math.max(0,n)),s=Buffer.alloc(o),{bytesRead:a}=await r.read(s,0,o,0),c=s.subarray(0,a).toString("utf8"),d=a>=i,l=c.lastIndexOf(`
|
|
3
|
+
`),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:a,complete:d}}catch{return null}finally{await r?.close()}}function dc(e){try{let t=JSON.parse(e);return pe(t)?t:null}catch{return null}}function Np(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=pe(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([s,a])=>{if(!pe(a))return;let c=mi(a.value);if(!c)return;let d=`${r}\0${s}\0${c}`,l=n.get(d)??{harness:r,dimension:s,kind:c,count:0};l.count+=1,n.set(d,l)}),!pe(e.context))return;let o=e.context.agent_provenance_outcomes;pe(o)&&Object.entries(o).forEach(([s,a])=>{if(!pe(a)||typeof a.resolver!="string"||!Lp.has(String(a.status)))return;let c=`${r}\0${s}\0${a.resolver}`,d=t.get(c)??{harness:r,dimension:s,resolver:a.resolver,attempts:0,successes:0};d.attempts+=1,a.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function $p(e,t,n,r,i,o){let s=i;for(let a of e.split(`
|
|
4
|
+
`)){if(a.trim().length===0)continue;if(s>=r)return{eventsRead:s,truncated:!0};s+=1;let c=dc(a);if(c===null){o.malformed_events+=1;continue}if(typeof c.ts=="string"&&Xt(c.ts)){let d=new Date(c.ts).toISOString();(o.earliest_event_at===null||d<o.earliest_event_at)&&(o.earliest_event_at=d),(o.latest_event_at===null||d>o.latest_event_at)&&(o.latest_event_at=d)}Np(c,t,n)}return{eventsRead:s,truncated:!1}}function Pp(e,t,n){return n?[...e.filter(r=>r.attempts>0&&r.successes===0).map(r=>`provenance_resolver_zero_success:${r.harness}:${r.dimension}:${r.resolver}:${String(r.attempts)}`),...t.map(r=>`provenance_value_domain_invalid:${r.harness}:${r.dimension}:${r.kind}:${String(r.count)}`)]:[]}async function lE(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:oc,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},r=new Map,i=new Map,o=0,s=0,a=!1,c=await cc(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let f=await Mp(e,u,Math.max(0,oc-s));if(f===null){n.unreadable_sources+=1;continue}s+=f.bytesRead;let p=$p(f.content,r,i,t,o,n);if(o=p.eventsRead,p.truncated){a=!0;break}if(!f.complete){a=!0;break}}let d=[...r.values()].sort((u,f)=>u.harness.localeCompare(f.harness)||u.dimension.localeCompare(f.dimension)||u.resolver.localeCompare(f.resolver)),l=[...i.values()].sort((u,f)=>u.harness.localeCompare(f.harness)||u.dimension.localeCompare(f.dimension)||u.kind.localeCompare(f.kind));return n.bytes_read=s,n.events_read=o,n.truncated=a,n.complete=!a&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:d,sample:n,invalid_values:l,warnings:Pp(d,l,n.complete),events_read:o,truncated:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5134bd12-d808-588f-af5d-fc71e5153e95")}catch{}})();var jp=Object.freeze({pm_item_scalar_missing:!0});function st(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function T(e){return e===void 0?jp:e}function Re(e){return re(I(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function pi(e,t){let n=Ge(e);if(n)throw new _(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,o]of e.split(/\r?\n/).entries()){let s=o.trim();if(s)try{let a=JSON.parse(s);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new _(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}}return r}function we(e){return I({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function Up(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&we(e[r])===we(t[r]);)r+=1;return r}function vE(e,t,n){let r=pi(e,"base"),i=pi(t,"ours"),o=pi(n,"theirs"),s=[r,i,o].map(p=>p.filter(m=>m.op==="create"));if(s[0].length===0&&s.slice(1).every(p=>p.length>0)||s.some(p=>p.length>1)||new Set(s.flat().map(we)).size>1)throw new _("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict"});let a=Up(i,o);if(a===i.length&&a===o.length)return{merged:xe(i),strategy:"identical",common_entries:a,entries_from_ours:0,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(a===o.length)return{merged:xe(i),strategy:"fast_forward_ours",common_entries:a,entries_from_ours:i.length-a,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(a===i.length)return{merged:xe(o),strategy:"fast_forward_theirs",common_entries:a,entries_from_ours:0,entries_from_theirs:o.length-a,entries_total:o.length,reanchored:!1};let c=i.slice(a),d=new Set(c.map(we)),l=o.slice(a).filter(p=>!d.has(we(p))),u=[...c,...l].sort((p,m)=>{let h=C(p.ts,m.ts);if(h!==0)return h;let y=d.has(we(p)),v=d.has(we(m));return y!==v?Number(v)-Number(y):we(p).localeCompare(we(m))}),f=an([...i.slice(0,a),...u],void 0,{continuousHashSurface:!0});if(f.skippedOps>0)throw new _(`History union cannot preserve ${f.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,g.GENERIC_FAILURE);return{merged:xe(f.entries),strategy:"union_reanchor",common_entries:a,entries_from_ours:c.length,entries_from_theirs:l.length,entries_total:f.entries.length,reanchored:!0}}function hi(e,t){let n=Ge(e);if(n)throw new _(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,o]of e.split(/\r?\n/).entries()){let s=o.trim();if(!s)continue;let a;try{a=JSON.parse(s)}catch{throw new _(`Relationship merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new _(`Relationship merge input (${t}) line ${i+1} is not a relationship event (eventId + sequence required).`,g.GENERIC_FAILURE);r.push(a)}return r}function Hn(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
5
|
+
`)}
|
|
6
|
+
`}function Bp(e){return e.map((t,n)=>({...t,sequence:n+1}))}function wE(e,t,n){hi(e,"base");let r=hi(t,"ours"),i=hi(n,"theirs"),o=Math.min(r.length,i.length),s=0;for(;s<o&&r[s].eventId===i[s].eventId;)s+=1;if(s===r.length&&s===i.length)return{merged:Hn(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===i.length)return{merged:Hn(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:Hn(i),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:i.length-s,entries_total:i.length,reanchored:!1};let a=r.slice(s),c=new Set(a.map(f=>f.eventId)),d=i.slice(s).filter(f=>!c.has(f.eventId)),l=[...a,...d].sort((f,p)=>{if(f.timestamp!==void 0&&p.timestamp!==void 0){let y=C(f.timestamp,p.timestamp);if(y!==0)return y}else{if(f.timestamp===void 0&&p.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let m=c.has(f.eventId),h=c.has(p.eventId);return m!==h?Number(h)-Number(m):0}),u=Bp([...r.slice(0,s),...l]);return{merged:Hn(u),strategy:"union_reanchor",common_entries:s,entries_from_ours:a.length,entries_from_theirs:d.length,entries_total:u.length,reanchored:!0}}var Hp=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],Gp=["acceptance_criteria"],Kp=["updated_at"];function Fe(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:I(e)===I(t)}function lc(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(l=>I(l))),o=r(t),s=new Set(o.map(l=>I(l))),a=r(n),c=new Set(a.map(l=>I(l))),d=o.filter(l=>{let u=I(l);return!i.has(u)||c.has(u)});for(let l of a){let u=I(l);!s.has(u)&&!i.has(u)&&d.push(l)}return d}function Ct(e){if(typeof e!="object"||e===null||Array.isArray(e))return I(e);let{provenance:t,...n}=e;return I(n)}function zp(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function Vp(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(Ct)),o=r(t),s=new Set(o.map(Ct)),a=r(n),c=new Set(a.map(Ct)),d=o.filter(l=>{let u=Ct(l);return!i.has(u)||c.has(u)});for(let l of a){let u=Ct(l);!s.has(u)&&!i.has(u)&&d.push(zp(l))}return d}function qp(e,t){return C(String(e),String(t))>=0?e:t}function uc(e,t,n,r){return Fe(t,n)?{value:t,from_theirs:!1,conflict:!1}:Fe(e,t)?{value:n,from_theirs:!0,conflict:!1}:Fe(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function fc(e,t,n,r,i,o,s){let a=uc(e,t,n,r);if(!a.conflict)return{...a,conflict:!1};if(i==="preferred_side")return{...a,resolution_basis:"requested_preference",retained_side:a.from_theirs?"theirs":"ours"};let c=C(o,s);if(i==="latest_document_update"&&c!==0){let l=c<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"document_updated_at",retained_side:l?"theirs":"ours"}}let d=I(T(n)).localeCompare(I(T(t)))<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:d?"theirs":"ours"}}function gi(e){return{...e.metadata}}function _i(e,t,n){try{let r=Ro(So(e,n),n),i=Object.entries(r.metadata).find(([,o])=>st(o))?.[0];if(i!==void 0)throw new TypeError(`metadata field ${i} uses the reserved missing-scalar evidence marker`);return r}catch(r){throw new _(`Item merge input (${t}) is not a readable item document: ${String(r)}`,g.GENERIC_FAILURE)}}function Wp(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?Vp(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?lc(un(e.baseValue),un(e.oursValue),un(e.theirsValue)).join("; "):lc(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,Fe(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function Yp(e){let t=fc(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:T(e.baseValue),ours:T(e.oursValue),theirs:T(e.theirsValue),retained:T(t.value),discarded:T(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function Xp(e,t,n,r,i,o,s){let a=new Set([...Hp,...Gp]),c=new Set(Kp),d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,f)=>u.localeCompare(f)),l={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of d){let f=e[u],p=t[u],m=n[u];if(!Wp({field:u,baseValue:f,oursValue:p,theirsValue:m,unionFieldSet:a,accumulator:l})){if(c.has(u)){l.merged[u]=qp(p,m);continue}Yp({field:u,baseValue:f,oursValue:p,theirsValue:m,preferred:r,conflictResolution:i,oursUpdatedAt:o,theirsUpdatedAt:s,accumulator:l})}}return l}function kE(e,t,n,r={}){let i=r.preferred??"ours",o=r.conflictResolution??"preferred_side",s=_i(t,"ours",r),a=_i(n,"theirs",r);if(e.trim().length===0)throw new _("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict",item_id:s.metadata.id});let c=_i(e,"base",r);if(c.metadata.id!==s.metadata.id||c.metadata.id!==a.metadata.id)throw new _("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",g.CONFLICT,{code:"item_identity_conflict",item_id:c.metadata.id});let d=gi(c),l=gi(s),u=gi(a),{merged:f,conflictFields:p,fieldsFromTheirs:m,unionFields:h,conflictDecisions:y}=Xp(d,l,u,i,o,s.metadata.updated_at,a.metadata.updated_at),v=fc(c.body,s.body,a.body,i,o,s.metadata.updated_at,a.metadata.updated_at);return v.conflict?(p.push("body"),y.push({field:"body",base:T(c.body),ours:T(s.body),theirs:T(a.body),retained:T(v.value),discarded:T(v.from_theirs?s.body:a.body),retained_side:v.retained_side,resolution_basis:v.resolution_basis})):v.from_theirs&&m.push("body"),{merged:To({metadata:f,body:v.value},r),conflict_fields:p,fields_from_theirs:m,union_fields:h,conflict_decisions:y,requested_preference:i,requested_preference_applied:o==="preferred_side",conflict_resolution:o}}function yi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bi(e,t){let n=Ge(e);if(n)throw new _(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,g.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new _(`JSON merge input (${t}) is not valid JSON.`,g.GENERIC_FAILURE)}}function Jp(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=d=>{let l=new Map;for(let u of d){let f=I(u);l.set(f,(l.get(f)??0)+1)}return l},i=r(e),o=r(t),s=r(n);for(let[d,l]of i)if((o.get(d)??0)<l||(s.get(d)??0)<l)return null;let a=new Map(o),c=[];for(let d of n){let l=I(d),u=a.get(l)??0;u>0?a.set(l,u-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function Qp(e,t,n,r,i,o,s){if(!yi(t)||!yi(n))return null;let a=yi(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,u)=>l.localeCompare(u));for(let l of d){let u=i.length>0?`${i}.${l}`:l,f=Zp(a,t,n,l,r,u,o,s);f!==void 0&&(c[l]=f)}return c}function mc(e,t,n,r,i,o,s){if(Fe(t,n))return t;let a=Jp(e,t,n);if(a!==null)return a.acceptedTheirs&&s.push(i),a.merged;let c=Qp(e,t,n,r,i,o,s);if(c!==null)return c;let d=uc(e,t,n,r);return d.conflict?o.push(i):d.from_theirs&&s.push(i),d.value}function Zp(e,t,n,r,i,o,s,a){let c=Object.prototype.hasOwnProperty.call(t,r),d=Object.prototype.hasOwnProperty.call(n,r),l=Object.prototype.hasOwnProperty.call(e,r);if(c&&d)return mc(e[r],t[r],n[r],i,o,s,a);if(c){if(l&&Fe(e[r],t[r])){a.push(o);return}return l?(s.push(o),i==="theirs"?void 0:t[r]):t[r]}if(!(l&&Fe(e[r],n[r])))return l?(s.push(o),i==="theirs"?n[r]:void 0):(a.push(o),n[r])}function EE(e,t,n,r={}){let i=r.preferred??"ours",o=bi(e,"base"),s=bi(t,"ours"),a=bi(n,"theirs"),c=[],d=[],l=mc(o,s,a,i,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
|
|
7
|
+
`,conflict_paths:c,paths_from_theirs:d,preferred:i}}import{execFile as Sh}from"node:child_process";import{randomUUID as Th}from"node:crypto";import{readdir as Rh,stat as xh}from"node:fs/promises";import G from"node:path";import{promisify as Dh}from"node:util";import{constants as pc}from"node:fs";import{lstat as eh,open as th}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b063a672-991a-5251-a2f3-6a1c7bcafd2f")}catch{}})();var nh={lstat:eh,open:th};function rh(e){return e.O_NOFOLLOW??0}async function St(e,t,n=nh){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,pc.O_RDONLY|rh(pc));try{let o=await i.stat();if(!o.isFile()||o.size>t)return null;let s=Buffer.alloc(o.size),a=0;for(;a<s.length;){let{bytesRead:c}=await i.read(s,a,s.length-a,a);if(c===0)break;a+=c}return(await i.stat()).size===o.size&&a===o.size?s.toString("utf8",0,a):null}finally{await i.close()}}import Gn from"node:path";import{execFile as ih}from"node:child_process";import{createHash as oh}from"node:crypto";import{readdir as sh}from"node:fs/promises";import ah from"node:path";import{promisify as ch}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ff7b12a2-17f8-5989-b153-3b8e5f9e628b")}catch{}})();var Me=ch(ih),vi=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function FE(e,t){let n=t.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n;for(let i of["rebase-merge","rebase-apply"])try{let{stdout:o}=await Me("git",["rev-parse","--path-format=absolute","--git-path",`${i}/orig-head`],{cwd:e,timeout:1e4}),s=(await St(o.trim(),128))?.trim();if(s===void 0||!vi.test(s))continue;let{stdout:a}=await Me("git",["rev-parse","--verify",`${s}:${r}`],{cwd:e,timeout:1e4}),c=a.trim();return{kind:"rebase",original_head:s,original_blob:c}}catch{}}function hc(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&t.kind==="rebase"&&typeof t.original_head=="string"&&vi.test(t.original_head)&&typeof t.original_blob=="string"&&vi.test(t.original_blob)}async function gc(e,t,n,r){if(r!==void 0&&oh(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex")!==n.original_blob)return!1;try{let{stdout:i}=await Me("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),o=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await sh(i.trim())).some(d=>o.has(d)))return!1;let{stdout:s}=await Me("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(s.trim()!==n.original_head)return!1;let{stdout:a}=await Me("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(a.trim()!==n.original_blob)return!1;let{stdout:c}=await Me("git",["hash-object","--",ah.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await Me("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();var dh=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,lh=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,zn=2048,uh=64,fh=1e5,mh=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function Vn(e){return dh.test(e)}var ph=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),qn="bounded_non_sensitive_scalars_v1",hh=new Set(["open","in_progress","blocked","closed","canceled"]),gh=new Set(["risk","confidence","severity"]),_h=new Set(["low","medium","high","critical"]),yc=new Map([["priority",new Set([0,1,2,3,4].map(I))],["status",new Set([...hh].map(I))],...[...gh].map(e=>[e,new Set([..._h].map(I))])]);function he(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bc(e,t){return Object.keys(e).every(n=>t.has(n))}function Kn(e){return Array.isArray(e)&&e.length<=zn&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Tt(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>fh||r.depth>uh)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(he(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function vc(e){if(!he(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[bc(e,ph),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),Tt(e.base),Tt(e.ours),Tt(e.theirs),Tt(e.retained),Tt(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function yh(e){if(!he(e))return!1;let t=Object.entries(e);return t.length<=zn&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function bh(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||Gn.posix.isAbsolute(e))return!1;let n=Gn.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&Gn.posix.basename(n,Gn.posix.extname(n))===t}function vh(e){return!Kn(e.fields_from_theirs)||!Kn(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>zn||!e.decisions.every(vc)?!1:e.merged_field_hashes===void 0||yh(e.merged_field_hashes)}function wh(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===qn)&&i.includes(e.evidence_source)}function kh(e){return typeof e.created_at=="string"&&vr(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&vr(e.reconciled_at))}function _c(e,t){if(!he(t)||Wn(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(i=>i==="pm_value_hash"||i==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||yc.get(e)?.has(I(r))===!0)&&Re(r)===t.pm_value_hash}function Eh(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&_c(r.field,r.retained)&&_c(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(he(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(he(i.discarded)&&Object.hasOwn(i.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===qn)}function Ih(e){return e.operation!==void 0&&!hc(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function Ch(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!bc(e,mh)?"required_fields":typeof e.id!="string"||!Vn(e.id)?"receipt_id":typeof e.item_id!="string"||!lh.test(e.item_id)?"item_id":bh(e.item_path,e.item_id)?null:"item_path"}function wi(e,t){if(!he(e))return"required_fields";let n=Ch(e);return n!==null?n:Ih(e)?vh(e)?wh(e)?kh(e)?t==="durable"&&!Eh(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function ki(e){if(!he(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(r=>!he(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:T(void 0),ours:T(void 0),theirs:T(void 0),...r})}}function wc(e){if(!he(e))return;if(!Kn(e.fields_from_theirs))return"fields_from_theirs";if(!Kn(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>zn)return"decisions";let t=e.decisions.findIndex(n=>!vc(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function Ei(e,t){return wi(e,t)===null}function Wn(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function Ii(e,t){let n=st(t),r=Re(n?void 0:t);return!n&&(t===null||yc.get(e)?.has(I(t))===!0)?{pm_value_hash:r,pm_value:t}:{pm_value_hash:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="03b0537b-0444-5351-b1ff-250d8bbfbd95")}catch{}})();var Ah=Dh(Sh),Ic=16*1024*1024,Yn=100;async function Ci(e){try{let{stdout:t}=await Ah("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Cc(e,t){let n=G.dirname(G.resolve(e,t));for(let r=0;r<12;r+=1){if(await Ht(G.join(n,"settings.json")))return n;let i=G.dirname(n);if(i===n)break;n=i}return null}function Si(e){return G.join(e,"merge-receipts")}function at(e){return`${e}.json`}async function kc(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await St(e.receiptPath,Ic)}catch(o){if(Pe(o))return null;throw o}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=ki(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!Ei(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||G.basename(e.receiptPath)!==at(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprints:Ti(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
|
|
8
|
+
`}}function Rt(e,t=!1){return re(I({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:re(I(T(n.retained))),discarded_hash:re(I(T(n.discarded)))})):Ri(e).decisions}))}function Ti(e){let t=[Rt(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(Rt(e,!0)),t}function Oh(e,t){if(e.state==="reconciled"&&t.state==="reconciled"&&e.settlement===t.settlement)return e;let{reconciled_at:n,settlement:r,...i}=e;return{...i,state:"pending"}}function Ri(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Wn(t.retained)??Re(st(t.retained)?void 0:t.retained),discarded_hash:Wn(t.discarded)??Re(st(t.discarded)?void 0:t.discarded)}))}}async function eI(e){let t=await Ci(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,i=G.basename(r,G.extname(r)),o={version:1,id:Th(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(a=>({...a,base:T(a.base),ours:T(a.ours),theirs:T(a.theirs),retained:T(a.retained),discarded:T(a.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:x(),value_availability:"clone_local"};await pr(t),await W(G.join(t,at(o.id)),`${JSON.stringify(o,null,2)}
|
|
9
|
+
`);let s=await Cc(e.cwd,o.item_path);if(s!==null){let a=Si(s),c=o.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:Ii(u.field,u.retained),discarded:Ii(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),d=c.reduce((u,f)=>u+(Object.hasOwn(f.retained,"pm_value")?1:0)+(Object.hasOwn(f.discarded,"pm_value")?1:0),0),l={...o,decisions:c,value_availability:d===0?"hash_only":d===c.length*2?"bounded_inline":"mixed",value_policy:qn};await pr(a),await W(G.join(a,at(o.id)),`${JSON.stringify(l,null,2)}
|
|
10
|
+
`)}return o}async function Ec(e,t){let n;try{n=await Rh(e)}catch(a){let c=await Lh(e,a);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,o=[],s=(a,c)=>{if(i+=1,o.length>=Yn)return;let d=a.slice(0,-5);o.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...Vn(d)?{receipt_id:d}:{candidate_name_hash:re(a)}})};for(let a of n.sort((c,d)=>c.localeCompare(d))){if(!a.endsWith(".json"))continue;let c=await Fh(e,a,t);c.receipt!==void 0?r.push(c.receipt):s(a,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:o,invalid_evidence_truncated:i>o.length}}async function Lh(e,t,n=xh){if(!ae(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!ae(i))return!1;let o=G.dirname(r);if(o===r)return!0;r=o}}async function Fh(e,t,n){let r;try{r=await St(G.join(e,t),Ic)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=ki(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let o=wi(i,n);if(o!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(o)?"identity_invalid":"schema_invalid",validation_error:o,...o==="collections"?{validation_path:wc(i)}:{}};let s=i;if(t!==at(s.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:a,evidence_source:c,...d}=s;return{receipt:{...d,requested_preference:s.requested_preference??a??"ours",requested_preference_applied:s.requested_preference_applied??(s.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:s.conflict_resolution??"preferred_side",evidence_source:n}}}async function Xn(e,t={}){let n=await Ci(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Ec(n,"clone_local"),i=t.pmRoot??G.join(e,".agents","pm"),o=await Ec(Si(i),"durable"),s=new Map(o.receipts.map(d=>[d.id,d])),a=0,c=[];for(let d of r.receipts){let l=s.get(d.id);if(l!==void 0&&!(l.value_policy===void 0?Ti(d):[Rt(d)]).includes(Rt(l))){s.delete(d.id),a+=1,r.invalid_evidence.length+o.invalid_evidence.length+c.length<Yn&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:d.id});continue}s.set(d.id,l===void 0?d:Oh(d,l))}return{receipts:[...s.values()].filter(d=>(t.includeReconciled||d.state==="pending")&&(t.includeLossless!==!1||d.decisions.length>0)).sort((d,l)=>d.created_at.localeCompare(l.created_at)),invalid_evidence_count:r.invalid_evidence_count+o.invalid_evidence_count+a,invalid_evidence:[...r.invalid_evidence,...o.invalid_evidence,...c].slice(0,Yn),invalid_evidence_truncated:r.invalid_evidence_truncated||o.invalid_evidence_truncated||r.invalid_evidence_count+o.invalid_evidence_count+a>Yn,clone_local_evidence_resolved:n!==null}}async function Mh(e,t={}){return(await Xn(e,t)).receipts}function tI(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function nI(e,t,n={}){let r=await Ci(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!Ei(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let o=x(),s=G.join(r,at(t.id)),a=await Cc(e,t.item_path),c=a===null?null:G.join(Si(a),at(t.id)),d=(await Promise.all([kc({receiptPath:s,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:o,settlement:n.settlement}),...c===null?[]:[kc({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:o,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[Rt(t)]:Ti(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await W(l.path,l.content)}async function rI(e){let t=await Mh(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:x()}}async function iI(e){let t=await Xn(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:x()}}import Nh from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eeaf2318-5964-5d98-ad90-9faa7fc69975")}catch{}})();function xi(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Zo(e.settings);if(n.ownership_enforcement==="strict")throw new _(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,g.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function $h(e){let t=await ge(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new _(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);let n=await de(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?e.readItem?await e.readItem(n):await Se(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new _(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function Jn(e){let t=e.writeHistoryRaw??W;try{await t(e.historyPath,e.nextHistoryRaw),await Er(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await Nh.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await Er(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function Sc(e){let t=[...xi({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await He(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let r=await $h({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(r),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();async function Tc(e){let{subject:t,settings:n,operation:r,options:i}=e,o=await Mo(t.historyPath,t.id);if(o.raw===null)throw new _(`No history stream exists for ${t.id}.`,g.NOT_FOUND);if(o.entries.length===0)throw new _(`No history entries exist for ${t.id}; nothing to ${r.slice(8)}.`,g.USAGE);let s=t.located?await Se(t.located,{schema:n.schema}):null,a=be(i.author,n.author_default),c=await e.transform({raw:o.raw,entries:o.entries,verification:Cr(o.entries),loadedItem:s,author:a}),d=Cr(c.rewrittenEntries);if(!d.ok)throw new _(`${r} produced an invalid rewritten chain (${d.errors.join(", ")}).`,g.GENERIC_FAILURE);let l=c.changed&&!i.dryRun?await Sc({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:o.raw,currentItemRawBeforeLock:s?.raw??null,operation:r,author:a,force:i.force,itemDocument:s?.document??null,applyRewrite:async u=>{await c.beforeWrite?.(),c.applyRewrite?await c.applyRewrite(u):await Jn({historyPath:t.historyPath,nextHistoryRaw:xe(c.rewrittenEntries),historyRawUnderLock:u.historyRawUnderLock})},applyPostRewrite:c.afterWrite??(async()=>zt({path:t.historyPath,scope:"project",op:`${r.replace("-","_")}:history`}))}):[];return c.report({verification:d,warnings:l})}import{isUtf8 as Ph}from"node:buffer";import{readFile as jh}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function Uh(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new _("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new _("History salvage would conceal interior corruption or a malformed record.",g.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(r=>typeof r=="string"))throw new _("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return n}function Bh(e){if(Ge(e))throw new _("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,r,i=0;for(let[s,a]of e.split(`
|
|
11
|
+
`).entries()){if(!a.trim()){n+=a.length+1;continue}let c=Uh(a);if(c===null){r===void 0&&(r=n,i=s+1),n+=a.length+1;continue}if(r!==void 0)throw new _("History salvage would discard a record or conceal interior corruption.",g.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.push(c),n+=a.length+1}let o=Ce(t);if(!o.ok||o.item_hash_version===void 0)throw new _("History salvage requires a nonempty verified prefix.",g.CONFLICT,{code:"history_salvage_refused",verification_errors:o.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:o.item_hash_version,prefix:r===void 0?e:e.slice(0,r),receipt:r===void 0?null:{first_invalid_line:i,discarded_bytes:Buffer.byteLength(e.slice(r)),discarded_sha256:re(e.slice(r)),retained_entries:t.length}}}async function Hh(e,t,n){if(!e.located)return{itemRaw:null,document:n};let r=await ss(e.located,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n}}async function Rc(e){let t;try{t=await jh(e)}catch(n){if(ae(n))return null;throw n}if(!Ph(t))throw new _("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",g.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function xc(e){let{subject:t,settings:n,options:r,author:i}=e;if([r.normalizeProvenance,r.auditOperation,r.auditContext,r.auditContextById,r.forceAuditEntry,r.mergeReceiptProof,r.mergeReceiptProofById].some(Boolean))throw new _("Tail salvage cannot be combined with other repair modes.",g.USAGE);let o=await Rc(t.historyPath);if(o===null)throw new _(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await Vt({path:t.historyPath,scope:"project"});let s=Bh(o),a=cn(s.entries,s.entries.length-1),c=Vo(a);if(typeof a.metadata.id=="string"&&a.metadata.id!==t.id)throw new _("History belongs to another item; salvage refused.",g.CONFLICT,{code:"history_salvage_refused"});let d=await Hh(t,n,c),l=xi({itemDocument:d.document,subjectId:t.id,author:i,force:r.force,settings:n}),u=s.itemHashVersion,f=r.dryRun===!0,p=s.receipt!==null;if(p&&!f){let m=await He(e.pmRoot,t.id,n.locks.ttl_seconds,i,!!r.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await Rc(t.historyPath),y=await de(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),v=y?await ge(y.itemPath):null;if(h!==o||v!==d.itemRaw)throw new _("History or item changed while waiting for salvage lock; retry.",g.CONFLICT);let b=on({...zo({hashAlgorithm:ye(s.entries.at(-1).hash_algorithm),nowIso:x(),author:i,op:"history_salvage",before:c,after:c,message:r.message,context:{history_salvage:s.receipt}}),before_hash:s.entries.at(-1).after_hash,after_hash:s.entries.at(-1).after_hash,item_hash_version:u});await Jn({historyPath:t.historyPath,historyRawUnderLock:o,nextHistoryRaw:`${s.prefix}${JSON.stringify(b)}
|
|
12
|
+
`}),l.push(...await zt({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await m()}}return{id:t.id,dry_run:f,changed:p,history:{path:t.historyPath,entries_scanned:s.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:p&&!f,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...s.receipt?{salvage:s.receipt}:{},warnings:l,generated_at:x()}}import{realpath as Hc}from"node:fs/promises";import Ai from"node:path";import Gc from"fast-json-patch";import xt from"node:fs/promises";import{createHash as Gh}from"node:crypto";import Ac from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="97537e2a-b8cb-559e-82bc-3c98b0c51db1")}catch{}})();var Di=new Set([void 0,...Co]),Oc=11,Kh="history-drift-cache.json";function Lc(e){return Ac.join(e,"runtime",Kh)}async function zh(e){try{let t=await xt.readFile(Lc(e),"utf8"),n=JSON.parse(t);return n.version!==Oc||n.history_item_hash_version!==rn||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!Di.has(r.hash_algorithm)||!ze.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&ze.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}function Fc(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function Mc(e){let t=[...new Set([...e.missingStreams,...e.unreadableStreams,...e.hashMismatches,...e.chainMismatches,...e.versionSkews,...e.workspaceStateMismatches.length>0||e.workspaceStateMissing.length>0||e.workspaceStateUnreadable.length>0?[Z]:[]])].sort((n,r)=>n.localeCompare(r));return{...e,driftedItems:t}}async function Vh(e,t,n,r,i){let o=Jo(e),s;try{s=await xt.stat(o)}catch(d){return ae(d)||i.unreadableStreams.push(Z),!1}let a=i.missingStreams.length,c=await Nc({itemId:Z,historyPath:o,stat:s,cached:t[Z],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(Z),c.verification.chainOk||i.chainMismatches.push(Z),n[Z]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion,hash_algorithm:c.verification.hashAlgorithm},c.cacheDirty):(i.missingStreams.splice(a),c.cacheDirty)}function qh(e){return!Di.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!ze.includes(e.item_hash_version)}async function Wh(e){let t=await xt.readFile(e,"utf8"),n=Gh("sha256").update(t).digest("hex");if(t.trim().length===0)return null;let r=[],i=null;for(let f of t.split(/\r?\n/)){let p=f.trim();if(p.length===0)continue;let m=JSON.parse(p);if(typeof m.after_hash!="string"||m.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(m),i=m.after_hash}if(!i)return null;let o=Ce(r),s=r.some(qh),a=r[r.length-1],c=Di.has(a.hash_algorithm),d=a.item_hash_version,l=d!==void 0&&ze.includes(d),u=l?d:o.item_hash_version;return{latestAfterHash:i,hashAlgorithm:c?ye(a.hash_algorithm):void 0,identityDiscontinuities:Ir(r),chainOk:o.ok,versionSkew:s,latestHashComparable:c&&u!==void 0&&(!s||l||d===void 0),contentHash:n,itemHashVersion:u??rn}}function Yh(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Dc(e,t,n){try{return await Wh(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function Xh(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function Nc(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Yh(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await Dc(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await Dc(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!Xh(n,e.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&ze.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function $c(e,t,n,r){let i,o;try{i=Ue(e,t.id),o=await xt.stat(i)}catch(d){return(ae(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await Nc({itemId:t.id,historyPath:i,stat:o,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!s.verification)return s.cacheDirty;s.verification.identityDiscontinuities.length>0&&(r.identityDiscontinuities??=[]).push(...s.verification.identityDiscontinuities.map(d=>({...d,item_id:t.id}))),s.verification.versionSkew&&r.versionSkews.push(t.id),s.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion,hash_algorithm:s.verification.hashAlgorithm};let{body:a,...c}=t;return s.verification.latestHashComparable&&(sn({metadata:c,body:a},s.verification.itemHashVersion,s.verification.hashAlgorithm).includes(s.verification.latestAfterHash)||r.hashMismatches.push(t.id)),s.cacheDirty}async function Jh(e,t){if(!(t.unreadableStreams.includes(Z)||t.chainMismatches.includes(Z)||t.versionSkews.includes(Z)))try{let n=await Qo(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(Z)}}async function JI(e,t){let n=Fc();return await $c(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),Mc(n)}async function Pc(e,t,n={}){let r=Fc(),i=(await zh(e))?.entries??{},o={},s=!1,a=n.cacheHitVerification!=="metadata",c={previousEntries:i,nextEntries:o,verifyCacheHitByContent:a};for(let l of t)await $c(e,l,c,r)&&(s=!0);let d=await Vh(e,i,o,a,r);if(s||=d,await Jh(e,r),s||Object.keys(i).length!==Object.keys(o).length){let l=Lc(e);try{await xt.mkdir(Ac.dirname(l),{recursive:!0}),await W(l,JSON.stringify({version:Oc,history_item_hash_version:rn,entries:o}))}catch{}}return Mc(r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5df05541-b114-52bd-9540-d741b2657edf")}catch{}})();function jc(e,t){return t==="body"?e.body:e.metadata[t]}function Oi(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(i=>{let o=t.findIndex((s,a)=>!r.has(a)&&Oi(i,s));return o<0?!1:(r.add(o),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,i])=>Object.hasOwn(n,r)&&Oi(i,n[r]))}function Uc(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let o=e[i],s=new Set;for(let c of Yo(o.patch))s.add(fn(c.path)),c.from&&s.add(fn(c.from));let a=[...n].filter(c=>s.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:i+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function Qh(e,t,n){let r=Gc.compare(t,n);if(r.length===0)return;let i=new Set;for(let m of r)i.add(fn(m.path));let o=new Set([...i].filter(m=>Oi(jc(t,m),jc(n,m)))),s=new Set([...i].filter(m=>!o.has(m))),a=Uc(e,s),c=Uc(e,o),d=[...i].sort((m,h)=>m.localeCompare(h)),l=[...s].sort((m,h)=>m.localeCompare(h)),u=[...o].sort((m,h)=>m.localeCompare(h)),f=[...new Set(a.map(m=>m.author))].sort((m,h)=>m.localeCompare(h)),p=[...new Set(c.map(m=>m.author))].sort((m,h)=>m.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:s.size,reverted_fields:l,discarded_events:a,discarded_authors:f,preserved_field_count:o.size,preserved_fields:u,preserved_events:c,preserved_authors:p,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function Zh(e){try{return await Hc(e)}catch{return null}}async function eg(e){if(await Zh(Ai.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let t=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(o=>o.field)])].sort(),n=e.receipt.merged_field_hashes;if(!n||t.length===0)return null;let r=Object.keys(n).sort();if(t.length!==r.length||t.some((o,s)=>o!==r[s]))return null;let i=e.currentItemReplay.metadata;return t.every(o=>{let s=o==="body"?e.currentItemReplay.body:i[o];return[Re(s),re(I(T(s)))].includes(n[o])})?{receipt:e.receipt,declaredFields:t}:null}async function tg(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(s=>s.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Hc(e.itemPath),r=[];for(let s of t){let a=await eg({receipt:s,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let i=new Set(r.flatMap(({declaredFields:s})=>s)),o=e.reconciliation?.reconciled_fields;return r.length>0&&(o===void 0||o.length>0&&o.every(s=>i.has(s)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function Bc(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:o}=e,s=t.currentItemPath===null?null:Ai.relative(o,t.currentItemPath).split(Ai.sep).join("/");if(!n||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||s!==i.item_path||i.operation===void 0||!await gc(o,i.item_path,i.operation,t.currentItemRawBeforeLock))throw new _("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function ng(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(o=>o.item_id===e.subjectId).map(o=>o.id)??[]),n=(e.options.mergeReceiptProof?await Xn(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(o=>o.item_id===e.subjectId&&t.has(o.id))??[],r=e.options.mergeReceiptProof?await tg({proof:{...e.options.mergeReceiptProof,receipts:n},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(r&&!r.trusted&&e.options.force!==!0)throw new _(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${r.reason}).`,g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let i=r?.trusted?n.filter(o=>r.receipt_ids.includes(o.id)):[];return{mergeReceiptProof:r,effectiveAuditContext:i.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:i.map(Ri)}}:e.options.auditContext}}function rg(e,t,n){let r=e.located?.itemPath??null,i=t.loadedItem,o=t.entries;if(!i)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=Wo(i.document),a=o[o.length-1].after_hash;return{currentItemReplay:s,currentItemPath:r,matchedChainBefore:Ve(s,n,ye(o.at(-1)?.hash_algorithm)).includes(a),currentItemRawBeforeLock:i.raw,loadedItem:i}}function ig(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function og(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=ye(e.reanchorEntries.at(-1)?.hash_algorithm),i=Ve(e.finalReplay,e.itemHashVersion,r),o=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,s=i.indexOf(o),a=Ve(n,e.itemHashVersion,r),c={hash_algorithm:r,ts:x(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Gc.compare(e.finalReplay,e.currentItemReplay):[],before_hash:i[s],after_hash:a[s],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(on({...c,event_class:No(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function sg(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function ag(e,t,n){let{pmRoot:r,settings:i,typeRegistry:o}=await Rr(n.path),s=await hn(r,e,i,o.type_to_folder);return t.salvageTail===!0?xc({pmRoot:r,subject:s,settings:i,typeRegistry:o,options:t,author:be(t.author,i.author_default)}):Tc({pmRoot:r,subject:s,settings:i,typeRegistry:o,operation:"history-repair",options:t,transform:a=>dg({pmRoot:r,subject:s,options:t},a)})}function cg(e,t){let n=e.mergeAbandonmentProof!==void 0&&e.auditContext!==void 0&&t.some(r=>r.op==="merge_reconcile"&&I(r.context)===I(e.auditContext));return e.forceAuditEntry===!0&&!n}async function dg(e,t){let{pmRoot:n,subject:r,options:i}=e,o=t.entries,s=t.verification,a=Ce(o),c=i.normalizeProvenance?sc(o):{entries:o,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=Xo(c.entries),l=new Set(c.entries.map(N=>N.item_hash_version).filter(N=>N!==void 0)),u=an(c.entries,d),f=rg(r,t,d);await Bc(i.mergeAbandonmentProof,f,s.ok,u);let p=u.finalDocument,m=Ve(p,d),h=!1;if(f.currentItemReplay!==null){let N=Ve(f.currentItemReplay,d);h=!m.some((B,Y)=>B===N[Y])}let y=h&&f.currentItemReplay?Qh(u.entries,p,f.currentItemReplay):void 0,{mergeReceiptProof:v,effectiveAuditContext:b}=await ng({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:f,reconciliation:y}),w=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,cg(i,o),c.receipt.changed].some(Boolean),k=t.author,S=!!i.dryRun,P=ig({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:j,auditEntryAdded:M}=og({reanchorEntries:u.entries,changed:w,reconcileNeeded:h,currentItemReplay:f.currentItemReplay,finalReplay:p,author:k,message:P,auditOperation:i.auditOperation??"history_repair",auditContext:c.receipt.changed?{...b,provenance_normalization:c.receipt}:b,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),Ee=sg(w,u.skippedOps,y);return{changed:w,rewrittenEntries:j,beforeWrite:async()=>Bc(i.mergeAbandonmentProof,f,s.ok,u),report:({verification:N,warnings:B})=>({id:r.id,dry_run:S,changed:w,history:{path:r.historyPath,entries_scanned:o.length,chain_drift_before:!s.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:M,verify_ok:N.ok,verify_errors:N.errors,item_hash_version_before:a.item_hash_version??null,item_hash_version_after:d,version_disposition:l.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:f.currentItemPath!==null,path:f.currentItemPath,matched_chain_before:f.matchedChainBefore},provenance_normalization:{requested:i.normalizeProvenance===!0,...c.receipt},...y?{reconciliation:y}:{},...v?{merge_receipt_proof:v}:{},warnings:[...new Set([...Ee,...B])].sort((Y,X)=>Y.localeCompare(X)),generated_at:x()})}}function kC(e,t){if(t&&e!==void 0)throw new _("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",g.USAGE);if(!t&&e===void 0)throw new _("history-repair: provide an item <id> or pass --all to repair every drifted stream.",g.USAGE)}async function EC(e,t){if(e.salvageTail===!0)throw new _("Tail salvage requires one explicit item ID; --all is not supported.",g.USAGE);let{pmRoot:n,settings:r,typeRegistry:i}=await Rr(t.path),o=[],s=await ln(n,r.item_format,i.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await Pc(n,s),c=e.normalizeProvenance?await ac(n):[],d=[...new Set([...a.driftedItems,...c])].sort((p,m)=>p.localeCompare(m)),l=[],u=[],f={repaired:0,skipped_clean:0,failed:0};for(let p of d)try{let m=await ag(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=m.changed?"repaired":"skipped_clean";f[h]+=1,u.push(...m.warnings.map(y=>`${p}:${y}`)),l.push({id:p,outcome:h,entries_rehashed:m.history.entries_rehashed,entries_patch_repaired:m.history.entries_patch_repaired,reconciled_with_item:m.history.reconciled_with_item,...m.reconciliation?{reconciliation:m.reconciliation}:{},...m.merge_receipt_proof?{merge_receipt_proof:m.merge_receipt_proof}:{},warnings:m.warnings})}catch(m){f.failed+=1,l.push({id:p,outcome:"failed",error:m instanceof Error?m.message:String(m)})}return e.dryRun||await Uo(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:s.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:f,warnings:[...new Set([...o,...u])].sort((p,m)=>p.localeCompare(m)),generated_at:x()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1433b417-e41f-5963-a551-094132afd717")}catch{}})();var Kc=16;async function zc(e,t,n){let r=L(t,D()).type_to_folder,i=[],o=new Set,s=n;for(;s&&i.length<Kc;){let a=s.trim().toLowerCase();if(!a||o.has(a))break;o.add(a);let c=await de(e,s,t.id_prefix,t.item_format,r);if(!c)break;let d=await Se(c,{schema:t.schema});i.push(d.document.metadata.id),s=d.document.metadata.parent}return i}async function xC(e){await Ao({pmRoot:e.pmRoot,principal:e.principal,itemId:e.itemId,lineageIds:await zc(e.pmRoot,e.settings,e.itemId)})}async function DC(e){await Oo(e)}async function AC(e){await Lo({pmRoot:e.pmRoot,principal:e.principal,...e.itemId?{itemId:e.itemId,lineageIds:await zc(e.pmRoot,e.settings,e.itemId)}:{}})}var OC={lineage_depth:Kc,active_items:64,evidence_rows:32};function Vc(e){if(!e)return;let t={};for(let n of e.active_item_ids)t[n]=1;e.focused_item_id&&(t[e.focused_item_id]=1);for(let n of e.evidence){let r=/^lineage:(.+)$/u.exec(n)?.[1];r&&t[r]===void 0&&(t[r]=.75)}return Object.keys(t).length>0?t:void 0}import{encode as lg}from"@toon-format/toon";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="809a4d75-4915-585d-9fc8-ad3e9ef15b1f")}catch{}})();var Li=["agenda","day","week","month"],Fi=["markdown","toon","json"],ug=["sun","mon","tue","wed","thu","fri","sat"],fg=365,mg=365,Yc=28,pg=1e3;function Mi(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new _(`${t} must be a non-negative integer`,g.USAGE);return n}function hg(e){if(!e)return new Set(["deadlines","reminders","events"]);let t=e.trim().toLowerCase();if(t==="all")return new Set(["deadlines","reminders","events"]);let n=t.split(/[|,]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new _("Calendar include filter must not be empty",g.USAGE);let r=new Set;for(let i of n){if(i==="deadlines"||i==="deadline"){r.add("deadlines");continue}if(i==="reminders"||i==="reminder"){r.add("reminders");continue}if(i==="events"||i==="event"||i==="scheduled"){r.add("events");continue}throw new _("Calendar include filter must be deadlines|reminders|events|scheduled|all",g.USAGE)}return r}function Xc(e,t){let n;for(let r of t){let i=ho(e,r,2);i!==null&&(n===void 0||i<n.distance)&&(n={choice:r,distance:i})}return n?.choice}function gg(e){if(!e)return"agenda";let t=e.trim().toLowerCase();if(!Li.includes(t)){let n=Xc(t,Li);throw new _(`Calendar view must be one of ${Li.join("|")}${n?`. Did you mean "${n}"?`:"."}`,g.USAGE)}return t}function _g(e){if(!e)return;let t=e.trim().toLowerCase();if(!Fi.includes(t)){let n=Xc(t,Fi);throw new _(`Calendar format must be one of ${Fi.join("|")}${n?`. Did you mean "${n}"?`:"."}`,g.USAGE)}return t}function jC(e,t){let n=_g(e.format);if(t.json&&n&&n!=="json")throw new _("Cannot combine --json with --format markdown|toon",g.USAGE);return t.json?"json":n??"markdown"}function yg(e,t){if(e===void 0)return;let n=Q(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new _(`Calendar status filter must be one of ${r.join("|")}`,g.USAGE)}return n}function bg(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!t)throw new _("Calendar assignee filter must be one of assigned|unassigned",g.USAGE);if(t!=="assigned"&&t!=="unassigned")throw new _(`Invalid calendar assignee filter "${e}". Allowed: assigned|unassigned`,g.USAGE);return t}function Qn(e){return new Date(e).toISOString().slice(0,10)}function Jc(e,t){if(!t||t==="UTC")return Qn(e);try{let n=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(e)),r=n.find(s=>s.type==="year")?.value,i=n.find(s=>s.type==="month")?.value,o=n.find(s=>s.type==="day")?.value;if(r&&i&&o)return`${r}-${i}-${o}`}catch{}return Qn(e)}function ji(e){let t=new Date(e);return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,0,0)).toISOString()}function ke(e,t){let n=new Date(e);return new Date(n.getTime()+t*24*60*60*1e3).toISOString()}function Qc(e){let t=new Date(ji(e)),n=t.getUTCDay(),r=n===0?-6:1-n;return ke(t.toISOString(),r)}function vg(e){let t=new Date(e);return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),1,0,0,0,0)).toISOString()}function wg(e){let t=new Date(e);return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+1,1,0,0,0,0)).toISOString()}function kg(e,t){return C(e,t)>=0?e:t}function qc(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function Wc(e,t){e.set(t,(e.get(t)??0)+1)}function Eg(e){if(!e)return null;let t=[`freq=${e.freq}`];if(e.interval!==void 0&&t.push(`interval=${e.interval}`),e.count!==void 0&&t.push(`count=${e.count}`),e.until&&t.push(`until=${e.until}`),e.by_weekday&&e.by_weekday.length>0){let n=[...e.by_weekday].sort((r,i)=>je(r)-je(i));t.push(`by_weekday=${n.join("|")}`)}if(e.by_month_day&&e.by_month_day.length>0){let n=[...e.by_month_day].sort((r,i)=>r-i);t.push(`by_month_day=${n.join("|")}`)}if(e.exdates&&e.exdates.length>0){let n=[...e.exdates].sort((r,i)=>r.localeCompare(i));t.push(`exdates=${n.join("|")}`)}return t.join(",")}function Zc(e,t,n,r){let i=new Date(Date.UTC(e,t,n,r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds()));if(!(i.getUTCFullYear()!==e||i.getUTCMonth()!==t||i.getUTCDate()!==n))return i.toISOString()}function ed(e){return ug[new Date(e).getUTCDay()]}function Ig(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function Cg(e){let t=new Set;for(let n of e??[]){let r=Ig(n);r&&t.add(r)}return t}function Sg(e,t,n,r,i){let o=e??ke(n,-(r??mg)),s=t??ke(e??n,i??fg);return{start:o,end:C(s,o)>0?s:ke(o,1)}}function Tg(e,t,n,r){let i=t.by_weekday!==void 0?[...t.by_weekday]:[ed(e)],o=t.by_month_day!==void 0?[...t.by_month_day]:[new Date(e).getUTCDate()];return{startAt:e,startDate:new Date(e),window:n,maxOccurrences:r??pg,interval:t.interval??1,countLimit:t.count??Number.POSITIVE_INFINITY,until:t.until,excluded:Cg(t.exdates),weekdayFilter:t.by_weekday!==void 0?new Set(t.by_weekday):void 0,monthDayFilter:t.by_month_day!==void 0?new Set(t.by_month_day):void 0,sortedWeekdays:[...new Set(i)].sort((s,a)=>je(s)-je(a)),sortedMonthDays:[...new Set(o)].sort((s,a)=>s-a),occurrences:[],produced:0}}function Zn(e,t){return C(t,e.startAt)<0?"continue":e.until&&C(t,e.until)>0||C(t,e.window.end)>=0?"stop":e.excluded.has(t)?"continue":(e.produced+=1,C(t,e.window.start)>=0&&e.occurrences.push(t),e.produced>=e.countLimit||e.occurrences.length>=e.maxOccurrences?"stop":"continue")}function er(e,t){let n=ed(t),r=new Date(t).getUTCDate(),i=!e.weekdayFilter||e.weekdayFilter.has(n),o=!e.monthDayFilter||e.monthDayFilter.has(r);return i&&o}function Rg(e){let t=e.startAt;for(let n=0;n<e.maxOccurrences&&!(er(e,t)&&Zn(e,t)==="stop");n+=1)t=ke(t,e.interval);return e.occurrences}function xg(e,t,n){let r=je(n),i=ke(t,r),o=new Date(i);return new Date(Date.UTC(o.getUTCFullYear(),o.getUTCMonth(),o.getUTCDate(),e.startDate.getUTCHours(),e.startDate.getUTCMinutes(),e.startDate.getUTCSeconds(),e.startDate.getUTCMilliseconds())).toISOString()}function Dg(e){let t=Qc(e.startAt);for(let n=0;n<e.maxOccurrences;n+=1){let r=ke(t,n*e.interval*7);for(let i of e.sortedWeekdays){let o=xg(e,r,i);if(er(e,o)&&Zn(e,o)==="stop")return e.occurrences}}return e.occurrences}function Ag(e){let t=e.startDate.getUTCFullYear(),n=e.startDate.getUTCMonth();for(let r=0;r<e.maxOccurrences;r+=1){let i=new Date(Date.UTC(t,n+r*e.interval,1,0,0,0,0));for(let o of e.sortedMonthDays){let s=Zc(i.getUTCFullYear(),i.getUTCMonth(),o,e.startDate);if(!(!s||!er(e,s))&&Zn(e,s)==="stop")return e.occurrences}}return e.occurrences}function Og(e){let t=e.startDate.getUTCFullYear(),n=e.startDate.getUTCMonth();for(let r=0;r<e.maxOccurrences;r+=1){let i=t+r*e.interval;for(let o of e.sortedMonthDays){let s=Zc(i,n,o,e.startDate);if(!(!s||!er(e,s))&&Zn(e,s)==="stop")return e.occurrences}}return e.occurrences}function Lg(e,t,n,r){let i=Tg(e,t,n,r);return t.freq==="daily"?Rg(i):t.freq==="weekly"?Dg(i):t.freq==="monthly"?Ag(i):Og(i)}function td(e){return[...e].sort((t,n)=>{let r=C(t.at,n.at);if(r!==0)return r;let i=t.item_priority-n.item_priority;if(i!==0)return i;let o=t.item_id.localeCompare(n.item_id);if(o!==0)return o;let s=t.kind.localeCompare(n.kind);if(s!==0)return s;let a=String(t.event_title).localeCompare(String(n.event_title));return a!==0?a:String(t.reminder_text).localeCompare(String(n.reminder_text))})}function Ui(e){return{item_id:e.id,item_title:e.title,item_type:e.type,item_status:e.status,item_priority:e.priority,item_assignee:e.assignee??null,item_deadline:e.deadline??null,item_tags:e.tags}}function Fg(e){return e.deadline?{at:e.deadline,date:Qn(e.deadline),kind:"deadline",reminder_text:null,event_title:null,event_end:null,event_location:null,event_all_day:null,event_timezone:null,event_recurring:null,event_recurrence_rule:null,...Ui(e),item_deadline:e.deadline}:null}function Mg(e){return(e.reminders??[]).map(t=>({at:t.at,date:Qn(t.at),kind:"reminder",reminder_text:t.text,event_title:null,event_end:null,event_location:null,event_all_day:null,event_timezone:null,event_recurring:null,event_recurrence_rule:null,...Ui(e)}))}function Ng(e,t){if(!t)return null;let n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function $g(e,t,n){return t.recurrence&&n!==null?new Date(new Date(e).getTime()+n).toISOString():t.end_at??null}function Pg(e,t,n,r){let i=Eg(t.recurrence),o=Ng(t.start_at,t.end_at);return(t.recurrence?Lg(t.start_at,t.recurrence,n,r):[t.start_at]).map(s=>({at:s,date:t.all_day===!0?s.slice(0,10):Jc(s,t.timezone),kind:"event",reminder_text:t.description??null,event_title:t.title??e.title,event_end:$g(s,t,o),event_location:t.location??null,event_all_day:t.all_day??null,event_timezone:t.timezone??null,event_recurring:!!t.recurrence,event_recurrence_rule:i,...Ui(e)}))}function jg(e,t,n,r){let i=[];for(let o of e){let s=n.has("deadlines")?Fg(o):null;s&&i.push(s),n.has("reminders")&&i.push(...Mg(o));for(let a of n.has("events")?o.events??[]:[])i.push(...Pg(o,a,t,r))}return td(i)}function Ug(e,t,n,r,i){let o=ws(t.type,n),s=t.tag?.trim().toLowerCase(),a=kn(t.priority),c=yg(t.status,r),d=t.assignee?.trim(),l=bg(t.assigneeFilter),u=t.sprint?.trim(),f=t.release?.trim();if(d&&(d.toLowerCase()==="none"||d.toLowerCase()==="null"))throw new _('--assignee no longer accepts "none" or "null". Use --assignee-filter unassigned.',g.USAGE);if(d!==void 0&&l==="unassigned")throw new _("Cannot combine --assignee with --assignee-filter unassigned",g.USAGE);return e.filter(p=>Bg(p,{typeFilter:o,tagFilter:s,priorityFilter:a,statusFilter:c,assigneeFilter:d,assigneeModeFilter:l,sprintFilter:u,releaseFilter:f,runtimeFieldFilters:i}))}function Bg(e,t){return Hg(e,t)&&Gg(e,t)&&pn(e,t.runtimeFieldFilters)}function Hg(e,t){return!(t.typeFilter&&e.type!==t.typeFilter||t.tagFilter&&!e.tags.some(n=>n.trim().toLowerCase()===t.tagFilter)||t.priorityFilter!==void 0&&e.priority!==t.priorityFilter||t.statusFilter&&e.status!==t.statusFilter)}function Gg(e,t){return!(t.assigneeModeFilter==="assigned"&&!e.assignee||t.assigneeModeFilter==="unassigned"&&e.assignee||t.assigneeFilter!==void 0&&e.assignee!==t.assigneeFilter||t.sprintFilter!==void 0&&e.sprint!==t.sprintFilter||t.releaseFilter!==void 0&&e.release!==t.releaseFilter)}function Kg(e,t,n){return!(t&&C(e.at,t)<0||n&&C(e.at,n)>=0)}function Ni(e,t,n){return e.trim().toLowerCase()==="today"?ji(t):_e(e,new Date(t),n)}function zg(e,t,n){let r=t.date?Ni(t.date,n,"--date"):n,i=t.past===!0,o=t.fullPeriod===!0,s=t.from?Ni(t.from,n,"--from"):void 0,a=t.to?Ni(t.to,n,"--to"):void 0;if(s&&a&&C(s,a)>=0)throw new _("Calendar --from must be before --to",g.USAGE);if(e!=="agenda"&&(t.from!==void 0||t.to!==void 0))throw new _("--from and --to are only supported for --view agenda",g.USAGE);if(e==="agenda")return Vg(r,t,n,i,o,s,a);if(e==="day"){let d=ji(r);return $i(r,n,i,o,d,ke(d,1))}if(e==="week"){let d=Qc(r);return $i(r,n,i,o,d,ke(d,7))}let c=vg(r);return $i(r,n,i,o,c,wg(r))}function Vg(e,t,n,r,i,o,s){if(i)throw new _("--full-period is only supported for --view day|week|month. For agenda windows, use --from and --to.",g.USAGE);return{anchor:e,start:o??(t.date?e:r?void 0:n),end:s,fullPeriod:!1}}function $i(e,t,n,r,i,o){let s=n||r;return{anchor:e,start:s?i:kg(i,t),end:o,periodStart:i,periodEnd:o,fullPeriod:s}}function qg(e){let t=new Map;for(let n of e){let r=t.get(n.date)??[];r.push(n),t.set(n.date,r)}return[...t.entries()].sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({date:n,count:r.length,events:td(r)}))}function Wg(e){let t=new Set,n=new Map,r=new Map,i=0,o=0,s=0,a=0;for(let c of e)t.add(c.item_id),Wc(n,c.item_type),Wc(r,c.item_status),c.kind==="deadline"?i+=1:c.kind==="reminder"?o+=1:(s+=1,c.event_recurring===!0&&(a+=1));return{events:e.length,items:t.size,deadlines:i,reminders:o,scheduled:s,by_kind:{deadline:i,reminder:o,event:s},by_type:qc(n),by_status:qc(r),recurring_events:a}}function Yg(e){let t=e.start??"unbounded",n=e.end??"unbounded";return`${t} -> ${n}`}function nd(e,t){if(t&&t!=="UTC")try{let n=new Intl.DateTimeFormat("en-GB",{timeZone:t,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(new Date(e)),r=n.find(o=>o.type==="hour")?.value,i=n.find(o=>o.type==="minute")?.value;if(r&&i)return`${r}:${i}`}catch{}return`${new Date(e).toISOString().slice(11,16)}Z`}function Pi(e){let t=Object.entries(e);return t.length===0?"empty":t.map(([n,r])=>`${n}=${r}`).join(", ")}function Xg(e){return e.event_end?e.event_all_day===!0?e.event_end.slice(0,10):e.date===Jc(e.event_end,e.event_timezone)?nd(e.event_end,e.event_timezone):e.event_end:null}function Jg(e){let t=`${nd(e.at,e.event_timezone)} [${e.kind}] ${e.item_id} type=${e.item_type} p${e.item_priority} ${e.item_status} ${e.item_title}`;if(e.kind==="reminder"){let n=e.reminder_text??"";return`${t} \u2014 ${n} reminder=${JSON.stringify(n)}`}if(e.kind==="event"){let n=[],r=e.event_title??e.item_title;e.event_title!==null&&e.event_title!==e.item_title&&(n.push(r),n.push(`title=${JSON.stringify(r)}`)),e.event_recurring&&(n.push("(recurring)"),n.push("recurring=true"));let i=Xg(e);return i&&n.push(`end=${i}`),e.event_all_day!==null&&n.push(`all_day=${e.event_all_day?"true":"false"}`),e.event_timezone&&n.push(`timezone=${e.event_timezone}`),e.event_location&&(n.push(`@ ${e.event_location}`),n.push(`location=${JSON.stringify(e.event_location)}`)),e.event_recurrence_rule&&n.push(`recurrence=${e.event_recurrence_rule}`),e.reminder_text&&n.push(`description=${JSON.stringify(e.reminder_text)}`),`${t} \u2014 ${n.join(" ")}`}return t}function UC(e){let t=[];if(t.push(`# pm calendar (${e.view})`),t.push(""),t.push(`- now: ${e.now}`),t.push(`- window: ${Yg(e.range)}`),e.range.period_start&&e.range.period_end&&(t.push(`- period: ${e.range.period_start} -> ${e.range.period_end}`),t.push(`- period-mode: ${e.range.full_period?"full-period":"active-window"}`)),t.push(`- events: ${e.summary.events} (deadlines: ${e.summary.deadlines}, reminders: ${e.summary.reminders}, scheduled: ${e.summary.scheduled})`),t.push(`- items: ${e.summary.items}`),t.push(`- by-kind: ${Pi(e.summary.by_kind)}`),t.push(`- by-type: ${Pi(e.summary.by_type)}`),t.push(`- by-status: ${Pi(e.summary.by_status)}`),t.push(`- recurring-events: ${e.summary.recurring_events}`),t.push(""),e.events.length===0)return t.push("No calendar events matched the selected filters."),t.join(`
|
|
13
|
+
`);for(let n of e.days){t.push(`## ${n.date} (${n.count})`);for(let r of n.events)t.push(`- ${Jg(r)}`);t.push("")}if(e.warnings&&e.warnings.length>0){t.push("### warnings");for(let n of e.warnings)t.push(`- ${n}`);t.push("")}return Qg(t.join(`
|
|
14
|
+
`))}function BC(e){return lg(e)}function Qg(e){let t=e.length;for(;t>0&&e[t-1]===`
|
|
15
|
+
`;)t-=1;return e.slice(0,t)}function Zg(e){let t=x(),n=gg(e.view),r=zg(n,e,t),i=ie(e.limit),o=hg(e.include),s=Mi(e.recurrenceLookaheadDays,"Calendar recurrence lookahead days"),a=Mi(e.recurrenceLookbackDays,"Calendar recurrence lookback days"),c=Mi(e.occurrenceLimit,"Calendar occurrence limit");if(c!==void 0&&c<1)throw new _("Calendar occurrence limit must be >= 1",g.USAGE);let d=o.has("events")&&!o.has("deadlines")&&!o.has("reminders"),l=e.to!==void 0||s!==void 0||a!==void 0||c!==void 0,u=d&&!l;return{nowValue:t,view:n,rangeBounds:r,limit:i,includeSources:o,occurrenceLimit:c,recurrenceLookaheadDays:u?Yc:s,recurrenceLookbackWindowDays:u&&a===void 0?0:a,eventsOnlyCapApplied:u}}function e_(e,t){t&&e.push(`recurring_events_default_cap_applied:lookback=0d,lookahead=${Yc}d -- use --recurrence-lookback-days/--recurrence-lookahead-days or --to for wider range`)}function t_(e,t){return{type:e.type??null,tag:e.tag??null,priority:e.priority??null,status:e.status??null,assignee:e.assignee??null,assignee_filter:e.assigneeFilter??null,sprint:e.sprint??null,release:e.release??null,runtime_filters:t,limit:e.limit??null,include:e.include??null,full_period:e.fullPeriod===!0?"true":null,recurrence_lookahead_days:e.recurrenceLookaheadDays??null,recurrence_lookback_days:e.recurrenceLookbackDays??null,occurrence_limit:e.occurrenceLimit??null}}function n_(e,t){return{start:t.start??null,end:t.end??null,period_start:t.periodStart??null,period_end:t.periodEnd??null,full_period:t.fullPeriod,past:e.past===!0,from:e.from??null,to:e.to??null}}async function rd(e,t){let n=O(process.cwd(),t.path);await U(n);let r=Zg(e),i=await F(n),o=J(i.schema),s=tn(i.schema),a=mn(e,s,"calendar"),c=L(i,D()),d=[];e_(d,r.eventsOnlyCapApplied);let l=await le(n,i.item_format,c.type_to_folder,d,i.schema),u=Ug(l,e,c,o,a),f=Sg(r.rangeBounds.start,r.rangeBounds.end,r.nowValue,r.recurrenceLookbackWindowDays,r.recurrenceLookaheadDays),p=jg(u,f,r.includeSources,r.occurrenceLimit).filter(v=>Kg(v,r.rangeBounds.start,r.rangeBounds.end)),m=r.limit===void 0?p:p.slice(0,r.limit),h=qg(m),y=[...new Set(d)].sort((v,b)=>v.localeCompare(b));return{view:r.view,output_default:"markdown",now:r.nowValue,anchor:r.rangeBounds.anchor,range:n_(e,r.rangeBounds),filters:t_(e,a),summary:Wg(m),events:m,days:h,...y.length>0?{warnings:y}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2e0c4f91-ea56-5bec-b071-448eff719fec")}catch{}})();var tr={version:1,aliases:{}};function nr(e=[]){let t=new Set(Ke),n=r=>{/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(r)&&t.add(r)};for(let r of e){for(let i of Object.keys(r.provenance_environment_keys??{}))n(i);for(let i of Object.keys(r.provenance_resolvers??{}))n(i);for(let i of r.provenance_unavailable_dimensions??[])n(i)}return[...t].sort()}function id(e){if(e===void 0)return;let t=(typeof e=="string"?[e]:e).flatMap(n=>n.split(",")).map(n=>n.trim()).filter(n=>n.length>0);return t.length===0?void 0:new Set(t)}function Bi(e,t){if(e.agent_harness?.trim())return{agent_harness:e.agent_harness,harness_source:"recorded"};let n=t.aliases[e.author];return n?{agent_harness:n,harness_source:"vocabulary"}:{harness_source:"unresolved"}}function Hi(e,t=Ke){let n=new Set(t),r=new Map,i=e.provenance===void 0?[]:typeof e.provenance=="string"?[e.provenance]:e.provenance;for(let o of i.flatMap(s=>s.split(","))){let s=o.indexOf("=");if(s<0)throw new _(`Provenance predicate must use dimension=value; received "${o.trim()}".`,g.USAGE,{code:"invalid_provenance_predicate"});let a=o.slice(0,s).trim().toLowerCase(),c=o.slice(s+1).trim();if(!n.has(a))throw new _(`Unknown provenance dimension "${a||o.trim()}". Declared dimensions: ${[...n].sort().join(", ")}.`,g.USAGE,{code:"unknown_provenance_dimension"});if(c.length===0)throw new _(`Provenance predicate must use dimension=value; received "${o.trim()}".`,g.USAGE,{code:"invalid_provenance_predicate"});let d=r.get(a)??new Set;d.add(c),r.set(a,d)}return r}function rr(e,t=tr,n={}){let r=Bi(e,t);return{...n.itemId===void 0?{}:{item_id:n.itemId},...n.version===void 0?{}:{version:n.version},ts:e.ts,op:e.op,author:e.author,...e.author_source===void 0?{}:{author_source:e.author_source},...r,vocabulary_version:t.version,...e.agent_instance===void 0?{}:{agent_instance:e.agent_instance},agent_provenance:e.agent_provenance??{},...e.message===void 0?{}:{message:e.message}}}function VC(e,t,n=tr,r=Ke){return Gi(t,n,r)(e)}function Gi(e,t=tr,n=Ke){let r=id(e.harness),i=id(e.agentInstance),o=Hi(e,n);return s=>{let a=Bi(s,t).agent_harness;if(r&&(!a||!r.has(a))||i&&!i.has(s.agent_instance??""))return!1;for(let[c,d]of o){let l=s.agent_provenance?.[c];if(!l||!d.has(l.value))return!1}return!0}}function ir(e,t=tr,n=Ke){let r=new Set(n),i=new Map,o=0;for(let s of e){for(let a of Object.keys(s.agent_provenance??{}))r.add(a);Bi(s,t).agent_harness?o+=1:i.set(s.author,(i.get(s.author)??0)+1)}return{entries:e.length,vocabulary_version:t.version,harness:{resolved:o,unresolved:e.length-o,unresolved_authors:[...i].map(([s,a])=>({author:s,entries:a})).sort((s,a)=>a.entries-s.entries||s.author.localeCompare(a.author)).slice(0,20)},dimensions:[...r].sort().map(s=>{let a=0,c=0;for(let d of e){let l=d.agent_provenance?.[s];l===null?c+=1:l!==void 0&&(a+=1)}return{dimension:s,observed:a,unavailable:c,legacy_missing:e.length-a-c}})}}import r_ from"node:fs/promises";import ad from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a4394793-55d4-5049-ab20-707c1c3d9f2c")}catch{}})();var i_=20,o_=5,s_=15,a_="-24h";function rS(e){let t={...e};return t.full===!0?(t.raw=!0,t.compact=!1):t.raw===!0&&t.compact===void 0&&(t.compact=!0),delete t.full,t}var c_={digest:"activity_digest",compact:"compact_activity",provenance:"provenance_activity",full:"activity"};function Ki(e,t){if(e===void 0)return;let n=e.trim();if(n.length===0)throw new _(`${t} must not be empty`,g.USAGE);return n}function od(e,t,n){if(e===void 0)return;let r=e.trim();if(r.length===0)throw new _("Activity time bounds must not be empty",g.USAGE);let i=n==="--from"&&/^\d+[hdwm]$/iu.test(r)?`-${r}`:r;return _e(i,new Date(t),n)}function d_(e,t,n){return!(e.ts.length===0&&(t||n)||t&&C(e.ts,t)<0||n&&C(e.ts,n)>=0)}function sd(e,t){return t===void 0?e:e.slice(0,t)}function Dt(e,t=""){return typeof e=="string"?e:t}function l_(e,t){return{...t,id:e,ts:Dt(t.ts),author:Dt(t.author,"unknown"),op:Dt(t.op,"unknown"),patch:Array.isArray(t.patch)?t.patch:[],before_hash:Dt(t.before_hash),after_hash:Dt(t.after_hash)}}function u_(e){return[...e].sort((t,n)=>{let r=n.ts.localeCompare(t.ts);if(r!==0)return r;let i=t.id.localeCompare(n.id);return i!==0?i:t.op.localeCompare(n.op)})}async function f_(e){try{return(await r_.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort((t,n)=>t.localeCompare(n))}catch(t){if(ae(t))return[];throw t}}function m_(e){return e.raw!==!0&&e.compact!==!0&&e.provenance!==!0?"digest":e.provenance===!0?"provenance":e.compact===!0||e.raw===!0&&e.compact!==!1?"compact":"full"}function p_(e,t,n){if(e.unbounded!==!0)return t!==void 0?t:n==="digest"?s_:n==="compact"?i_:o_}function h_(e,t){let n=x(),r=t==="digest",i=od(e.to??(r?n:void 0),n,"--to"),o=od(e.from??(r?a_:void 0),e.from===void 0&&r?i:n,"--from");if(o&&i&&C(o,i)>=0)throw new _("Activity --from must be before --to",g.USAGE);let s=Tr(e.limit);if(e.unbounded===!0&&s!==void 0)throw new _("Activity --unbounded cannot be combined with --limit",g.USAGE);return{id:Ki(e.id,"Activity --id"),op:Ki(e.op,"Activity --op"),author:Ki(e.author,"Activity --author"),from:o,to:i,limit:p_(e,s,t),limitSource:e.unbounded===!0||s!==void 0?"explicit":"default",harness:e.harness,agentInstance:e.agentInstance,provenance:e.provenanceFilter}}async function g_(e){let t=O(process.cwd(),e.path);return await U(t),{pmRoot:t,settings:await F(t)}}async function __(e){let t=L(e.settings,D()),n=await le(e.pmRoot,e.settings.item_format,t.type_to_folder,void 0,e.settings.schema);await rs({pmRoot:e.pmRoot,settings:e.settings,itemIds:n.map(i=>i.id),commandLabel:"activity"});let r=ad.join(e.pmRoot,"history");return await Vt({path:r,scope:"project"}),{historyDir:r,itemsById:new Map(n.map(i=>[i.id,{title:i.title,type:i.type,status:i.status}]))}}function y_(e,t,n){return n.op&&e.op!==n.op||n.author&&e.author!==n.author?!1:d_(t,n.from,n.to)}async function b_(e,t){let n=[];for(let r of await f_(e)){let i=r.slice(0,-6);if(t.id&&i!==t.id)continue;let o=await nn(ad.join(e,r),i);for(let s of o){let a=l_(i,s);y_(s,a,t)&&n.push(a)}}return n}function v_(e){return e.map(t=>({id:t.id,op:t.op,ts:t.ts,author:t.author,...t.message?{msg:t.message}:{}}))}function w_(e){let t=[...e.entries()].sort(([r,i],[o,s])=>s-i||r.localeCompare(o)),n=t.slice(0,4).map(([r,i])=>`${r}:${i}`);return t.length>n.length&&n.push(`+${t.length-n.length}`),n.join(",")}function k_(e,t){let n=new Map;for(let r of e){let i=n.get(r.id);if(i===void 0){n.set(r.id,{firstTs:r.ts,lastTs:r.ts,eventCount:1,operations:new Map([[r.op,1]])});continue}i.eventCount+=1,C(r.ts,i.firstTs)<0&&(i.firstTs=r.ts),C(r.ts,i.lastTs)>0&&(i.lastTs=r.ts),i.operations.set(r.op,(i.operations.get(r.op)??0)+1)}return[...n.entries()].map(([r,i])=>{let o=t.get(r);return{id:r,type:o?.type??"unknown",status:o?.status??"unknown",title:(o?.title??"(item metadata unavailable)").slice(0,160),event_count:i.eventCount,first_ts:i.firstTs,last_ts:i.lastTs,operations:w_(i.operations)}}).sort((r,i)=>C(i.last_ts,r.last_ts)||r.id.localeCompare(i.id))}function E_(e){let t=new Map;for(let i of e)t.set(i.op,(t.get(i.op)??0)+1);let n=[...t.entries()].sort((i,o)=>o[1]-i[1]||i[0].localeCompare(o[0])),r=n.slice(0,8);return r.length<n.length&&r.push([`+${String(n.length-r.length)}`,n.slice(r.length).reduce((i,[,o])=>i+o,0)]),Object.fromEntries(r)}function I_(e,t,n,r,i){if(e==="digest"){let s=k_(t,r),a=sd(s,n);return{rows:{activity_digest:a},compact:!1,totalRows:s.length,returnedRows:a.length}}let o=sd(t,n);return e==="compact"?{rows:{compact_activity:v_(o)},compact:!0,totalRows:t.length,returnedRows:o.length}:e==="provenance"?{rows:{provenance_activity:o.map(i)},compact:!1,totalRows:t.length,returnedRows:o.length}:{rows:{activity:o},compact:!1,totalRows:t.length,returnedRows:o.length}}async function cd(e,t){let n=await g_(t),r=m_(e),i=h_(e,r),o=await __(n),s=nr(n.settings.agent_identity.harness_signals),a=n.settings.agent_identity.identity_vocabulary,c=Gi({harness:i.harness,agentInstance:i.agentInstance,provenance:i.provenance},a,s),d=u_(await b_(o.historyDir,i)).filter(c),l=I_(r,d,i.limit,o.itemsById,f=>rr(f,a,{itemId:f.id})),u=l.totalRows-l.returnedRows;return{...l.rows,compact:l.compact,projection:{mode:r,row_key:c_[r]},omission_receipt:vo("activity",r),count:l.returnedRows,total_count:l.totalRows,limit:i.limit??null,omitted_count:u,has_more:u>0,...r==="digest"?{activity_summary:{window:{from:i.from,to:i.to},event_count:d.length,item_count:l.totalRows,author_count:new Set(d.map(f=>f.author)).size,operation_counts:E_(d)}}:{},...e.provenanceSummary===!0?{provenance_summary:ir(d,a,s)}:{},applied_bound:{kind:i.limit===void 0?"unbounded":"limit",source:i.limitSource,value:i.limit??null}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cdfc765-7370-57bb-a4dc-be2df8aa1e6f")}catch{}})();var dd="1970-01-01T00:00:00.000Z";function At(e){if(typeof e!="string")return null;let t=e.trim();if(!Xt(t)&&!/^\d{4}-\d{2}-\d{2}$/u.test(t))return null;try{return _e(t,new Date(Number.NaN),"context signal recency coordinate")}catch{return null}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e750a203-8bef-5bfd-85a5-a584c2105472")}catch{}})();var zi=["structural","recency","activity_density","graph_proximity","claim_focus","priority_pressure","risk_pressure","deadline_pressure","knowledge_density","author_affinity","usage_affinity","semantic_similarity"],C_=Symbol("no-context-author"),S_=Symbol("no-item-assignee");function ld(e,t){if(typeof e!="string")return t;let n=e.trim().toLowerCase();return n.length>0?n:t}function T_(e){if(typeof e!="string")return;let t=/^v?(\d{4})\.(\d{1,2})\.(\d{1,2})(?:$|[-+])/u.exec(e.trim());if(!t)return;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),o=new Date(Date.UTC(n,r-1,i));return o.getUTCFullYear()===n&&o.getUTCMonth()===r-1&&o.getUTCDate()===i?o.toISOString():void 0}function R_(e){let t=T_(e.release);return t!==void 0?{source:"release_cohort",coordinate:t}:{source:"created_at",coordinate:At(e.created_at)??dd}}function x_(e){if(!["substantive_history","release_cohort","created_at"].includes(e.source)||(e.source==="substantive_history"?e.history_op!==void 0&&typeof e.history_op!="string"||e.event_class!==void 0&&e.event_class!=="substantive":e.history_op!==void 0||e.event_class!==void 0))throw new TypeError("Context signal recency provenance must match its source");let t=At(e.coordinate);if(t===null)throw new TypeError("Context signal recency coordinate must be a valid absolute timestamp with millisecond precision");return{...e,coordinate:t}}function D_(e,t){let n=typeof e=="number"?e:typeof e=="string"?Number.parseFloat(e):Number.NaN;return Number.isFinite(n)?1-Math.min(Math.max(n,0),t)/t:0}function A_(e,t){let n=typeof e=="string"?Date.parse(e):e instanceof Date?e.getTime():typeof e=="number"?e:Number.NaN;if(!Number.isFinite(n)||!Number.isFinite(t))return 0;let r=(n-t)/864e5;return r<=0?1:1/(1+r/30)}function O_(e){let t=typeof e=="string"?e.trim().toLowerCase():void 0;return t==="critical"||t==="high"?1:t==="medium"?.5:t==="low"?.1:0}function or(e,t,n){return e?.[t]??n}function sr(e,t){let n=new Map(e.map(d=>{let l=t.recencyEvidence?.[d.id];return[d.id,l===void 0?R_(d):x_(l)]})),r=[...e].sort((d,l)=>{let u=n.get(d.id).coordinate,f=n.get(l.id).coordinate;return C(f,u)||d.id.localeCompare(l.id)}),i=new Map(r.map((d,l)=>[d.id,l])),o=Math.max(e.length-1,1),s=ld(t.author,C_),a=Q("in_progress",t.statusRegistry),c=Date.parse(t.now);return e.map(d=>{let l=ld(d.assignee,S_)===s,u=(d.comments?.length??0)+(d.notes?.length??0)+(d.learnings?.length??0);return{id:d.id,item:d,signal_provenance:{recency:n.get(d.id)},signals:{recency:e.length===1?1:1-i.get(d.id)/o,activity_density:t.activityDensity?.[d.id],graph_proximity:or(t.graphProximity,d.id,d.parent?.3:0),claim_focus:or(t.claimFocus,d.id,R(d.status,t.statusRegistry)===a?1:l?.75:0),priority_pressure:D_(d.priority,4),risk_pressure:O_(d.risk),deadline_pressure:A_(d.deadline,c),knowledge_density:or(t.knowledgeDensity,d.id,Math.min(u/5,1)),author_affinity:or(t.authorAffinity,d.id,l?1:0),usage_affinity:t.usageAffinity?.[d.id],semantic_similarity:t.semanticSimilarity?.[d.id]}}})}var L_="context_relevance",F_={structural:.4,recency:.35,activity_density:.25,graph_proximity:.15,claim_focus:.6,priority_pressure:.35,risk_pressure:.2,deadline_pressure:.45,knowledge_density:.25,author_affinity:.2,usage_affinity:.3,semantic_similarity:.5},M_=new TextEncoder;function N_(e){let t=new Set;for(let n of e){if(typeof n.id!="string"||n.id.trim().length===0||t.has(n.id))throw new TypeError("Context relevance candidates require unique non-empty ids");t.add(n.id);for(let[r,i]of Object.entries(n.signals??{})){if(r==="structural"||!zi.includes(r))throw new TypeError(`Unknown context relevance signal: ${r}`);if(i!==void 0&&(!Number.isFinite(i)||i<0||i>1))throw new TypeError(`Context relevance signal ${r} must be a finite number from 0 to 1`)}}}function $_(e){let t={...F_};for(let[n,r]of Object.entries(e??{}))r!==void 0&&zi.includes(n)&&(t[n]=r);for(let[n,r]of Object.entries(t))if(!Number.isFinite(r)||r<0)throw new TypeError(`Context relevance weight ${n} must be a finite non-negative number`);return t}function fd(e,t={}){N_(e);let n=$_(t.weights),r=Math.max(e.length-1,1),i=new Set(["structural"]);for(let a of e)for(let[c,d]of Object.entries(a.signals??{}))d!==void 0&&i.add(c);let o=zi.filter(a=>i.has(a)),s=e.map((a,c)=>{let d={structural:e.length===1?1:1-c/r,...a.signals},l={},u=0,f=0;for(let p of o){let m=d[p];if(m===void 0)continue;let h=m*n[p];l[p]=h,u+=h,f+=n[p]}return{...a,baseline_rank:c+1,rank:0,score:f===0?0:u/f,contributions:l}});return s.sort((a,c)=>c.score-a.score||a.baseline_rank-c.baseline_rank),s.forEach((a,c)=>{a.rank=c+1}),{model:"default-weighted-v1",available_signals:o,ranked:s}}async function P_(e,t={}){let n=fd(e,t);if(!t.scorer)return n;let r=await t.scorer({candidates:e,default_report:n}),i=new Map;for(let s of r){if(i.has(s.id)||!Number.isFinite(s.score))throw new TypeError("Context relevance scorer must return one finite score for every candidate");i.set(s.id,s.score)}if(i.size!==e.length||e.some(s=>!i.has(s.id)))throw new TypeError("Context relevance scorer must return one finite score for every candidate");let o=n.ranked.map(s=>{let a=i.get(s.id);return{...s,score:a,contributions:{custom:a}}});return o.sort((s,a)=>a.score-s.score||s.baseline_rank-a.baseline_rank),o.forEach((s,a)=>{s.rank=a+1}),{model:"custom",available_signals:n.available_signals,ranked:o}}async function ar(e,t,n={}){let r=fd(t,n),i=await yo(L_,{surface:e,candidates:t,default_report:r});if(!i.handled)return i.warnings.length>0?{...r,warnings:i.warnings}:r;if(!Array.isArray(i.result)||!i.result.every(o=>typeof o=="object"&&o!==null&&typeof o.id=="string"&&typeof o.score=="number"&&Number.isFinite(o.score)))return{...r,warnings:[...i.warnings,"extension_context_relevance_invalid_result"]};try{let o=await P_(t,{...n,scorer:()=>i.result});return i.warnings.length>0?{...o,warnings:i.warnings}:o}catch{return{...r,warnings:[...i.warnings,"extension_context_relevance_invalid_result"]}}}var j_=["ndcg","reciprocal_rank","required_recall","continuity_coverage","token_budget_adherence"];function ud(e,t){return e.length===0?1:e.filter(n=>t.has(n)).length/e.length}function U_(e){if(!Number.isFinite(e.actual_tokens)||e.actual_tokens<0||!Number.isFinite(e.token_budget)||e.token_budget<=0)throw new TypeError("Context ranking token counts require actual_tokens >= 0 and token_budget > 0");let t=e.judgments??{},n=e.ranked_ids.map(d=>Math.max(0,t[d]??0)),r=Object.values(t).map(d=>Math.max(0,d)).sort((d,l)=>l-d).slice(0,n.length||1),i=d=>d.reduce((l,u,f)=>l+(2**u-1)/Math.log2(f+2),0),o=i(r),s=n.findIndex(d=>d>0),a=new Set(e.ranked_ids),c=e.actual_tokens<=e.token_budget;return{ndcg:o===0?1:i(n)/o,reciprocal_rank:s<0?0:1/(s+1),required_recall:ud(e.required_ids??[],a),continuity_coverage:ud(e.continuity_ids??[],a),token_budget_adherence:c?1:e.token_budget/e.actual_tokens,within_token_budget:c}}function B_(e){return Math.ceil(M_.encode(JSON.stringify(e)).byteLength/4)}function H_(e){return Math.round(e*1e4)/1e4}function G_(e,t){let n=t==="context"?[...e.high_level??[],...e.low_level??[],...e.blocked_fallback??[]].map(o=>o.id):[...e.recommended?[e.recommended]:[],...e.ready??[]].map(o=>o.id),r=new Set(n),i=(e.ranking?.items??[]).filter(o=>r.has(o.id)).map(o=>({id:o.id,contributions:o.contributions}));return{rankedIds:n,attribution:i}}async function K_(e,t){if(e.id.trim().length===0||e.rationale.trim().length===0)throw new TypeError("Context evaluation scenarios require non-empty id and rationale values");let n=e.surface==="context"?await t.context({...e.options,explainRanking:!0,outputBudget:e.options?.outputBudget??"unbounded"}):await t.next({...e.options,explainRanking:!0,outputBudget:e.options?.outputBudget??"unbounded"}),{rankedIds:r,attribution:i}=G_(n,e.surface),o={...n,ranking:void 0},s=B_(o);return{id:e.id,surface:e.surface,rationale:e.rationale,ranked_ids:r,actual_tokens:s,metrics:U_({ranked_ids:r,judgments:e.judgments,required_ids:e.required_ids,continuity_ids:e.continuity_ids,actual_tokens:s,token_budget:e.token_budget}),attribution:i}}function z_(e,t){if(e.length===0)throw new TypeError("Context evaluation requires at least one scenario report");let n=j_;for(let o of n)if(!Number.isFinite(t[o]))throw new TypeError(`Context evaluation threshold ${o} must be a finite number`);let r=Object.fromEntries(n.map(o=>[o,H_(e.reduce((s,a)=>s+a.metrics[o],0)/e.length)])),i=n.filter(o=>r[o]<t[o]).map(o=>`${o}:${r[o]}<${t[o]}`);return{scenario_count:e.length,aggregate:r,scenarios:[...e],passed:i.length===0,failures:i}}async function uS(e,t,n){let r=[];for(let i of e)r.push(await K_(i,t));return z_(r,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d07ec2dc-762a-58ab-83ee-734ca1bf76a7")}catch{}})();var V_={balanced:{redundancyPenalty:.35,uncertaintyPenalty:.2},context:{redundancyPenalty:.45,uncertaintyPenalty:.15},next:{redundancyPenalty:.25,uncertaintyPenalty:.3}},q_=["identity","summary","full"];function W_(e){if(!e.id.trim()||!Number.isInteger(e.rank)||e.rank<1)throw new TypeError("Context packing candidates require a non-empty id and positive integer rank");if(!Number.isFinite(e.score)||e.score<0)throw new TypeError("Context packing candidate scores must be finite and non-negative");let t=q_.map(n=>e.token_costs[n]);if(t.some(n=>!Number.isInteger(n)||n<1)||t[0]>t[1]||t[1]>t[2])throw new TypeError("Context projection costs must be positive monotone integers");if(e.uncertainty!==void 0&&(!Number.isFinite(e.uncertainty)||e.uncertainty<0))throw new TypeError("Context packing uncertainty must be finite and non-negative")}function Y_(e){if(!Number.isInteger(e.tokenBudget)||e.tokenBudget<1)throw new TypeError("Context packing tokenBudget must be a positive integer");let t=e.profile??"balanced",n=V_[t];if(!n)throw new TypeError("Unknown context packing profile");let r=e.redundancyPenalty??n.redundancyPenalty,i=e.uncertaintyPenalty??n.uncertaintyPenalty;if(!Number.isFinite(r)||r<0||r>1||!Number.isFinite(i)||i<0)throw new TypeError("Context packing penalties must be finite and within their supported ranges");if(e.latencyBudgetMs!==void 0&&(!Number.isFinite(e.latencyBudgetMs)||e.latencyBudgetMs<=0))throw new TypeError("Context packing latencyBudgetMs must be positive");return{redundancy:r,uncertainty:i,profile:t}}function X_(e){let t=new Set;for(let n of e){if(W_(n),t.has(n.id))throw new TypeError("Context packing candidates require unique ids");t.add(n.id)}return[...e].sort((n,r)=>n.rank-r.rank||n.id.localeCompare(r.id))}function J_(e,t,n,r,i){let o=-1,s=0;for(let a=0;a<e.length;a+=1){if(a%128===0&&i()>=r)return{index:o,evaluated:s,timedOut:!0};let c=e[a];if(c.token_costs.identity>t)continue;s+=1;let d=o<0?void 0:e[o],l=n(c)/c.token_costs.identity,u=d===void 0?Number.NEGATIVE_INFINITY:n(d)/d.token_costs.identity;(l>u||l===u&&d!==void 0&&(c.rank<d.rank||c.rank===d.rank&&c.id.localeCompare(d.id)<0))&&(o=a)}return{index:o,evaluated:s,timedOut:!1}}function Q_(e){let t=new Set,n=[],r=e.tokenBudget,i=d=>{let l=d.lineage??d.cluster,u=l&&t.has(l)?1-e.redundancyPenalty:1;return Math.max(0,(d.score-e.uncertaintyPenalty*(d.uncertainty??0))*u)},o=d=>{let l=d.token_costs.identity;n.push({...d,projection:"identity",tokens:l,marginal_value:i(d)}),r-=l;let u=d.lineage??d.cluster;u&&t.add(u)};for(let d of e.ordered.filter(l=>l.required))d.token_costs.identity<=r&&o(d);let s=e.ordered.filter(d=>!d.required),a=!0,c=0;for(;s.length>0;){let d=J_(s,r,i,e.deadline,e.readClock);if(c+=d.evaluated,d.timedOut&&(a=!1),d.index<0||d.timedOut)break;o(s.splice(d.index,1)[0])}return{included:n,remaining:r,selectionComplete:a,evaluatedCandidates:c}}function Z_(e,t){let n=t;for(let r of["summary","full"]){let i=r==="summary"?"identity":"summary",o=[...e].sort((s,a)=>{let c=s.token_costs[r]-s.token_costs[i],d=a.token_costs[r]-a.token_costs[i];return a.marginal_value/Math.max(d,1)-s.marginal_value/Math.max(c,1)||s.rank-a.rank||s.id.localeCompare(a.id)});for(let s of o){if(s.projection!==i)continue;let a=s.token_costs[r]-s.tokens;a>n||(s.projection=r,s.tokens+=a,n-=a)}}return n}function md(e,t){let n=Y_(t),r=X_(e),i=t.readClock??performance.now.bind(performance),o=t.latencyBudgetMs===void 0?Number.POSITIVE_INFINITY:i()+t.latencyBudgetMs,s=Q_({ordered:r,tokenBudget:t.tokenBudget,redundancyPenalty:n.redundancy,uncertaintyPenalty:n.uncertainty,deadline:o,readClock:i}),{included:a}=s,c=Z_(a,s.remaining);a.sort((l,u)=>l.rank-u.rank||l.id.localeCompare(u.id));let d=new Set(a.map(l=>l.id));return{included:a,omitted_ids:r.filter(l=>!d.has(l.id)).map(l=>l.id),token_budget:t.tokenBudget,used_tokens:t.tokenBudget-c,remaining_tokens:c,complete:s.selectionComplete&&a.length===e.length&&a.every(l=>l.projection==="full"),selection_complete:s.selectionComplete,termination_reason:s.selectionComplete?"exhausted":"latency_budget",evaluated_candidates:s.evaluatedCandidates,latency_budget_ms:t.latencyBudgetMs??null,profile:n.profile,degradation_ladder:["full","summary","identity"]}}import Ot from"node:fs/promises";import Lt from"node:path";import{createHash as pd,randomUUID as ey}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01eff51c-7656-5c3f-b0c0-28594fca8a1e")}catch{}})();var Vi=3,qi=2,hd=["recency","activity_density","graph_proximity","priority_pressure","risk_pressure","knowledge_density"],ty=new Set(["substantive_history","release_cohort","created_at"]),ny={context_signal_store_invalid:{code:"context_signal_store_invalid",meaning:"The persisted context-signal snapshot was unreadable or invalid and was rebuilt from authoritative items.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot can be loaded without the warning."},context_signal_store_stale:{code:"context_signal_store_stale",meaning:"The persisted context-signal snapshot did not match the authoritative cursor or item corpus and was rebuilt.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot is now fresh."},context_signal_store_write_failed:{code:"context_signal_store_write_failed",meaning:"Context signals were rebuilt in memory, but the derived snapshot could not be persisted.",recovery_command:"pm context",recovery_effect:"Retry the derived snapshot write and confirm the warning clears after storage access is restored."}};function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gd(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function ry(e){let t={};for(let n of hd){let r=e[n];if(r!==void 0){if(!gd(r))throw new TypeError(`Context relevance signal ${n} must be a finite number from 0 to 1`);t[n]=r}}return t}function iy(e,t){let n=e.map(i=>[i.id,t(i)]),r=Math.max(0,...n.map(([,i])=>i));return Object.fromEntries(n.map(([i,o])=>[i,r===0?0:o/r]))}function oy(e){let t=new Map(e.map(i=>[i.id,0])),n=i=>{t.set(i,(t.get(i)??0)+1)};for(let i of e){typeof i.parent=="string"&&i.parent.trim()&&(n(i.id),n(i.parent.trim()));for(let o of i.dependencies??[])typeof o.id!="string"||!o.id.trim()||(n(i.id),n(o.id.trim()))}let r=Math.max(0,...t.values());return Object.fromEntries(e.map(i=>[i.id,r===0?0:t.get(i.id)/r]))}function _d(e,t){return{...t,activityDensity:t.activityDensity??iy(e,n=>(n.comments?.length??0)+(n.notes?.length??0)+(n.learnings?.length??0)+(n.test_runs?.length??0)),graphProximity:t.graphProximity??oy(e)}}function Xi(e){let t=pd("sha256");for(let{id:n,signal_provenance:{recency:r}}of[...e].sort((i,o)=>i.id.localeCompare(o.id)))t.update(JSON.stringify([n,r.source,r.coordinate,r.history_op??null,r.event_class??null]));return`sha256:${t.digest("hex")}`}function sy(e){if(!ct(e))return null;let t=e.signal_provenance;if(![typeof e.id=="string",ct(e.signals),ct(t)].every(Boolean))return null;let n=t.recency;if(!ct(n))return null;let r=At(n.coordinate);if(r===null)return null;let i=new Set(hd),o=Object.entries(e.signals);return!o.every(([s,a])=>i.has(s)&&gd(a))||![typeof n.source=="string"&&ty.has(n.source),["undefined","string"].includes(typeof n.history_op),[void 0,"substantive","maintenance"].includes(n.event_class),n.source==="substantive_history"?n.event_class===void 0||n.event_class==="substantive":n.history_op===void 0&&n.event_class===void 0].every(Boolean)?null:{id:e.id,signals:Object.fromEntries(o),signal_provenance:{recency:{source:n.source,coordinate:r,history_op:n.history_op,event_class:n.event_class}}}}function ay(e,t){let n=Array.from(e,sy);if(n.some(i=>i===null))return null;let r=n;return new Set(r.map(i=>i.id)).size!==r.length||r.some(i=>i.id.trim().length===0)||t!==Xi(r)?null:r.sort((i,o)=>i.id.localeCompare(o.id))}function cy(e){if(!ct(e)||e.format_version!==Vi||e.signal_set_version!==qi||typeof e.source_cursor!="string"||e.source_cursor.trim().length===0||typeof e.recency_evidence_fingerprint!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.recency_evidence_fingerprint)||typeof e.generated_at!="string"||!Number.isFinite(Date.parse(e.generated_at))||e.source!=="derived_index"&&e.source!=="scan_fallback"||!Array.isArray(e.items))return null;let t=ay(e.items,e.recency_evidence_fingerprint);return t===null?null:{format_version:Vi,signal_set_version:qi,source_cursor:e.source_cursor,recency_evidence_fingerprint:e.recency_evidence_fingerprint,generated_at:e.generated_at,source:e.source,items:t}}function yd(e){if(typeof e.sourceCursor!="string"||e.sourceCursor.trim().length===0)throw new TypeError("Context signal source cursor must be non-empty");if(!Number.isFinite(Date.parse(e.now)))throw new TypeError("Context signal snapshot clock must be a valid timestamp");if(e.source!=="derived_index"&&e.source!=="scan_fallback")throw new TypeError("Context signal snapshot source must be derived_index or scan_fallback")}function bd(e,t,n=Xi(e)){let r=e.map(({id:o})=>o);if(new Set(r).size!==r.length||r.some(o=>o.trim().length===0))throw new TypeError("Context signal snapshot item IDs must be unique and non-empty");let i=e.map(({id:o,signals:s,signal_provenance:a})=>({id:o,signals:ry(s),signal_provenance:a})).sort((o,s)=>o.id.localeCompare(s.id));return Object.freeze({format_version:Vi,signal_set_version:qi,source_cursor:t.sourceCursor,recency_evidence_fingerprint:n,generated_at:t.now,source:t.source,items:Object.freeze(i.map(o=>Object.freeze(o)))})}function kS(e,t){return yd(t),bd(sr(e,_d(e,t)),t)}var Wi=class{filePath;constructor(t){if(typeof t!="string"||t.trim().length===0)throw new TypeError("Context signal store path must be non-empty");this.filePath=Lt.resolve(t)}async read(){try{return JSON.parse(await Ot.readFile(this.filePath,"utf8"))}catch(t){if(ct(t)&&Pe(t))return null;throw t}}async write(t){let n=Lt.dirname(this.filePath);await Ot.mkdir(n,{recursive:!0});let r=Lt.join(n,`.${Lt.basename(this.filePath)}.${ey()}.tmp`);try{await Ot.writeFile(r,`${JSON.stringify(t)}
|
|
16
|
+
`,{encoding:"utf8",flag:"wx"}),await Ot.rename(r,this.filePath)}finally{try{await Ot.rm(r,{force:!0})}catch{}}}},Yi=class{adapter;constructor(t){this.adapter=t}async readOrRebuild(t,n){yd(n);let r=[],i=null;try{let f=await this.adapter.read();i=cy(f),f!==null&&i===null&&r.push("context_signal_store_invalid")}catch{r.push("context_signal_store_invalid")}let o=t.map(f=>f.id).sort((f,p)=>f.localeCompare(p)),s=i?.items.map(f=>f.id)??[],a=sr(t,_d(t,n)),c=Xi(a),d=i!==null&&i.source_cursor===n.sourceCursor&&i.recency_evidence_fingerprint===c&&i.source===n.source&&s.length===o.length&&s.every((f,p)=>f===o[p]),l;if(d&&i!==null)l=i;else{i!==null&&r.push("context_signal_store_stale"),l=bd(a,n,c);try{await this.adapter.write(l)}catch{r.push("context_signal_store_write_failed")}}let u=new Map(l.items.map(f=>[f.id,f]));return{snapshot:l,candidates:a.map(f=>({...f,signals:{...f.signals,...u.get(f.id)?.signals},signal_provenance:u.get(f.id).signal_provenance})),cache_status:d?"fresh":"rebuilt",warnings:r,warning_details:r.map(f=>ny[f])}}};function dy(e){let t=pd("sha256");for(let n of[...e].sort((r,i)=>r.id.localeCompare(i.id)))t.update(JSON.stringify([n.id,n.updated_at,n.status,n.parent??null,n.priority??null,n.risk??null,(n.dependencies??[]).map(r=>r.id).sort(),n.comments?.length??0,n.notes?.length??0,n.learnings?.length??0,n.test_runs?.length??0]));return`scan:${t.digest("hex")}`}async function cr(e,t){let n=t.sourceCursor!==void 0,r=t.source!==void 0;if(n!==r)throw new TypeError("Context signal source and source cursor must be provided together");if(t.storeKey!==void 0&&!/^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/u.test(t.storeKey))throw new TypeError("Context signal store key must be a filesystem-safe identifier");let i=n?null:await qe(t.pmRoot),o=t.sourceCursor??i?.source_cursor??dy(e),s=t.source??(i===null?"scan_fallback":"derived_index"),a=new Yi(new Wi(Lt.join(t.pmRoot,"runtime",t.storeKey?`context-signals-${t.storeKey}.json`:"context-signals.json"))),c=t.recencyEvidence??Object.fromEntries(Object.entries(await jo(t.pmRoot,e.map(d=>d.id))).map(([d,l])=>[d,{source:"substantive_history",coordinate:l.entry.ts,history_op:l.entry.op,event_class:"substantive"}]));return a.readOrRebuild(e,{...t,recencyEvidence:c,sourceCursor:o,source:s})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="61e27cd0-a444-5b66-a8e3-d81c76e4f8ae")}catch{}})();function ly(e){for(let t of e.patch){if(t.path==="/metadata/status"||t.path==="/front_matter/status"){if(typeof t.value=="string")return t.value.trim().toLowerCase();continue}if(t.path!==""||typeof t.value!="object")continue;let n=t.value,r=n.metadata??n.front_matter;if(typeof r?.status=="string")return r.status.trim().toLowerCase()}}function uy(e,t,n){let r,i;for(let o of t){let s=ly(o);if(s===void 0)continue;let a=n.has(s)&&(r!==void 0&&!n.has(r)||r===void 0&&o.op==="create");r=s,a&&Number.isFinite(Date.parse(o.ts))&&(i={id:e,completed_at:o.ts,history_op:o.op})}return i}function vd(e){return e.completed_at!==void 0?{resolved:!0,timestamp:e.completed_at,source:"completed_at",fallback:!1}:e.closed_at!==void 0?{resolved:!0,timestamp:e.closed_at,source:"closed_at",fallback:!0}:e.updated_at!==void 0?{resolved:!0,timestamp:e.updated_at,source:"updated_at",fallback:!0}:{resolved:!1}}function IS(e,t,n){let r=[];for(let i of e){if(i.completed_at!==void 0||!n.has(i.status.trim().toLowerCase()))continue;let o=uy(i.id,t.get(i.id)??[],n);o!==void 0&&r.push(o)}return r.sort((i,o)=>i.id.localeCompare(o.id))}import fy from"node:path";import{createHash as my}from"node:crypto";import py from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="df753f1d-cfc1-555e-a411-e1417eab0b53")}catch{}})();var wd=1,hy=1e4,kd=12;function gy(e){let t=new Date(e);return`${t.getUTCFullYear()}-Q${Math.floor(t.getUTCMonth()/3)+1}`}function _y(e,t){let n=new Set,r=e.parent;for(;r&&!n.has(r);){n.add(r);let i=t.get(r);if(!i)return;if(i.type.toLowerCase()==="epic")return i;r=i.parent}}function yy(e){let t=[...e.items].sort((i,o)=>o.completion.timestamp.localeCompare(i.completion.timestamp)||i.item.id.localeCompare(o.item.id)),n=new Set,r=0;for(let{item:i}of t){let o=i.resolution??i.close_reason;o?.trim()&&n.add(o.trim()),r+=(i.notes?.length??0)+(i.learnings?.length??0)}return{kind:e.kind,key:e.key,label:e.label,item_count:t.length,first_closed_at:t.at(-1).completion.timestamp,last_closed_at:t[0].completion.timestamp,representative_items:t.slice(0,5).map(({item:{id:i,title:o}})=>({id:i,title:o})),outcomes:[...n].sort().slice(0,5),knowledge_entries:r}}function by(e,t){if(!t.sourceCursor.trim())throw new TypeError("Workspace memory source cursor must be non-empty");if(!Number.isFinite(Date.parse(t.now)))throw new TypeError("Workspace memory clock must be a valid timestamp");let n=e.filter(o=>t.statusRegistry.terminal_done_statuses.has(R(o.status,t.statusRegistry))).map(o=>{let s=vd(o);if(!s.resolved)throw new TypeError(`Completed item ${o.id} has no reporting timestamp`);return{item:o,completion:s}}),r=new Map(e.map(o=>[o.id,o])),i=new Map;for(let o of n){let{item:s,completion:a}=o,c=gy(a.timestamp),d=`epoch:${c}`,l=i.get(d)??{kind:"epoch",key:c,label:c,items:[]};l.items.push(o),i.set(d,l);let u=_y(s,r);if(u){let f=`epic:${u.id}`,p=i.get(f)??{kind:"epic",key:u.id,label:u.title,items:[]};p.items.push(o),i.set(f,p)}}return{format_version:wd,source_cursor:t.sourceCursor,source_item_count:e.length,generated_at:t.now,completion_time_sources:n.reduce((o,{completion:s})=>(o[s.source]+=1,o),{completed_at:0,closed_at:0,updated_at:0}),rollups:[...i.values()].map(yy).sort((o,s)=>s.last_closed_at.localeCompare(o.last_closed_at)||o.kind.localeCompare(s.kind)||o.key.localeCompare(s.key))}}function vy(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"&&e.id.length>0&&"title"in e&&typeof e.title=="string"}function wy(e){if(typeof e!="object"||e===null)return!1;let t=e,n=[t.key,t.label].every(i=>typeof i=="string"&&i.length>0),r=[t.first_closed_at,t.last_closed_at].every(i=>typeof i=="string"&&Number.isFinite(Date.parse(i)));return(t.kind==="epoch"||t.kind==="epic")&&n&&Number.isSafeInteger(t.item_count)&&t.item_count>0&&r&&Array.isArray(t.representative_items)&&t.representative_items.every(vy)&&Array.isArray(t.outcomes)&&t.outcomes.every(i=>typeof i=="string")&&Number.isSafeInteger(t.knowledge_entries)&&t.knowledge_entries>=0}function ky(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;return t.format_version!==wd||typeof t.source_cursor!="string"||!t.source_cursor.trim()||!Number.isSafeInteger(t.source_item_count)||t.source_item_count<0||typeof t.generated_at!="string"||!Number.isFinite(Date.parse(t.generated_at))||!Array.isArray(t.rollups)?null:t.rollups.every(wy)?t:null}function Ey(e){return`scan:${my("sha256").update(I(e.map(t=>[t.id,t.updated_at,t.status,t.parent]).sort(([t],[n])=>String(t).localeCompare(String(n))))).digest("hex")}`}async function Iy(e,t,n){return n!==void 0?n:(await qe(t))?.source_cursor??Ey(e)}async function Cy(e){try{let t=ky(JSON.parse(await py.readFile(e,"utf8")));return{snapshot:t,invalid:t===null}}catch(t){return{snapshot:null,invalid:!(typeof t=="object"&&t!==null&&"code"in t&&Pe(t))}}}async function Ed(e,t){let n=Math.max(1,Math.floor(t.minimumItems??hy));if(e.length<n)return{snapshot:null,cache_status:"skipped",warnings:[]};let r=await Iy(e,t.pmRoot,t.sourceCursor),i=fy.join(t.pmRoot,"runtime","workspace-memory.json"),o=[],s=await Cy(i),a=s.snapshot;if(s.invalid&&o.push("workspace_memory_invalid"),a?.source_cursor===r&&a.source_item_count===e.length)return{snapshot:a,cache_status:"fresh",warnings:o};a&&o.push("workspace_memory_stale");let c=by(e,{statusRegistry:t.statusRegistry,sourceCursor:r,now:t.now});try{await W(i,`${JSON.stringify(c)}
|
|
17
|
+
`)}catch{o.push("workspace_memory_write_failed")}return{snapshot:c,cache_status:"rebuilt",warnings:o}}function Sy(e,t,n=kd){let r=Math.max(0,Math.floor(t)),i=0,o=[];for(let s of e.rollups){if(o.length>=Math.max(0,Math.floor(n)))break;let a=Math.ceil(JSON.stringify(s).length/4);i+a>r||(o.push(s),i+=a)}return o}function Id(e,t,n=kd){if(e.snapshot===null)return;let r=Sy(e.snapshot,t,n);if(r.length!==0)return{cache_status:e.cache_status==="fresh"?"fresh":"rebuilt",source_cursor:e.snapshot.source_cursor,...e.snapshot.completion_time_sources?{completion_time_sources:{...e.snapshot.completion_time_sources}}:{},rollups:r}}function Ty(e,t,n=5){if(e===null)return[];let r=t.trim().toLowerCase().split(/\s+/u).filter(Boolean);return r.length===0?[]:e.rollups.map(i=>({rollup:i,score:r.filter(o=>[i.key,i.label,...i.outcomes,...i.representative_items.flatMap(s=>[s.id,s.title])].join(" ").toLowerCase().includes(o)).length})).filter(({score:i})=>i>0).sort((i,o)=>o.score-i.score||o.rollup.last_closed_at.localeCompare(i.rollup.last_closed_at)||i.rollup.key.localeCompare(o.rollup.key)).slice(0,Math.max(0,Math.floor(n))).map(({rollup:i})=>i)}function FS(e,t,n=5){let r=Ty(e.snapshot,t,n);if(r.length!==0)return{cache_status:e.cache_status==="fresh"?"fresh":"rebuilt",matches:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="599ebac9-d3e8-561d-a971-8164179f1adf")}catch{}})();var Ry=["markdown","toon","json","ndjson"],dr=new Set(["Epic","Feature"]),xd=10,Dd=1e4,Ad=["hierarchy","activity","progress","recently_created","unparented","workload"],xy=[...Ad,"blockers","files","staleness","tests"],Dy=/^(\d{4})-(\d{2})-(\d{2})/,Ay=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,Oy=/^(\d{4})(\d{2})(\d{2})$/,Ly=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function Fy(e){if(!e)return;let t=e.trim().toLowerCase();if(!Ry.includes(t))throw new _("Context format must be one of markdown|toon|json|ndjson",g.USAGE);return t}var Cd=new Set(["id","title","type","status","priority","order","deadline","assignee","tags","tags_inherited","updated_at","parent","children_total","children_closed","completion_pct","blocked","blocker_ids","created_at"]);function My(e){if(e===void 0)return;let t=[];for(let n of e.split(",")){let r=n.trim().toLowerCase();if(r.length!==0){if(!Cd.has(r))throw new _(`Context --fields value not projectable: ${r} (valid: ${[...Cd].join(", ")})`,g.USAGE);t.includes(r)||t.push(r)}}if(t.length===0)throw new _("Context --fields requires at least one field name",g.USAGE);return t}function Ft(e,t){return e.map(n=>{let r={},i=n;for(let o of t)r[o]=i[o]??null;return r})}function nT(e,t){let n=Fy(e.format);if(t.json&&n&&n!=="json"&&n!=="ndjson")throw new _("Cannot combine --json with --format markdown|toon",g.USAGE);return t.json?n==="ndjson"?"ndjson":"json":n??"toon"}function Ny(e,t){return ie(e,"--limit")??(t==="full"?Number.MAX_SAFE_INTEGER:xd)}function Zi(e,t){if(e===void 0)return t;let n=typeof e=="number"?e:Number(e);if(!Number.isInteger(n)||n<1)throw new _("--token-budget must be a positive integer",g.USAGE);return n}function $y(e,t){return t>=Dd&&e===Number.MAX_SAFE_INTEGER?xd:e}function Py(e,t){if(!e)return t.default_depth;let n=e.trim().toLowerCase();if(!gr.includes(n))throw new _(`Context --depth must be one of ${gr.join("|")}`,g.USAGE);return n}function jy(e,t,n){if(e&&e.length>0){let r=[];for(let i of e){let o=i.trim().toLowerCase();if(!Gt.includes(o))throw new _(`Context --section must be one of ${Gt.join("|")}`,g.USAGE);r.includes(o)||r.push(o)}return r}return t==="brief"?[]:t==="full"?[...Gt]:(t==="deep"?xy:Ad).filter(r=>n.sections[r])}function Uy(e,t){return e?ie(e,"--activity-limit")??t.activity_limit:t.activity_limit}function By(e,t){if(!e)return t.stale_threshold_days;let n=e.trim().toLowerCase(),r=/^(\d+)d?$/.exec(n);if(!r)throw new _("--stale-threshold must be a number of days (e.g. 7 or 7d)",g.USAGE);let i=parseInt(r[1],10);if(i<=0)throw new _("--stale-threshold must be positive",g.USAGE);return i}function Sd(e,t){let n=R(e,t),r=Q("blocked",t),i=Q("draft",t);return n===t.in_progress_status?0:t.active_statuses.has(n)?1:r&&n===r?2:i&&n===i?3:t.blocked_statuses.has(n)?5:t.terminal_statuses.has(n)?7:6}function Mt(e,t){let n=Q("closed",t);return R(e,t)===n}function eo(e,t){return R(e,t)===t.in_progress_status}function Od(e,t){let n=R(e,t);return n!==t.in_progress_status&&t.active_statuses.has(n)}function Hy(e,t){return t.blocked_statuses.has(R(e,t))}var Gy=["compact","brief","fields","includeBody","include_body","parent"];function Ky(e){let t={...e};for(let n of Gy)delete t[n];return t}function to(e,t){let n=t.trim().toLowerCase(),r=e.find(s=>s.id.trim().toLowerCase()===n);if(!r)return{ids:new Set,found:!1};let i=dt(e),o=Nt(r.id,i);return{ids:new Set([r.id,...o.map(s=>s.id)].map(s=>s.trim().toLowerCase())),found:!0}}function zy(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new _("Context --parent requires an item id",g.USAGE);return t}function Vy(e,t){let n=e??null,r=t??null;return n===null&&r===null?0:n===null?1:r===null?-1:n-r}function qy(e,t){let n=e??null,r=t??null;return n===null&&r===null?0:n===null?1:r===null?-1:C(n,r)}function Wy(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function Yy(e){let t=Dy.exec(e)??Ay.exec(e);if(!t)return!0;let n=Number.parseInt(t[1],10),r=Number.parseInt(t[2],10),i=Number.parseInt(t[3],10);return r>=1&&r<=12&&i>=1&&i<=Wy(n,r-1)}function Xy(e){let t=Oy.exec(e);if(t)return`${t[1]}-${t[2]}-${t[3]}`;let n=Ly.exec(e);if(n){let[,r,i,o,s,a,c,d]=n,l=c?`:${c}`:"",u=d&&d.length===5&&d!=="Z"?`${d.slice(0,3)}:${d.slice(3)}`:d??"";return`${r}-${i}-${o}T${s}:${a}${l}${u}`}return e}function Ld(e){if(typeof e!="string")return Number.NaN;let t=e.trim();if(t.length===0||!Yy(t))return Number.NaN;let n=Date.parse(Xy(t));return Number.isFinite(n)?n:Number.NaN}function Qi(e){let t=Ld(e);return Number.isFinite(t)?new Date(t).toISOString():""}function Jy(e){let t=Ld(e);return Number.isFinite(t)?new Date(t).toISOString().slice(0,10):"unknown"}function no(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ne(e,t,n){let r=Sd(e.status,n)-Sd(t.status,n);if(r!==0)return r;let i=e.priority-t.priority;if(i!==0)return i;let o=Vy(e.order,t.order);if(o!==0)return o;let s=qy(e.deadline,t.deadline);if(s!==0)return s;let a=C(Qi(t.updated_at),Qi(e.updated_at)),c=e.id.localeCompare(t.id);return a!==0?a:c}function Ji(e){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4))}function ro(e,t,n=new Set,r="context"){return md(e.ranked.map(i=>({id:i.id,item:i.item,rank:i.rank,score:i.score,required:n.has(i.id),cluster:i.item.parent?.trim()||i.item.type,token_costs:{identity:Ji({id:i.id,title:i.item.title}),summary:Ji({id:i.id,title:i.item.title,type:i.item.type,status:i.item.status,priority:i.item.priority,parent:i.item.parent}),full:Ji(i.item)}})),{tokenBudget:t,profile:r,latencyBudgetMs:25})}function io(e){return{...e,included:e.included.map(t=>({id:t.id,projection:t.projection,tokens:t.tokens}))}}function oo(e,t,n){let r=n===void 0?e.ranked:e.ranked.filter(i=>n.has(i.id));return{model:e.model,available_signals:e.available_signals,items:r.map(i=>({id:i.id,rank:i.rank,baseline_rank:i.baseline_rank,score:i.score,contributions:i.contributions,...i.signal_provenance===void 0?{}:{recency:i.signal_provenance.recency}})),candidate_count:e.ranked.length,omitted_count:e.ranked.length-r.length,...t?{feature_store:{source:t.snapshot.source,cache_status:t.cache_status,source_cursor:t.snapshot.source_cursor,generated_at:t.snapshot.generated_at}}:{}}}function Fd(e,t){return t>0?Math.round(e/t*100):0}function dt(e){let t=new Map;for(let n of e){let r=no(n.parent);if(!r)continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function $t(e,t,n){let r={id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,order:e.order??null,deadline:e.deadline??null,assignee:e.assignee??null,tags:Array.isArray(e.tags)?[...e.tags]:[],updated_at:e.updated_at,parent:no(e.parent)};if(t&&n){let i=Nt(e.id,n),o=i.length;if(o>0){let s=i.filter(a=>Mt(a.status,t)).length;r.children_total=o,r.children_closed=s,r.completion_pct=Fd(s,o)}}return r}function Qy(e){let t=0,n=0,r=0,i=new Set;for(let o of e){if(i.add(o.item_id),o.kind==="deadline"){t+=1;continue}if(o.kind==="reminder"){n+=1;continue}r+=1}return{events:e.length,items:i.size,deadlines:t,reminders:n,scheduled:r}}function lr(...e){return[...new Set(e.flatMap(t=>t??[]))].sort((t,n)=>t.localeCompare(n))}function Zy(e,t){return e.filter(n=>!t.terminal_statuses.has(R(n.item_status,t)))}function eb(e,t,n,r){let i=new Map;for(let c of e)i.set(c.id,c);let o=dt(e),s=new Set(t.filter(c=>dr.has(c.type)).map(c=>c.id)),a=[];for(let c of s){let d=i.get(c);if(!d)continue;let l=Nt(c,o),u=o.get(c)??[],f=0,p=0,m=0,h=0;for(let v of l)Mt(v.status,n)?f++:eo(v.status,n)?m++:Hy(v.status,n)?h++:Od(v.status,n)&&p++;let y=u.sort((v,b)=>Ne(v,b,n)).slice(0,r).map(v=>{let b=Nt(v.id,o),w=b.filter(k=>Mt(k.status,n)).length;return{id:v.id,title:v.title,type:v.type,status:v.status,children_total:b.length,children_closed:w}});a.push({id:d.id,title:d.title,type:d.type,status:d.status,children_total:l.length,children_closed:f,children_open:p,children_in_progress:m,children_blocked:h,children:y})}return a.sort((c,d)=>{let l=i.get(c.id),u=i.get(d.id);return Ne(l,u,n)}).slice(0,r)}function Nt(e,t){let n=[],r=[e],i=new Set;for(;r.length>0;){let o=r.pop();if(i.has(o))continue;i.add(o);let s=t.get(o)??[];for(let a of s)n.push(a),r.push(a.id)}return n}async function tb(e,t){return(await cd({compact:!0,limit:String(e)},t)).compact_activity??[]}function nb(e,t,n,r,i){let o=new Map;for(let c of e){if(!c.parent)continue;let d=o.get(c.parent)??[];d.push(c),o.set(c.parent,d)}let s=t.filter(c=>dr.has(c.type)),a=[];for(let c of s){let d=Nt(c.id,o),l=d.length;if(l===0)continue;let u=0,f=0,p=0,m=0;for(let h of d)Mt(h.status,r)?u++:n.has(h.id.trim().toLowerCase())?m++:eo(h.status,r)?p++:Od(h.status,r)&&f++;a.push({id:c.id,title:c.title,type:c.type,total:l,closed:u,open:f,in_progress:p,blocked:m,completion_pct:Fd(u,l)})}return a.sort((c,d)=>c.completion_pct-d.completion_pct).slice(0,i)}function rb(e,t,n,r){let i=new Map(t.map(o=>[o.id.trim().toLowerCase(),o]));return e.slice(0,r).map(o=>{let s=wn(o,i,n),a=s.find(d=>!d.resolved)?.id??s[0]?.id??null,c=a?i.get(a.trim().toLowerCase()):void 0;return{id:o.id,title:o.title,blocked_by:a,blocked_by_title:c?.title??null,blocked_by_status:c?.status??null,blocked_reason:o.blocked_reason??null,unblock_note:o.unblock_note??null}})}function ib(e,t){let n=new Map;for(let r of e)for(let i of r.files??[]){let o=n.get(i.path)??new Set;o.add(r.id),n.set(i.path,o)}return[...n.entries()].map(([r,i])=>({path:r,references:i.size,items:[...i].sort()})).sort((r,i)=>i.references-r.references).slice(0,t)}function ob(e,t,n){let r=new Map;for(let i of e){let o=i.assignee??null,s=r.get(o)??[];s.push(i),r.set(o,s)}return[...r.entries()].map(([i,o])=>({assignee:i,active:o.length,in_progress:o.filter(s=>eo(s.status,t)).length,items:o.map(s=>s.id).sort()})).sort((i,o)=>o.active-i.active).slice(0,n)}function sb(e,t,n,r){let i=new Date(n).getTime()-t*24*60*60*1e3;return e.filter(o=>new Date(o.updated_at).getTime()<i).map(o=>({id:o.id,title:o.title,status:o.status,updated_at:o.updated_at,stale_days:Math.floor((new Date(n).getTime()-new Date(o.updated_at).getTime())/(1440*60*1e3))})).sort((o,s)=>s.stale_days-o.stale_days).slice(0,r)}function ab(e,t,n,r){return e.map(i=>({item:i,sortKey:Qi(i.created_at)})).sort((i,o)=>{let s=C(o.sortKey,i.sortKey);return s!==0?s:i.item.id.localeCompare(o.item.id)}).slice(0,r).map(({item:i})=>({...$t(i,t,n),created_at:i.created_at}))}function cb(e,t,n,r){return e.filter(i=>!no(i.parent)&&!dr.has(i.type)).sort((i,o)=>Ne(i,o,t)).slice(0,r).map(i=>$t(i,t,n))}function db(e){let t=0,n=0,r=0,i=0,o=0,s=[];for(let a of e){(a.tests??[]).length>0&&t++;let c=a.test_runs??[];if(c.length>0){n++;let d=!1;for(let l of c)r+=l.passed??0,i+=l.failed??0,o+=l.skipped??0,(l.failed??0)>0&&(d=!0);d&&s.push(a.id)}}return{items_with_tests:t,items_with_recent_runs:n,recent_runs:{passed:r,failed:i,skipped:o},items_failing:s.sort()}}function Td(e){return`${new Date(e).toISOString().slice(11,16)}Z`}function Md(e){let t=e.order===null?"-":String(e.order),n=e.deadline??"-",r=e.parent?` parent:${e.parent}`:"",i=e.children_total!==void 0&&e.children_closed!==void 0&&e.completion_pct!==void 0?` children:${e.children_closed}/${e.children_total} done:${e.completion_pct}%`:"",o=e.blocked===!0?` blocked:${e.blocker_ids?.join(",")||"lifecycle"}`:"";return`${e.id} p${e.priority} ${e.status} ${e.type} order:${t} deadline:${n}${r}${i}${o} ${e.title}`}function lb(e,t){let n=e;return t.map(r=>{let i=n[r];return Array.isArray(i)?`${r}:${i.join(",")}`:`${r}:${i??"-"}`}).join(" ")}function ub(e){if("reference_only"in e){let n=e.kind==="reminder"?` \u2014 ${e.reminder_text??"reminder"}`:e.kind==="event"?` \u2014 ${e.event_title??"event"}${e.event_recurring?" (recurring)":""}`:"";return`${Td(e.at)} [${e.kind}] ${e.item_id} (see focus item)${n}`}let t=`${Td(e.at)} [${e.kind}] ${e.item_id} p${e.item_priority} ${e.item_status} ${e.item_title}`;if(e.kind==="reminder")return`${t} \u2014 ${e.reminder_text}`;if(e.kind==="event"){let n=e.event_recurring?" (recurring)":"",r=e.event_title??e.item_title;return`${t} \u2014 ${r}${n}`}return t}function Rd(e,t,n,r,i){if(e.push(`## ${t}`),n.length===0)e.push(r);else for(let o of n)e.push(`- ${i(o)}`);e.push("")}function fb(e,t,n){if(t.blocked_fallback.length!==0){e.push("## Blocked fallback");for(let r of t.blocked_fallback)e.push(`- ${n(r)}`);e.push("")}}function mb(e,t){if(e.push("## Agenda"),e.push(`- events: ${t.agenda.summary.events} (deadlines: ${t.agenda.summary.deadlines}, reminders: ${t.agenda.summary.reminders}, scheduled: ${t.agenda.summary.scheduled})`),t.agenda.events.length===0)e.push("No agenda events matched the selected filters.");else for(let n of t.agenda.events)e.push(`- ${ub(n)}`);e.push("")}function pb(e,t){if(!(!t.hierarchy||t.hierarchy.length===0)){e.push("## Hierarchy");for(let n of t.hierarchy){let r=n.children_total>0?Math.round(n.children_closed/n.children_total*100):0;e.push(`- ${n.id} ${n.type} ${n.status} "${n.title}" [${n.children_closed}/${n.children_total} done ${r}%]`);for(let i of n.children){let o=i.children_total>0?Math.round(i.children_closed/i.children_total*100):0;e.push(` - ${i.id} ${i.type} ${i.status} "${i.title}" [${i.children_closed}/${i.children_total} done ${o}%]`)}}e.push("")}}function hb(e,t){if(!(!t.progress||t.progress.length===0)){e.push("## Progress");for(let n of t.progress)e.push(`- ${n.id} "${n.title}" ${n.completion_pct}% (${n.closed}/${n.total} closed, ${n.in_progress} wip, ${n.open} open, ${n.blocked} blocked)`);e.push("")}}function gb(e,t,n,r){if(!(!t.recently_created||t.recently_created.length===0)){e.push("## Recently created");for(let i of t.recently_created)e.push(n?`- ${r(i)}`:`- ${Jy(i.created_at)} ${Md(i)}`);e.push("")}}function _b(e,t,n){if(!(!t.unparented||t.unparented.length===0)){e.push("## Unparented");for(let r of t.unparented)e.push(`- ${n(r)}`);e.push("")}}function yb(e,t){if(!(!t.activity||t.activity.length===0)){e.push("## Recent activity");for(let n of t.activity){let r=n.msg?` ${n.msg}`:"";e.push(`- ${n.ts.slice(0,16)}Z ${n.id} ${n.op} by:${n.author}${r}`)}e.push("")}}function bb(e,t){if(!(!t.blockers||t.blockers.length===0)){e.push("## Blockers");for(let n of t.blockers){let r=n.blocked_by?`blocked_by:${n.blocked_by}(${n.blocked_by_status??"?"})`:"blocked_by:-",i=n.blocked_reason?` reason:"${n.blocked_reason}"`:"",o=n.unblock_note?` unblock:"${n.unblock_note}"`:"";e.push(`- ${n.id} "${n.title}" ${r}${i}${o}`)}e.push("")}}function vb(e,t){if(!(!t.files||t.files.length===0)){e.push("## Hot files");for(let n of t.files)e.push(`- ${n.path} refs:${n.references} items:[${n.items.join(",")}]`);e.push("")}}function wb(e,t){if(!(!t.workload||t.workload.length===0)){e.push("## Workload");for(let n of t.workload){let r=n.assignee??"(unassigned)";e.push(`- ${r} active:${n.active} wip:${n.in_progress} items:[${n.items.join(",")}]`)}e.push("")}}function kb(e,t){if(!(!t.staleness||t.staleness.length===0)){e.push("## Stale items");for(let n of t.staleness)e.push(`- ${n.id} ${n.status} stale:${n.stale_days}d last:${n.updated_at.slice(0,10)} "${n.title}"`);e.push("")}}function Eb(e,t){t.tests&&(e.push("## Test health"),e.push(`- items_with_tests: ${t.tests.items_with_tests}`),e.push(`- items_with_recent_runs: ${t.tests.items_with_recent_runs}`),e.push(`- passed: ${t.tests.recent_runs.passed}, failed: ${t.tests.recent_runs.failed}, skipped: ${t.tests.recent_runs.skipped}`),t.tests.items_failing.length>0&&e.push(`- items_failing: [${t.tests.items_failing.join(",")}]`),e.push(""))}function Ib(e,t){t.summary.active_items===0&&t.summary.blocked===0&&t.agenda.summary.events===0&&(e.push("## Suggestions"),e.push("No active work items or upcoming events. Consider:"),e.push('- `pm create --type Task --title "..."` to add a new work item'),e.push("- `pm list --status closed --limit 5` to review recent completions"),e.push("- `pm search <keywords>` to find related past work"),e.push("- `pm aggregate` for a full project status overview"))}function rT(e){let t=[],n=e.focus_fields,r=o=>n?lb(o,n):Md(o);if(t.push("# pm context"),t.push(""),t.push(`- now: ${e.now}`),t.push(`- depth: ${e.depth}`),e.filters.parent&&t.push(`- scope: subtree of ${e.filters.parent}`),t.push(`- active_items: ${e.summary.active_items} (in_progress: ${e.summary.in_progress}, open: ${e.summary.open})`),e.summary.total_items!==void 0&&t.push(`- total_items: ${e.summary.total_items} (closed: ${e.summary.closed??0}, canceled: ${e.summary.canceled??0})`),t.push(`- agenda_events: ${e.summary.agenda_events}`),t.push(`- blocked_fallback_used: ${e.summary.blocked_fallback_used}`),e.extension_health){let o=e.extension_health.packages.filter(s=>s.status==="degraded").map(s=>s.name);t.push(`- extensions: ${e.extension_health.ok} ok, ${e.extension_health.degraded} degraded${o.length>0?` (${o.join(", ")})`:""}`)}let i=e.sections_included.filter(o=>o!=="blockers"||(e.blockers?.length??0)>0);if(i.length>0&&t.push(`- sections: ${i.join(", ")}`),t.push(""),Rd(t,"High-level focus",e.high_level,"No high-level active items.",r),Rd(t,"Low-level focus",e.low_level,"No low-level active items.",r),fb(t,e,r),mb(t,e),e.workspace_memory){t.push("## Workspace memory");for(let o of e.workspace_memory.rollups)t.push(`- ${o.kind}:${o.key} \u2014 ${o.label} (${o.item_count} completed, latest ${o.last_closed_at})`);t.push("")}return pb(t,e),hb(t,e),gb(t,e,n,r),_b(t,e,r),yb(t,e),bb(t,e),vb(t,e),wb(t,e),kb(t,e),Eb(t,e),Ib(t,e),t.join(`
|
|
18
|
+
`)}async function Cb(e,t){let n=O(process.cwd(),t.path),r=await F(n),i=r.context??fo.context,o=J(r.schema),s=Py(e.depth,i),a=Ny(e.limit??e.maxItems,s);return{settings:r,contextSettings:i,statusRegistry:o,depth:s,limit:a,sectionsIncluded:jy(e.section,s,i),activityLimit:Uy(e.activityLimit,i),staleThresholdDays:By(e.staleThreshold,i),parentScope:zy(e.parent),focusFields:My(e.fields),baseListOptions:Ky(e)}}function Sb(e){return e.some(t=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(t))}function Tb(e,t){return{...e,...t,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function Rb(e,t){let n=await wt(void 0,Tb(t.baseListOptions,{excludeTerminal:!1}),e),r=n.items,i=r.filter(a=>!$(a.status,t.statusRegistry)),o=r,s=xb(t.parentScope,r);return s&&(i=i.filter(a=>s.has(a.id.trim().toLowerCase())),o=o.filter(a=>s.has(a.id.trim().toLowerCase()))),{listed:n,listedItemMetadata:i,allItems:o,fullCorpus:r,subtreeIds:s}}function xb(e,t){if(e===void 0)return;let n=to(t,e);if(!n.found)throw new _(`Context --parent item not found: ${e}`,g.NOT_FOUND);return n.ids}function Db(e,t,n,r){let i=new Set(mt(e,t,n,r).containers.map(o=>o.item.id));return new Set(e.filter(o=>dr.has(o.type)||i.has(o.id)||Te(o.type,r)!=="agent").map(o=>o.id))}async function Ab(e,t,n,r,i,o,s,a,c,d,l,u,f,p,m,h){let y=[...e].sort((E,lt)=>Ne(E,lt,i)),v=await en({pmRoot:f,author:c,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),b=await cr(y,{pmRoot:f,storeKey:"context",statusRegistry:i,now:a,author:c,usageAffinity:v.affinity,claimFocus:m}),w=await ar("context",b.candidates),k=w.ranked.map(E=>E.item),S=i.active_statuses,P=k.filter(E=>S.has(R(E.status,i))),j=u?Be(P,d,l,E=>E.id):0,M=u?P.slice(j,j+s):P,Ee=u&&M.length>0&&j+M.length<P.length,N=Ee&&M.length>0?ce(l,M[M.length-1].id,j+M.length-1):void 0,B=k.filter(E=>r.has(E.id.trim().toLowerCase())),Y=new Set([...M.map(E=>E.id),...B.slice(0,s).map(E=>E.id)]),X=ro({...w,ranked:w.ranked.filter(E=>Y.has(E.id))},p,new Set(Object.entries(m??{}).filter(([,E])=>E>=1).map(([E])=>E))),te=X.included.map(E=>E.item),se=te.filter(E=>S.has(R(E.status,i))),V=te.filter(E=>r.has(E.id.trim().toLowerCase())),$e=dt(t),fr=Sb(o)?$e:void 0,q=new Map(n.map(E=>[E.id.trim().toLowerCase(),E])),H=E=>{let lt=$t(E,i,fr);return r.has(E.id.trim().toLowerCase())&&(lt.blocked=!0,lt.blocker_ids=wn(E,q,i).filter(mr=>!mr.resolved).map(mr=>mr.id)),lt},co=Db(se,n,i,h),Xd=se.filter(E=>co.has(E.id)).slice(0,u?M.length:s).map(H),Jd=se.filter(E=>!co.has(E.id)).slice(0,u?M.length:s).map(H),lo=P.length===0;return{activeItems:se,blockedItems:V,highLevel:Xd,lowLevel:Jd,blockedFallback:lo?V.slice(0,s).map(H):[],blockedFallbackUsed:lo,ranking:w,packing:X,featureStore:b,pageExtras:{...u?{applied_limit:s}:{},...Ee?{has_more:!0,truncated:!0}:{},...N?{next_cursor:N}:{}}}}function Ob(e,t){return Ie("context",{pmRoot:t,options:Wt(e,ds)})}function Lb(e,t){return e.limit!==void 0||e.maxItems!==void 0||e.after!==void 0||t>=Dd}async function Fb(e,t,n,r){let i={...t.baseListOptions,view:"agenda",include:"all",limit:t.parentScope===void 0?String(t.limit):void 0},o=await rd(i,e),s=n===void 0?o.events:o.events.filter(d=>n.has(d.item_id.trim().toLowerCase())),a=Zy(s,t.statusRegistry).slice(0,t.limit),c=a.map(d=>r.has(d.item_id)?{at:d.at,date:d.date,kind:d.kind,item_id:d.item_id,reference_only:!0,...d.kind==="reminder"?{reminder_text:d.reminder_text}:{},...d.kind==="event"?{event_title:d.event_title,event_recurring:d.event_recurring}:{}}:d);return{agenda:o,agendaEvents:c,agendaSummary:Qy(a)}}function Nd(e,t,n){let r=String(t);return e.filter(i=>R(i.status,n)===r).length}async function Mb(e){let{runtime:t,allItems:n,fullCorpus:r,blockedIds:i,focusGroups:o,now:s,global:a}=e,c=dt(n),d=n.filter(u=>!$(u.status,t.statusRegistry)),l=u=>t.sectionsIncluded.includes(u);return{hierarchy:l("hierarchy")?eb(n,o.activeItems,t.statusRegistry,t.limit):void 0,activity:l("activity")?await tb(t.activityLimit,a):void 0,progress:l("progress")?nb(n,o.activeItems,i,t.statusRegistry,t.limit):void 0,blockersSection:l("blockers")?rb(o.blockedItems,r,t.statusRegistry,t.limit):void 0,recentlyCreated:l("recently_created")?ab(d,t.statusRegistry,c,t.limit):void 0,unparented:l("unparented")?cb(d,t.statusRegistry,c,t.limit):void 0,filesSection:l("files")?ib(o.activeItems,t.limit):void 0,workload:l("workload")?ob(o.activeItems,t.statusRegistry,t.limit):void 0,staleness:l("staleness")?sb(d,t.staleThresholdDays,s,t.limit):void 0,tests:l("tests")?db(o.activeItems):void 0}}function Nb(e,t,n){let r=Q("canceled",t),i=e.filter(s=>t.active_statuses.has(R(s.status,t))),o=Nd(i,t.in_progress_status,t);return{scope:"matching_items",active_items:i.length,open:i.length-o,in_progress:o,blocked:e.filter(s=>n.has(s.id.trim().toLowerCase())).length,total_items:e.length,closed:e.filter(s=>Mt(s.status,t)).length,canceled:e.filter(s=>R(s.status,t)===r).length}}function $b(e,t,n){t.hierarchy&&(e.hierarchy=t.hierarchy),t.activity&&(e.activity=t.activity),t.progress&&(e.progress=t.progress),t.blockersSection&&(e.blockers=t.blockersSection),t.recentlyCreated&&(e.recently_created=t.recentlyCreated),t.unparented&&(e.unparented=t.unparented),t.filesSection&&(e.files=t.filesSection),t.workload&&(e.workload=t.workload),t.staleness&&(e.staleness=t.staleness),t.tests&&(e.tests=t.tests),n!==void 0&&n.length>0&&(e.warning_details=n)}function Pb(e,t){t&&(e.focus_fields=t,e.high_level=Ft(e.high_level,t),e.low_level=Ft(e.low_level,t),e.blocked_fallback=Ft(e.blocked_fallback,t),e.recently_created&&(e.recently_created=Ft(e.recently_created,t)),e.unparented&&(e.unparented=Ft(e.unparented,t)))}function jb(e,t){let n=[e.high_level,e.low_level,e.blocked_fallback,e.recently_created??[],e.unparented??[]].flat();if(t){for(let o of n)delete o.tags,delete o.tags_inherited;return}let r=new Map(n.map(o=>[o.id,o])),i=new Map(n.map(o=>[o.id,o.tags?[...o.tags].sort().join("\0"):void 0]));for(let o of n){if(!o.parent||!o.tags)continue;let s=r.get(o.parent);s&&i.get(o.id)===i.get(s.id)&&(delete o.tags,o.tags_inherited=s.id)}}function Ub(e,t,n){t.length>0||n.length>0||e.agenda.events.length>0||(e.suggestions=['pm create --type Task --title "..." to add a new work item',"pm list --status closed --limit 5 to review recent completions","pm search <keywords> to find related past work","pm aggregate for a full project status overview"])}async function Bb(e,t,n,r){try{let i=new Set(t.packing.included.map(c=>c.id)),o=t.ranking.ranked.map(c=>({id:c.id,rank:c.rank,included:i.has(c.id)})),s=new Set(o.map(c=>c.id));for(let c of Qt(e,"context"))s.has(c)||(o.push({id:c,rank:o.length+1,included:!1}),s.add(c));let a=await Zt({pmRoot:n,author:r,surface:"context",profile:t.packing.profile,rows:o,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});Jt(e,a)}catch{e.warnings=lr(e.warnings,["context_usage_feedback_write_failed"])}}async function Hb(e,t,n){if(e)return{};let r=(await go({pmRoot:t,settings:n,cwd:process.cwd(),noExtensions:!1})).discovered.map(o=>({name:o.name??o.directory,status:o.status==="ok"?"ok":"degraded"})).sort((o,s)=>o.name.localeCompare(s.name)),i=r.filter(o=>o.status==="degraded").length;return r.length===0?{}:{extension_health:{total:r.length,ok:r.length-i,degraded:i,packages:r.slice(0,20),...r.length>20?{truncated:!0}:{}}}}async function Gb(e,t){let n=Fo(),r=await xo(e),i=n.instance||Do(t);return Vc(r.semantic_attribution?.[i])}async function iT(e,t){let n=O(process.cwd(),t.path),r=await Cb(e,t),i=await Rb(t,r),o=$y(r.limit,i.fullCorpus.length),s={...r,limit:o,tokenBudget:Zi(e.tokenBudget,Math.max(256,o*160))},a=be(void 0,s.settings.author_default),c=await Gb(n,a),d=Hb(e.noExtensionHealth===!0,n,s.settings),l=ft(i.fullCorpus,s.statusRegistry),u=await Ab(i.listedItemMetadata,i.allItems,i.fullCorpus,l,s.statusRegistry,s.sectionsIncluded,s.limit,x(),a,e.after,Ob(e,n),Lb(e,i.fullCorpus.length),n,s.tokenBudget,c,L(s.settings,D())),f=await Fb(t,s,i.subtreeIds,new Set([...u.highLevel,...u.lowLevel,...u.blockedFallback].map(k=>k.id))),p=await Ed(i.fullCorpus,{pmRoot:n,statusRegistry:s.statusRegistry,now:f.agenda.now}),m=lr(i.listed.warnings,f.agenda.warnings,u.ranking.warnings,[...u.featureStore.warnings],p.warnings),h=Nd(u.activeItems,s.statusRegistry.in_progress_status,s.statusRegistry),y=u.activeItems.length-h,v=await Mb({runtime:s,allItems:i.allItems,fullCorpus:i.fullCorpus,blockedIds:l,focusGroups:u,now:f.agenda.now,global:t}),b=Nb(i.allItems,s.statusRegistry,l),w={output_default:"toon",now:f.agenda.now,depth:s.depth,sections_included:s.sectionsIncluded,window:{anchor:f.agenda.anchor,start:f.agenda.range.start,end:f.agenda.range.end,past:f.agenda.range.past,from:f.agenda.range.from,to:f.agenda.range.to},filters:{type:e.type??null,tag:e.tag??null,priority:e.priority??null,assignee:e.assignee??null,assignee_filter:e.assigneeFilter??null,sprint:e.sprint??null,release:e.release??null,limit:e.limit??e.maxItems??null,parent:s.parentScope??null,token_budget:s.tokenBudget,runtime_filters:i.listed.filters.runtime_filters??f.agenda.filters.runtime_filters??{}},summary:{returned_focus:{active_items:u.activeItems.length,in_progress:h,open:y,blocked:u.blockedItems.length},blocked_fallback_used:u.blockedFallbackUsed,high_level:u.highLevel.length,low_level:u.lowLevel.length,agenda_events:f.agendaSummary.events,...b},high_level:u.highLevel,low_level:u.lowLevel,blocked_fallback:u.blockedFallback,agenda:{summary:f.agendaSummary,events:f.agendaEvents},...u.pageExtras};return w.workspace_memory=Id(p,Math.min(800,Math.floor(s.tokenBudget*.2))),Object.assign(w,await d),$b(w,v,u.featureStore.warning_details),jb(w,e.noTags===!0),e.explainRanking===!0&&(w.ranking=oo(u.ranking,u.featureStore,new Set([...u.highLevel,...u.lowLevel,...u.blockedFallback].map(k=>k.id))),w.packing=io(u.packing)),ko(w,[...u.highLevel,...u.lowLevel,...u.blockedFallback].map(k=>({id:k.id,status:R(k.status,s.statusRegistry)===s.statusRegistry.in_progress_status?"in_progress":"open",blocked:k.blocked}))),Pb(w,s.focusFields),Eo(w),m.length>0&&(w.warnings=m),Ub(w,u.activeItems,u.blockedItems),await Bb(w,u,n,a),w}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7328ddd0-a555-56d2-9f7d-3496dad501f5")}catch{}})();function $d(e,t,n){let r={recommended:e.recommended,ready:e.ready},i=()=>Math.max(yr(r,"json"),yr(r,"toon")),o=r.ready.length+ +(r.recommended!==null),s=i(),a=s,c=r.ready;if(a>t&&(r.ready=[],a=i()),s>t&&a<=t){let u=0,f=c.length;for(;u<f;){let p=Math.ceil((u+f)/2);r.ready=c.slice(0,p),i()<=t?u=p:f=p-1}r.ready=c.slice(0,u),a=i()}let d=a>t&&r.recommended!==null;d&&(r.recommended=null,a=i()),e.recommended=r.recommended,e.ready=r.ready,e.summary.recommended=r.recommended!==null;let l=o-r.ready.length-+(r.recommended!==null);n&&l===0&&a<=t||(e.truncation={...e.truncation,...l>0?{ready_total:e.summary.ready}:{},ready_budget:{scope:"recommended_and_ready",budget_tokens:t,estimated_tokens:a,within_budget:a<=t,omitted_count:l,recommendation_omitted:d,restore_budget_tokens:s}},d&&(e.suggestions=[`Ready work exists but the selection budget omitted the recommendation. Retry pm next --token-budget ${s}; use --output-budget to bound the entire response.`]))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f610c3be-8212-56de-86d4-2b5b9752b87c")}catch{}})();var Kb=["markdown","toon","json"],zb=5,Vb=1440*60*1e3;function qb(e){if(!e)return;let t=e.trim().toLowerCase();if(!Kb.includes(t))throw new _("Next format must be one of markdown|toon|json",g.USAGE);return t}function yT(e,t){let n=qb(e.format);if(t.json&&n&&n!=="json")throw new _("Cannot combine --json with --format markdown|toon",g.USAGE);return t.json?"json":n??"toon"}function Pd(e,t,n){let r=ie(e,t);return r===void 0||r<=0?n:r}function Pt(e,t,n,r){return{...$t(e.item,t,n),open_blocker_count:e.open_blockers.length,blockers:e.open_blockers.map(i=>({id:i.id,title:i.title,status:i.status,...i.external?{external:!0}:{},...i.blocked_since?{blocked_since:i.blocked_since}:{},...i.external?{resolver:i.resolver??null}:{}})),unblocks:e.unblocks,rank:r}}function Wb(e,t,n,r){let i=e.item,o=[],s=Q("in_progress",t);return o.push(R(i.status,t)===s?"resume work":"ready"),r&&o.push("completed container \u2014 governance closeout"),o.push(`p${i.priority}${i.priority===0?" (highest)":""}`),typeof i.deadline=="string"&&i.deadline.trim().length>0&&o.push(Yb(i.deadline,n)),o.push(De(i).length>0?"all blockers resolved":"no blockers"),typeof i.parent=="string"&&i.parent.trim().length>0&&o.push(`advances ${i.parent.trim()}`),e.unblocks.length>0&&o.push(`unblocks ${e.unblocks.length} item(s)`),o}function jd(e,t,n){let r=be(n,t),i=[],o=[];for(let s of e){let a=typeof s.item.assignee=="string"?s.item.assignee.trim():"";a.length>0&&a!==r?o.push({id:s.item.id,assignee:a}):i.push(s)}return{available:i,held:o}}var bT={partitionCallerOwnedReady:jd,resolveNextCallerAuthor:(e,t)=>Ud(e,t)};function vT(e,t,n){let r=e.filter(i=>Te(i.item.type,n)==="human");return{agent:t?e:e.filter(i=>Te(i.item.type,n)!=="human"),decisions:t?[]:r}}function Yb(e,t){let n=Date.parse(e);if(!Number.isFinite(n))return`deadline ${e.trim()}`;let r=new Date(n).toISOString().slice(0,10),i=new Date(Date.parse(t)).toISOString().slice(0,10),o=Math.round((Date.parse(r)-Date.parse(i))/Vb);return o<0?`deadline ${r} (overdue ${-o}d)`:o===0?`deadline ${r} (due today)`:`deadline ${r} (in ${o}d)`}function Xb(e,t){let n=Q("in_progress",t);return e.filter(r=>R(r.status,t)===n).length}function so(e,t){return(t.get(e.id.trim().toLowerCase())??[]).length>0}function Jb(e,t){return{type:e.type,tag:e.tag,priority:typeof e.priority=="number"?String(e.priority):e.priority,assignee:e.assignee,assigneeFilter:e.assigneeFilter,sprint:e.sprint,release:e.release,noTruncate:!0,...t}}function ur(e,t,n){return[...e].sort((r,i)=>{let o=so(r.item,t),s=so(i.item,t);return o!==s?Number(o)-Number(s):Ne(r.item,i.item,n)})}function Qb(e){return e.projectedReady.length===0?null:{...e.readyRows[0],reasons:Wb(e.projectedReady[0],e.statusRegistry,e.now,e.completedContainer)}}function Zb(e,t,n){if(e!==null)return;let r=n>0?["No executable recommendation: outcome gates require verification. Inspect gate_needed, or use pm next --include-gates to opt in."]:[];if(t.length>0){let i=t.find(o=>o.blockers.length>0);return[...r,i?`${t.length} item(s) are blocked; unblock the top one by closing ${i.blockers.map(o=>o.id).join(", ")}`:`${t.length} item(s) are blocked; add blocker context or move the top item back to an active status`,"pm next --ready-only after a blocker closes to re-check ready work",'pm create --type Task --title "..." to add new ready work']}return[...r,'pm create --type Task --title "..." to add a new work item',"pm list --status in_progress to review work already underway","pm context --depth deep for the full project snapshot"]}function ev(e,t,n,r){let i={};return e>r&&(i.decision_needed_total=e),t>r&&(i.held_by_others_total=t),n>r+1&&(i.ready_total=n),Object.keys(i).length>0?i:void 0}async function tv(e){try{let t=new Set([...e.result.recommended?[e.result.recommended.id]:[],...e.result.ready.map(o=>o.id)]),n=e.ranking.ranked.map(o=>({id:o.id,rank:o.rank,included:t.has(o.id)})),r=new Set(n.map(o=>o.id));for(let o of Qt(e.result,"next"))r.has(o)||(n.push({id:o,rank:n.length+1,included:!1}),r.add(o));let i=await Zt({pmRoot:e.pmRoot,author:e.author,surface:"next",profile:"next",rows:n,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});Jt(e.result,i)}catch{e.result.warnings=lr(e.result.warnings,["context_usage_feedback_write_failed"])}}async function nv(e){let t=[...new Set([...e.candidatesWarnings??[],...e.corpusWarnings??[],...e.readyRanking.warnings??[],...e.featureStore.warnings])].sort((n,r)=>n.localeCompare(r));return t.length>0&&(e.result.warnings=t),e.result.suggestions=Zb(e.recommended,e.blockedRows,e.gateCount),e.tokenBudget!==void 0&&$d(e.result,e.tokenBudget,e.hasIntentBudget),e.explainRanking&&(e.result.ranking=oo(e.readyRanking,e.featureStore,new Set([...e.result.recommended?[e.result.recommended.id]:[],...e.result.ready.map(n=>n.id)])),e.result.packing=io(ro(e.readyRanking,e.packingBudget,new Set,"next"))),await tv({result:e.result,pmRoot:e.pmRoot,author:e.author,ranking:e.readyRanking}),e.result}function rv(e,t,n){if(!n)return e;let r=to(t,n);if(!r.found)throw new _(`Next --parent item not found: ${n}`,g.NOT_FOUND);return e.filter(i=>r.ids.has(i.id.trim().toLowerCase()))}async function iv(e,t,n,r,i,o,s){let a=e.filter(p=>!so(p.item,t)),c=s||a.length===0?e:a,d=await en({pmRoot:o,author:i,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),l=await cr(c.map(p=>p.item),{pmRoot:o,storeKey:"next",statusRegistry:n,now:r,author:i,usageAffinity:d.affinity}),u=await ar("next",l.candidates),f=new Map(c.map(p=>[p.item.id,p]));return{projectedReady:u.ranked.map(p=>f.get(p.id)).filter(p=>p!==void 0),ranking:u,completedContainer:a.length===0&&!s,featureStore:l}}function Ud(e,t){let n=e.assignee?.trim();return be(e.callerAuthor??(n&&n.length>0?n:void 0),t)}async function wT(e,t){let n=O(process.cwd(),t.path),r=await F(n),i=Ud(e,r.author_default),o=J(r.schema),s=L(r,D()),a=x(),c=Pd(e.limit,"--limit",zb),d=Zi(e.tokenBudget,Math.max(192,c*128)),l=Pd(e.blockedLimit,"--blocked-limit",c),u=e.readyOnly===!0,f=typeof e.parent=="string"?e.parent.trim():"",p=await wt(void 0,Jb(e,{excludeTerminal:!0}),t),m=await wt(void 0,{excludeTerminal:!1,noTruncate:!0},t),h=rv(p.items,m.items,f),y=m.items,v=mt(h,y,o,s),b=dt(y),w=Or(v,o,e,s),k=jd(w.ready,r.author_default,i),S=ur(k.available,b,o),P=[...v.blocked].sort((q,H)=>Ne(q.item,H.item,o)),{projectedReady:j,ranking:M,completedContainer:Ee,featureStore:N}=await iv(S,b,o,a,i,n,e.includeContainers===!0),B=j.map((q,H)=>Pt(q,o,b,H+1)),Y=P.map((q,H)=>Pt(q,o,b,H+1)),X=ur(w.decisions,b,o).map((q,H)=>Pt(q,o,b,H+1)),te=ur(w.gates,b,o).map((q,H)=>Pt(q,o,b,H+1)),se=ur(v.containers,b,o).map((q,H)=>Pt(q,o,b,H+1)),V=Qb({projectedReady:j,readyRows:B,statusRegistry:o,now:a,completedContainer:Ee}),$e=ev(X.length,k.held.length,B.length,c)??{};te.length>c&&($e.gate_needed_total=te.length),se.length>c&&($e.containers_total=se.length);let fr={output_default:"toon",now:a,recommended:V,ready:B.slice(1,c+1),decision_needed:X.slice(0,c),gate_needed:te.slice(0,c),containers:se.slice(0,c),blocked:u?[]:Y.slice(0,l),held_by_others:k.held.slice(0,c),summary:{recommended:V!==null,ready:B.length,blocked:Y.length,in_progress:Xb(B,o),candidates:v.active_count,containers:v.container_count,decision_needed:X.length,gate_needed:te.length,held_by_others:k.held.length},filters:{type:e.type??null,tag:e.tag??null,priority:e.priority??null,assignee:e.assignee??null,assignee_filter:e.assigneeFilter??null,sprint:e.sprint??null,release:e.release??null,parent:f.length>0?f:null,limit:c,blocked_limit:l,ready_only:u,include_decisions:e.includeDecisions===!0,include_gates:e.includeGates===!0,include_containers:e.includeContainers===!0,token_budget:d},truncation:Object.keys($e).length>0?$e:void 0};return nv({result:fr,recommended:V,blockedRows:Y,gateCount:te.length,candidatesWarnings:p.warnings,corpusWarnings:m.warnings,readyRanking:M,explainRanking:e.explainRanking===!0,pmRoot:n,author:i,packingBudget:d,featureStore:N,tokenBudget:e.tokenBudget===void 0?void 0:d,hasIntentBudget:typeof e.for=="string"})}function kT(e){let t=["# pm next","",...ov(e)];for(let[n,r]of[["Gate verification needed",e.gate_needed],["Containers",e.containers]])r&&r.length>0&&t.push(...jt(n,r.map(i=>`- ${Ut(i)}`),""));if(t.push(...jt("Recommended",sv(e.recommended),e.truncation?.ready_budget?.recommendation_omitted?"Recommendation omitted by the selection budget; ready work still exists.":"No ready work.")),t.push(...jt("Decision needed",(e.decision_needed??[]).map(n=>`- ${Ut(n)}`),"No human-gated decisions.")),t.push(...jt("Ready",e.ready.map(n=>`- ${Ut(n)}`),"No ready items.")),e.filters.ready_only||t.push(...jt("Blocked",e.blocked.map(n=>`- ${av(n)}`),"No blocked items.")),e.suggestions&&e.suggestions.length>0){t.push("## Suggestions");for(let n of e.suggestions)t.push(`- ${n}`)}return t.join(`
|
|
19
|
+
`).trimEnd()}function ov(e){let t=[`- now: ${e.now}`,`- ready: ${e.summary.ready} (in_progress: ${e.summary.in_progress}), blocked: ${e.summary.blocked}, candidates: ${e.summary.candidates}`];return e.filters.parent&&t.push(`- scope: subtree of ${e.filters.parent}`),t.push(""),t}function sv(e){return e?[`- ${Ut(e)}`,` why: ${e.reasons.join("; ")}`]:[]}function jt(e,t,n){return[`## ${e}`,...t.length===0?[n]:t,""]}function av(e){let t=e.blockers.map(n=>`${n.id}(${n.status??"?"})`).join(", ");return`${Ut(e)} blocked_by:${t}`}function Ut(e){let t=e.deadline??"-",n=e.parent?` parent:${e.parent}`:"",r=e.unblocks.length>0?` unblocks:${e.unblocks.length}`:"";return`${Number.isInteger(e.rank)?`#${e.rank} `:""}${e.id} p${e.priority} ${e.status} ${e.type} deadline:${t}${n}${r} ${e.title}`}import{createHash as cv}from"node:crypto";import{setTimeout as dv}from"node:timers/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3483e997-6bee-52bf-a048-8fe5c2427d06")}catch{}})();var Hd=1,Gd=/^[A-Za-z0-9_-]+$/,lv=100,Bd=1e3,uv=250,FT=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function oe(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,i)=>r.localeCompare(i));return n.length===0?void 0:n}function Kd(e){return cv("sha256").update(I({type:oe(e.type),author:oe(e.author),item:oe(e.item),harness:oe(e.harness),agent_instance:oe(e.agentInstance),provenance:oe(e.provenanceFilter)})).digest("hex").slice(0,24)}function ao(e,t){let n={version:Hd,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function zd(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Hd,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function Vd(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Gd.test(n))throw new _("Invalid mutation event cursor.",g.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new _("Invalid mutation event cursor.",g.USAGE,{code:"invalid_event_cursor"})}if(!zd(r,t))throw new _("Mutation event cursor does not match this query.",g.USAGE,{code:"event_cursor_query_mismatch"});return r}function qd(e){let t=e??lv;if(!Number.isSafeInteger(t)||t<0||t>Bd)throw new _(`Mutation event limit must be an integer from 0 to ${Bd}.`,g.USAGE,{code:"invalid_event_limit"});return t}function Wd(e){return e instanceof Error&&e.name==="AbortError"}function Yd(e,t){let n=e?.trim();if(!n)return{};if(Gd.test(n))return{cursor:Vd(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new _("Mutation event --since must be an event cursor or ISO timestamp.",g.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function fv(e,t){let n=await kr(e,t);if(n===null){if(!await $o(e))return{...await Po(e,t),source:"authoritative_history"};n=await kr(e,t)}if(n===null)throw new _("Mutation event index could not be opened after rebuild.",g.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function mv(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new _("Mutation event cursor mode must be batch or row.",g.USAGE,{code:"invalid_event_cursor_mode"});return t}async function pv(e={}){let t=O(e.cwd??process.cwd(),e.pmRoot);await U(t);let n=qd(e.limit),r=mv(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new _("Mutation event projections are mutually exclusive. Use --provenance or --full.",g.USAGE);let i=await F(t),o=i.agent_identity.identity_vocabulary,s=nr(i.agent_identity.harness_signals),a=Hi({provenance:e.provenanceFilter},s),c=oe(e.harness),d=Kd(e),{cursor:l,sinceTimestamp:u}=Yd(e.since,d),f={...l?{after_ts:l.ts,after_stream_id:l.stream_id,after_stream_offset:l.stream_offset}:u?{since_ts:u}:{},ops:oe(e.type),authors:oe(e.author),harnesses:c,harness_alias_authors:c?Object.entries(o.aliases).filter(([,h])=>c.includes(h)).map(([h])=>h):void 0,agent_instances:oe(e.agentInstance),provenance:[...a].map(([h,y])=>({dimension:h,values:[...y]})),stream_ids:oe(e.item),limit:n},p=await fv(t,f),m=p.events.map(h=>({...r==="row"?{cursor:ao(h,d)}:{},item_id:h.stream_id,version:h.stream_offset+1,ts:h.entry.ts,author:h.entry.author,type:h.entry.op,...h.entry.message===void 0?{}:{message:h.entry.message},patch_count:h.entry.patch.length,...e.full===!0?{entry:h.entry}:{},...e.provenance===!0?{provenance:rr(h.entry,o,{itemId:h.stream_id,version:h.stream_offset+1})}:{}}));return{events:m,count:m.length,has_more:p.has_more,cursor_mode:r,...p.events.length===0?{}:{next_cursor:ao(p.events[p.events.length-1],d)},source:p.source,...e.provenanceSummary===!0?{provenance_summary:ir(p.events.map(h=>h.entry),o,s)}:{}}}async function*hv(e={}){let t=e.intervalMs??uv;if(!Number.isSafeInteger(t)||t<10)throw new _("Mutation event follow interval must be an integer of at least 10ms.",g.USAGE,{code:"invalid_event_follow_interval"});let n=e.since;for(;e.signal?.aborted!==!0;){let r=await pv({...e,cursorMode:e.cursorMode??"batch",since:n});if(yield r.next_cursor===void 0&&n!==void 0?{...r,next_cursor:n}:r,r.events.length>0){n=r.next_cursor;continue}try{await dv(t,void 0,{signal:e.signal})}catch(i){if(Wd(i))return;throw i}}}async function*MT(e={}){for await(let t of hv({...e,cursorMode:"row"}))for(let n of t.events)yield n}var NT={decodeMutationEventCursor:Vd,encodeMutationEventCursor:ao,eventQueryFingerprint:Kd,isAbortError:Wd,isMutationEventCursorEnvelope:zd,parseMutationEventLimit:qd,resolveMutationEventStart:Yd};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f091d0c3-f2a7-5d76-8656-4aebe82e9798")}catch{}})();function PT(e,t){let n=t??{};return e.filter(r=>n[r.id]!==r.updated_at).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}export{Rr as a,hn as b,zv as c,Vv as d,yn as e,_n as f,_s as g,Xv as h,Te as i,dl as j,De as k,vn as l,bs as m,wn as n,ft as o,Or as p,mt as q,ie as r,kn as s,ws as t,Lr as u,pt as v,ks as w,Es as x,Ms as y,Gr as z,$s as A,zw as B,Vw as C,Us as D,Bs as E,Ww as F,fl as G,_w as H,ml as I,yw as J,bw as K,vw as L,ww as M,_l as N,z as O,Ts as P,In as Q,xw as R,Mr as S,Dw as T,_t as U,Tl as V,xl as W,$r as X,Dl as Y,Je as Z,Pr as _,jr as $,Ll as aa,Ur as ba,jw as ca,Uw as da,Bw as ea,Hw as fa,ru as ga,Xs as ha,zs as ia,Vs as ja,cu as ka,du as la,lu as ma,wt as na,Sn as oa,zr as pa,Tn as qa,x0 as ra,da as sa,me as ta,J0 as ua,ga as va,_a as wa,ya as xa,ba as ya,va as za,Ln as Aa,ka as Ba,tt as Ca,Ea as Da,Ta as Ea,Nn as Fa,Ra as Ga,xa as Ha,Um as Ia,Ba as Ja,jn as Ka,ni as La,Un as Ma,Ha as Na,Ka as Oa,ri as Pa,It as Qa,Va as Ra,oi as Sa,si as Ta,ai as Ua,qa as Va,ci as Wa,Ya as Xa,Xa as Ya,Qa as Za,fp as _a,iE as $a,JI as ab,Pc as bb,PT as cb,sc as db,ac as eb,lE as fb,jp as gb,st as hb,T as ib,Re as jb,vE as kb,wE as lb,Hp as mb,Kp as nb,kE as ob,EE as pb,FE as qb,gc as rb,Vn as sb,Ri as tb,eI as ub,Xn as vb,Mh as wb,tI as xb,nI as yb,rI as zb,iI as Ab,$h as Bb,Tc as Cb,Qh as Db,ag as Eb,kC as Fb,EC as Gb,zc as Hb,xC as Ib,DC as Jb,AC as Kb,OC as Lb,Vc as Mb,jC as Nb,UC as Ob,BC as Pb,rd as Qb,tr as Rb,nr as Sb,Hi as Tb,rr as Ub,VC as Vb,Gi as Wb,ir as Xb,rS as Yb,cd as Zb,dd as _b,At as $b,zi as ac,sr as bc,L_ as cc,fd as dc,P_ as ec,ar as fc,j_ as gc,U_ as hc,K_ as ic,z_ as jc,uS as kc,V_ as lc,md as mc,Vi as nc,qi as oc,ny as pc,cy as qc,kS as rc,Wi as sc,Yi as tc,cr as uc,vd as vc,IS as wc,hy as xc,by as yc,Ed as zc,Sy as Ac,Id as Bc,Ty as Cc,FS as Dc,Ry as Ec,My as Fc,Ft as Gc,nT as Hc,Zi as Ic,Py as Jc,jy as Kc,to as Lc,Ne as Mc,ro as Nc,io as Oc,oo as Pc,dt as Qc,$t as Rc,lr as Sc,rT as Tc,jb as Uc,iT as Vc,Kb as Wc,yT as Xc,bT as Yc,vT as Zc,wT as _c,kT as $c,FT as ad,pv as bd,hv as cd,MT as dd,NT as ed};
|
|
20
|
+
//# sourceMappingURL=chunk-AJ7H6XUF.js.map
|