@unbrained/pm-cli 2026.10.4 → 2026.10.6
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 +37 -1
- package/dist/cli/after-command-context-usage.js +1 -1
- package/dist/cli/argv-utils.js +1 -1
- package/dist/cli/bootstrap-args.js +1 -1
- package/dist/cli/bundle-integrity.js +2 -2
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/commander-usage.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-SMKHR6BM.js → chunk-25EW53VO.js} +89 -88
- package/dist/cli-bundle/chunks/chunk-3CCVTV6Q.js +8 -0
- package/dist/cli-bundle/chunks/chunk-3REXBTST.js +3 -0
- package/dist/cli-bundle/chunks/chunk-4WB55TBC.js +80 -0
- package/dist/cli-bundle/chunks/{chunk-7CE2DJMA.js → chunk-6STTPXOC.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-ATB4ZZBQ.js +20 -0
- package/dist/cli-bundle/chunks/chunk-D4G43LBV.js +238 -0
- package/dist/cli-bundle/chunks/chunk-K6D6DMRT.js +31 -0
- package/dist/cli-bundle/chunks/chunk-KIRHWPZB.js +2 -0
- package/dist/cli-bundle/chunks/chunk-O67BH435.js +6 -0
- package/dist/cli-bundle/chunks/chunk-R7CG2DB7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-RJHLD64E.js +3 -0
- package/dist/cli-bundle/chunks/chunk-TUKO5NF7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-UZ7BIUCI.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-GZMWISWW.js → chunk-XJD47LUH.js} +3 -3
- package/dist/cli-bundle/chunks/{register-list-query-QBGXO5JJ.js → register-list-query-53WYLNZT.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-34XXUBVI.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-WANO6EIM.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-WT37UPBQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-6KFKQD2D.js +165 -0
- package/dist/cli-bundle/focused-chunks/chunk-FOHRPFIT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GRQXL5G5.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-467EW5RL.js → chunk-JZ4WGUVH.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-NM3PM6O6.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-OT7HK7SG.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-Q6DJ5DFQ.js → chunk-PCLU34KB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HFAW3FJQ.js → chunk-PSXFFQFT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QQIE4L42.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RPUNVKXK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RXSVJPZ7.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-SPN5QTZ3.js +30 -0
- package/dist/cli-bundle/focused-chunks/chunk-SUZJNPGB.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-W4BG5HHS.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y5HXFDTZ.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZK5SOOPC.js +75 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZQK2XUSS.js +12 -0
- package/dist/cli-bundle/main.js +25 -25
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +25 -24
- 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.d.ts +2 -0
- 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.d.ts +5 -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.d.ts +2 -2
- 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.d.ts +2 -0
- package/dist/sdk/extension/managed-state.js +2 -2
- package/dist/sdk/extension/managed-update-status.d.ts +3 -0
- package/dist/sdk/extension/managed-update-status.js +2 -0
- 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.d.ts +2 -6
- package/dist/sdk/extension/source-resolution.js +1 -1
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/extension/update-check.d.ts +10 -0
- package/dist/sdk/extension/update-check.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -1
- package/dist/sdk/extension-contracts.js +1 -1
- package/dist/sdk/extension.d.ts +4 -0
- 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.d.ts +2 -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/DEVELOPMENT_DEPENDENCY_SECURITY.md +36 -0
- package/docs/GET_READ_EVIDENCE.md +84 -0
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
- package/docs/PR_REVIEW_LOOP.md +21 -4
- package/docs/README.md +3 -0
- package/docs/RELEASING.md +18 -0
- package/docs/SDK_CONFIGURATION_SAFETY.md +123 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +3 -3
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
- package/marketplace.json +2 -2
- package/package.json +3 -3
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/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-7O4NUJVO.js +0 -2
- 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-JCVMOSWQ.js +0 -2
- 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
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1433b417-e41f-5963-a551-094132afd717")}catch{}})();import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{recordClaimedWorkAttribution,recordFocusedWorkAttribution,releaseClaimedWorkAttribution}from"../../core/session/session-state.js";import{locateItem,readLocatedItem}from"../../core/store/item-store.js";const MAX_SEMANTIC_LINEAGE_DEPTH=16;async function resolveSemanticLineageIds(pmRoot,settings,itemId){const typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,lineage=[],seen=new Set;let cursor=itemId;for(;cursor&&lineage.length<MAX_SEMANTIC_LINEAGE_DEPTH;){const normalized=cursor.trim().toLowerCase();if(!normalized||seen.has(normalized))break;seen.add(normalized);const located=await locateItem(pmRoot,cursor,settings.id_prefix,settings.item_format,typeToFolder);if(!located)break;const loaded=await readLocatedItem(located,{schema:settings.schema});lineage.push(loaded.document.metadata.id),cursor=loaded.document.metadata.parent}return lineage}async function recordClaimSemanticAttribution(params){await recordClaimedWorkAttribution({pmRoot:params.pmRoot,principal:params.principal,itemId:params.itemId,lineageIds:await resolveSemanticLineageIds(params.pmRoot,params.settings,params.itemId)})}async function recordReleaseSemanticAttribution(params){await releaseClaimedWorkAttribution(params)}async function recordFocusSemanticAttribution(params){await recordFocusedWorkAttribution({pmRoot:params.pmRoot,principal:params.principal,...params.itemId?{itemId:params.itemId,lineageIds:await resolveSemanticLineageIds(params.pmRoot,params.settings,params.itemId)}:{}})}const SEMANTIC_ATTRIBUTION_LIMITS={lineage_depth:MAX_SEMANTIC_LINEAGE_DEPTH,active_items:64,evidence_rows:32};function semanticAttributionAffinity(attribution){if(!attribution)return;const affinity={};for(const itemId of attribution.active_item_ids)affinity[itemId]=1;attribution.focused_item_id&&(affinity[attribution.focused_item_id]=1);for(const evidence of attribution.evidence){const lineage=/^lineage:(.+)$/u.exec(evidence)?.[1];lineage&&affinity[lineage]===void 0&&(affinity[lineage]=.75)}return Object.keys(affinity).length>0?affinity:void 0}export{SEMANTIC_ATTRIBUTION_LIMITS,recordClaimSemanticAttribution,recordFocusSemanticAttribution,recordReleaseSemanticAttribution,resolveSemanticLineageIds,semanticAttributionAffinity};
|
|
2
2
|
//# sourceMappingURL=semantic-session-attribution.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0a4abc17-0fcb-573f-8f89-6e505e112261")}catch{}})();import{finalizeContextUsageDelivery}from"../context-usage.js";async function finalizeContextUsageEgress(pmRoot,projected,finalize=finalizeContextUsageDelivery){try{await finalize({pmRoot,result:projected})}catch{if(typeof projected=="object"&&projected!==null&&!Array.isArray(projected)){const record=projected,warnings=Array.isArray(record.warnings)?record.warnings.filter(warning=>typeof warning=="string"):[];record.warnings=[...new Set([...warnings,"context_usage_feedback_write_failed"])].sort()}}}export{finalizeContextUsageEgress};
|
|
2
2
|
//# sourceMappingURL=usage-egress.js.map
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
`)
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="71b65888-baa5-5c5f-a02c-4a0fd818fadb")}catch{}})();import{randomUUID}from"node:crypto";import{constants}from"node:fs";import{lstat,mkdir,open,rename,rm}from"node:fs/promises";import path from"node:path";import{isFileMissingError}from"../../core/fs/fs-utils.js";import{acquireLock}from"../../core/lock/lock.js";const CONTEXT_USAGE_LIMITS={max_serving_rows:256,max_bytes:262144,max_event_bytes:32768,retained_byte_fraction:.5,max_events:2048,retention_days:30};class ContextUsageValidationError extends TypeError{code="context_usage_validation_failed";constructor(message){super(message),this.name="ContextUsageValidationError"}}function resolveNow(options){const ms=Date.parse(options.now??new Date().toISOString());if(!Number.isFinite(ms))throw new ContextUsageValidationError("Context usage now must be a valid timestamp");return{iso:new Date(ms).toISOString(),ms}}function bounds(options){const maxBytes=options.maxBytes??CONTEXT_USAGE_LIMITS.max_bytes,maxEvents=options.maxEvents??CONTEXT_USAGE_LIMITS.max_events,retentionDays=options.retentionDays??CONTEXT_USAGE_LIMITS.retention_days;if(!Number.isSafeInteger(maxBytes)||maxBytes<1024||maxBytes>CONTEXT_USAGE_LIMITS.max_bytes||!Number.isSafeInteger(maxEvents)||maxEvents<1||!Number.isFinite(retentionDays)||retentionDays<=0)throw new ContextUsageValidationError("Context usage retention requires positive maxEvents and retentionDays, and maxBytes from 1024 through 262144");return{maxBytes,maxEvents,cutoff:resolveNow(options).ms-retentionDays*864e5}}async function openLedger(target,flags){if(!(await lstat(path.dirname(target))).isDirectory())throw new ContextUsageValidationError("Context usage runtime must be a real directory");try{if((await lstat(target)).isSymbolicLink())throw new ContextUsageValidationError("Context usage ledger must not be a symbolic link")}catch(error){if(!isFileMissingError(error))throw error}const handle=await open(target,flags|constants.O_NOFOLLOW|constants.O_NONBLOCK,384);try{const metadata=await handle.stat();if(!metadata.isFile()||metadata.nlink!==1)throw new ContextUsageValidationError("Context usage ledger must be an unshared regular file");return handle}catch(error){throw await handle.close(),error}}async function readEvents(options){const policy=bounds(options);try{const handle=await openLedger(path.join(options.pmRoot,"runtime","context-usage.jsonl"),constants.O_RDONLY);try{const size=(await handle.stat()).size,start=Math.max(0,size-policy.maxBytes),buffer=Buffer.alloc(Math.min(size,policy.maxBytes)),{bytesRead}=await handle.read(buffer,0,buffer.length,start),text=buffer.subarray(0,bytesRead).toString("utf8");return(start>0?text.includes(`
|
|
2
|
+
`)?text.slice(text.indexOf(`
|
|
3
|
+
`)+1):"":text).split(`
|
|
4
|
+
`).flatMap(line=>{try{const event=JSON.parse(line);return event&&Date.parse(event.at)>=policy.cutoff?[event]:[]}catch{return[]}}).slice(-policy.maxEvents)}finally{await handle.close()}}catch{return[]}}function retainedText(events,byteLimit,maxEvents){const lines=[];let bytes=0;for(let index=events.length-1;index>=0&&lines.length<maxEvents;index-=1){const line=`${JSON.stringify(events[index])}
|
|
5
|
+
`;if(bytes+=Buffer.byteLength(line),bytes>byteLimit)break;lines.push(line)}return lines.reverse().join("")}async function appendEvents(options,events,deliveryServeId){const policy=bounds(options),target=path.join(options.pmRoot,"runtime","context-usage.jsonl"),retainedBytes=Math.floor(policy.maxBytes*CONTEXT_USAGE_LIMITS.retained_byte_fraction),eventLimit=Math.min(CONTEXT_USAGE_LIMITS.max_event_bytes,retainedBytes);if(events.some(event=>Buffer.byteLength(`${JSON.stringify(event)}
|
|
6
|
+
`)>eventLimit))throw new ContextUsageValidationError("Context usage event exceeds the declared byte ceiling");const current=events.filter(event=>Date.parse(event.at)>=policy.cutoff),appended=retainedText(current,retainedBytes,policy.maxEvents),lockStarted=performance.now(),releaseLock=await acquireLock(options.pmRoot,"context-usage-ledger",30,`context-usage:${process.pid}`,!1,!1,3e3),lockWaitMs=performance.now()-lockStarted;try{await mkdir(path.dirname(target),{recursive:!0});let handle=await openLedger(target,constants.O_WRONLY|constants.O_CREAT|constants.O_APPEND);try{const size=(await handle.stat()).size,previous=deliveryServeId===void 0?void 0:await readEvents(options);if(previous?.some(event=>event.kind==="delivery"&&event.serve_id===deliveryServeId))return{written_bytes:0,ledger_bytes:size,compacted:!1,lock_wait_ms:lockWaitMs};if(!(options.maxEvents!==void 0||options.retentionDays!==void 0)&&size+Buffer.byteLength(appended)<=policy.maxBytes)return await handle.writeFile(appended,"utf8"),{written_bytes:Buffer.byteLength(appended),ledger_bytes:size+Buffer.byteLength(appended),compacted:!1,lock_wait_ms:lockWaitMs};const retained=retainedText([...previous??await readEvents(options),...current],retainedBytes,policy.maxEvents),temporary=`${target}.${process.pid}.${randomUUID()}.tmp`,replacement=await open(temporary,"wx",384);try{try{await replacement.writeFile(retained,"utf8")}finally{await replacement.close()}return await handle.close(),handle=void 0,await rename(temporary,target),{written_bytes:Buffer.byteLength(retained),ledger_bytes:Buffer.byteLength(retained),compacted:!0,lock_wait_ms:lockWaitMs}}finally{await rm(temporary,{force:!0})}}finally{await handle?.close()}}finally{await releaseLock()}}export{CONTEXT_USAGE_LIMITS,ContextUsageValidationError,appendEvents,readEvents,resolveNow};
|
|
4
7
|
//# sourceMappingURL=usage-ledger.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="aa8baa4d-a287-5be7-8429-69bb5ace633f")}catch(e2){}})();import{AsyncLocalStorage}from"node:async_hooks";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]);const activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase();const intent=declaration.intent.trim().toLowerCase();const key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent)){throw new TypeError(`Invalid context intent command or name: ${key}`)}if(declaration.description.trim().length===0){throw new TypeError(`Context intent ${key} requires a non-empty description`)}if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0){throw new TypeError(`Context intent ${key} requires a positive integer token_budget`)}const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0){throw new TypeError(`Context intent ${key} requires included_field_groups`)}return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:false},{source:"package",contracts:packageContracts,allowOverride:false},{source:"workspace",contracts:workspaceContracts,allowOverride:true}];const composed=new Map;const keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source);const key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key)){throw new TypeError(`Duplicate context intent declaration: ${key}`)}keysSeenWithinLayer.add(key);if(!layer.allowOverride&&composed.has(key)){throw new TypeError(`Duplicate context intent declaration: ${key}`)}composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase();const normalizedIntent=intent.trim().toLowerCase();const exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return void 0;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1));previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate;const attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent];const suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion];const suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget)=>{if(projected.section===void 0&&projected.depth===void 0){projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]}if(projected.depth===void 0){projected.depth=contract.intent==="handoff"?"deep":"standard"}const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget);const budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget);const requestedLimit=parsePositiveIntentTokenBudget(projected.limit);const derivedLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));if(projected.limit===void 0||requestedLimit!==void 0){projected.limit=derivedLimit}if(projected.activityLimit===void 0){projected.activityLimit=derivedLimit}},get:projected=>{if(projected.depth===void 0&&projected.fields===void 0){projected.depth="standard"}},list:(projected,contract,explicitTokenBudget)=>{if(projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0){projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by"}const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget);const budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget);const requestedLimit=parsePositiveIntentTokenBudget(projected.limit);if(projected.limit===void 0||requestedLimit!==void 0){projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit))}},next:projected=>{if(projected.readyOnly===void 0)projected.readyOnly=true},search:(projected,contract,explicitTokenBudget)=>{if(projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0){projected.compact=true}const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget);const budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget);const requestedLimit=parsePositiveIntentTokenBudget(projected.limit);if(projected.limit===void 0||requestedLimit!==void 0){projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit))}}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!=="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search")){throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]})}if(options.tokenBudget!==void 0||options.token_budget===void 0){return options}const projected2={...options,tokenBudget};delete projected2.token_budget;return projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments);const explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0;const projected={...options};if(projected.tokenBudget===void 0&&tokenBudget!==void 0){projected.tokenBudget=tokenBudget}delete projected.token_budget;if(projected.tokenBudget===void 0){projected.tokenBudget=String(contract.token_budget)}CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget);return projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"};const MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){if(Array.isArray(value)){return value.map(compactContextIntentValue)}if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactContextIntentValue(entry)]))}return typeof value==="string"&&value.length>240?`${value.slice(0,240)}\u2026`:value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value==="number"?value:typeof value==="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET){throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(value),required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]})}return parsed}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return void 0;const contextOrient=command==="context"&&intent==="orient";const overhead=command==="context"?contextOrient?1200:800:command==="list"?520:480;const rowCost=command==="context"?contextOrient?600:500:16;const calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt){let measuredTokens=receipt.estimated_tokens;for(;;){receipt.estimated_tokens=measuredTokens;const nextMeasurement=Math.ceil(Buffer.byteLength(JSON.stringify(projected),"utf8")/4);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement}}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));if(typeof parsed.fingerprint!=="string"||!Number.isSafeInteger(parsed.after_index)){return void 0}return{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot==="string"?{snapshot:parsed.snapshot}:{}}}catch{return void 0}}function contextIntentRowId(row){if(row===null||typeof row!=="object")return void 0;if(typeof row.id==="string"){return row.id}const nestedId=row.item?.id;return typeof nestedId==="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows){let compacted=false;for(;;){updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens<=receipt.token_budget||rows.length<=1){return compacted}const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8");const excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length))))));compacted=true}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items;const cursorContinuesExistingPage=typeof projected.next_cursor==="string";const cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!=="string")return false;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return false;const originalRowCount=rows.length;const originalRows=[...rows];let compacted=false;for(;;){compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows)||compacted;if(!compacted)return false;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0){rows.splice(0,rows.length,...originalRows);updateContextIntentEstimate(projected,receipt);return false}projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot);updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens<=receipt.token_budget||rows.length<=1){break}}if(typeof projected.count==="number")projected.count=rows.length;if(typeof projected.applied_limit==="number"){projected.applied_limit=rows.length}return true}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search"){return compactPaginatedContextIntentRows(projected,receipt,options)}if(command!=="next"||typeof projected.next_cursor==="string"){return false}let compacted=false;for(;;){updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1);const candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8");const estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length));const excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;const removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount);compacted=true}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!=="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand;const contract=resolveContextIntentContract(builtInCommand,options.for);const effectiveTokenBudget=resolveIntentTokenBudget(options.tokenBudget??options.token_budget,contract.token_budget);const receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:true,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:true,result_omitted:false};const resultWithDiagnostics={...result};const budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0);if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit);const explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit;receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget";receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.";resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit}let projected={...resultWithDiagnostics,context_intent:receipt};updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens>receipt.token_budget){receipt.degradation="recursive_budget_compaction";projected={...compactContextIntentValue(resultWithDiagnostics),context_intent:receipt};updateContextIntentEstimate(projected,receipt)}if(receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)){receipt.degradation="budget_row_compaction";updateContextIntentEstimate(projected,receipt)}receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget;if(receipt.estimated_tokens>receipt.token_budget){receipt.degradation="budget_receipt_only";receipt.result_omitted=true;receipt.within_budget=false;projected={budget_exceeded:{omitted_result:true,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,receipt,resultWithDiagnostics)},context_intent:receipt}}return projected}function collapseContinuationMetadata(options,result){if(typeof options.after!=="string"||options.after.length===0){return result}const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor";const projected={...result};for(const key of["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"]){delete projected[key]}projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"};return projected}function isOutputRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id==="string"?result.item.id:builtInCommand==="search"&&typeof result.query==="string"?result.query:void 0;const recoveryPositional=recoveryTarget===void 0?"":` '${recoveryTarget.replaceAll("'",`'"'"'`)}'`;const boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`;return`pm ${command}${recoveryPositional} --for ${intent} --token-budget ${Math.ceil(receipt.estimated_tokens/100)*100}${boundedRowLimit}`}function receiptEstimate(value,field){if(!isOutputRecord(value))return void 0;return typeof value[field]==="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens");const previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens");const previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)){updateContextIntentEstimate(finalized,finalized.context_intent)}finalized=stabilizeReadOutputReceiptEstimates(finalized,options);if(receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate){break}}return finalized}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,result);const projected=typeof disclosedResult==="object"&&disclosedResult!==null&&!Array.isArray(disclosedResult)?applyReadOutputDimensions(command??"",{...options,outputRowContract:options.outputRowContract===true||options.output_row_contract===true},collapseContinuationMetadata(options,attachContextIntentReceipt(command??"",options,disclosedResult))):disclosedResult;propagateContextUsageServingReceipt(result,projected);if(options.outputRowContract===true||options.output_row_contract===true||typeof projected!=="object"||projected===null||Array.isArray(projected)||!Object.hasOwn(projected,"row_contract")){return projected}const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:false,configurable:true});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);delete suppressed.row_contract;propagateContextUsageServingReceipt(projected,suppressed);return suppressed}export{PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e834062a-97f7-51d7-b934-1e4b43e3d6b2")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase(),intent=declaration.intent.trim().toLowerCase(),key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent))throw new TypeError(`Invalid context intent command or name: ${key}`);if(declaration.description.trim().length===0)throw new TypeError(`Context intent ${key} requires a non-empty description`);if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0)throw new TypeError(`Context intent ${key} requires a positive integer token_budget`);const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0)throw new TypeError(`Context intent ${key} requires included_field_groups`);return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:!1},{source:"package",contracts:packageContracts,allowOverride:!1},{source:"workspace",contracts:workspaceContracts,allowOverride:!0}],composed=new Map,keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source),key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);if(keysSeenWithinLayer.add(key),!layer.allowOverride&&composed.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase(),normalizedIntent=intent.trim().toLowerCase(),exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1)),previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate,attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent],suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion],suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget)=>{projected.section===void 0&&projected.depth===void 0&&(projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),projected.depth===void 0&&(projected.depth=contract.intent==="handoff"?"deep":"standard");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit),derivedLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=derivedLimit),projected.activityLimit===void 0&&(projected.activityLimit=derivedLimit)},get:projected=>{projected.depth===void 0&&projected.fields===void 0&&(projected.depth="standard")},list:(projected,contract,explicitTokenBudget)=>{projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit);(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit)))},next:projected=>{projected.readyOnly===void 0&&(projected.readyOnly=!0)},search:(projected,contract,explicitTokenBudget)=>{projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.compact=!0);const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit);(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit)))}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search"))throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(options.tokenBudget!==void 0||options.token_budget===void 0)return options;const projected2={...options,tokenBudget};return delete projected2.token_budget,projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments),explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0,projected={...options};return projected.tokenBudget===void 0&&tokenBudget!==void 0&&(projected.tokenBudget=tokenBudget),delete projected.token_budget,projected.tokenBudget===void 0&&(projected.tokenBudget=String(contract.token_budget)),CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget),projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){return Array.isArray(value)?value.map(compactContextIntentValue):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactContextIntentValue(entry)])):typeof value=="string"&&value.length>240?`${value.slice(0,240)}\u2026`:value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET)throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(value),required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]});return parsed}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return;const contextOrient=command==="context"&&intent==="orient",overhead=command==="context"?contextOrient?1200:800:command==="list"?520:480,rowCost=command==="context"?contextOrient?600:500:16,calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt){let measuredTokens=receipt.estimated_tokens;for(;;){receipt.estimated_tokens=measuredTokens;const nextMeasurement=Math.ceil(Buffer.byteLength(JSON.stringify(projected),"utf8")/4);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement}}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));return typeof parsed.fingerprint!="string"||!Number.isSafeInteger(parsed.after_index)?void 0:{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot=="string"?{snapshot:parsed.snapshot}:{}}}catch{return}}function contextIntentRowId(row){if(row===null||typeof row!="object")return;if(typeof row.id=="string")return row.id;const nestedId=row.item?.id;return typeof nestedId=="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows){let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)return compacted;const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8"),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length)))))),compacted=!0}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items,cursorContinuesExistingPage=typeof projected.next_cursor=="string",cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!="string")return!1;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return!1;const originalRowCount=rows.length,originalRows=[...rows];let compacted=!1;for(;;){if(compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows)||compacted,!compacted)return!1;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0)return rows.splice(0,rows.length,...originalRows),updateContextIntentEstimate(projected,receipt),!1;if(projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot),updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)break}return typeof projected.count=="number"&&(projected.count=rows.length),typeof projected.applied_limit=="number"&&(projected.applied_limit=rows.length),!0}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search")return compactPaginatedContextIntentRows(projected,receipt,options);if(command!=="next"||typeof projected.next_cursor=="string")return!1;let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1),candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8"),estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length)),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4,removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount),compacted=!0}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand,contract=resolveContextIntentContract(builtInCommand,options.for),effectiveTokenBudget=resolveIntentTokenBudget(options.tokenBudget??options.token_budget,contract.token_budget),receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:!0,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:!0,result_omitted:!1},resultWithDiagnostics={...result},budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0);if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit),explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit,receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget",receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit}let projected={...resultWithDiagnostics,context_intent:receipt};return updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="recursive_budget_compaction",projected={...compactContextIntentValue(resultWithDiagnostics),context_intent:receipt},updateContextIntentEstimate(projected,receipt)),receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)&&(receipt.degradation="budget_row_compaction",updateContextIntentEstimate(projected,receipt)),receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget,receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="budget_receipt_only",receipt.result_omitted=!0,receipt.within_budget=!1,projected={budget_exceeded:{omitted_result:!0,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,receipt,resultWithDiagnostics)},context_intent:receipt}),projected}function collapseContinuationMetadata(options,result){if(typeof options.after!="string"||options.after.length===0)return result;const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor",projected={...result};for(const key of["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"])delete projected[key];return projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"},projected}function isOutputRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id=="string"?result.item.id:builtInCommand==="search"&&typeof result.query=="string"?result.query:void 0,recoveryPositional=recoveryTarget===void 0?"":` '${recoveryTarget.replaceAll("'",`'"'"'`)}'`,boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`;return`pm ${command}${recoveryPositional} --for ${intent} --token-budget ${Math.ceil(receipt.estimated_tokens/100)*100}${boundedRowLimit}`}function receiptEstimate(value,field){if(isOutputRecord(value))return typeof value[field]=="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens"),previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens"),previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)&&updateContextIntentEstimate(finalized,finalized.context_intent),finalized=stabilizeReadOutputReceiptEstimates(finalized,options),receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate)break}return finalized}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,result),projected=typeof disclosedResult=="object"&&disclosedResult!==null&&!Array.isArray(disclosedResult)?applyReadOutputDimensions(command??"",{...options,outputRowContract:options.outputRowContract===!0||options.output_row_contract===!0},collapseContinuationMetadata(options,attachContextIntentReceipt(command??"",options,disclosedResult))):disclosedResult;if(propagateContextUsageServingReceipt(result,projected),options.outputRowContract===!0||options.output_row_contract===!0||typeof projected!="object"||projected===null||Array.isArray(projected)||!Object.hasOwn(projected,"row_contract"))return projected;const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:!1,configurable:!0});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);return delete suppressed.row_contract,propagateContextUsageServingReceipt(projected,suppressed),suppressed}export{PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
|
|
2
2
|
//# sourceMappingURL=context-intent-contracts.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="20a3a324-d176-5918-8167-5e548be4abc9")}catch{}})();import{readFile}from"node:fs/promises";import path from"node:path";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{assertReadableTrackerRoot}from"./environment/tracker-preflight.js";import{runWithContextIntentContracts}from"./context-intent-contracts.js";const PM_CONTEXT_INTENTS_FILE="context-intents.json";function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseDeclaration(value,sourceLabel,index){if(!isRecord(value))throw new TypeError(`${sourceLabel} context intent at index ${String(index)} must be an object`);const includedFieldGroups=value.included_field_groups;if(typeof value.command!="string"||typeof value.intent!="string"||typeof value.description!="string"||!Array.isArray(includedFieldGroups)||!includedFieldGroups.every(entry=>typeof entry=="string")||typeof value.token_budget!="number")throw new TypeError(`${sourceLabel} context intent at index ${String(index)} has an invalid contract shape`);return{command:value.command,intent:value.intent,description:value.description,included_field_groups:includedFieldGroups,token_budget:value.token_budget}}function parseContextIntentDeclarations(value,sourceLabel){const declarations=Array.isArray(value)?value:isRecord(value)&&Array.isArray(value.intents)?value.intents:void 0;if(!declarations)throw new TypeError(`${sourceLabel} context intents must be an array or an object with an intents array`);return declarations.map((entry,index)=>parseDeclaration(entry,sourceLabel,index))}async function readWorkspaceContextIntentContracts(pmRoot){const declarationPath=path.join(pmRoot,PM_CONTEXT_INTENTS_FILE);let source;try{source=await readFile(declarationPath,"utf8")}catch(error){if(isFileAbsentError(error))return[];throw await assertReadableTrackerRoot(pmRoot),error}let parsed;try{parsed=JSON.parse(source)}catch(error){const detail=error instanceof Error?error.message:String(error);throw new TypeError(`Invalid ${PM_CONTEXT_INTENTS_FILE}: ${detail}`,{cause:error})}return parseContextIntentDeclarations(parsed,PM_CONTEXT_INTENTS_FILE)}function packageDeclarationExport(module){if(!isRecord(module))return;const direct=module.contextIntents??module.context_intents;if(direct!==void 0)return direct;const defaultExport=module.default;return isRecord(defaultExport)?defaultExport.contextIntents??defaultExport.context_intents:void 0}function collectPackageContextIntentContracts(packages){return packages.flatMap(entry=>{const declaration=packageDeclarationExport(entry.module);return declaration===void 0?[]:parseContextIntentDeclarations(declaration,`package ${entry.name}`)})}async function loadContextIntentRuntimeLayers(options){const workspaceContracts=await readWorkspaceContextIntentContracts(options.pmRoot),packageContracts=collectPackageContextIntentContracts(options.packages??[]);return{workspaceContracts,packageContracts}}async function runWithDiscoveredContextIntentContracts(options,run){const layers=await loadContextIntentRuntimeLayers(options);return await runWithContextIntentContracts(layers,run)}export{PM_CONTEXT_INTENTS_FILE,collectPackageContextIntentContracts,loadContextIntentRuntimeLayers,parseContextIntentDeclarations,readWorkspaceContextIntentContracts,runWithDiscoveredContextIntentContracts};
|
|
2
2
|
//# sourceMappingURL=context-intent-runtime.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d07ec2dc-762a-58ab-83ee-734ca1bf76a7")}catch{}})();const CONTEXT_PACKING_PROFILES={balanced:{redundancyPenalty:.35,uncertaintyPenalty:.2},context:{redundancyPenalty:.45,uncertaintyPenalty:.15},next:{redundancyPenalty:.25,uncertaintyPenalty:.3}},PROJECTION_LEVELS=["identity","summary","full"];function assertPackingCandidate(candidate){if(!candidate.id.trim()||!Number.isInteger(candidate.rank)||candidate.rank<1)throw new TypeError("Context packing candidates require a non-empty id and positive integer rank");if(!Number.isFinite(candidate.score)||candidate.score<0)throw new TypeError("Context packing candidate scores must be finite and non-negative");const costs=PROJECTION_LEVELS.map(level=>candidate.token_costs[level]);if(costs.some(cost=>!Number.isInteger(cost)||cost<1)||costs[0]>costs[1]||costs[1]>costs[2])throw new TypeError("Context projection costs must be positive monotone integers");if(candidate.uncertainty!==void 0&&(!Number.isFinite(candidate.uncertainty)||candidate.uncertainty<0))throw new TypeError("Context packing uncertainty must be finite and non-negative")}function resolvePackingPenalties(options){if(!Number.isInteger(options.tokenBudget)||options.tokenBudget<1)throw new TypeError("Context packing tokenBudget must be a positive integer");const profile=options.profile??"balanced",policy=CONTEXT_PACKING_PROFILES[profile];if(!policy)throw new TypeError("Unknown context packing profile");const redundancy=options.redundancyPenalty??policy.redundancyPenalty,uncertainty=options.uncertaintyPenalty??policy.uncertaintyPenalty;if(!Number.isFinite(redundancy)||redundancy<0||redundancy>1||!Number.isFinite(uncertainty)||uncertainty<0)throw new TypeError("Context packing penalties must be finite and within their supported ranges");if(options.latencyBudgetMs!==void 0&&(!Number.isFinite(options.latencyBudgetMs)||options.latencyBudgetMs<=0))throw new TypeError("Context packing latencyBudgetMs must be positive");return{redundancy,uncertainty,profile}}function orderPackingCandidates(candidates){const ids=new Set;for(const candidate of candidates){if(assertPackingCandidate(candidate),ids.has(candidate.id))throw new TypeError("Context packing candidates require unique ids");ids.add(candidate.id)}return[...candidates].sort((left,right)=>left.rank-right.rank||left.id.localeCompare(right.id))}function findBestAffordableCandidate(candidates,remaining,valueOf,deadline,readClock){let bestIndex=-1,evaluated=0;for(let index=0;index<candidates.length;index+=1){if(index%128===0&&readClock()>=deadline)return{index:bestIndex,evaluated,timedOut:!0};const candidate=candidates[index];if(candidate.token_costs.identity>remaining)continue;evaluated+=1;const best=bestIndex<0?void 0:candidates[bestIndex],density=valueOf(candidate)/candidate.token_costs.identity,bestDensity=best===void 0?Number.NEGATIVE_INFINITY:valueOf(best)/best.token_costs.identity;(density>bestDensity||density===bestDensity&&best!==void 0&&(candidate.rank<best.rank||candidate.rank===best.rank&&candidate.id.localeCompare(best.id)<0))&&(bestIndex=index)}return{index:bestIndex,evaluated,timedOut:!1}}function selectIdentityCandidates(params){const represented=new Set,included=[];let remaining=params.tokenBudget;const valueOf=candidate=>{const key=candidate.lineage??candidate.cluster,redundancy=key&&represented.has(key)?1-params.redundancyPenalty:1;return Math.max(0,(candidate.score-params.uncertaintyPenalty*(candidate.uncertainty??0))*redundancy)},admit=candidate=>{const tokens=candidate.token_costs.identity;included.push({...candidate,projection:"identity",tokens,marginal_value:valueOf(candidate)}),remaining-=tokens;const key=candidate.lineage??candidate.cluster;key&&represented.add(key)};for(const candidate of params.ordered.filter(entry=>entry.required))candidate.token_costs.identity<=remaining&&admit(candidate);const optional=params.ordered.filter(entry=>!entry.required);let selectionComplete=!0,evaluatedCandidates=0;for(;optional.length>0;){const selection=findBestAffordableCandidate(optional,remaining,valueOf,params.deadline,params.readClock);if(evaluatedCandidates+=selection.evaluated,selection.timedOut&&(selectionComplete=!1),selection.index<0||selection.timedOut)break;admit(optional.splice(selection.index,1)[0])}return{included,remaining,selectionComplete,evaluatedCandidates}}function upgradeSelectedProjections(included,initialRemaining){let remaining=initialRemaining;for(const target of["summary","full"]){const previous=target==="summary"?"identity":"summary",upgrades=[...included].sort((left,right)=>{const leftCost=left.token_costs[target]-left.token_costs[previous],rightCost=right.token_costs[target]-right.token_costs[previous];return right.marginal_value/Math.max(rightCost,1)-left.marginal_value/Math.max(leftCost,1)||left.rank-right.rank||left.id.localeCompare(right.id)});for(const entry of upgrades){if(entry.projection!==previous)continue;const extra=entry.token_costs[target]-entry.tokens;extra>remaining||(entry.projection=target,entry.tokens+=extra,remaining-=extra)}}return remaining}function packContextCandidates(candidates,options){const penalties=resolvePackingPenalties(options),ordered=orderPackingCandidates(candidates),readClock=options.readClock??performance.now.bind(performance),deadline=options.latencyBudgetMs===void 0?Number.POSITIVE_INFINITY:readClock()+options.latencyBudgetMs,selection=selectIdentityCandidates({ordered,tokenBudget:options.tokenBudget,redundancyPenalty:penalties.redundancy,uncertaintyPenalty:penalties.uncertainty,deadline,readClock}),{included}=selection,remaining=upgradeSelectedProjections(included,selection.remaining);included.sort((left,right)=>left.rank-right.rank||left.id.localeCompare(right.id));const selected=new Set(included.map(entry=>entry.id));return{included,omitted_ids:ordered.filter(entry=>!selected.has(entry.id)).map(entry=>entry.id),token_budget:options.tokenBudget,used_tokens:options.tokenBudget-remaining,remaining_tokens:remaining,complete:selection.selectionComplete&&included.length===candidates.length&&included.every(entry=>entry.projection==="full"),selection_complete:selection.selectionComplete,termination_reason:selection.selectionComplete?"exhausted":"latency_budget",evaluated_candidates:selection.evaluatedCandidates,latency_budget_ms:options.latencyBudgetMs??null,profile:penalties.profile,degradation_ladder:["full","summary","identity"]}}export{CONTEXT_PACKING_PROFILES,packContextCandidates};
|
|
2
2
|
//# sourceMappingURL=context-packing.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="33841a67-2bd5-5cbd-a9d4-14833ddcf9d2")}catch(e2){}})();import{runActiveServiceOverride}from"../core/extensions/index.js";import{normalizeStatusForRegistry,normalizeStatusInput}from"../core/item/status.js";import{compareTimestampStrings}from"../core/shared/time.js";import{canonicalizeContextRecencyCoordinate,CONTEXT_RECENCY_EPOCH}from"./context/recency.js";const CONTEXT_RELEVANCE_SIGNAL_NAMES=["structural","recency","activity_density","graph_proximity","claim_focus","priority_pressure","risk_pressure","deadline_pressure","knowledge_density","author_affinity","usage_affinity","semantic_similarity"];const NO_CONTEXT_AUTHOR=Symbol("no-context-author");const NO_ITEM_ASSIGNEE=Symbol("no-item-assignee");function normalizeContextActor(value,missingValue){if(typeof value!=="string")return missingValue;const normalized=value.trim().toLowerCase();return normalized.length>0?normalized:missingValue}function releaseCohortCoordinate(value){if(typeof value!=="string")return void 0;const match=/^v?(\d{4})\.(\d{1,2})\.(\d{1,2})(?:$|[-+])/u.exec(value.trim());if(!match)return void 0;const year=Number(match[1]);const month=Number(match[2]);const day=Number(match[3]);const date=new Date(Date.UTC(year,month-1,day));return date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date.toISOString():void 0}function fallbackRecencyEvidence(item){const releaseCoordinate=releaseCohortCoordinate(item.release);if(releaseCoordinate!==void 0){return{source:"release_cohort",coordinate:releaseCoordinate}}return{source:"created_at",coordinate:canonicalizeContextRecencyCoordinate(item.created_at)??CONTEXT_RECENCY_EPOCH}}function canonicalizeRecencyEvidence(evidence){if(!["substantive_history","release_cohort","created_at"].includes(evidence.source)||(evidence.source==="substantive_history"?evidence.history_op!==void 0&&typeof evidence.history_op!=="string"||evidence.event_class!==void 0&&evidence.event_class!=="substantive":evidence.history_op!==void 0||evidence.event_class!==void 0)){throw new TypeError("Context signal recency provenance must match its source")}const coordinate=canonicalizeContextRecencyCoordinate(evidence.coordinate);if(coordinate===null){throw new TypeError("Context signal recency coordinate must be a valid absolute timestamp with millisecond precision")}return{...evidence,coordinate}}function normalizedPressure(value,maximum){const parsed=typeof value==="number"?value:typeof value==="string"?Number.parseFloat(value):Number.NaN;return Number.isFinite(parsed)?1-Math.min(Math.max(parsed,0),maximum)/maximum:0}function deadlinePressure(deadline,nowMs){const deadlineMs=typeof deadline==="string"?Date.parse(deadline):deadline instanceof Date?deadline.getTime():typeof deadline==="number"?deadline:Number.NaN;if(!Number.isFinite(deadlineMs)||!Number.isFinite(nowMs))return 0;const days=(deadlineMs-nowMs)/864e5;return days<=0?1:1/(1+days/30)}function riskPressure(risk){const normalized=typeof risk==="string"?risk.trim().toLowerCase():void 0;if(normalized==="critical"||normalized==="high")return 1;if(normalized==="medium")return .5;return normalized==="low"?.1:0}function derivedSignalOrFallback(values,id,fallback){return values?.[id]??fallback}function buildItemContextRelevanceCandidates(items,options){const recencyEvidence=new Map(items.map(item=>{const suppliedEvidence=options.recencyEvidence?.[item.id];return[item.id,suppliedEvidence===void 0?fallbackRecencyEvidence(item):canonicalizeRecencyEvidence(suppliedEvidence)]}));const recencyOrder=[...items].sort((left,right)=>{const leftTime=recencyEvidence.get(left.id).coordinate;const rightTime=recencyEvidence.get(right.id).coordinate;return compareTimestampStrings(rightTime,leftTime)||left.id.localeCompare(right.id)});const recencyRank=new Map(recencyOrder.map((item,index)=>[item.id,index]));const denominator=Math.max(items.length-1,1);const normalizedAuthor=normalizeContextActor(options.author,NO_CONTEXT_AUTHOR);const inProgressStatus=normalizeStatusInput("in_progress",options.statusRegistry);const nowMs=Date.parse(options.now);return items.map(item=>{const assigned=normalizeContextActor(item.assignee,NO_ITEM_ASSIGNEE)===normalizedAuthor;const knowledgeEntries=(item.comments?.length??0)+(item.notes?.length??0)+(item.learnings?.length??0);return{id:item.id,item,signal_provenance:{recency:recencyEvidence.get(item.id)},signals:{recency:items.length===1?1:1-recencyRank.get(item.id)/denominator,activity_density:options.activityDensity?.[item.id],graph_proximity:derivedSignalOrFallback(options.graphProximity,item.id,item.parent?.3:0),claim_focus:derivedSignalOrFallback(options.claimFocus,item.id,normalizeStatusForRegistry(item.status,options.statusRegistry)===inProgressStatus?1:assigned?.75:0),priority_pressure:normalizedPressure(item.priority,4),risk_pressure:riskPressure(item.risk),deadline_pressure:deadlinePressure(item.deadline,nowMs),knowledge_density:derivedSignalOrFallback(options.knowledgeDensity,item.id,Math.min(knowledgeEntries/5,1)),author_affinity:derivedSignalOrFallback(options.authorAffinity,item.id,assigned?1:0),usage_affinity:options.usageAffinity?.[item.id],semantic_similarity:options.semanticSimilarity?.[item.id]}}})}const CONTEXT_RELEVANCE_SERVICE="context_relevance";const DEFAULT_CONTEXT_RELEVANCE_WEIGHTS={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};const JSON_TOKEN_ENCODER=new TextEncoder;function assertCandidates(candidates){const ids=new Set;for(const candidate of candidates){if(typeof candidate.id!=="string"||candidate.id.trim().length===0||ids.has(candidate.id)){throw new TypeError("Context relevance candidates require unique non-empty ids")}ids.add(candidate.id);for(const[signal,value]of Object.entries(candidate.signals??{})){if(signal==="structural"||!CONTEXT_RELEVANCE_SIGNAL_NAMES.includes(signal)){throw new TypeError(`Unknown context relevance signal: ${signal}`)}if(value===void 0)continue;if(!Number.isFinite(value)||value<0||value>1){throw new TypeError(`Context relevance signal ${signal} must be a finite number from 0 to 1`)}}}}function resolveWeights(overrides){const weights={...DEFAULT_CONTEXT_RELEVANCE_WEIGHTS};for(const[signal,weight]of Object.entries(overrides??{})){if(weight!==void 0&&CONTEXT_RELEVANCE_SIGNAL_NAMES.includes(signal)){weights[signal]=weight}}for(const[signal,weight]of Object.entries(weights)){if(!Number.isFinite(weight)||weight<0){throw new TypeError(`Context relevance weight ${signal} must be a finite non-negative number`)}}return weights}function defaultScoreContextCandidates(candidates,options={}){assertCandidates(candidates);const weights=resolveWeights(options.weights);const denominator=Math.max(candidates.length-1,1);const available=new Set(["structural"]);for(const candidate of candidates){for(const[signal,value]of Object.entries(candidate.signals??{})){if(value!==void 0)available.add(signal)}}const availableSignals=CONTEXT_RELEVANCE_SIGNAL_NAMES.filter(signal=>available.has(signal));const scored=candidates.map((candidate,index)=>{const signalValues={structural:candidates.length===1?1:1-index/denominator,...candidate.signals};const contributions={};let weightedScore=0;let totalWeight=0;for(const signal of availableSignals){const value=signalValues[signal];if(value===void 0)continue;const contribution=value*weights[signal];contributions[signal]=contribution;weightedScore+=contribution;totalWeight+=weights[signal]}return{...candidate,baseline_rank:index+1,rank:0,score:totalWeight===0?0:weightedScore/totalWeight,contributions}});scored.sort((left,right)=>right.score-left.score||left.baseline_rank-right.baseline_rank);scored.forEach((entry,index)=>{entry.rank=index+1});return{model:"default-weighted-v1",available_signals:availableSignals,ranked:scored}}async function scoreContextCandidates(candidates,options={}){const defaultReport=defaultScoreContextCandidates(candidates,options);if(!options.scorer)return defaultReport;const customScores=await options.scorer({candidates,default_report:defaultReport});const scoreById=new Map;for(const entry of customScores){if(scoreById.has(entry.id)||!Number.isFinite(entry.score)){throw new TypeError("Context relevance scorer must return one finite score for every candidate")}scoreById.set(entry.id,entry.score)}if(scoreById.size!==candidates.length||candidates.some(candidate=>!scoreById.has(candidate.id))){throw new TypeError("Context relevance scorer must return one finite score for every candidate")}const ranked=defaultReport.ranked.map(entry=>{const score=scoreById.get(entry.id);return{...entry,score,contributions:{custom:score}}});ranked.sort((left,right)=>right.score-left.score||left.baseline_rank-right.baseline_rank);ranked.forEach((entry,index)=>{entry.rank=index+1});return{model:"custom",available_signals:defaultReport.available_signals,ranked}}async function scoreContextCandidatesWithActiveExtensions(surface,candidates,options={}){const defaultReport=defaultScoreContextCandidates(candidates,options);const override=await runActiveServiceOverride(CONTEXT_RELEVANCE_SERVICE,{surface,candidates,default_report:defaultReport});if(!override.handled){return override.warnings.length>0?{...defaultReport,warnings:override.warnings}:defaultReport}if(!Array.isArray(override.result)||!override.result.every(entry=>typeof entry==="object"&&entry!==null&&typeof entry.id==="string"&&typeof entry.score==="number"&&Number.isFinite(entry.score))){return{...defaultReport,warnings:[...override.warnings,"extension_context_relevance_invalid_result"]}}try{const report=await scoreContextCandidates(candidates,{...options,scorer:()=>override.result});return override.warnings.length>0?{...report,warnings:override.warnings}:report}catch{return{...defaultReport,warnings:[...override.warnings,"extension_context_relevance_invalid_result"]}}}const CONTEXT_EVALUATION_METRIC_NAMES=["ndcg","reciprocal_rank","required_recall","continuity_coverage","token_budget_adherence"];function ratioOfPresent(expected,actual){if(expected.length===0)return 1;return expected.filter(id=>actual.has(id)).length/expected.length}function evaluateContextRanking(input){if(!Number.isFinite(input.actual_tokens)||input.actual_tokens<0||!Number.isFinite(input.token_budget)||input.token_budget<=0){throw new TypeError("Context ranking token counts require actual_tokens >= 0 and token_budget > 0")}const judgments=input.judgments??{};const gains=input.ranked_ids.map(id=>Math.max(0,judgments[id]??0));const idealGains=Object.values(judgments).map(grade=>Math.max(0,grade)).sort((left,right)=>right-left).slice(0,gains.length||1);const discountedGain=values=>values.reduce((total,grade,index)=>total+(2**grade-1)/Math.log2(index+2),0);const ideal=discountedGain(idealGains);const firstRelevant=gains.findIndex(grade=>grade>0);const actualIds=new Set(input.ranked_ids);const withinBudget=input.actual_tokens<=input.token_budget;return{ndcg:ideal===0?1:discountedGain(gains)/ideal,reciprocal_rank:firstRelevant<0?0:1/(firstRelevant+1),required_recall:ratioOfPresent(input.required_ids??[],actualIds),continuity_coverage:ratioOfPresent(input.continuity_ids??[],actualIds),token_budget_adherence:withinBudget?1:input.token_budget/input.actual_tokens,within_token_budget:withinBudget}}function estimateJsonTokens(value){return Math.ceil(JSON_TOKEN_ENCODER.encode(JSON.stringify(value)).byteLength/4)}function roundEvaluationMetric(value){return Math.round(value*1e4)/1e4}function rankingPayloadForScenario(result,surface){const rankedIds=surface==="context"?[...result.high_level??[],...result.low_level??[],...result.blocked_fallback??[]].map(item=>item.id):[...result.recommended?[result.recommended]:[],...result.ready??[]].map(item=>item.id);const servedIds=new Set(rankedIds);const attribution=(result.ranking?.items??[]).filter(item=>servedIds.has(item.id)).map(item=>({id:item.id,contributions:item.contributions}));return{rankedIds,attribution}}async function runContextEvaluationScenario(scenario,reader){if(scenario.id.trim().length===0||scenario.rationale.trim().length===0){throw new TypeError("Context evaluation scenarios require non-empty id and rationale values")}const result=scenario.surface==="context"?await reader.context({...scenario.options,explainRanking:true,outputBudget:scenario.options?.outputBudget??"unbounded"}):await reader.next({...scenario.options,explainRanking:true,outputBudget:scenario.options?.outputBudget??"unbounded"});const{rankedIds,attribution}=rankingPayloadForScenario(result,scenario.surface);const packet={...result,ranking:void 0};const actualTokens=estimateJsonTokens(packet);return{id:scenario.id,surface:scenario.surface,rationale:scenario.rationale,ranked_ids:rankedIds,actual_tokens:actualTokens,metrics:evaluateContextRanking({ranked_ids:rankedIds,judgments:scenario.judgments,required_ids:scenario.required_ids,continuity_ids:scenario.continuity_ids,actual_tokens:actualTokens,token_budget:scenario.token_budget}),attribution}}function summarizeContextEvaluationReports(reports,thresholds){if(reports.length===0){throw new TypeError("Context evaluation requires at least one scenario report")}const metrics=CONTEXT_EVALUATION_METRIC_NAMES;for(const metric of metrics){if(!Number.isFinite(thresholds[metric])){throw new TypeError(`Context evaluation threshold ${metric} must be a finite number`)}}const aggregate=Object.fromEntries(metrics.map(metric=>[metric,roundEvaluationMetric(reports.reduce((total,report)=>total+report.metrics[metric],0)/reports.length)]));const failures=metrics.filter(metric=>aggregate[metric]<thresholds[metric]).map(metric=>`${metric}:${aggregate[metric]}<${thresholds[metric]}`);return{scenario_count:reports.length,aggregate,scenarios:[...reports],passed:failures.length===0,failures}}async function runContextEvaluationCorpus(scenarios,reader,thresholds){const reports=[];for(const scenario of scenarios){reports.push(await runContextEvaluationScenario(scenario,reader))}return summarizeContextEvaluationReports(reports,thresholds)}export{CONTEXT_EVALUATION_METRIC_NAMES,CONTEXT_RELEVANCE_SERVICE,CONTEXT_RELEVANCE_SIGNAL_NAMES,buildItemContextRelevanceCandidates,defaultScoreContextCandidates,evaluateContextRanking,runContextEvaluationCorpus,runContextEvaluationScenario,scoreContextCandidates,scoreContextCandidatesWithActiveExtensions,summarizeContextEvaluationReports};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e750a203-8bef-5bfd-85a5-a584c2105472")}catch{}})();import{runActiveServiceOverride}from"../core/extensions/index.js";import{normalizeStatusForRegistry,normalizeStatusInput}from"../core/item/status.js";import{compareTimestampStrings}from"../core/shared/time.js";import{canonicalizeContextRecencyCoordinate,CONTEXT_RECENCY_EPOCH}from"./context/recency.js";const CONTEXT_RELEVANCE_SIGNAL_NAMES=["structural","recency","activity_density","graph_proximity","claim_focus","priority_pressure","risk_pressure","deadline_pressure","knowledge_density","author_affinity","usage_affinity","semantic_similarity"],NO_CONTEXT_AUTHOR=Symbol("no-context-author"),NO_ITEM_ASSIGNEE=Symbol("no-item-assignee");function normalizeContextActor(value,missingValue){if(typeof value!="string")return missingValue;const normalized=value.trim().toLowerCase();return normalized.length>0?normalized:missingValue}function releaseCohortCoordinate(value){if(typeof value!="string")return;const match=/^v?(\d{4})\.(\d{1,2})\.(\d{1,2})(?:$|[-+])/u.exec(value.trim());if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(Date.UTC(year,month-1,day));return date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date.toISOString():void 0}function fallbackRecencyEvidence(item){const releaseCoordinate=releaseCohortCoordinate(item.release);return releaseCoordinate!==void 0?{source:"release_cohort",coordinate:releaseCoordinate}:{source:"created_at",coordinate:canonicalizeContextRecencyCoordinate(item.created_at)??CONTEXT_RECENCY_EPOCH}}function canonicalizeRecencyEvidence(evidence){if(!["substantive_history","release_cohort","created_at"].includes(evidence.source)||(evidence.source==="substantive_history"?evidence.history_op!==void 0&&typeof evidence.history_op!="string"||evidence.event_class!==void 0&&evidence.event_class!=="substantive":evidence.history_op!==void 0||evidence.event_class!==void 0))throw new TypeError("Context signal recency provenance must match its source");const coordinate=canonicalizeContextRecencyCoordinate(evidence.coordinate);if(coordinate===null)throw new TypeError("Context signal recency coordinate must be a valid absolute timestamp with millisecond precision");return{...evidence,coordinate}}function normalizedPressure(value,maximum){const parsed=typeof value=="number"?value:typeof value=="string"?Number.parseFloat(value):Number.NaN;return Number.isFinite(parsed)?1-Math.min(Math.max(parsed,0),maximum)/maximum:0}function deadlinePressure(deadline,nowMs){const deadlineMs=typeof deadline=="string"?Date.parse(deadline):deadline instanceof Date?deadline.getTime():typeof deadline=="number"?deadline:Number.NaN;if(!Number.isFinite(deadlineMs)||!Number.isFinite(nowMs))return 0;const days=(deadlineMs-nowMs)/864e5;return days<=0?1:1/(1+days/30)}function riskPressure(risk){const normalized=typeof risk=="string"?risk.trim().toLowerCase():void 0;return normalized==="critical"||normalized==="high"?1:normalized==="medium"?.5:normalized==="low"?.1:0}function derivedSignalOrFallback(values,id,fallback){return values?.[id]??fallback}function buildItemContextRelevanceCandidates(items,options){const recencyEvidence=new Map(items.map(item=>{const suppliedEvidence=options.recencyEvidence?.[item.id];return[item.id,suppliedEvidence===void 0?fallbackRecencyEvidence(item):canonicalizeRecencyEvidence(suppliedEvidence)]})),recencyOrder=[...items].sort((left,right)=>{const leftTime=recencyEvidence.get(left.id).coordinate,rightTime=recencyEvidence.get(right.id).coordinate;return compareTimestampStrings(rightTime,leftTime)||left.id.localeCompare(right.id)}),recencyRank=new Map(recencyOrder.map((item,index)=>[item.id,index])),denominator=Math.max(items.length-1,1),normalizedAuthor=normalizeContextActor(options.author,NO_CONTEXT_AUTHOR),inProgressStatus=normalizeStatusInput("in_progress",options.statusRegistry),nowMs=Date.parse(options.now);return items.map(item=>{const assigned=normalizeContextActor(item.assignee,NO_ITEM_ASSIGNEE)===normalizedAuthor,knowledgeEntries=(item.comments?.length??0)+(item.notes?.length??0)+(item.learnings?.length??0);return{id:item.id,item,signal_provenance:{recency:recencyEvidence.get(item.id)},signals:{recency:items.length===1?1:1-recencyRank.get(item.id)/denominator,activity_density:options.activityDensity?.[item.id],graph_proximity:derivedSignalOrFallback(options.graphProximity,item.id,item.parent?.3:0),claim_focus:derivedSignalOrFallback(options.claimFocus,item.id,normalizeStatusForRegistry(item.status,options.statusRegistry)===inProgressStatus?1:assigned?.75:0),priority_pressure:normalizedPressure(item.priority,4),risk_pressure:riskPressure(item.risk),deadline_pressure:deadlinePressure(item.deadline,nowMs),knowledge_density:derivedSignalOrFallback(options.knowledgeDensity,item.id,Math.min(knowledgeEntries/5,1)),author_affinity:derivedSignalOrFallback(options.authorAffinity,item.id,assigned?1:0),usage_affinity:options.usageAffinity?.[item.id],semantic_similarity:options.semanticSimilarity?.[item.id]}}})}const CONTEXT_RELEVANCE_SERVICE="context_relevance",DEFAULT_CONTEXT_RELEVANCE_WEIGHTS={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},JSON_TOKEN_ENCODER=new TextEncoder;function assertCandidates(candidates){const ids=new Set;for(const candidate of candidates){if(typeof candidate.id!="string"||candidate.id.trim().length===0||ids.has(candidate.id))throw new TypeError("Context relevance candidates require unique non-empty ids");ids.add(candidate.id);for(const[signal,value]of Object.entries(candidate.signals??{})){if(signal==="structural"||!CONTEXT_RELEVANCE_SIGNAL_NAMES.includes(signal))throw new TypeError(`Unknown context relevance signal: ${signal}`);if(value!==void 0&&(!Number.isFinite(value)||value<0||value>1))throw new TypeError(`Context relevance signal ${signal} must be a finite number from 0 to 1`)}}}function resolveWeights(overrides){const weights={...DEFAULT_CONTEXT_RELEVANCE_WEIGHTS};for(const[signal,weight]of Object.entries(overrides??{}))weight!==void 0&&CONTEXT_RELEVANCE_SIGNAL_NAMES.includes(signal)&&(weights[signal]=weight);for(const[signal,weight]of Object.entries(weights))if(!Number.isFinite(weight)||weight<0)throw new TypeError(`Context relevance weight ${signal} must be a finite non-negative number`);return weights}function defaultScoreContextCandidates(candidates,options={}){assertCandidates(candidates);const weights=resolveWeights(options.weights),denominator=Math.max(candidates.length-1,1),available=new Set(["structural"]);for(const candidate of candidates)for(const[signal,value]of Object.entries(candidate.signals??{}))value!==void 0&&available.add(signal);const availableSignals=CONTEXT_RELEVANCE_SIGNAL_NAMES.filter(signal=>available.has(signal)),scored=candidates.map((candidate,index)=>{const signalValues={structural:candidates.length===1?1:1-index/denominator,...candidate.signals},contributions={};let weightedScore=0,totalWeight=0;for(const signal of availableSignals){const value=signalValues[signal];if(value===void 0)continue;const contribution=value*weights[signal];contributions[signal]=contribution,weightedScore+=contribution,totalWeight+=weights[signal]}return{...candidate,baseline_rank:index+1,rank:0,score:totalWeight===0?0:weightedScore/totalWeight,contributions}});return scored.sort((left,right)=>right.score-left.score||left.baseline_rank-right.baseline_rank),scored.forEach((entry,index)=>{entry.rank=index+1}),{model:"default-weighted-v1",available_signals:availableSignals,ranked:scored}}async function scoreContextCandidates(candidates,options={}){const defaultReport=defaultScoreContextCandidates(candidates,options);if(!options.scorer)return defaultReport;const customScores=await options.scorer({candidates,default_report:defaultReport}),scoreById=new Map;for(const entry of customScores){if(scoreById.has(entry.id)||!Number.isFinite(entry.score))throw new TypeError("Context relevance scorer must return one finite score for every candidate");scoreById.set(entry.id,entry.score)}if(scoreById.size!==candidates.length||candidates.some(candidate=>!scoreById.has(candidate.id)))throw new TypeError("Context relevance scorer must return one finite score for every candidate");const ranked=defaultReport.ranked.map(entry=>{const score=scoreById.get(entry.id);return{...entry,score,contributions:{custom:score}}});return ranked.sort((left,right)=>right.score-left.score||left.baseline_rank-right.baseline_rank),ranked.forEach((entry,index)=>{entry.rank=index+1}),{model:"custom",available_signals:defaultReport.available_signals,ranked}}async function scoreContextCandidatesWithActiveExtensions(surface,candidates,options={}){const defaultReport=defaultScoreContextCandidates(candidates,options),override=await runActiveServiceOverride(CONTEXT_RELEVANCE_SERVICE,{surface,candidates,default_report:defaultReport});if(!override.handled)return override.warnings.length>0?{...defaultReport,warnings:override.warnings}:defaultReport;if(!Array.isArray(override.result)||!override.result.every(entry=>typeof entry=="object"&&entry!==null&&typeof entry.id=="string"&&typeof entry.score=="number"&&Number.isFinite(entry.score)))return{...defaultReport,warnings:[...override.warnings,"extension_context_relevance_invalid_result"]};try{const report=await scoreContextCandidates(candidates,{...options,scorer:()=>override.result});return override.warnings.length>0?{...report,warnings:override.warnings}:report}catch{return{...defaultReport,warnings:[...override.warnings,"extension_context_relevance_invalid_result"]}}}const CONTEXT_EVALUATION_METRIC_NAMES=["ndcg","reciprocal_rank","required_recall","continuity_coverage","token_budget_adherence"];function ratioOfPresent(expected,actual){return expected.length===0?1:expected.filter(id=>actual.has(id)).length/expected.length}function evaluateContextRanking(input){if(!Number.isFinite(input.actual_tokens)||input.actual_tokens<0||!Number.isFinite(input.token_budget)||input.token_budget<=0)throw new TypeError("Context ranking token counts require actual_tokens >= 0 and token_budget > 0");const judgments=input.judgments??{},gains=input.ranked_ids.map(id=>Math.max(0,judgments[id]??0)),idealGains=Object.values(judgments).map(grade=>Math.max(0,grade)).sort((left,right)=>right-left).slice(0,gains.length||1),discountedGain=values=>values.reduce((total,grade,index)=>total+(2**grade-1)/Math.log2(index+2),0),ideal=discountedGain(idealGains),firstRelevant=gains.findIndex(grade=>grade>0),actualIds=new Set(input.ranked_ids),withinBudget=input.actual_tokens<=input.token_budget;return{ndcg:ideal===0?1:discountedGain(gains)/ideal,reciprocal_rank:firstRelevant<0?0:1/(firstRelevant+1),required_recall:ratioOfPresent(input.required_ids??[],actualIds),continuity_coverage:ratioOfPresent(input.continuity_ids??[],actualIds),token_budget_adherence:withinBudget?1:input.token_budget/input.actual_tokens,within_token_budget:withinBudget}}function estimateJsonTokens(value){return Math.ceil(JSON_TOKEN_ENCODER.encode(JSON.stringify(value)).byteLength/4)}function roundEvaluationMetric(value){return Math.round(value*1e4)/1e4}function rankingPayloadForScenario(result,surface){const rankedIds=surface==="context"?[...result.high_level??[],...result.low_level??[],...result.blocked_fallback??[]].map(item=>item.id):[...result.recommended?[result.recommended]:[],...result.ready??[]].map(item=>item.id),servedIds=new Set(rankedIds),attribution=(result.ranking?.items??[]).filter(item=>servedIds.has(item.id)).map(item=>({id:item.id,contributions:item.contributions}));return{rankedIds,attribution}}async function runContextEvaluationScenario(scenario,reader){if(scenario.id.trim().length===0||scenario.rationale.trim().length===0)throw new TypeError("Context evaluation scenarios require non-empty id and rationale values");const result=scenario.surface==="context"?await reader.context({...scenario.options,explainRanking:!0,outputBudget:scenario.options?.outputBudget??"unbounded"}):await reader.next({...scenario.options,explainRanking:!0,outputBudget:scenario.options?.outputBudget??"unbounded"}),{rankedIds,attribution}=rankingPayloadForScenario(result,scenario.surface),packet={...result,ranking:void 0},actualTokens=estimateJsonTokens(packet);return{id:scenario.id,surface:scenario.surface,rationale:scenario.rationale,ranked_ids:rankedIds,actual_tokens:actualTokens,metrics:evaluateContextRanking({ranked_ids:rankedIds,judgments:scenario.judgments,required_ids:scenario.required_ids,continuity_ids:scenario.continuity_ids,actual_tokens:actualTokens,token_budget:scenario.token_budget}),attribution}}function summarizeContextEvaluationReports(reports,thresholds){if(reports.length===0)throw new TypeError("Context evaluation requires at least one scenario report");const metrics=CONTEXT_EVALUATION_METRIC_NAMES;for(const metric of metrics)if(!Number.isFinite(thresholds[metric]))throw new TypeError(`Context evaluation threshold ${metric} must be a finite number`);const aggregate=Object.fromEntries(metrics.map(metric=>[metric,roundEvaluationMetric(reports.reduce((total,report)=>total+report.metrics[metric],0)/reports.length)])),failures=metrics.filter(metric=>aggregate[metric]<thresholds[metric]).map(metric=>`${metric}:${aggregate[metric]}<${thresholds[metric]}`);return{scenario_count:reports.length,aggregate,scenarios:[...reports],passed:failures.length===0,failures}}async function runContextEvaluationCorpus(scenarios,reader,thresholds){const reports=[];for(const scenario of scenarios)reports.push(await runContextEvaluationScenario(scenario,reader));return summarizeContextEvaluationReports(reports,thresholds)}export{CONTEXT_EVALUATION_METRIC_NAMES,CONTEXT_RELEVANCE_SERVICE,CONTEXT_RELEVANCE_SIGNAL_NAMES,buildItemContextRelevanceCandidates,defaultScoreContextCandidates,evaluateContextRanking,runContextEvaluationCorpus,runContextEvaluationScenario,scoreContextCandidates,scoreContextCandidatesWithActiveExtensions,summarizeContextEvaluationReports};
|
|
2
2
|
//# sourceMappingURL=context-relevance.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
`,{encoding:"utf8",flag:"wx"})
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="01eff51c-7656-5c3f-b0c0-28594fca8a1e")}catch{}})();import{isFileAbsentError}from"../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{buildItemContextRelevanceCandidates}from"./context-relevance.js";import{readItemMetadataDerivedIndexState}from"./item-metadata-index.js";import{readLatestSubstantiveHistoryEvents}from"../core/history/event-index.js";import{canonicalizeContextRecencyCoordinate}from"./context/recency.js";const CONTEXT_SIGNAL_STORE_FORMAT_VERSION=3,CONTEXT_SIGNAL_SET_VERSION=2,STORED_CONTEXT_SIGNAL_NAMES=["recency","activity_density","graph_proximity","priority_pressure","risk_pressure","knowledge_density"],CONTEXT_RECENCY_SOURCES=new Set(["substantive_history","release_cohort","created_at"]),CONTEXT_SIGNAL_STORE_WARNING_DETAILS={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 isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNormalizedSignal(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=1}function compactSignals(signals){const compact={};for(const name of STORED_CONTEXT_SIGNAL_NAMES){const value=signals[name];if(value!==void 0){if(!isNormalizedSignal(value))throw new TypeError(`Context relevance signal ${name} must be a finite number from 0 to 1`);compact[name]=value}}return compact}function normalizedCountsById(items,count){const counts=items.map(item=>[item.id,count(item)]),maximum=Math.max(0,...counts.map(([,value])=>value));return Object.fromEntries(counts.map(([id,value])=>[id,maximum===0?0:value/maximum]))}function deriveGraphProximity(items){const degree=new Map(items.map(item=>[item.id,0])),increment=id=>{degree.set(id,(degree.get(id)??0)+1)};for(const item of items){typeof item.parent=="string"&&item.parent.trim()&&(increment(item.id),increment(item.parent.trim()));for(const dependency of item.dependencies??[])typeof dependency.id!="string"||!dependency.id.trim()||(increment(item.id),increment(dependency.id.trim()))}const maximum=Math.max(0,...degree.values());return Object.fromEntries(items.map(item=>[item.id,maximum===0?0:degree.get(item.id)/maximum]))}function stableSnapshotOptions(items,options){return{...options,activityDensity:options.activityDensity??normalizedCountsById(items,item=>(item.comments?.length??0)+(item.notes?.length??0)+(item.learnings?.length??0)+(item.test_runs?.length??0)),graphProximity:options.graphProximity??deriveGraphProximity(items)}}function recencyEvidenceFingerprint(candidates){const hash=createHash("sha256");for(const{id,signal_provenance:{recency:evidence}}of[...candidates].sort((left,right)=>left.id.localeCompare(right.id)))hash.update(JSON.stringify([id,evidence.source,evidence.coordinate,evidence.history_op??null,evidence.event_class??null]));return`sha256:${hash.digest("hex")}`}function parseSnapshotItem(value){if(!isRecord(value))return null;const signalProvenance=value.signal_provenance;if(![typeof value.id=="string",isRecord(value.signals),isRecord(signalProvenance)].every(Boolean))return null;const recency=signalProvenance.recency;if(!isRecord(recency))return null;const coordinate=canonicalizeContextRecencyCoordinate(recency.coordinate);if(coordinate===null)return null;const supportedSignals=new Set(STORED_CONTEXT_SIGNAL_NAMES),signalEntries=Object.entries(value.signals);return!signalEntries.every(([name,signal])=>supportedSignals.has(name)&&isNormalizedSignal(signal))||![typeof recency.source=="string"&&CONTEXT_RECENCY_SOURCES.has(recency.source),["undefined","string"].includes(typeof recency.history_op),[void 0,"substantive","maintenance"].includes(recency.event_class),recency.source==="substantive_history"?recency.event_class===void 0||recency.event_class==="substantive":recency.history_op===void 0&&recency.event_class===void 0].every(Boolean)?null:{id:value.id,signals:Object.fromEntries(signalEntries),signal_provenance:{recency:{source:recency.source,coordinate,history_op:recency.history_op,event_class:recency.event_class}}}}function parseSnapshotItems(values,expectedRecencyEvidenceFingerprint){const items=Array.from(values,parseSnapshotItem);if(items.some(item=>item===null))return null;const validItems=items;return new Set(validItems.map(item=>item.id)).size!==validItems.length||validItems.some(item=>item.id.trim().length===0)||expectedRecencyEvidenceFingerprint!==recencyEvidenceFingerprint(validItems)?null:validItems.sort((left,right)=>left.id.localeCompare(right.id))}function parseContextSignalSnapshot(value){if(!isRecord(value)||value.format_version!==CONTEXT_SIGNAL_STORE_FORMAT_VERSION||value.signal_set_version!==CONTEXT_SIGNAL_SET_VERSION||typeof value.source_cursor!="string"||value.source_cursor.trim().length===0||typeof value.recency_evidence_fingerprint!="string"||!/^sha256:[a-f0-9]{64}$/u.test(value.recency_evidence_fingerprint)||typeof value.generated_at!="string"||!Number.isFinite(Date.parse(value.generated_at))||value.source!=="derived_index"&&value.source!=="scan_fallback"||!Array.isArray(value.items))return null;const items=parseSnapshotItems(value.items,value.recency_evidence_fingerprint);return items===null?null:{format_version:CONTEXT_SIGNAL_STORE_FORMAT_VERSION,signal_set_version:CONTEXT_SIGNAL_SET_VERSION,source_cursor:value.source_cursor,recency_evidence_fingerprint:value.recency_evidence_fingerprint,generated_at:value.generated_at,source:value.source,items}}function validateSnapshotOptions(options){if(typeof options.sourceCursor!="string"||options.sourceCursor.trim().length===0)throw new TypeError("Context signal source cursor must be non-empty");if(!Number.isFinite(Date.parse(options.now)))throw new TypeError("Context signal snapshot clock must be a valid timestamp");if(options.source!=="derived_index"&&options.source!=="scan_fallback")throw new TypeError("Context signal snapshot source must be derived_index or scan_fallback")}function snapshotFromCandidates(candidates,options,fingerprint=recencyEvidenceFingerprint(candidates)){const candidateIds=candidates.map(({id})=>id);if(new Set(candidateIds).size!==candidateIds.length||candidateIds.some(id=>id.trim().length===0))throw new TypeError("Context signal snapshot item IDs must be unique and non-empty");const rows=candidates.map(({id,signals,signal_provenance})=>({id,signals:compactSignals(signals),signal_provenance})).sort((left,right)=>left.id.localeCompare(right.id));return Object.freeze({format_version:CONTEXT_SIGNAL_STORE_FORMAT_VERSION,signal_set_version:CONTEXT_SIGNAL_SET_VERSION,source_cursor:options.sourceCursor,recency_evidence_fingerprint:fingerprint,generated_at:options.now,source:options.source,items:Object.freeze(rows.map(row=>Object.freeze(row)))})}function buildContextSignalSnapshot(items,options){return validateSnapshotOptions(options),snapshotFromCandidates(buildItemContextRelevanceCandidates(items,stableSnapshotOptions(items,options)),options)}class JsonFileContextSignalStoreAdapter{filePath;constructor(filePath){if(typeof filePath!="string"||filePath.trim().length===0)throw new TypeError("Context signal store path must be non-empty");this.filePath=path.resolve(filePath)}async read(){try{return JSON.parse(await fs.readFile(this.filePath,"utf8"))}catch(error){if(isRecord(error)&&isFileAbsentError(error))return null;throw error}}async write(snapshot){const directory=path.dirname(this.filePath);await fs.mkdir(directory,{recursive:!0});const temporaryPath=path.join(directory,`.${path.basename(this.filePath)}.${randomUUID()}.tmp`);try{await fs.writeFile(temporaryPath,`${JSON.stringify(snapshot)}
|
|
2
|
+
`,{encoding:"utf8",flag:"wx"}),await fs.rename(temporaryPath,this.filePath)}finally{try{await fs.rm(temporaryPath,{force:!0})}catch{}}}}class ContextSignalStore{adapter;constructor(adapter){this.adapter=adapter}async readOrRebuild(items,options){validateSnapshotOptions(options);const warnings=[];let snapshot=null;try{const serialized=await this.adapter.read();snapshot=parseContextSignalSnapshot(serialized),serialized!==null&&snapshot===null&&warnings.push("context_signal_store_invalid")}catch{warnings.push("context_signal_store_invalid")}const authoritativeIds=items.map(item=>item.id).sort((left,right)=>left.localeCompare(right)),snapshotIds=snapshot?.items.map(item=>item.id)??[],authoritativeCandidates=buildItemContextRelevanceCandidates(items,stableSnapshotOptions(items,options)),authoritativeFingerprint=recencyEvidenceFingerprint(authoritativeCandidates),fresh=snapshot!==null&&snapshot.source_cursor===options.sourceCursor&&snapshot.recency_evidence_fingerprint===authoritativeFingerprint&&snapshot.source===options.source&&snapshotIds.length===authoritativeIds.length&&snapshotIds.every((id,index)=>id===authoritativeIds[index]);let resolvedSnapshot;if(fresh&&snapshot!==null)resolvedSnapshot=snapshot;else{snapshot!==null&&warnings.push("context_signal_store_stale"),resolvedSnapshot=snapshotFromCandidates(authoritativeCandidates,options,authoritativeFingerprint);try{await this.adapter.write(resolvedSnapshot)}catch{warnings.push("context_signal_store_write_failed")}}const snapshotItemsById=new Map(resolvedSnapshot.items.map(item=>[item.id,item]));return{snapshot:resolvedSnapshot,candidates:authoritativeCandidates.map(candidate=>({...candidate,signals:{...candidate.signals,...snapshotItemsById.get(candidate.id)?.signals},signal_provenance:snapshotItemsById.get(candidate.id).signal_provenance})),cache_status:fresh?"fresh":"rebuilt",warnings,warning_details:warnings.map(warning=>CONTEXT_SIGNAL_STORE_WARNING_DETAILS[warning])}}}function fallbackWorkspaceCursor(items){const hash=createHash("sha256");for(const item of[...items].sort((left,right)=>left.id.localeCompare(right.id)))hash.update(JSON.stringify([item.id,item.updated_at,item.status,item.parent??null,item.priority??null,item.risk??null,(item.dependencies??[]).map(dependency=>dependency.id).sort(),item.comments?.length??0,item.notes?.length??0,item.learnings?.length??0,item.test_runs?.length??0]));return`scan:${hash.digest("hex")}`}async function readWorkspaceContextSignals(items,options){const hasSourceCursor=options.sourceCursor!==void 0,hasSource=options.source!==void 0;if(hasSourceCursor!==hasSource)throw new TypeError("Context signal source and source cursor must be provided together");if(options.storeKey!==void 0&&!/^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/u.test(options.storeKey))throw new TypeError("Context signal store key must be a filesystem-safe identifier");const indexState=hasSourceCursor?null:await readItemMetadataDerivedIndexState(options.pmRoot),sourceCursor=options.sourceCursor??indexState?.source_cursor??fallbackWorkspaceCursor(items),source=options.source??(indexState===null?"scan_fallback":"derived_index"),store=new ContextSignalStore(new JsonFileContextSignalStoreAdapter(path.join(options.pmRoot,"runtime",options.storeKey?`context-signals-${options.storeKey}.json`:"context-signals.json"))),recencyEvidence=options.recencyEvidence??Object.fromEntries(Object.entries(await readLatestSubstantiveHistoryEvents(options.pmRoot,items.map(item=>item.id))).map(([id,event])=>[id,{source:"substantive_history",coordinate:event.entry.ts,history_op:event.entry.op,event_class:"substantive"}]));return store.readOrRebuild(items,{...options,recencyEvidence,sourceCursor,source})}export{CONTEXT_SIGNAL_SET_VERSION,CONTEXT_SIGNAL_STORE_FORMAT_VERSION,CONTEXT_SIGNAL_STORE_WARNING_DETAILS,ContextSignalStore,JsonFileContextSignalStoreAdapter,buildContextSignalSnapshot,parseContextSignalSnapshot,readWorkspaceContextSignals};
|
|
3
3
|
//# sourceMappingURL=context-signal-store.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3b38d564-6034-54ae-ad24-eddba01a2c5c")}catch(e2){}})();import{randomUUID}from"node:crypto";import{appendEvents,readEvents,resolveNow,ContextUsageValidationError,CONTEXT_USAGE_LIMITS}from"./context/usage-ledger.js";import{ContextUsageValidationError as ContextUsageValidationError2,CONTEXT_USAGE_LIMITS as CONTEXT_USAGE_LIMITS2}from"./context/usage-ledger.js";const DAY_MS=864e5;const CONTEXT_USAGE_SERVING_RECEIPT=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function asObjectRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)?value:null}function attachContextUsageServingReceipt(result,receipt){const record=asObjectRecord(result);if(record!==null&&receipt!==null){record[CONTEXT_USAGE_SERVING_RECEIPT]=receipt}}function propagateContextUsageServingReceipt(source,target){const sourceRecord=asObjectRecord(source);const targetRecord=asObjectRecord(target);const receipt=sourceRecord?.[CONTEXT_USAGE_SERVING_RECEIPT];if(targetRecord!==null&&receipt!==void 0){targetRecord[CONTEXT_USAGE_SERVING_RECEIPT]=receipt}}function receiptFromResult(result){return asObjectRecord(result)?.[CONTEXT_USAGE_SERVING_RECEIPT]??null}function resultReceiptSaysOmitted(result){const record=asObjectRecord(result);for(const key of["read_output","context_intent"]){const receipt=asObjectRecord(record?.[key]);if(receipt?.result_omitted===true)return true}return false}function addContextUsageId(ids,value){if(typeof value==="string"&&value.trim().length>0){ids.add(value.trim())}}function addContextUsageDirectRows(ids,value){if(!Array.isArray(value))return;for(const row of value){addContextUsageId(ids,asObjectRecord(row)?.id)}}function addContextUsageIdList(ids,value){if(!Array.isArray(value))return;for(const itemId of value)addContextUsageId(ids,itemId)}function collectNextResultItemIds(record,ids){const rows=asObjectRecord(record.recommended)===null?[]:[record.recommended];for(const key of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"]){if(Array.isArray(record[key]))rows.push(...record[key])}for(const value of rows){const row=asObjectRecord(value);addContextUsageId(ids,row?.id);for(const blocker of Array.isArray(row?.blockers)?row.blockers:[]){addContextUsageId(ids,asObjectRecord(blocker)?.id)}for(const unblockedId of Array.isArray(row?.unblocks)?row.unblocks:[]){addContextUsageId(ids,unblockedId)}}}function collectContextResultItemIds(record,ids){for(const key of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"]){addContextUsageDirectRows(ids,record[key])}for(const value of Array.isArray(record.blockers)?record.blockers:[]){addContextUsageId(ids,asObjectRecord(value)?.blocked_by)}collectContextNestedItemIds(record,ids)}function collectContextNestedItemIds(record,ids){for(const value of Array.isArray(record.hierarchy)?record.hierarchy:[]){const node=asObjectRecord(value);addContextUsageId(ids,node?.id);addContextUsageDirectRows(ids,node?.children)}for(const key of["files","workload"]){for(const value of Array.isArray(record[key])?record[key]:[]){addContextUsageIdList(ids,asObjectRecord(value)?.items)}}const agenda=asObjectRecord(record.agenda);for(const value of Array.isArray(agenda?.events)?agenda.events:[]){addContextUsageId(ids,asObjectRecord(value)?.item_id)}const tests=asObjectRecord(record.tests);addContextUsageIdList(ids,tests?.items_failing)}function collectContextUsageDeliveredItemIds(result,surface){const record=asObjectRecord(result);if(record===null||resultReceiptSaysOmitted(result))return[];const ids=new Set;if(surface==="next"){collectNextResultItemIds(record,ids)}else{collectContextResultItemIds(record,ids)}return[...ids]}async function finalizeContextUsageDelivery(options){const receipt=receiptFromResult(options.result);if(receipt===null)return false;const resultOmitted=resultReceiptSaysOmitted(options.result);await recordContextUsageDelivery({pmRoot:options.pmRoot,receipt,deliveredItemIds:collectContextUsageDeliveredItemIds(options.result,receipt.surface),resultOmitted});return true}async function recordContextUsageServing(options){if([process.env.PM_CONTEXT_USAGE_DISABLED==="1",options.enabled===false].includes(true))return null;if(!options.author.trim()||options.rows.some(row=>!row.id.trim()||!Number.isInteger(row.rank)||row.rank<1)){throw new ContextUsageValidationError("Context usage serving requires an author and valid ranked rows")}const normalizedRows=options.rows.map(row=>({id:row.id.trim(),rank:row.rank,included:row.included}));if(new Set(normalizedRows.map(row=>row.id)).size!==normalizedRows.length){throw new ContextUsageValidationError("Context usage serving requires unique normalized row ids")}const recordedRows=normalizedRows.slice(0,CONTEXT_USAGE_LIMITS.max_serving_rows);const receipt={serve_id:randomUUID(),author:options.author.trim(),surface:options.surface,rows:normalizedRows,recorded_item_ids:recordedRows.map(row=>row.id)};receipt.storage=await appendEvents(options,[{kind:"serve",schema_version:2,serve_id:receipt.serve_id,at:resolveNow(options).iso,author:options.author.trim(),surface:options.surface,profile:options.profile.trim()||"balanced",rows:recordedRows,candidate_count:normalizedRows.length,omitted_row_count:normalizedRows.length-recordedRows.length,result_omitted:false,packed_item_ids:recordedRows.filter(row=>row.included).map(row=>row.id)}]);return receipt}async function recordContextUsageDelivery(options){if(options.receipt===null||process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===false){return}const rankedIds=new Set(options.receipt.rows.map(row=>row.id));const deliveredItemIds=[...new Set(options.deliveredItemIds.map(id=>id.trim()))];if(deliveredItemIds.some(id=>id.length===0||!rankedIds.has(id))||options.resultOmitted&&deliveredItemIds.length>0){throw new ContextUsageValidationError("Context usage delivery requires emitted ranked ids and zero ids for an omitted result")}const recordedIds=new Set(options.receipt.recorded_item_ids??options.receipt.rows.map(row=>row.id));const delivery={kind:"delivery",schema_version:2,serve_id:options.receipt.serve_id,at:resolveNow(options).iso,author:options.receipt.author,surface:options.receipt.surface,result_omitted:options.resultOmitted,delivered_item_ids:deliveredItemIds.filter(id=>recordedIds.has(id))};await appendEvents(options,[delivery],delivery.serve_id)}async function recordContextUsageTouch(options){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===false)return;if(!options.author.trim()||!options.itemId.trim()||!options.intent.trim()){throw new ContextUsageValidationError("Context usage touch requires author, itemId, and intent")}await appendEvents(options,[{kind:"touch",at:resolveNow(options).iso,author:options.author.trim(),item_id:options.itemId.trim(),intent:options.intent.trim()}])}async function recordContextUsageTouches(options){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===false||options.itemIds.length===0)return;const author=options.author.trim();const intent=options.intent.trim();if(!author||!intent){throw new ContextUsageValidationError("Context usage touch requires author and intent")}const itemIds=new Set;for(const itemId of options.itemIds){if(typeof itemId!=="string"){throw new ContextUsageValidationError("Context usage touch requires string itemIds")}const trimmedId=itemId.trim();if(!trimmedId)throw new ContextUsageValidationError("Context usage touch requires non-empty itemId");itemIds.add(trimmedId)}const at=resolveNow(options).iso;const events=[...itemIds].map(itemId=>({kind:"touch",at,author,item_id:itemId,intent}));await appendEvents(options,events)}function findTouchTimeInHorizon(touches,itemId,servedAt,horizonMs){return touches.find(({entry,time})=>entry.item_id===itemId&&time>=servedAt&&time-servedAt<=horizonMs)?.time}function firstDeliveriesByServeId(events,author){const deliveries=new Map;for(const event of events){if(event.kind==="delivery"&&event.schema_version===2&&event.author===author&&!deliveries.has(event.serve_id)){deliveries.set(event.serve_id,event)}}return deliveries}async function readContextUsageAffinity(options){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===false)return{affinity:{},positive_judgments:0,serving_events:0,untrusted_serving_events:0};const events=await readEvents(options);const now=resolveNow(options).ms;const horizonMs=(options.horizonHours??24)*36e5;if(![Number.isFinite(horizonMs),horizonMs>0].every(Boolean))throw new ContextUsageValidationError("Context usage horizonHours must be positive");const author=options.author.trim();const touches=events.filter(event=>event.kind==="touch").filter(event=>event.author===author).map(entry=>({entry,time:Date.parse(entry.at)}));const scores=new Map;let servingEvents=0;let untrustedServingEvents=0;let positiveJudgments=0;const deliveries=firstDeliveriesByServeId(events,author);events.filter(event=>event.kind==="serve").filter(event=>event.author===author).forEach(event=>{if(![event.schema_version===2,Boolean(event.serve_id)].every(Boolean)){untrustedServingEvents+=1;return}servingEvents+=1;const servedAt=Date.parse(event.at);const delivery=deliveries.get(event.serve_id);const deliveredIds=new Set(delivery?.delivered_item_ids??[]);for(const row of event.rows){if(!deliveredIds.has(row.id))continue;const touchTime=findTouchTimeInHorizon(touches,row.id,servedAt,horizonMs);if(touchTime===void 0)continue;positiveJudgments+=1;const ageDays=Math.max(0,(now-touchTime)/DAY_MS);scores.set(row.id,(scores.get(row.id)??0)+Math.exp(-ageDays/14))}});const maximum=Math.max(0,...scores.values());const affinity=Object.fromEntries([...scores.entries()].map(([id,score])=>[id,maximum===0?.05:.05+.95*score/maximum]));return{affinity,positive_judgments:positiveJudgments,serving_events:servingEvents,untrusted_serving_events:untrustedServingEvents}}export{CONTEXT_USAGE_LIMITS2 as CONTEXT_USAGE_LIMITS,ContextUsageValidationError2 as ContextUsageValidationError,attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,finalizeContextUsageDelivery,propagateContextUsageServingReceipt,readContextUsageAffinity,recordContextUsageDelivery,recordContextUsageServing,recordContextUsageTouch,recordContextUsageTouches};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e76b38ce-b2aa-589b-9d17-0952eca9e7a2")}catch{}})();import{randomUUID}from"node:crypto";import{appendEvents,readEvents,resolveNow,ContextUsageValidationError,CONTEXT_USAGE_LIMITS}from"./context/usage-ledger.js";import{ContextUsageValidationError as ContextUsageValidationError2,CONTEXT_USAGE_LIMITS as CONTEXT_USAGE_LIMITS2}from"./context/usage-ledger.js";const DAY_MS=864e5,CONTEXT_USAGE_SERVING_RECEIPT=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function asObjectRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:null}function attachContextUsageServingReceipt(result,receipt){const record=asObjectRecord(result);record!==null&&receipt!==null&&(record[CONTEXT_USAGE_SERVING_RECEIPT]=receipt)}function propagateContextUsageServingReceipt(source,target){const sourceRecord=asObjectRecord(source),targetRecord=asObjectRecord(target),receipt=sourceRecord?.[CONTEXT_USAGE_SERVING_RECEIPT];targetRecord!==null&&receipt!==void 0&&(targetRecord[CONTEXT_USAGE_SERVING_RECEIPT]=receipt)}function receiptFromResult(result){return asObjectRecord(result)?.[CONTEXT_USAGE_SERVING_RECEIPT]??null}function resultReceiptSaysOmitted(result){const record=asObjectRecord(result);for(const key of["read_output","context_intent"])if(asObjectRecord(record?.[key])?.result_omitted===!0)return!0;return!1}function addContextUsageId(ids,value){typeof value=="string"&&value.trim().length>0&&ids.add(value.trim())}function addContextUsageDirectRows(ids,value){if(Array.isArray(value))for(const row of value)addContextUsageId(ids,asObjectRecord(row)?.id)}function addContextUsageIdList(ids,value){if(Array.isArray(value))for(const itemId of value)addContextUsageId(ids,itemId)}function collectNextResultItemIds(record,ids){const rows=asObjectRecord(record.recommended)===null?[]:[record.recommended];for(const key of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"])Array.isArray(record[key])&&rows.push(...record[key]);for(const value of rows){const row=asObjectRecord(value);addContextUsageId(ids,row?.id);for(const blocker of Array.isArray(row?.blockers)?row.blockers:[])addContextUsageId(ids,asObjectRecord(blocker)?.id);for(const unblockedId of Array.isArray(row?.unblocks)?row.unblocks:[])addContextUsageId(ids,unblockedId)}}function collectContextResultItemIds(record,ids){for(const key of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])addContextUsageDirectRows(ids,record[key]);for(const value of Array.isArray(record.blockers)?record.blockers:[])addContextUsageId(ids,asObjectRecord(value)?.blocked_by);collectContextNestedItemIds(record,ids)}function collectContextNestedItemIds(record,ids){for(const value of Array.isArray(record.hierarchy)?record.hierarchy:[]){const node=asObjectRecord(value);addContextUsageId(ids,node?.id),addContextUsageDirectRows(ids,node?.children)}for(const key of["files","workload"])for(const value of Array.isArray(record[key])?record[key]:[])addContextUsageIdList(ids,asObjectRecord(value)?.items);const agenda=asObjectRecord(record.agenda);for(const value of Array.isArray(agenda?.events)?agenda.events:[])addContextUsageId(ids,asObjectRecord(value)?.item_id);const tests=asObjectRecord(record.tests);addContextUsageIdList(ids,tests?.items_failing)}function collectContextUsageDeliveredItemIds(result,surface){const record=asObjectRecord(result);if(record===null||resultReceiptSaysOmitted(result))return[];const ids=new Set;return surface==="next"?collectNextResultItemIds(record,ids):collectContextResultItemIds(record,ids),[...ids]}async function finalizeContextUsageDelivery(options){const receipt=receiptFromResult(options.result);if(receipt===null)return!1;const resultOmitted=resultReceiptSaysOmitted(options.result);return await recordContextUsageDelivery({pmRoot:options.pmRoot,receipt,deliveredItemIds:collectContextUsageDeliveredItemIds(options.result,receipt.surface),resultOmitted}),!0}async function recordContextUsageServing(options){if([process.env.PM_CONTEXT_USAGE_DISABLED==="1",options.enabled===!1].includes(!0))return null;if(!options.author.trim()||options.rows.some(row=>!row.id.trim()||!Number.isInteger(row.rank)||row.rank<1))throw new ContextUsageValidationError("Context usage serving requires an author and valid ranked rows");const normalizedRows=options.rows.map(row=>({id:row.id.trim(),rank:row.rank,included:row.included}));if(new Set(normalizedRows.map(row=>row.id)).size!==normalizedRows.length)throw new ContextUsageValidationError("Context usage serving requires unique normalized row ids");const recordedRows=normalizedRows.slice(0,CONTEXT_USAGE_LIMITS.max_serving_rows),receipt={serve_id:randomUUID(),author:options.author.trim(),surface:options.surface,rows:normalizedRows,recorded_item_ids:recordedRows.map(row=>row.id)};return receipt.storage=await appendEvents(options,[{kind:"serve",schema_version:2,serve_id:receipt.serve_id,at:resolveNow(options).iso,author:options.author.trim(),surface:options.surface,profile:options.profile.trim()||"balanced",rows:recordedRows,candidate_count:normalizedRows.length,omitted_row_count:normalizedRows.length-recordedRows.length,result_omitted:!1,packed_item_ids:recordedRows.filter(row=>row.included).map(row=>row.id)}]),receipt}async function recordContextUsageDelivery(options){if(options.receipt===null||process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===!1)return;const rankedIds=new Set(options.receipt.rows.map(row=>row.id)),deliveredItemIds=[...new Set(options.deliveredItemIds.map(id=>id.trim()))];if(deliveredItemIds.some(id=>id.length===0||!rankedIds.has(id))||options.resultOmitted&&deliveredItemIds.length>0)throw new ContextUsageValidationError("Context usage delivery requires emitted ranked ids and zero ids for an omitted result");const recordedIds=new Set(options.receipt.recorded_item_ids??options.receipt.rows.map(row=>row.id)),delivery={kind:"delivery",schema_version:2,serve_id:options.receipt.serve_id,at:resolveNow(options).iso,author:options.receipt.author,surface:options.receipt.surface,result_omitted:options.resultOmitted,delivered_item_ids:deliveredItemIds.filter(id=>recordedIds.has(id))};await appendEvents(options,[delivery],delivery.serve_id)}async function recordContextUsageTouch(options){if(!(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===!1)){if(!options.author.trim()||!options.itemId.trim()||!options.intent.trim())throw new ContextUsageValidationError("Context usage touch requires author, itemId, and intent");await appendEvents(options,[{kind:"touch",at:resolveNow(options).iso,author:options.author.trim(),item_id:options.itemId.trim(),intent:options.intent.trim()}])}}async function recordContextUsageTouches(options){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===!1||options.itemIds.length===0)return;const author=options.author.trim(),intent=options.intent.trim();if(!author||!intent)throw new ContextUsageValidationError("Context usage touch requires author and intent");const itemIds=new Set;for(const itemId of options.itemIds){if(typeof itemId!="string")throw new ContextUsageValidationError("Context usage touch requires string itemIds");const trimmedId=itemId.trim();if(!trimmedId)throw new ContextUsageValidationError("Context usage touch requires non-empty itemId");itemIds.add(trimmedId)}const at=resolveNow(options).iso,events=[...itemIds].map(itemId=>({kind:"touch",at,author,item_id:itemId,intent}));await appendEvents(options,events)}function findTouchTimeInHorizon(touches,itemId,servedAt,horizonMs){return touches.find(({entry,time})=>entry.item_id===itemId&&time>=servedAt&&time-servedAt<=horizonMs)?.time}function firstDeliveriesByServeId(events,author){const deliveries=new Map;for(const event of events)event.kind==="delivery"&&event.schema_version===2&&event.author===author&&!deliveries.has(event.serve_id)&&deliveries.set(event.serve_id,event);return deliveries}async function readContextUsageAffinity(options){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===!1)return{affinity:{},positive_judgments:0,serving_events:0,untrusted_serving_events:0};const events=await readEvents(options),now=resolveNow(options).ms,horizonMs=(options.horizonHours??24)*36e5;if(![Number.isFinite(horizonMs),horizonMs>0].every(Boolean))throw new ContextUsageValidationError("Context usage horizonHours must be positive");const author=options.author.trim(),touches=events.filter(event=>event.kind==="touch").filter(event=>event.author===author).map(entry=>({entry,time:Date.parse(entry.at)})),scores=new Map;let servingEvents=0,untrustedServingEvents=0,positiveJudgments=0;const deliveries=firstDeliveriesByServeId(events,author);events.filter(event=>event.kind==="serve").filter(event=>event.author===author).forEach(event=>{if(![event.schema_version===2,!!event.serve_id].every(Boolean)){untrustedServingEvents+=1;return}servingEvents+=1;const servedAt=Date.parse(event.at),delivery=deliveries.get(event.serve_id),deliveredIds=new Set(delivery?.delivered_item_ids??[]);for(const row of event.rows){if(!deliveredIds.has(row.id))continue;const touchTime=findTouchTimeInHorizon(touches,row.id,servedAt,horizonMs);if(touchTime===void 0)continue;positiveJudgments+=1;const ageDays=Math.max(0,(now-touchTime)/DAY_MS);scores.set(row.id,(scores.get(row.id)??0)+Math.exp(-ageDays/14))}});const maximum=Math.max(0,...scores.values());return{affinity:Object.fromEntries([...scores.entries()].map(([id,score])=>[id,maximum===0?.05:.05+.95*score/maximum])),positive_judgments:positiveJudgments,serving_events:servingEvents,untrusted_serving_events:untrustedServingEvents}}export{CONTEXT_USAGE_LIMITS2 as CONTEXT_USAGE_LIMITS,ContextUsageValidationError2 as ContextUsageValidationError,attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,finalizeContextUsageDelivery,propagateContextUsageServingReceipt,readContextUsageAffinity,recordContextUsageDelivery,recordContextUsageServing,recordContextUsageTouch,recordContextUsageTouches};
|
|
2
2
|
//# sourceMappingURL=context-usage.js.map
|
package/dist/sdk/contracts.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0aafe4f4-d636-597e-b594-c0a32ebced38")}catch{}})();export*from"./cli-contracts.js";export*from"./graph/query-contracts.js";export*from"./cli-contracts/grammar-contracts.js";export*from"./cli-contracts/command-exit-contracts.js";export*from"./context-intent-contracts.js";export*from"./error-code-catalog.js";export*from"./generated-error-code-catalog.js";export*from"./flag-invocation-contracts.js";export*from"./cli-contracts/flag-lexicon-contracts.js";export*from"./output-token-accounting.js";export*from"./output-contracts.js";export*from"./agent/task-transcript-contracts.js";export*from"./read-output-contracts.js";export*from"./history/attestation-contract.js";export*from"../core/history/operation-contract.js";export*from"./agent/refusal-closure.js";export*from"./agent/closed-domain-contracts.js";export*from"./agent/tracker-preflight-contracts.js";
|
|
2
2
|
//# sourceMappingURL=contracts.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="48d03e9b-14a4-545c-8e5d-5f5f2092a113")}catch{}})();import{AGENT_PROVENANCE_DIMENSIONS,BUILTIN_AGENT_PROVENANCE_ADAPTERS,BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,diagnoseAgentIdentity,detectAgentIdentity,detectHarnessIdentity,listAgentProvenanceAdapters,normalizeAgentProvenanceAdapterValue,readAuthorEnvironment,registerHarnessSignalDescriptors,registerAgentProvenanceAdapters,resolveAuthorIdentity,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,writeAuthorEnvironment}from"../core/shared/author.js";import{SEMANTIC_ATTRIBUTION_LIMITS,recordClaimSemanticAttribution,recordFocusSemanticAttribution,recordReleaseSemanticAttribution,resolveSemanticLineageIds,semanticAttributionAffinity}from"./context/semantic-session-attribution.js";import{explainSourceTraceability,parseSourceLineRange}from"./traceability/source-traceability.js";import{analyzeAgentProvenanceDescriptorCoverage,evaluateSemanticAttributionCoverage,groupHistoryByEpisode,resolveHistoryEpisodeGroupIdentity,summarizeAgentProvenance,summarizeAgentModelProvenance}from"./provenance.js";import{analyzeSdkCliParameterCompleteness}from"./cli-contracts.js";export{AGENT_PROVENANCE_DIMENSIONS,BUILTIN_AGENT_PROVENANCE_ADAPTERS,BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,SEMANTIC_ATTRIBUTION_LIMITS,analyzeAgentProvenanceDescriptorCoverage,analyzeSdkCliParameterCompleteness,detectAgentIdentity,detectHarnessIdentity,diagnoseAgentIdentity,evaluateSemanticAttributionCoverage,explainSourceTraceability,groupHistoryByEpisode,listAgentProvenanceAdapters,normalizeAgentProvenanceAdapterValue,parseSourceLineRange,readAuthorEnvironment,recordClaimSemanticAttribution,recordFocusSemanticAttribution,recordReleaseSemanticAttribution,registerAgentProvenanceAdapters,registerHarnessSignalDescriptors,resolveAuthorIdentity,resolveHistoryEpisodeGroupIdentity,resolveSemanticLineageIds,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,semanticAttributionAffinity,summarizeAgentModelProvenance,summarizeAgentProvenance,writeAuthorEnvironment};
|
|
2
2
|
//# sourceMappingURL=core-governance.js.map
|
package/dist/sdk/core.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3eaa41f7-77a1-5838-8a2f-2ab6a49c21ef")}catch{}})();import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,listAllComplete}from"./runtime.js";export*from"./core-governance.js";export*from"./agent-session-context.js";import{isAlreadyClaimedError}from"./lifecycle/claim.js";import{PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions}from"./read-output-contracts.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,aggregate,append,applyReadOutputDimensions,applyReadOutputSessionReferences,attachReadOutputSessionReceipt,canonicalDocument,claim,claimNext,classifyItemFormatVersion,close,comments,context,copy,create,createPmCliExpectedError,decodeReadOutputContinuationCursor,deleteItem,deps,docs,effectiveItemFormatVersion,emptyImportedDocument,encodeReadOutputContinuationCursor,files,filesDiscover,focus,get,graph,isAlreadyClaimedError,isPmCliExpectedError,isReadOutputBudgetExceeded,learnings,list,listAllComplete,next,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,notes,nowIso,parseReadOutputSession,readOutputSessionRemainingTokens,release,reopen,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,restore,runAction,search,serializeItemDocument,update,validateReadOutputOptions};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|
package/dist/sdk/corpus-shape.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="9394fb87-fb36-5886-b262-ce2787326053")}catch(e2){}})();const PM_CORPUS_SHAPE_SCHEMA="https://schema.unbrained.dev/pm/corpus-shape/v1";function positiveInteger(value,field){if(!Number.isSafeInteger(value)||value<=0){throw new TypeError(`Corpus shape ${field} must be a positive safe integer`)}return value}function nonNegativeInteger(value,field){if(!Number.isSafeInteger(value)||value<0){throw new TypeError(`Corpus shape ${field} must be a non-negative safe integer`)}return value}function deepFreeze(value){if(typeof value!=="object"||value===null||Object.isFrozen(value)){return}for(const nested of Object.values(value)){deepFreeze(nested)}Object.freeze(value)}function defineCorpusShape(shape){if(shape.schema!==PM_CORPUS_SHAPE_SCHEMA){throw new TypeError(`Unsupported corpus shape schema: ${shape.schema}`)}if(shape.name.trim().length===0||shape.description.trim().length===0){throw new TypeError("Corpus shape name and description must be non-empty")}positiveInteger(shape.hierarchy_depth,"hierarchy_depth");positiveInteger(shape.hierarchy_fanout,"hierarchy_fanout");nonNegativeInteger(shape.age_span_days,"age_span_days");positiveInteger(shape.history_entries_per_item,"history_entries_per_item");nonNegativeInteger(shape.comments_per_100_items,"comments_per_100_items");nonNegativeInteger(shape.notes_per_100_items,"notes_per_100_items");nonNegativeInteger(shape.learnings_per_100_items,"learnings_per_100_items");positiveInteger(shape.author_cardinality,"author_cardinality");positiveInteger(shape.component_count,"component_count");if(shape.edge_kind_mix.length===0||shape.edge_kind_mix.some(edge=>edge.kind.trim().length===0||edge.weight<=0)){throw new TypeError("Corpus shape edge_kind_mix requires non-empty kinds with positive weights")}if(shape.terminal_statuses.some(status=>!shape.custom_statuses.includes(status))){throw new TypeError("Corpus shape terminal_statuses must be declared in custom_statuses")}const detached=structuredClone(shape);deepFreeze(detached);return detached}const COMMON_EDGE_MIX=[{kind:"implements",weight:5},{kind:"blocked_by",weight:2},{kind:"discovered_from",weight:2},{kind:"verifies",weight:2},{kind:"supersedes",weight:1},{kind:"related",weight:4}];const BUILTIN_CORPUS_SHAPES=Object.freeze({scratch:defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"scratch",description:"Seconds-old, shallow project with minimal history.",hierarchy_depth:2,hierarchy_fanout:50,age_span_days:0,history_entries_per_item:1,comments_per_100_items:2,notes_per_100_items:1,learnings_per_100_items:1,edge_kind_mix:[{kind:"related",weight:1}],author_cardinality:2,component_count:1,include_cycles:false,custom_types:[],custom_statuses:[],terminal_statuses:[],custom_fields:[]}),representative:defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"representative",description:"Medium-lived project with rich evidence and typed lineage.",hierarchy_depth:5,hierarchy_fanout:8,age_span_days:730,history_entries_per_item:12,comments_per_100_items:30,notes_per_100_items:12,learnings_per_100_items:10,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:32,component_count:1,include_cycles:false,custom_types:["Experiment"],custom_statuses:["review"],terminal_statuses:[],custom_fields:["domain"]}),"deep-graph":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"deep-graph",description:"Deep typed relationship graph with deterministic cycles.",hierarchy_depth:16,hierarchy_fanout:2,age_span_days:3650,history_entries_per_item:6,comments_per_100_items:15,notes_per_100_items:8,learnings_per_100_items:8,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:16,component_count:1,include_cycles:true,custom_types:[],custom_statuses:[],terminal_statuses:[],custom_fields:[]}),"multi-decade":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"multi-decade",description:"Thirty-year event history with dense per-item evolution.",hierarchy_depth:6,hierarchy_fanout:6,age_span_days:10958,history_entries_per_item:24,comments_per_100_items:40,notes_per_100_items:20,learnings_per_100_items:16,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:64,component_count:1,include_cycles:false,custom_types:["Program"],custom_statuses:["archived"],terminal_statuses:["archived"],custom_fields:["portfolio"]}),"disconnected-archive":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"disconnected-archive",description:"Multiple disconnected historical project components.",hierarchy_depth:4,hierarchy_fanout:10,age_span_days:7305,history_entries_per_item:8,comments_per_100_items:10,notes_per_100_items:5,learnings_per_100_items:6,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:24,component_count:5,include_cycles:false,custom_types:["Archive"],custom_statuses:["archived"],terminal_statuses:["archived"],custom_fields:["archive_source"]})});function listBuiltinCorpusShapes(){return Object.keys(BUILTIN_CORPUS_SHAPES).sort().map(name=>BUILTIN_CORPUS_SHAPES[name])}function resolveBuiltinCorpusShape(name){const normalized=name.trim().toLowerCase();if(!Object.hasOwn(BUILTIN_CORPUS_SHAPES,normalized)){throw new TypeError(`Unknown corpus shape "${name}". Available: ${Object.keys(BUILTIN_CORPUS_SHAPES).join(", ")}`)}return BUILTIN_CORPUS_SHAPES[normalized]}const expandedEdgeKinds=new WeakMap;function selectedEdgeKinds(index,shape){if(index===0){return[]}let expanded=expandedEdgeKinds.get(shape);if(expanded===void 0){expanded=shape.edge_kind_mix.flatMap(entry=>Array.from({length:entry.weight},()=>entry.kind));expandedEdgeKinds.set(shape,expanded)}const kinds=[expanded[index%expanded.length]];if(shape.include_cycles&&index>2&&index%17===0){kinds.push("related")}return[...new Set(kinds)]}function buildCorpusShapeItemPlan(shape,index,itemCount,seed=42){nonNegativeInteger(index,"item index");positiveInteger(itemCount,"item count");if(index>=itemCount){throw new RangeError(`Corpus item index ${index} exceeds ${itemCount}`)}const componentCount=Math.min(shape.component_count,itemCount);const component=index%componentCount;const componentPosition=Math.floor(index/componentCount);let hierarchyCapacity=0;let levelWidth=1;for(let depth=0;depth<shape.hierarchy_depth;depth+=1){hierarchyCapacity=Math.min(Number.MAX_SAFE_INTEGER,hierarchyCapacity+levelWidth);levelWidth=Math.min(Number.MAX_SAFE_INTEGER,levelWidth*shape.hierarchy_fanout)}const treeOffset=componentPosition%hierarchyCapacity;const treeStart=componentPosition-treeOffset;const parentIndex=treeOffset===0?void 0:component+(treeStart+Math.floor((treeOffset-1)/shape.hierarchy_fanout))*componentCount;const base=Date.UTC(2026,0,1);const spanMs=shape.age_span_days*864e5;const timestamp=new Date(base+(itemCount===1?0:Math.round(index/(itemCount-1)*spanMs))).toISOString();const annotationBucket=(index*37+seed)%100;return{index,id:`pm-s${index.toString(36).padStart(7,"0")}`,...parentIndex===void 0?{}:{parent:`pm-s${parentIndex.toString(36).padStart(7,"0")}`},component,timestamp,author:`pm-corpus-agent-${(index+seed)%Math.min(shape.author_cardinality,itemCount)}`,history_entry_count:shape.history_entries_per_item,dependency_kinds:selectedEdgeKinds(index,shape),has_comment:annotationBucket<shape.comments_per_100_items,has_note:annotationBucket<shape.notes_per_100_items,has_learning:annotationBucket<shape.learnings_per_100_items,...shape.custom_types.length>0&&index%11===0?{custom_type:shape.custom_types[index%shape.custom_types.length]}:{},...shape.custom_statuses.length>0&&index%13===0?{custom_status:shape.custom_statuses[index%shape.custom_statuses.length]}:{}}}class IncrementalCorpusShapeMeasurement{shape;authors=new Set;components=new Set;depths=new Map;childCounts=new Map;edgeKinds={};expectedEdgeKinds={};annotations={comments:0,notes:0,learnings:0};annotationFields;planMismatches=[];itemCount=0;observedDepth=0;observedFanout=0;historyEntryCount=0;firstTimestamp=null;lastTimestamp=null;constructor(shape){this.shape=shape;this.annotationFields=[["comments","has_comment",shape.comments_per_100_items],["notes","has_note",shape.notes_per_100_items],["learnings","has_learning",shape.learnings_per_100_items]]}recordMismatch(mismatched,message){if(mismatched)this.planMismatches.push(message)}recordEdgeKinds(counts,kinds){for(const kind of kinds)counts[kind]=(counts[kind]??0)+1}add(plan){this.itemCount+=1;this.authors.add(plan.author);this.components.add(plan.component);this.recordMismatch(this.depths.has(plan.id),`duplicate_id:${plan.id}`);let depth=1;if(plan.parent!==void 0){const parentDepth=this.depths.get(plan.parent);this.recordMismatch(parentDepth===void 0,`parent_missing:${plan.parent}`);depth=(parentDepth??0)+1;const childCount=(this.childCounts.get(plan.parent)??0)+1;this.childCounts.set(plan.parent,childCount);this.observedFanout=Math.max(this.observedFanout,childCount)}this.depths.set(plan.id,depth);this.observedDepth=Math.max(this.observedDepth,depth);this.historyEntryCount+=plan.history_entry_count;this.recordMismatch(plan.history_entry_count!==this.shape.history_entries_per_item,"history_entries_per_item:drift");this.firstTimestamp=this.firstTimestamp===null||plan.timestamp<this.firstTimestamp?plan.timestamp:this.firstTimestamp;this.lastTimestamp=this.lastTimestamp===null||plan.timestamp>this.lastTimestamp?plan.timestamp:this.lastTimestamp;for(const[annotation,property]of this.annotationFields){this.annotations[annotation]+=Number(plan[property])}this.recordEdgeKinds(this.edgeKinds,plan.dependency_kinds);this.recordEdgeKinds(this.expectedEdgeKinds,selectedEdgeKinds(plan.index,this.shape))}finish(){const expectedAuthors=Math.min(this.shape.author_cardinality,this.itemCount);const expectedComponents=Math.min(this.shape.component_count,this.itemCount);const mismatches=[...this.planMismatches,...this.itemCount===0?["item_count:empty"]:[],...this.authors.size===expectedAuthors?[]:[`author_count:${this.authors.size}!=${expectedAuthors}`],...this.components.size===expectedComponents?[]:[`component_count:${this.components.size}!=${expectedComponents}`],...this.observedDepth<=this.shape.hierarchy_depth?[]:[`hierarchy_depth:${this.observedDepth}>${this.shape.hierarchy_depth}`],...this.observedFanout<=this.shape.hierarchy_fanout?[]:[`hierarchy_fanout:${this.observedFanout}>${this.shape.hierarchy_fanout}`]];for(const[annotation,,rate]of this.annotationFields){const completeBuckets=Math.floor(this.itemCount/100);const remainder=this.itemCount%100;const minimum=completeBuckets*rate+Math.max(0,rate+remainder-100);const maximum=completeBuckets*rate+Math.min(rate,remainder);const observed=this.annotations[annotation];if(observed<minimum||observed>maximum){mismatches.push(`${annotation}:${observed}!in[${minimum},${maximum}]`)}}const edgeKindNames=new Set([...Object.keys(this.edgeKinds),...Object.keys(this.expectedEdgeKinds)]);for(const kind of[...edgeKindNames].sort()){const observed=this.edgeKinds[kind]??0;const expected=this.expectedEdgeKinds[kind]??0;if(observed!==expected){mismatches.push(`edge_kind:${kind}:${observed}!=${expected}`)}}const uniqueMismatches=[...new Set(mismatches)];return{shape:this.shape.name,item_count:this.itemCount,author_count:this.authors.size,component_count:this.components.size,hierarchy_depth:this.observedDepth,hierarchy_fanout:this.observedFanout,timestamp_range:{first:this.firstTimestamp,last:this.lastTimestamp},history_entry_count:this.historyEntryCount,annotations:{...this.annotations},edge_kinds:{...this.edgeKinds},matches_declaration:uniqueMismatches.length===0,mismatches:uniqueMismatches}}}function createCorpusShapeMeasurement(shape){return new IncrementalCorpusShapeMeasurement(shape)}function measureCorpusShapePlan(shape,plans){const measurement=createCorpusShapeMeasurement(shape);for(const plan of plans)measurement.add(plan);return measurement.finish()}export{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="14472bc2-ebca-5b9c-9462-bd8694b630a0")}catch{}})();const PM_CORPUS_SHAPE_SCHEMA="https://schema.unbrained.dev/pm/corpus-shape/v1";function positiveInteger(value,field){if(!Number.isSafeInteger(value)||value<=0)throw new TypeError(`Corpus shape ${field} must be a positive safe integer`);return value}function nonNegativeInteger(value,field){if(!Number.isSafeInteger(value)||value<0)throw new TypeError(`Corpus shape ${field} must be a non-negative safe integer`);return value}function deepFreeze(value){if(!(typeof value!="object"||value===null||Object.isFrozen(value))){for(const nested of Object.values(value))deepFreeze(nested);Object.freeze(value)}}function defineCorpusShape(shape){if(shape.schema!==PM_CORPUS_SHAPE_SCHEMA)throw new TypeError(`Unsupported corpus shape schema: ${shape.schema}`);if(shape.name.trim().length===0||shape.description.trim().length===0)throw new TypeError("Corpus shape name and description must be non-empty");if(positiveInteger(shape.hierarchy_depth,"hierarchy_depth"),positiveInteger(shape.hierarchy_fanout,"hierarchy_fanout"),nonNegativeInteger(shape.age_span_days,"age_span_days"),positiveInteger(shape.history_entries_per_item,"history_entries_per_item"),nonNegativeInteger(shape.comments_per_100_items,"comments_per_100_items"),nonNegativeInteger(shape.notes_per_100_items,"notes_per_100_items"),nonNegativeInteger(shape.learnings_per_100_items,"learnings_per_100_items"),positiveInteger(shape.author_cardinality,"author_cardinality"),positiveInteger(shape.component_count,"component_count"),shape.edge_kind_mix.length===0||shape.edge_kind_mix.some(edge=>edge.kind.trim().length===0||edge.weight<=0))throw new TypeError("Corpus shape edge_kind_mix requires non-empty kinds with positive weights");if(shape.terminal_statuses.some(status=>!shape.custom_statuses.includes(status)))throw new TypeError("Corpus shape terminal_statuses must be declared in custom_statuses");const detached=structuredClone(shape);return deepFreeze(detached),detached}const COMMON_EDGE_MIX=[{kind:"implements",weight:5},{kind:"blocked_by",weight:2},{kind:"discovered_from",weight:2},{kind:"verifies",weight:2},{kind:"supersedes",weight:1},{kind:"related",weight:4}],BUILTIN_CORPUS_SHAPES=Object.freeze({scratch:defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"scratch",description:"Seconds-old, shallow project with minimal history.",hierarchy_depth:2,hierarchy_fanout:50,age_span_days:0,history_entries_per_item:1,comments_per_100_items:2,notes_per_100_items:1,learnings_per_100_items:1,edge_kind_mix:[{kind:"related",weight:1}],author_cardinality:2,component_count:1,include_cycles:!1,custom_types:[],custom_statuses:[],terminal_statuses:[],custom_fields:[]}),representative:defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"representative",description:"Medium-lived project with rich evidence and typed lineage.",hierarchy_depth:5,hierarchy_fanout:8,age_span_days:730,history_entries_per_item:12,comments_per_100_items:30,notes_per_100_items:12,learnings_per_100_items:10,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:32,component_count:1,include_cycles:!1,custom_types:["Experiment"],custom_statuses:["review"],terminal_statuses:[],custom_fields:["domain"]}),"deep-graph":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"deep-graph",description:"Deep typed relationship graph with deterministic cycles.",hierarchy_depth:16,hierarchy_fanout:2,age_span_days:3650,history_entries_per_item:6,comments_per_100_items:15,notes_per_100_items:8,learnings_per_100_items:8,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:16,component_count:1,include_cycles:!0,custom_types:[],custom_statuses:[],terminal_statuses:[],custom_fields:[]}),"multi-decade":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"multi-decade",description:"Thirty-year event history with dense per-item evolution.",hierarchy_depth:6,hierarchy_fanout:6,age_span_days:10958,history_entries_per_item:24,comments_per_100_items:40,notes_per_100_items:20,learnings_per_100_items:16,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:64,component_count:1,include_cycles:!1,custom_types:["Program"],custom_statuses:["archived"],terminal_statuses:["archived"],custom_fields:["portfolio"]}),"disconnected-archive":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"disconnected-archive",description:"Multiple disconnected historical project components.",hierarchy_depth:4,hierarchy_fanout:10,age_span_days:7305,history_entries_per_item:8,comments_per_100_items:10,notes_per_100_items:5,learnings_per_100_items:6,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:24,component_count:5,include_cycles:!1,custom_types:["Archive"],custom_statuses:["archived"],terminal_statuses:["archived"],custom_fields:["archive_source"]})});function listBuiltinCorpusShapes(){return Object.keys(BUILTIN_CORPUS_SHAPES).sort().map(name=>BUILTIN_CORPUS_SHAPES[name])}function resolveBuiltinCorpusShape(name){const normalized=name.trim().toLowerCase();if(!Object.hasOwn(BUILTIN_CORPUS_SHAPES,normalized))throw new TypeError(`Unknown corpus shape "${name}". Available: ${Object.keys(BUILTIN_CORPUS_SHAPES).join(", ")}`);return BUILTIN_CORPUS_SHAPES[normalized]}const expandedEdgeKinds=new WeakMap;function selectedEdgeKinds(index,shape){if(index===0)return[];let expanded=expandedEdgeKinds.get(shape);expanded===void 0&&(expanded=shape.edge_kind_mix.flatMap(entry=>Array.from({length:entry.weight},()=>entry.kind)),expandedEdgeKinds.set(shape,expanded));const kinds=[expanded[index%expanded.length]];return shape.include_cycles&&index>2&&index%17===0&&kinds.push("related"),[...new Set(kinds)]}function buildCorpusShapeItemPlan(shape,index,itemCount,seed=42){if(nonNegativeInteger(index,"item index"),positiveInteger(itemCount,"item count"),index>=itemCount)throw new RangeError(`Corpus item index ${index} exceeds ${itemCount}`);const componentCount=Math.min(shape.component_count,itemCount),component=index%componentCount,componentPosition=Math.floor(index/componentCount);let hierarchyCapacity=0,levelWidth=1;for(let depth=0;depth<shape.hierarchy_depth;depth+=1)hierarchyCapacity=Math.min(Number.MAX_SAFE_INTEGER,hierarchyCapacity+levelWidth),levelWidth=Math.min(Number.MAX_SAFE_INTEGER,levelWidth*shape.hierarchy_fanout);const treeOffset=componentPosition%hierarchyCapacity,treeStart=componentPosition-treeOffset,parentIndex=treeOffset===0?void 0:component+(treeStart+Math.floor((treeOffset-1)/shape.hierarchy_fanout))*componentCount,base=Date.UTC(2026,0,1),spanMs=shape.age_span_days*864e5,timestamp=new Date(base+(itemCount===1?0:Math.round(index/(itemCount-1)*spanMs))).toISOString(),annotationBucket=(index*37+seed)%100;return{index,id:`pm-s${index.toString(36).padStart(7,"0")}`,...parentIndex===void 0?{}:{parent:`pm-s${parentIndex.toString(36).padStart(7,"0")}`},component,timestamp,author:`pm-corpus-agent-${(index+seed)%Math.min(shape.author_cardinality,itemCount)}`,history_entry_count:shape.history_entries_per_item,dependency_kinds:selectedEdgeKinds(index,shape),has_comment:annotationBucket<shape.comments_per_100_items,has_note:annotationBucket<shape.notes_per_100_items,has_learning:annotationBucket<shape.learnings_per_100_items,...shape.custom_types.length>0&&index%11===0?{custom_type:shape.custom_types[index%shape.custom_types.length]}:{},...shape.custom_statuses.length>0&&index%13===0?{custom_status:shape.custom_statuses[index%shape.custom_statuses.length]}:{}}}class IncrementalCorpusShapeMeasurement{shape;authors=new Set;components=new Set;depths=new Map;childCounts=new Map;edgeKinds={};expectedEdgeKinds={};annotations={comments:0,notes:0,learnings:0};annotationFields;planMismatches=[];itemCount=0;observedDepth=0;observedFanout=0;historyEntryCount=0;firstTimestamp=null;lastTimestamp=null;constructor(shape){this.shape=shape,this.annotationFields=[["comments","has_comment",shape.comments_per_100_items],["notes","has_note",shape.notes_per_100_items],["learnings","has_learning",shape.learnings_per_100_items]]}recordMismatch(mismatched,message){mismatched&&this.planMismatches.push(message)}recordEdgeKinds(counts,kinds){for(const kind of kinds)counts[kind]=(counts[kind]??0)+1}add(plan){this.itemCount+=1,this.authors.add(plan.author),this.components.add(plan.component),this.recordMismatch(this.depths.has(plan.id),`duplicate_id:${plan.id}`);let depth=1;if(plan.parent!==void 0){const parentDepth=this.depths.get(plan.parent);this.recordMismatch(parentDepth===void 0,`parent_missing:${plan.parent}`),depth=(parentDepth??0)+1;const childCount=(this.childCounts.get(plan.parent)??0)+1;this.childCounts.set(plan.parent,childCount),this.observedFanout=Math.max(this.observedFanout,childCount)}this.depths.set(plan.id,depth),this.observedDepth=Math.max(this.observedDepth,depth),this.historyEntryCount+=plan.history_entry_count,this.recordMismatch(plan.history_entry_count!==this.shape.history_entries_per_item,"history_entries_per_item:drift"),this.firstTimestamp=this.firstTimestamp===null||plan.timestamp<this.firstTimestamp?plan.timestamp:this.firstTimestamp,this.lastTimestamp=this.lastTimestamp===null||plan.timestamp>this.lastTimestamp?plan.timestamp:this.lastTimestamp;for(const[annotation,property]of this.annotationFields)this.annotations[annotation]+=Number(plan[property]);this.recordEdgeKinds(this.edgeKinds,plan.dependency_kinds),this.recordEdgeKinds(this.expectedEdgeKinds,selectedEdgeKinds(plan.index,this.shape))}finish(){const expectedAuthors=Math.min(this.shape.author_cardinality,this.itemCount),expectedComponents=Math.min(this.shape.component_count,this.itemCount),mismatches=[...this.planMismatches,...this.itemCount===0?["item_count:empty"]:[],...this.authors.size===expectedAuthors?[]:[`author_count:${this.authors.size}!=${expectedAuthors}`],...this.components.size===expectedComponents?[]:[`component_count:${this.components.size}!=${expectedComponents}`],...this.observedDepth<=this.shape.hierarchy_depth?[]:[`hierarchy_depth:${this.observedDepth}>${this.shape.hierarchy_depth}`],...this.observedFanout<=this.shape.hierarchy_fanout?[]:[`hierarchy_fanout:${this.observedFanout}>${this.shape.hierarchy_fanout}`]];for(const[annotation,,rate]of this.annotationFields){const completeBuckets=Math.floor(this.itemCount/100),remainder=this.itemCount%100,minimum=completeBuckets*rate+Math.max(0,rate+remainder-100),maximum=completeBuckets*rate+Math.min(rate,remainder),observed=this.annotations[annotation];(observed<minimum||observed>maximum)&&mismatches.push(`${annotation}:${observed}!in[${minimum},${maximum}]`)}const edgeKindNames=new Set([...Object.keys(this.edgeKinds),...Object.keys(this.expectedEdgeKinds)]);for(const kind of[...edgeKindNames].sort()){const observed=this.edgeKinds[kind]??0,expected=this.expectedEdgeKinds[kind]??0;observed!==expected&&mismatches.push(`edge_kind:${kind}:${observed}!=${expected}`)}const uniqueMismatches=[...new Set(mismatches)];return{shape:this.shape.name,item_count:this.itemCount,author_count:this.authors.size,component_count:this.components.size,hierarchy_depth:this.observedDepth,hierarchy_fanout:this.observedFanout,timestamp_range:{first:this.firstTimestamp,last:this.lastTimestamp},history_entry_count:this.historyEntryCount,annotations:{...this.annotations},edge_kinds:{...this.edgeKinds},matches_declaration:uniqueMismatches.length===0,mismatches:uniqueMismatches}}}function createCorpusShapeMeasurement(shape){return new IncrementalCorpusShapeMeasurement(shape)}function measureCorpusShapePlan(shape,plans){const measurement=createCorpusShapeMeasurement(shape);for(const plan of plans)measurement.add(plan);return measurement.finish()}export{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape};
|
|
2
2
|
//# sourceMappingURL=corpus-shape.js.map
|
package/dist/sdk/define.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4e72da21-425b-568d-9174-bc5021e1d4f4")}catch{}})();function defineExtensionManifest(manifest){return manifest}function defineProjectProfile(profile){return profile}function defineCommand(definition){return definition}function defineFlag(flag){return flag}function defineItemType(type){return type}function defineItemField(field){return field}function defineMigration(migration){return migration}function defineSearchProvider(provider){return provider}function defineVectorStoreAdapter(adapter){return adapter}function defineCommandOverride(override){return override}function defineParserOverride(override){return override}function definePreflightOverride(override){return override}function defineServiceOverride(override){return override}function handleServiceOverride(result){return{handled:!0,result}}function declineServiceOverride(){return{handled:!1}}function defineRendererOverride(renderer){return renderer}function defineImporter(importer){return importer}function defineExporter(exporter){return exporter}function defineBeforeCommandHook(hook){return hook}function defineBeforeMutationHook(hook){return hook}function defineAfterCommandHook(hook){return hook}function defineOnWriteHook(hook){return hook}function defineOnReadHook(hook){return hook}function defineOnIndexHook(hook){return hook}export{declineServiceOverride,defineAfterCommandHook,defineBeforeCommandHook,defineBeforeMutationHook,defineCommand,defineCommandOverride,defineExporter,defineExtensionManifest,defineFlag,defineImporter,defineItemField,defineItemType,defineMigration,defineOnIndexHook,defineOnReadHook,defineOnWriteHook,defineParserOverride,definePreflightOverride,defineProjectProfile,defineRendererOverride,defineSearchProvider,defineServiceOverride,defineVectorStoreAdapter,handleServiceOverride};
|
|
2
2
|
//# sourceMappingURL=define.js.map
|