@unbrained/pm-cli 2026.9.26 → 2026.9.27

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.
Files changed (130) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +16 -0
  3. package/dist/cli/commander-usage.js +2 -2
  4. package/dist/cli/error-guidance.js +1 -1
  5. package/dist/cli/main.js +2 -2
  6. package/dist/cli/register-setup.js +1 -1
  7. package/dist/cli/runtime/selection.d.ts +3 -1
  8. package/dist/cli/runtime/selection.js +1 -1
  9. package/dist/cli-bundle/bundle-manifest.json +160 -152
  10. package/dist/cli-bundle/chunks/{chunk-IYN4MJ2C.js → chunk-3BTJ66CB.js} +56 -56
  11. package/dist/cli-bundle/chunks/{chunk-FOTXRNY6.js → chunk-4SLLCDFL.js} +39 -39
  12. package/dist/cli-bundle/chunks/{chunk-GRWPZR7F.js → chunk-4UPZLUT2.js} +7 -7
  13. package/dist/cli-bundle/chunks/{chunk-U55RYT3I.js → chunk-6OJVQ7SW.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-TYJXMT3Q.js → chunk-7TAGYNFP.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-QQD3VRMZ.js → chunk-AUS6USO4.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-4ODHIX7N.js → chunk-IEP3VAT5.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-HTHTX6E6.js → chunk-JX6WCCHL.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-LC6WEA5U.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-VMO4P5MX.js → chunk-LKGQUZ5M.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-TC74K7SS.js → chunk-OKVDVERQ.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-SZQCHJI4.js → chunk-TSF2LPIH.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-MJWKR7YA.js → chunk-V5UGBYHN.js} +3 -3
  23. package/dist/cli-bundle/chunks/{register-list-query-426QTRET.js → register-list-query-6PAJ4PBU.js} +2 -2
  24. package/dist/cli-bundle/chunks/{register-mutation-FLI3HHMP.js → register-mutation-RZCXZXYS.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-operations-TP7ZG4MK.js → register-operations-GK6VU2H2.js} +2 -2
  26. package/dist/cli-bundle/chunks/register-setup-ASEMNMBF.js +2 -0
  27. package/dist/cli-bundle/focused-chunks/{chunk-H3BI4EDO.js → chunk-6J2YCGSN.js} +3 -3
  28. package/dist/cli-bundle/focused-chunks/{chunk-XKH2FC5D.js → chunk-6UNKK3UH.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-NRHTXBTI.js → chunk-DQ3MB7BO.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-PMPFLA6X.js → chunk-E7LYK7V5.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-25BBHWMH.js → chunk-GZD4ZYIB.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/chunk-KMPKKSA6.js +2 -0
  33. package/dist/cli-bundle/focused-chunks/{chunk-TLF6N56J.js → chunk-LBDWUHQD.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-UIFVIE5F.js → chunk-MILJCOFJ.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-MK5AKKHK.js → chunk-NETVXIH5.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-Q355NPLH.js → chunk-NWRVNHAD.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-XVBWZTU2.js → chunk-NZAG7OKB.js} +12 -12
  38. package/dist/cli-bundle/focused-chunks/{chunk-OY3VHCTX.js → chunk-OJKJFDIG.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/chunk-OJRX6G22.js +2 -0
  40. package/dist/cli-bundle/focused-chunks/{chunk-NVVB2HJC.js → chunk-PDVL7QYU.js} +16 -16
  41. package/dist/cli-bundle/focused-chunks/{chunk-O7MIBEMK.js → chunk-QO4MTAEA.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-ABA3KRPY.js → chunk-SMADBUPL.js} +2 -2
  43. package/dist/cli-bundle/main.js +21 -21
  44. package/dist/cli-bundle/sdk-authoring.js +1 -1
  45. package/dist/cli-bundle/sdk-contracts.js +1 -1
  46. package/dist/cli-bundle/sdk-core.js +2 -2
  47. package/dist/cli-bundle/sdk-governance.js +1 -1
  48. package/dist/cli-bundle/sdk-graph.js +1 -1
  49. package/dist/cli-bundle/sdk-merge.js +23 -23
  50. package/dist/cli-bundle/sdk-query.js +1 -1
  51. package/dist/cli-bundle/sdk-runtime.js +1 -1
  52. package/dist/cli-bundle/sdk-testing.js +1 -1
  53. package/dist/cli-bundle/sdk.js +8 -8
  54. package/dist/sdk/agent-capability-contracts.js +1 -1
  55. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  56. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  57. package/dist/sdk/completion/shared.d.ts +1 -1
  58. package/dist/sdk/completion/shared.js +1 -1
  59. package/dist/sdk/extension/static-inventory.d.ts +54 -0
  60. package/dist/sdk/extension/static-inventory.js +2 -0
  61. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  62. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  63. package/dist/sdk/guide-topics.js +1 -1
  64. package/dist/sdk/index.d.ts +1 -0
  65. package/dist/sdk/index.js +1 -1
  66. package/dist/sdk/public-surface.json +1 -1
  67. package/dist/sdk/query/complete-list.js +1 -1
  68. package/dist/sdk/read-output/provenance.d.ts +20 -0
  69. package/dist/sdk/read-output/provenance.js +2 -0
  70. package/dist/sdk/read-output-contracts.js +1 -1
  71. package/dist/sdk/runtime-input.js +1 -1
  72. package/docs/CLI_GRAMMAR.md +31 -0
  73. package/docs/CODEX_PLUGIN.md +8 -0
  74. package/docs/EXTENSION_LIFECYCLE.md +18 -0
  75. package/docs/RELEASING.md +46 -1
  76. package/docs/agent-task-token-baseline.json +4 -4
  77. package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
  78. package/docs/generated/AGENT_COMMAND_SURFACE.md +5 -1
  79. package/docs/generated/FLAG_LEXICON_BUDGETS.md +4 -0
  80. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +14 -7
  81. package/marketplace.json +2 -2
  82. package/package.json +2 -2
  83. package/packages/pm-beads/package.json +1 -1
  84. package/packages/pm-calendar/package.json +1 -1
  85. package/packages/pm-command-kit/package.json +1 -1
  86. package/packages/pm-digital-twin/package.json +1 -1
  87. package/packages/pm-governance-audit/package.json +1 -1
  88. package/packages/pm-guide-shell/package.json +1 -1
  89. package/packages/pm-kanban/package.json +1 -1
  90. package/packages/pm-lifecycle-hooks/package.json +1 -1
  91. package/packages/pm-linked-test-adapters/package.json +1 -1
  92. package/packages/pm-search-advanced/package.json +1 -1
  93. package/packages/pm-templates/package.json +1 -1
  94. package/packages/pm-todos/package.json +1 -1
  95. package/packages/pm-vcs/package.json +1 -1
  96. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  97. package/plugins/pm-claude/README.md +5 -1
  98. package/plugins/pm-claude/package.json +2 -2
  99. package/plugins/pm-claude/skills/pm-audit/SKILL.md +14 -103
  100. package/plugins/pm-claude/skills/pm-audit/agents/openai.yaml +4 -0
  101. package/plugins/pm-claude/skills/pm-developer/SKILL.md +20 -143
  102. package/plugins/pm-claude/skills/pm-developer/agents/openai.yaml +4 -0
  103. package/plugins/pm-claude/skills/pm-planner/SKILL.md +16 -167
  104. package/plugins/pm-claude/skills/pm-planner/agents/openai.yaml +4 -0
  105. package/plugins/pm-claude/skills/pm-release/SKILL.md +18 -102
  106. package/plugins/pm-claude/skills/pm-release/agents/openai.yaml +4 -0
  107. package/plugins/pm-claude/skills/pm-workflow/SKILL.md +25 -156
  108. package/plugins/pm-claude/skills/pm-workflow/agents/openai.yaml +4 -0
  109. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  110. package/plugins/pm-codex/README.md +10 -2
  111. package/plugins/pm-codex/mcp.json +11 -0
  112. package/plugins/pm-codex/package.json +2 -2
  113. package/plugins/pm-codex/plugin.json +45 -0
  114. package/plugins/pm-codex/skills/pm-audit/SKILL.md +21 -0
  115. package/plugins/pm-codex/skills/pm-audit/agents/openai.yaml +4 -0
  116. package/plugins/pm-codex/skills/pm-auditor/SKILL.md +5 -40
  117. package/plugins/pm-codex/skills/pm-auditor/agents/openai.yaml +3 -5
  118. package/plugins/pm-codex/skills/pm-developer/SKILL.md +26 -0
  119. package/plugins/pm-codex/skills/pm-developer/agents/openai.yaml +4 -0
  120. package/plugins/pm-codex/skills/pm-native/SKILL.md +7 -87
  121. package/plugins/pm-codex/skills/pm-native/agents/openai.yaml +3 -5
  122. package/plugins/pm-codex/skills/pm-planner/SKILL.md +22 -0
  123. package/plugins/pm-codex/skills/pm-planner/agents/openai.yaml +4 -0
  124. package/plugins/pm-codex/skills/pm-release/SKILL.md +17 -38
  125. package/plugins/pm-codex/skills/pm-release/agents/openai.yaml +2 -4
  126. package/plugins/pm-codex/skills/pm-workflow/SKILL.md +39 -0
  127. package/plugins/pm-codex/skills/pm-workflow/agents/openai.yaml +4 -0
  128. package/dist/cli-bundle/chunks/register-setup-574SIVQZ.js +0 -2
  129. package/dist/cli-bundle/focused-chunks/chunk-HNHMK5JI.js +0 -2
  130. package/dist/cli-bundle/focused-chunks/chunk-HQPTDJLF.js +0 -2
@@ -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]="f6e02611-4b44-5aa3-b762-9fd984aa12bc")}catch(e2){}})();const PM_COMPLETE_LIST_FINDING_CODES=["invalid_envelope","source_incomplete","source_unchecked","filtered_corpus","terminal_items_excluded","strict_read_unproven","page_incomplete","count_mismatch","projection_incomplete","field_omission","omission_receipt_missing","omission_receipt_invalid","read_output_missing","read_output_invalid","read_output_dimensions_incomplete","budget_compaction","budget_omission","session_projection","invalid_item_id","duplicate_item_id"];class PmCompleteListValidationError extends Error{receipt;constructor(findings){super(`Complete-list certification failed: ${findings.map(finding=>finding.code).join(", ")}.`);this.name="PmCompleteListValidationError";this.receipt={contract_version:1,contract:"complete_list",findings,recovery:{suggested_retry:"pm list --all --output-include full --strict-read --no-truncate --output-budget unbounded --output-limit unbounded --json",sdk:"await client.listAllComplete()"}}}}function createCompleteListOptions(options={}){return{excludeTerminal:false,full:true,...options.includeBody===void 0?{}:{includeBody:options.includeBody},noTruncate:true,outputBudget:"unbounded",outputLimit:"unbounded",strictRead:true}}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function addFinding(findings,condition,code,message){if(condition)findings.push({code,message})}function inspectSourceScope(candidate,findings){const completeness=isRecord(candidate.completeness)?candidate.completeness:{};addFinding(findings,completeness.status==="partial","source_incomplete","The source scan reported unreadable tracker artifacts.");addFinding(findings,completeness.status!=="complete"&&completeness.status!=="partial","source_unchecked","The source scan did not prove completeness.");const unreadableItemCount=completeness.unreadable_item_count;const unreadableDirectoryCount=completeness.unreadable_directory_count;addFinding(findings,completeness.status==="complete"&&(unreadableItemCount!==0||unreadableDirectoryCount!==0)&&Number.isSafeInteger(unreadableItemCount)&&Number.isSafeInteger(unreadableDirectoryCount),"source_incomplete","The source scan reports unreadable tracker artifacts despite a complete status.");addFinding(findings,completeness.status==="complete"&&(!Number.isSafeInteger(unreadableItemCount)||!Number.isSafeInteger(unreadableDirectoryCount)||Number(unreadableItemCount)<0||Number(unreadableDirectoryCount)<0),"source_unchecked","The source scan did not report safe non-negative unreadable counts.");const filters=isRecord(candidate.filters)?candidate.filters:{};const runtimeFilters=isRecord(filters.runtime_filters)?filters.runtime_filters:{};const filterEchoKeys=new Set(["exclude_terminal","include_body","no_truncate","runtime_filters","status","strict_read"]);addFinding(findings,filters.status!=="all"||Object.keys(runtimeFilters).length>0||Object.keys(filters).some(key=>!filterEchoKeys.has(key)),"filtered_corpus","The list did not explicitly select every lifecycle status.");addFinding(findings,filters.exclude_terminal===true,"terminal_items_excluded","Terminal lifecycle states were explicitly excluded.");addFinding(findings,filters.strict_read!==true,"strict_read_unproven","The result does not echo strict source-read enforcement.");return filters}function inspectEnvelopeShape(candidate,filters,findings){addFinding(findings,candidate.has_more!==false||candidate.next_cursor!==null||candidate.truncated!==false||candidate.applied_limit!==void 0||filters.no_truncate!==true,"page_incomplete","Pagination or a row ceiling may have withheld items.");addFinding(findings,candidate.count!==candidate.items.length||candidate.total!==candidate.items.length,"count_mismatch","Envelope counts do not equal the returned item count.");const projection=isRecord(candidate.projection)?candidate.projection:{};addFinding(findings,projection.mode!=="full"||projection.fields!==null,"projection_incomplete","The result is not the full metadata projection.");const omissionReceipt=isRecord(candidate.omission_receipt)?candidate.omission_receipt:void 0;addFinding(findings,omissionReceipt===void 0,"omission_receipt_missing","The result carries no field-omission receipt.");addFinding(findings,omissionReceipt!==void 0&&(omissionReceipt.has_omissions!==false||omissionReceipt.omitted_field_group_count!==0||!Number.isSafeInteger(omissionReceipt.omitted_field_group_count)||!Array.isArray(omissionReceipt.omitted_field_groups)||omissionReceipt.omitted_field_groups.length!==0),"omission_receipt_invalid","The field-omission receipt is malformed or contradicts its no-omission claim.");addFinding(findings,omissionReceipt?.has_omissions===true,"field_omission","The omission receipt reports withheld field groups.")}function isInvalidCompleteListReadOutput(readOutput){return readOutput.contract_version!==1||readOutput.command!=="list"||readOutput.within_budget!==true||readOutput.strings_compacted!==false||readOutput.rows_compacted!==false||readOutput.result_omitted!==false}function hasCompleteListReadOutputDimensions(readOutput){if(!Array.isArray(readOutput.requested_dimensions))return false;const requestedDimensions=new Set(readOutput.requested_dimensions);return["include","amount","cost"].every(dimension=>requestedDimensions.has(dimension))}function inspectOutputScope(candidate,findings){const readOutput=isRecord(candidate.read_output)?candidate.read_output:void 0;addFinding(findings,readOutput===void 0,"read_output_missing","The result carries no universal read-output receipt.");addFinding(findings,readOutput!==void 0&&isInvalidCompleteListReadOutput(readOutput),"read_output_invalid","The universal read-output receipt does not prove an intact list result.");addFinding(findings,readOutput!==void 0&&!hasCompleteListReadOutputDimensions(readOutput),"read_output_dimensions_incomplete","The universal read-output receipt does not prove full, unbounded include, amount, and cost dimensions.");addFinding(findings,readOutput?.strings_compacted===true||readOutput?.rows_compacted===true||candidate.output_budget_truncation!==void 0,"budget_compaction","Universal output shaping compacted the result.");const budgetExceeded=isRecord(candidate.output_budget_exceeded)?candidate.output_budget_exceeded:void 0;addFinding(findings,readOutput?.result_omitted===true||budgetExceeded?.omitted_result===true,"budget_omission","Universal output shaping omitted the useful result.");addFinding(findings,candidate.read_session!==void 0,"session_projection","A cross-call read session can suppress previously served facts.")}function inspectItemIds(items,findings){const ids=items.map(item=>isRecord(item)&&typeof item.id==="string"?item.id.trim():"");addFinding(findings,ids.some(id=>id.length===0),"invalid_item_id","Every full item row must carry a non-empty string id.");addFinding(findings,new Set(ids).size!==ids.length,"duplicate_item_id","Every item id must occur exactly once.")}function inspectCompleteListResult(candidate){if(!isRecord(candidate)||!Array.isArray(candidate.items)){return{ok:false,findings:[{code:PM_COMPLETE_LIST_FINDING_CODES[0],message:"The result must be an object with an items array."}]}}const envelope=candidate;const findings=[];const filters=inspectSourceScope(envelope,findings);inspectEnvelopeShape(envelope,filters,findings);inspectOutputScope(envelope,findings);inspectItemIds(envelope.items,findings);return{ok:findings.length===0,findings}}function certifyCompleteListResult(candidate){const inspection=inspectCompleteListResult(candidate);if(!inspection.ok){throw new PmCompleteListValidationError(inspection.findings)}const result=candidate;return{...result,complete_list:{contract_version:1,item_count:result.items.length,unique_item_id_count:new Set(result.items.map(item=>item.id)).size,terminal_items_included:true,source_complete:true,full_projection:true,no_omissions:true,unbounded:true}}}function assertCompleteListResult(candidate){certifyCompleteListResult(candidate)}export{PM_COMPLETE_LIST_FINDING_CODES,PmCompleteListValidationError,assertCompleteListResult,certifyCompleteListResult,createCompleteListOptions,inspectCompleteListResult};
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]="5f9ac16a-d51e-5f69-9379-1d3b2e971014")}catch(e2){}})();import{markCanonicalSdkReadOutputOptions}from"../read-output/provenance.js";const PM_COMPLETE_LIST_FINDING_CODES=["invalid_envelope","source_incomplete","source_unchecked","filtered_corpus","terminal_items_excluded","strict_read_unproven","page_incomplete","count_mismatch","projection_incomplete","field_omission","omission_receipt_missing","omission_receipt_invalid","read_output_missing","read_output_invalid","read_output_dimensions_incomplete","budget_compaction","budget_omission","session_projection","invalid_item_id","duplicate_item_id"];class PmCompleteListValidationError extends Error{receipt;constructor(findings){super(`Complete-list certification failed: ${findings.map(finding=>finding.code).join(", ")}.`);this.name="PmCompleteListValidationError";this.receipt={contract_version:1,contract:"complete_list",findings,recovery:{suggested_retry:"pm list --all --output-include full --strict-read --no-truncate --output-budget unbounded --output-limit unbounded --json",sdk:"await client.listAllComplete()"}}}}function createCompleteListOptions(options={}){return markCanonicalSdkReadOutputOptions({excludeTerminal:false,full:true,...options.includeBody===void 0?{}:{includeBody:options.includeBody},noTruncate:true,outputBudget:"unbounded",outputLimit:"unbounded",strictRead:true},["full"])}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function addFinding(findings,condition,code,message){if(condition)findings.push({code,message})}function inspectSourceScope(candidate,findings){const completeness=isRecord(candidate.completeness)?candidate.completeness:{};addFinding(findings,completeness.status==="partial","source_incomplete","The source scan reported unreadable tracker artifacts.");addFinding(findings,completeness.status!=="complete"&&completeness.status!=="partial","source_unchecked","The source scan did not prove completeness.");const unreadableItemCount=completeness.unreadable_item_count;const unreadableDirectoryCount=completeness.unreadable_directory_count;addFinding(findings,completeness.status==="complete"&&(unreadableItemCount!==0||unreadableDirectoryCount!==0)&&Number.isSafeInteger(unreadableItemCount)&&Number.isSafeInteger(unreadableDirectoryCount),"source_incomplete","The source scan reports unreadable tracker artifacts despite a complete status.");addFinding(findings,completeness.status==="complete"&&(!Number.isSafeInteger(unreadableItemCount)||!Number.isSafeInteger(unreadableDirectoryCount)||Number(unreadableItemCount)<0||Number(unreadableDirectoryCount)<0),"source_unchecked","The source scan did not report safe non-negative unreadable counts.");const filters=isRecord(candidate.filters)?candidate.filters:{};const runtimeFilters=isRecord(filters.runtime_filters)?filters.runtime_filters:{};const filterEchoKeys=new Set(["exclude_terminal","include_body","no_truncate","runtime_filters","status","strict_read"]);addFinding(findings,filters.status!=="all"||Object.keys(runtimeFilters).length>0||Object.keys(filters).some(key=>!filterEchoKeys.has(key)),"filtered_corpus","The list did not explicitly select every lifecycle status.");addFinding(findings,filters.exclude_terminal===true,"terminal_items_excluded","Terminal lifecycle states were explicitly excluded.");addFinding(findings,filters.strict_read!==true,"strict_read_unproven","The result does not echo strict source-read enforcement.");return filters}function inspectEnvelopeShape(candidate,filters,findings){addFinding(findings,candidate.has_more!==false||candidate.next_cursor!==null||candidate.truncated!==false||candidate.applied_limit!==void 0||filters.no_truncate!==true,"page_incomplete","Pagination or a row ceiling may have withheld items.");addFinding(findings,candidate.count!==candidate.items.length||candidate.total!==candidate.items.length,"count_mismatch","Envelope counts do not equal the returned item count.");const projection=isRecord(candidate.projection)?candidate.projection:{};addFinding(findings,projection.mode!=="full"||projection.fields!==null,"projection_incomplete","The result is not the full metadata projection.");const omissionReceipt=isRecord(candidate.omission_receipt)?candidate.omission_receipt:void 0;addFinding(findings,omissionReceipt===void 0,"omission_receipt_missing","The result carries no field-omission receipt.");addFinding(findings,omissionReceipt!==void 0&&(omissionReceipt.has_omissions!==false||omissionReceipt.omitted_field_group_count!==0||!Number.isSafeInteger(omissionReceipt.omitted_field_group_count)||!Array.isArray(omissionReceipt.omitted_field_groups)||omissionReceipt.omitted_field_groups.length!==0),"omission_receipt_invalid","The field-omission receipt is malformed or contradicts its no-omission claim.");addFinding(findings,omissionReceipt?.has_omissions===true,"field_omission","The omission receipt reports withheld field groups.")}function isInvalidCompleteListReadOutput(readOutput){return readOutput.contract_version!==1||readOutput.command!=="list"||readOutput.within_budget!==true||readOutput.strings_compacted!==false||readOutput.rows_compacted!==false||readOutput.result_omitted!==false}function hasCompleteListReadOutputDimensions(readOutput){if(!Array.isArray(readOutput.requested_dimensions))return false;const requestedDimensions=new Set(readOutput.requested_dimensions);return["include","amount","cost"].every(dimension=>requestedDimensions.has(dimension))}function inspectOutputScope(candidate,findings){const readOutput=isRecord(candidate.read_output)?candidate.read_output:void 0;addFinding(findings,readOutput===void 0,"read_output_missing","The result carries no universal read-output receipt.");addFinding(findings,readOutput!==void 0&&isInvalidCompleteListReadOutput(readOutput),"read_output_invalid","The universal read-output receipt does not prove an intact list result.");addFinding(findings,readOutput!==void 0&&!hasCompleteListReadOutputDimensions(readOutput),"read_output_dimensions_incomplete","The universal read-output receipt does not prove full, unbounded include, amount, and cost dimensions.");addFinding(findings,readOutput?.strings_compacted===true||readOutput?.rows_compacted===true||candidate.output_budget_truncation!==void 0,"budget_compaction","Universal output shaping compacted the result.");const budgetExceeded=isRecord(candidate.output_budget_exceeded)?candidate.output_budget_exceeded:void 0;addFinding(findings,readOutput?.result_omitted===true||budgetExceeded?.omitted_result===true,"budget_omission","Universal output shaping omitted the useful result.");addFinding(findings,candidate.read_session!==void 0,"session_projection","A cross-call read session can suppress previously served facts.")}function inspectItemIds(items,findings){const ids=items.map(item=>isRecord(item)&&typeof item.id==="string"?item.id.trim():"");addFinding(findings,ids.some(id=>id.length===0),"invalid_item_id","Every full item row must carry a non-empty string id.");addFinding(findings,new Set(ids).size!==ids.length,"duplicate_item_id","Every item id must occur exactly once.")}function inspectCompleteListResult(candidate){if(!isRecord(candidate)||!Array.isArray(candidate.items)){return{ok:false,findings:[{code:PM_COMPLETE_LIST_FINDING_CODES[0],message:"The result must be an object with an items array."}]}}const envelope=candidate;const findings=[];const filters=inspectSourceScope(envelope,findings);inspectEnvelopeShape(envelope,filters,findings);inspectOutputScope(envelope,findings);inspectItemIds(envelope.items,findings);return{ok:findings.length===0,findings}}function certifyCompleteListResult(candidate){const inspection=inspectCompleteListResult(candidate);if(!inspection.ok){throw new PmCompleteListValidationError(inspection.findings)}const result=candidate;return{...result,complete_list:{contract_version:1,item_count:result.items.length,unique_item_id_count:new Set(result.items.map(item=>item.id)).size,terminal_items_included:true,source_complete:true,full_projection:true,no_omissions:true,unbounded:true}}}function assertCompleteListResult(candidate){certifyCompleteListResult(candidate)}export{PM_COMPLETE_LIST_FINDING_CODES,PmCompleteListValidationError,assertCompleteListResult,certifyCompleteListResult,createCompleteListOptions,inspectCompleteListResult};
2
2
  //# sourceMappingURL=complete-list.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @module sdk/read-output/provenance
3
+ *
4
+ * Retains private invocation-origin evidence through SDK option normalization.
5
+ */
6
+ /** Private invocation origin shared by SDK option construction and read-output resolution. */
7
+ export declare const READ_OUTPUT_INVOCATION_PROVENANCE: unique symbol;
8
+ /** Internal evidence that distinguishes caller aliases from forwarded command options. */
9
+ export interface PmReadOutputInvocationProvenance {
10
+ /** Canonical include modes forwarded through command-local option keys. */
11
+ canonical_include_modes: string[];
12
+ /** Compatibility aliases observed before defaults or canonical forwarding. */
13
+ explicit_legacy_aliases: string[];
14
+ /** Whether the CLI captured the complete set of caller-supplied aliases. */
15
+ cli_invocation_observed?: boolean;
16
+ /** Whether an SDK helper constructed every command-local option itself. */
17
+ sdk_invocation_observed?: boolean;
18
+ }
19
+ /** Mark a complete SDK helper request so internal command options are not reported as caller aliases. */
20
+ export declare function markCanonicalSdkReadOutputOptions<Options extends object>(options: Options, canonicalIncludeModes: readonly string[]): Options;
@@ -0,0 +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]="c649c902-db30-5a05-982e-46669ca96148")}catch(e2){}})();const READ_OUTPUT_INVOCATION_PROVENANCE=Symbol.for("pm.readOutputInvocationProvenance");function markCanonicalSdkReadOutputOptions(options,canonicalIncludeModes){Reflect.set(options,READ_OUTPUT_INVOCATION_PROVENANCE,{canonical_include_modes:[...canonicalIncludeModes],explicit_legacy_aliases:[],sdk_invocation_observed:true});return options}export{READ_OUTPUT_INVOCATION_PROVENANCE,markCanonicalSdkReadOutputOptions};
2
+ //# sourceMappingURL=provenance.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]="8a044fa0-4028-5527-b6ff-43ec995e8830")}catch(e2){}})();import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactReadOutputToBudget,estimateReadOutputTokens,projectReadOutputItemToBrief,preserveReadOutputRowContract,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths,readOutputRowCollections}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint}from"./read-output/continuation.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];const PM_READ_OUTPUT_SURFACES=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"];const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"];const CANONICAL_OPTIONS={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};const READ_OUTPUT_INVOCATION_PROVENANCE=Symbol.for("pm.readOutputInvocationProvenance");const PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension]));const PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]);const LEGACY_FLAGS_BY_COMMAND={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}};const VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]);const BEHAVIOR_PRESERVING_MIGRATION_HINTS=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function flagSelector(flag){return flag.slice(2).replaceAll("-","_")}function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command];const dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:true,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptions(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract));const SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase());const packageMode=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===true||options.target==="catalog"||options.action==="catalog");const root=packageMode?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0];const normalized=root.startsWith("list-")?"list":root==="ctx"?"context":root;return PM_READ_OUTPUT_SURFACES.includes(normalized)?normalized:void 0}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"];const HYBRID_READ_MUTATION_KEYS={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>key!=="outputFormat"&&key!=="output_format"&&options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:value=>{parseReadOutputSession(value);return true},message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value==="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function validateReadOutputOptions(command,options){const encoding=options.outputFormat??options.output_format;if(encoding!==void 0&&encoding!=="json"&&encoding!=="toon"){throw new PmCliError("--output-format must be toon or json.",EXIT_CODE.USAGE)}if(!hasCanonicalReadOutputOptions(options))return;const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand){throw new PmCliError(`Universal output controls apply only to read commands; ${command||"this command"} is not a read surface.`,EXIT_CODE.USAGE)}if((HYBRID_READ_MUTATION_KEYS[normalizedCommand]??[]).some(key=>options[key]!==void 0&&options[key]!==false)){throw new PmCliError(`Universal output controls cannot be combined with a ${normalizedCommand} mutation.`,EXIT_CODE.USAGE)}for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value)){throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);if(!surface)return new Map;return new Map((LEGACY_FLAGS_BY_COMMAND[surface].include??[]).filter(flag=>!VALUE_BEARING_INCLUDE_ALIASES.has(flag)&&BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0).map(flag=>[flagSelector(flag),optionKey(flag)]))}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[];const modeOptions=readOutputIncludeModeOptions(command);const selectors=[];const modes=[];const optionsWithProvenance=commandOptions;const existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE];const canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]);const explicitLegacyAliases=new Set(existingProvenance?.explicit_legacy_aliases??[]);for(const token of requested){const option=modeOptions.get(token);if(option===void 0){selectors.push(token);continue}const legacyFlag=`--${token.replaceAll("_","-")}`;if(isRequestedOption(readOption(commandOptions,legacyFlag))){explicitLegacyAliases.add(legacyFlag)}commandOptions[option]=true;modes.push(token);canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[];const forwardedGetFields=forwardedGetFieldSelectors.length>0;if(forwardedGetFields){commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(",");canonicalModes.add("fields")}if(modes.length>0||forwardedGetFields){optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===true?{cli_invocation_observed:true}:{}}}return{selectors,modes}}function normalizeReadOutputIncludeModeOptions(command,options){const include=options.outputInclude??options.output_include;if(include===void 0)return;const{selectors,modes}=applyReadOutputIncludeModes(command,include,options);if(modes.length===0)return;const residual=selectors.length>0?selectors.join(","):void 0;options.outputInclude=residual;if(Object.hasOwn(options,"output_include")){options.output_include=residual}}function optionKey(flag){return flag.slice(2).replace(/-([a-z])/gu,(_,character)=>character.toUpperCase())}function readOption(options,flag){const key=optionKey(flag);if(Object.hasOwn(options,key))return options[key];const snakeKey=flag.slice(2).replaceAll("-","_");if(Object.hasOwn(options,snakeKey))return options[snakeKey];if(flag==="--no-truncate"&&options.truncate===false)return true;return void 0}function isRequestedOption(value){return value!==void 0&&value!==false&&value!==null}function stringList(value){const values=Array.isArray(value)?value:[value];const normalized=values.flatMap(entry=>typeof entry==="string"?entry.split(","):[]).map(entry=>entry.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function positiveInteger(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 resolveLegacyDimension(contract,options,usable,ignore){for(const alias of contract.legacy_aliases){if(ignore(alias.flag))continue;const value=readOption(options,alias.flag);const candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}return void 0}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(!legacy)return void 0;return{source:"legacy",value:stringList(legacy.value)??[flagSelector(legacy.flag)]}}function resolveAmountValue(canonical,legacy){if(canonical==="unbounded"){return{source:"canonical",value:"unbounded"}}const canonicalLimit=positiveInteger(canonical);if(canonicalLimit!==void 0){return{source:"canonical",value:canonicalLimit}}if(!legacy)return void 0;if(legacy.flag==="--no-truncate"||legacy.flag==="--unbounded"){return{source:"legacy",value:"unbounded"}}const legacyLimit=positiveInteger(legacy.value);return legacyLimit===void 0?void 0:{source:"legacy",value:legacyLimit}}function resolveCostValue(canonical,legacy){if(canonical==="unbounded"){return{source:"canonical",value:"unbounded"}}const canonicalBudget=positiveInteger(canonical);if(canonicalBudget!==void 0){return{source:"canonical",value:canonicalBudget}}if(!legacy)return void 0;const legacyBudget=positiveInteger(legacy.value);return legacyBudget===void 0?void 0:{source:"legacy",value:legacyBudget}}function resolveEncodingValue(canonical,legacy){if(canonical==="json"||canonical==="toon"){return{source:"canonical",value:canonical}}if(!legacy)return void 0;if(legacy.flag==="--stream"||legacy.flag==="--follow"){return{source:"legacy",value:"stream"}}return legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return false;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===true){return!explicitLegacyAliases.has(flag)}const forwardedIncludeAliases=new Set(provenance.canonical_include_modes.map(mode=>`--${mode.replaceAll("_","-")}`));return dimension==="include"&&forwardedIncludeAliases.has(flag)&&!explicitLegacyAliases.has(flag)}function hasCompleteReadOutputIntent(command,legacyByDimension,provenance){const root=command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0];return root==="list-all"||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===true}function canonicalReadOutputOptionsUsed(resolvedByDimension,provenance){return PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>resolvedByDimension[dimension]?.source==="canonical"||dimension==="include"&&(provenance?.canonical_include_modes.length??0)>0?[CANONICAL_OPTIONS[dimension]]:[])}function resolveReadOutputDimensions(command,options){const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)return void 0;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand);const invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE];const legacyResolvers={include:candidate=>resolveIncludeValue(void 0,candidate),amount:candidate=>resolveAmountValue(void 0,candidate),cost:candidate=>resolveCostValue(void 0,candidate),encoding:candidate=>resolveEncodingValue(void 0,candidate)};const legacyByDimension=Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,resolveLegacyDimension(contract.dimensions[dimension],options,candidate=>legacyResolvers[dimension](candidate)!==void 0,flag=>shouldIgnoreReadOutputLegacyAlias(invocationProvenance,dimension,flag))]));const legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]});const migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];if(!resolved)return[];const alias=contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag);return[alias.migration_hint]});const encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding);const include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include);const amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount);const explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost);const completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance);const budget=resolvePmCommandOutputBudget(command,{generateFallback:true});const resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon";const cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});const resolvedByDimension={include,amount,cost,encoding};return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed(resolvedByDimension,invocationProvenance),legacy_aliases_used:legacyAliasesUsed,migration_hints:migrationHints,precedence:READ_OUTPUT_PRECEDENCE}}function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}const ENVELOPE_KEYS=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]);const GET_STABLE_DERIVED_ITEM_SELECTORS=["collection_counts","notes_count","tests_count"];function projectRecordFields(value,selectors){const selected=new Set(selectors.map(selector=>selector.split(".")[0]));return Object.fromEntries(Object.entries(value).filter(([key])=>selected.has(key)))}function getProjectionVocabulary(result){const item=isRecord(result.item)?result.item:{};const itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right));const sections=Object.keys(result).filter(key=>key!=="item"&&key!=="read_output"&&!ENVELOPE_KEYS.has(key)).sort((left,right)=>left.localeCompare(right));return{item,itemFields,sections,valid:[...itemFields,"item",...itemFields.map(field=>`item.${field}`),...sections]}}function applyGetIncludeProjection(result,selectors){const vocabulary=getProjectionVocabulary(result);const unknown=selectors.filter(selector=>!vocabulary.valid.includes(selector));if(unknown.length>0){throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`,EXIT_CODE.USAGE)}const fullItem=selectors.includes("item");const itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice("item.".length)]:vocabulary.itemFields.includes(selector)?[selector]:[]).filter((selector,index,values)=>values.indexOf(selector)===index);if(fullItem&&itemSelectors.length>0){throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",EXIT_CODE.USAGE)}const selectedSections=new Set(selectors.filter(selector=>vocabulary.sections.includes(selector)));const projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));if(fullItem){projected.item=vocabulary.item}else if(itemSelectors.length>0){projected.item=projectRecordFields(vocabulary.item,itemSelectors)}const omittedFieldGroups=[...fullItem?[]:itemSelectors.length>0?vocabulary.itemFields.filter(field=>!itemSelectors.includes(field)).map(field=>({name:`item.${field}`,restore_with:`--output-include item.${field}`})):[{name:"item",restore_with:"--output-include item"}],...vocabulary.sections.filter(section=>!selectedSections.has(section)).map(section=>({name:section,restore_with:`--output-include ${section}`}))];const inheritedOmittedFieldGroups=isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[];const combinedOmittedFieldGroups=[...inheritedOmittedFieldGroups,...omittedFieldGroups];projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups};return projected}function countPopulatedRows(result){let populated=0;mapReadOutputRows({...result},entry=>{if(isRecord(entry)&&Object.keys(entry).length>0)populated+=1;return entry});return populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0){return}const modes=[...readOutputIncludeModeOptions(command).keys()];const domain=modes.length>0?` Declared ${command} projection modes: ${modes.join(", ")}.`:` The ${command} surface declares no projection modes; name row fields instead.`;throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`,EXIT_CODE.USAGE)}function applyIncludeProjection(command,result,selectors){if(command==="get"){return applyGetIncludeProjection(result,selectors)}const rows=readOutputRowPaths(result);const qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[]));const selectedRoot=selectors.some(selector=>Object.hasOwn(result,selector.split(".")[0])&&!rows.some(rowPath=>selector.startsWith(`${rowPath}.`)));if(rows.length>0&&(!selectedRoot||qualifiedRowSelectors.length>0)){const projected={...result};const rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors;const shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);rejectEmptyIncludeProjection(command,result,shaped,rowSelectors);return shaped}return Object.fromEntries(Object.entries(result).filter(([key])=>selectors.some(selector=>selector.split(".")[0]===key)||ENVELOPE_KEYS.has(key)))}function applyAmountBound(result,amount){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount);if(!truncated)return bounded;bounded.has_more=true;bounded.truncated=true;if(typeof bounded.count==="number"){bounded.count=countReadOutputRows(bounded)}bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount};return bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function readOutputMeasurementFormat(options){const format=options.resolvedOutputFormat??options.outputFormat??options.output_format??options.format;return format==="json"||format==="toon"?format:void 0}function attachReadOutputSessionContracts(result,state,receipt,format){let withSession=attachReadOutputSessionReceipt(result,state,format);preserveReadOutputRowContract(result,withSession);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens;const previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt,format);const previous=withSession;withSession=attachReadOutputSessionReceipt(withSession,state,format);preserveReadOutputRowContract(previous,withSession);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate){return withSession}}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const format=readOutputMeasurementFormat(options);const receipt=result.read_output;const session=parseReadOutputSession(options.outputSession??options.output_session);if(session===void 0){updateReadOutputReceiptEstimate(result,receipt,format);return result}return attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;const declaredFieldGroups=Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[];if(!declaredFieldGroups.some(group=>isRecord(group)&&group.name==="diagnostic_rows")){return result}const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))];const diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{};const existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry==="string"):[];const existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry==="string"):[];const rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys;const continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector==="string"?existingContract.jq_selector:".checks[].details"}}}function projectReadOutputRows(result,resolved,session,cursor){let projected={...result};if(resolved.include?.source==="canonical"){projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)}if(resolved.command==="assurance"){projected=prioritizeAssuranceAssertions(projected)}projected=applyReadOutputContinuation(projected,resolved.command,cursor);if(resolved.amount?.source==="canonical"){projected=applyAmountBound(projected,resolved.amount.value)}return session===void 0?projected:applyReadOutputSessionReferences(projected,session)}function resolveBindingReadOutputBudget(resolved,session){const budgets=[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]];return budgets.sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...bindingBudget.source==="default"?{budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens}:{},precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:false,strings_compacted:false,rows_compacted:false,result_omitted:true,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}};const omitted={output_budget_exceeded:{omitted_result:true,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt};const boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0){updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format)}if(session!==void 0&&minimalReceipt.estimated_tokens>bindingBudget.tokens){throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",EXIT_CODE.USAGE)}return boundedOmission}function requiresReadOutputAudit(resolved,options){return options.outputRowContract===true||options.output_row_contract===true||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===true}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||requiresReadOutputAudit(resolved,options))return false;if(resolved.amount?.source==="canonical"&&resolved.amount.value!=="unbounded"){const limit=resolved.amount.value;if(readOutputRowCollections(result).some(({value})=>(Array.isArray(value)?value.length:Object.keys(value).length)>limit))return false}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"||estimateReadOutputTokens(options.outputRowContract===false?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result,format)<=resolved.cost.value}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[];const afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length]));const continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);if(retainedRows>=before.rows)return[];const offset=before.baseOffset+retainedRows;return[{path,cursor:encodeReadOutputContinuationCursor({command:resolved.command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint}),retained_rows:retainedRows,remaining_rows:before.totalRows-offset,total_rows:before.totalRows}]});const primary=continuations[0];const continuationHint=primary?"; page --output-cursor":"";const budgetHint=bindingBudget.source==="session"?`Truncated by the remaining ${bindingBudget.tokens}-token session budget; start a new output session with a larger token_budget${continuationHint}.`:`${bindingBudget.tokens}-token: raise --output-budget${continuationHint}`;receipt.migration_hints=[budgetHint,...resolved.migration_hints];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});if(primary&&!continuationCursorRebased&&(typeof projected.next_cursor!=="string"||projected.continuation_kind==="output_cursor")){projected.next_cursor=primary.cursor}projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none";projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"recovery":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseBudgetCompactedCursor(projected,originalItemCount,cursorSource,cursorContinuesExistingPage){if(typeof cursorSource!=="string"||!Array.isArray(projected.items)){return false}const retainedCount=projected.items.length;if(retainedCount===0||retainedCount>=originalItemCount){return false}let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return false}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return false;const last=projected.items.at(-1);if(Object.prototype.toString.call(last)!=="[object Object]"){return false}const lastId=Reflect.get(last,"id");if(typeof lastId!=="string"||lastId.length===0)return false;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+retainedCount;if(afterIndex<0)return false;projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot);return true}function captureReadOutputContinuationState(projected,command,cursor,options){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length;const continued=cursor?.path===collection.path;return[collection.path,{rows,totalRows:continued?cursor.total_rows:rows,baseOffset:continued?cursor.offset:0,fingerprint:continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,collection.value,command)}]}));const cursorContinuesExistingPage=typeof projected.next_cursor==="string";return{collectionsBeforeBudget,originalItemCount:Array.isArray(projected.items)?projected.items.length:0,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after}}function compactReadOutputProjection(projected,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0;return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,assuranceMinimumRows>0?new Map([["assertions",assuranceMinimumRows]]):new Map,format,compacted=>{const continuationCursorRebased=rebaseBudgetCompactedCursor(compacted,continuationState.originalItemCount,continuationState.cursorSource,continuationState.cursorContinuesExistingPage);attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget);if(session!==void 0){Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))}})}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options);const session=parseReadOutputSession(options.outputSession??options.output_session);const rawCursor=options.outputCursor??options.output_cursor;const cursor=typeof rawCursor==="string"?decodeReadOutputContinuationCursor(rawCursor):void 0;const requested=requestedDimensions(resolved);const continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options)){return continuationReadyResult}const bindingBudget=resolveBindingReadOutputBudget(resolved,session);let projected=projectReadOutputRows(continuationReadyResult,resolved,session,cursor);preserveReadOutputRowContract(projected,projected,options.outputRowContract===false);const receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...bindingBudget?.source==="default"?{budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens}:{},precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:true,strings_compacted:false,rows_compacted:false,result_omitted:false};projected.read_output=receipt;projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format);updateReadOutputReceiptEstimate(projected,receipt,format);if(bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);if(brief!==void 0){receipt.applied_depth="brief";receipt.degradation_reason="output_budget_reached";preserveReadOutputRowContract(projected,brief);projected=stabilizeReadOutputReceiptEstimates(brief,options)}if(receipt.estimated_tokens>bindingBudget.tokens){projected=compactReadOutputProjection(projected,resolved,receipt,bindingBudget,session,captureReadOutputContinuationState(projected,resolved.command,cursor,options),receipt.estimated_tokens,format)}}if(bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){return omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format)}return projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===true&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const canonical=options.outputFormat??options.output_format;if(canonical==="json"||canonical==="toon")return canonical;const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
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]="7e99eae1-0d3d-5c91-8ba7-a103601ccfe7")}catch(e2){}})();import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactReadOutputToBudget,estimateReadOutputTokens,projectReadOutputItemToBrief,preserveReadOutputRowContract,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths,readOutputRowCollections}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint}from"./read-output/continuation.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];const PM_READ_OUTPUT_SURFACES=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"];const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"];const CANONICAL_OPTIONS={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};const PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension]));const PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]);const LEGACY_FLAGS_BY_COMMAND={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}};const VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]);const BEHAVIOR_PRESERVING_MIGRATION_HINTS=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function flagSelector(flag){return flag.slice(2).replaceAll("-","_")}function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command];const dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:true,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptions(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract));const SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase());const packageMode=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===true||options.target==="catalog"||options.action==="catalog");const root=packageMode?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0];const normalized=root.startsWith("list-")?"list":root==="ctx"?"context":root;return PM_READ_OUTPUT_SURFACES.includes(normalized)?normalized:void 0}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"];const HYBRID_READ_MUTATION_KEYS={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>key!=="outputFormat"&&key!=="output_format"&&options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:value=>{parseReadOutputSession(value);return true},message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value==="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function validateReadOutputOptions(command,options){const encoding=options.outputFormat??options.output_format;if(encoding!==void 0&&encoding!=="json"&&encoding!=="toon"){throw new PmCliError("--output-format must be toon or json.",EXIT_CODE.USAGE)}if(!hasCanonicalReadOutputOptions(options))return;const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand){throw new PmCliError(`Universal output controls apply only to read commands; ${command||"this command"} is not a read surface.`,EXIT_CODE.USAGE)}if((HYBRID_READ_MUTATION_KEYS[normalizedCommand]??[]).some(key=>options[key]!==void 0&&options[key]!==false)){throw new PmCliError(`Universal output controls cannot be combined with a ${normalizedCommand} mutation.`,EXIT_CODE.USAGE)}for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value)){throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);if(!surface)return new Map;return new Map((LEGACY_FLAGS_BY_COMMAND[surface].include??[]).filter(flag=>!VALUE_BEARING_INCLUDE_ALIASES.has(flag)&&BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0).map(flag=>[flagSelector(flag),optionKey(flag)]))}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[];const modeOptions=readOutputIncludeModeOptions(command);const selectors=[];const modes=[];const optionsWithProvenance=commandOptions;const existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE];const canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]);const explicitLegacyAliases=new Set(existingProvenance?.explicit_legacy_aliases??[]);for(const token of requested){const option=modeOptions.get(token);if(option===void 0){selectors.push(token);continue}const legacyFlag=`--${token.replaceAll("_","-")}`;if(isRequestedOption(readOption(commandOptions,legacyFlag))){explicitLegacyAliases.add(legacyFlag)}commandOptions[option]=true;modes.push(token);canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[];const forwardedGetFields=forwardedGetFieldSelectors.length>0;if(forwardedGetFields){commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(",");canonicalModes.add("fields")}if(modes.length>0||forwardedGetFields){optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===true?{cli_invocation_observed:true}:{}}}return{selectors,modes}}function normalizeReadOutputIncludeModeOptions(command,options){const include=options.outputInclude??options.output_include;if(include===void 0)return;const{selectors,modes}=applyReadOutputIncludeModes(command,include,options);if(modes.length===0)return;const residual=selectors.length>0?selectors.join(","):void 0;options.outputInclude=residual;if(Object.hasOwn(options,"output_include")){options.output_include=residual}}function optionKey(flag){return flag.slice(2).replace(/-([a-z])/gu,(_,character)=>character.toUpperCase())}function readOption(options,flag){const key=optionKey(flag);if(Object.hasOwn(options,key))return options[key];const snakeKey=flag.slice(2).replaceAll("-","_");if(Object.hasOwn(options,snakeKey))return options[snakeKey];if(flag==="--no-truncate"&&options.truncate===false)return true;return void 0}function isRequestedOption(value){return value!==void 0&&value!==false&&value!==null}function stringList(value){const values=Array.isArray(value)?value:[value];const normalized=values.flatMap(entry=>typeof entry==="string"?entry.split(","):[]).map(entry=>entry.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function positiveInteger(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 resolveLegacyDimension(contract,options,usable,ignore){for(const alias of contract.legacy_aliases){if(ignore(alias.flag))continue;const value=readOption(options,alias.flag);const candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}return void 0}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(!legacy)return void 0;return{source:"legacy",value:stringList(legacy.value)??[flagSelector(legacy.flag)]}}function resolveAmountValue(canonical,legacy){if(canonical==="unbounded"){return{source:"canonical",value:"unbounded"}}const canonicalLimit=positiveInteger(canonical);if(canonicalLimit!==void 0){return{source:"canonical",value:canonicalLimit}}if(!legacy)return void 0;if(legacy.flag==="--no-truncate"||legacy.flag==="--unbounded"){return{source:"legacy",value:"unbounded"}}const legacyLimit=positiveInteger(legacy.value);return legacyLimit===void 0?void 0:{source:"legacy",value:legacyLimit}}function resolveCostValue(canonical,legacy){if(canonical==="unbounded"){return{source:"canonical",value:"unbounded"}}const canonicalBudget=positiveInteger(canonical);if(canonicalBudget!==void 0){return{source:"canonical",value:canonicalBudget}}if(!legacy)return void 0;const legacyBudget=positiveInteger(legacy.value);return legacyBudget===void 0?void 0:{source:"legacy",value:legacyBudget}}function resolveEncodingValue(canonical,legacy){if(canonical==="json"||canonical==="toon"){return{source:"canonical",value:canonical}}if(!legacy)return void 0;if(legacy.flag==="--stream"||legacy.flag==="--follow"){return{source:"legacy",value:"stream"}}return legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return false;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===true||provenance.sdk_invocation_observed===true){return!explicitLegacyAliases.has(flag)}const forwardedIncludeAliases=new Set(provenance.canonical_include_modes.map(mode=>`--${mode.replaceAll("_","-")}`));return dimension==="include"&&forwardedIncludeAliases.has(flag)&&!explicitLegacyAliases.has(flag)}function hasCompleteReadOutputIntent(command,legacyByDimension,provenance){const root=command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0];return root==="list-all"||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===true}function canonicalReadOutputOptionsUsed(resolvedByDimension,provenance){return PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>resolvedByDimension[dimension]?.source==="canonical"||dimension==="include"&&(provenance?.canonical_include_modes.length??0)>0?[CANONICAL_OPTIONS[dimension]]:[])}function resolveReadOutputDimensions(command,options){const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)return void 0;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand);const invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE];const legacyResolvers={include:candidate=>resolveIncludeValue(void 0,candidate),amount:candidate=>resolveAmountValue(void 0,candidate),cost:candidate=>resolveCostValue(void 0,candidate),encoding:candidate=>resolveEncodingValue(void 0,candidate)};const legacyByDimension=Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,resolveLegacyDimension(contract.dimensions[dimension],options,candidate=>legacyResolvers[dimension](candidate)!==void 0,flag=>shouldIgnoreReadOutputLegacyAlias(invocationProvenance,dimension,flag))]));const legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]});const migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];if(!resolved)return[];const alias=contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag);return[alias.migration_hint]});const encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding);const include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include);const amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount);const explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost);const completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance);const budget=resolvePmCommandOutputBudget(command,{generateFallback:true});const resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon";const cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});const resolvedByDimension={include,amount,cost,encoding};return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed(resolvedByDimension,invocationProvenance),legacy_aliases_used:legacyAliasesUsed,migration_hints:migrationHints,precedence:READ_OUTPUT_PRECEDENCE}}function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}const ENVELOPE_KEYS=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]);const GET_STABLE_DERIVED_ITEM_SELECTORS=["collection_counts","notes_count","tests_count"];function projectRecordFields(value,selectors){const selected=new Set(selectors.map(selector=>selector.split(".")[0]));return Object.fromEntries(Object.entries(value).filter(([key])=>selected.has(key)))}function getProjectionVocabulary(result){const item=isRecord(result.item)?result.item:{};const itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right));const sections=Object.keys(result).filter(key=>key!=="item"&&key!=="read_output"&&!ENVELOPE_KEYS.has(key)).sort((left,right)=>left.localeCompare(right));return{item,itemFields,sections,valid:[...itemFields,"item",...itemFields.map(field=>`item.${field}`),...sections]}}function applyGetIncludeProjection(result,selectors){const vocabulary=getProjectionVocabulary(result);const unknown=selectors.filter(selector=>!vocabulary.valid.includes(selector));if(unknown.length>0){throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`,EXIT_CODE.USAGE)}const fullItem=selectors.includes("item");const itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice("item.".length)]:vocabulary.itemFields.includes(selector)?[selector]:[]).filter((selector,index,values)=>values.indexOf(selector)===index);if(fullItem&&itemSelectors.length>0){throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",EXIT_CODE.USAGE)}const selectedSections=new Set(selectors.filter(selector=>vocabulary.sections.includes(selector)));const projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));if(fullItem){projected.item=vocabulary.item}else if(itemSelectors.length>0){projected.item=projectRecordFields(vocabulary.item,itemSelectors)}const omittedFieldGroups=[...fullItem?[]:itemSelectors.length>0?vocabulary.itemFields.filter(field=>!itemSelectors.includes(field)).map(field=>({name:`item.${field}`,restore_with:`--output-include item.${field}`})):[{name:"item",restore_with:"--output-include item"}],...vocabulary.sections.filter(section=>!selectedSections.has(section)).map(section=>({name:section,restore_with:`--output-include ${section}`}))];const inheritedOmittedFieldGroups=isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[];const combinedOmittedFieldGroups=[...inheritedOmittedFieldGroups,...omittedFieldGroups];projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups};return projected}function countPopulatedRows(result){let populated=0;mapReadOutputRows({...result},entry=>{if(isRecord(entry)&&Object.keys(entry).length>0)populated+=1;return entry});return populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0){return}const modes=[...readOutputIncludeModeOptions(command).keys()];const domain=modes.length>0?` Declared ${command} projection modes: ${modes.join(", ")}.`:` The ${command} surface declares no projection modes; name row fields instead.`;throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`,EXIT_CODE.USAGE)}function applyIncludeProjection(command,result,selectors){if(command==="get"){return applyGetIncludeProjection(result,selectors)}const rows=readOutputRowPaths(result);const qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[]));const selectedRoot=selectors.some(selector=>Object.hasOwn(result,selector.split(".")[0])&&!rows.some(rowPath=>selector.startsWith(`${rowPath}.`)));if(rows.length>0&&(!selectedRoot||qualifiedRowSelectors.length>0)){const projected={...result};const rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors;const shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);rejectEmptyIncludeProjection(command,result,shaped,rowSelectors);return shaped}return Object.fromEntries(Object.entries(result).filter(([key])=>selectors.some(selector=>selector.split(".")[0]===key)||ENVELOPE_KEYS.has(key)))}function applyAmountBound(result,amount){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount);if(!truncated)return bounded;bounded.has_more=true;bounded.truncated=true;if(typeof bounded.count==="number"){bounded.count=countReadOutputRows(bounded)}bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount};return bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function readOutputMeasurementFormat(options){const format=options.resolvedOutputFormat??options.outputFormat??options.output_format??options.format;return format==="json"||format==="toon"?format:void 0}function attachReadOutputSessionContracts(result,state,receipt,format){let withSession=attachReadOutputSessionReceipt(result,state,format);preserveReadOutputRowContract(result,withSession);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens;const previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt,format);const previous=withSession;withSession=attachReadOutputSessionReceipt(withSession,state,format);preserveReadOutputRowContract(previous,withSession);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate){return withSession}}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const format=readOutputMeasurementFormat(options);const receipt=result.read_output;const session=parseReadOutputSession(options.outputSession??options.output_session);if(session===void 0){updateReadOutputReceiptEstimate(result,receipt,format);return result}return attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;const declaredFieldGroups=Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[];if(!declaredFieldGroups.some(group=>isRecord(group)&&group.name==="diagnostic_rows")){return result}const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))];const diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{};const existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry==="string"):[];const existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry==="string"):[];const rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys;const continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector==="string"?existingContract.jq_selector:".checks[].details"}}}function projectReadOutputRows(result,resolved,session,cursor){let projected={...result};if(resolved.include?.source==="canonical"){projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)}if(resolved.command==="assurance"){projected=prioritizeAssuranceAssertions(projected)}projected=applyReadOutputContinuation(projected,resolved.command,cursor);if(resolved.amount?.source==="canonical"){projected=applyAmountBound(projected,resolved.amount.value)}return session===void 0?projected:applyReadOutputSessionReferences(projected,session)}function resolveBindingReadOutputBudget(resolved,session){const budgets=[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]];return budgets.sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...bindingBudget.source==="default"?{budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens}:{},precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:false,strings_compacted:false,rows_compacted:false,result_omitted:true,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}};const omitted={output_budget_exceeded:{omitted_result:true,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt};const boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0){updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format)}if(session!==void 0&&minimalReceipt.estimated_tokens>bindingBudget.tokens){throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",EXIT_CODE.USAGE)}return boundedOmission}function requiresReadOutputAudit(resolved,options){return options.outputRowContract===true||options.output_row_contract===true||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===true}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||requiresReadOutputAudit(resolved,options))return false;if(resolved.amount?.source==="canonical"&&resolved.amount.value!=="unbounded"){const limit=resolved.amount.value;if(readOutputRowCollections(result).some(({value})=>(Array.isArray(value)?value.length:Object.keys(value).length)>limit))return false}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"||estimateReadOutputTokens(options.outputRowContract===false?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result,format)<=resolved.cost.value}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[];const afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length]));const continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);if(retainedRows>=before.rows)return[];const offset=before.baseOffset+retainedRows;return[{path,cursor:encodeReadOutputContinuationCursor({command:resolved.command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint}),retained_rows:retainedRows,remaining_rows:before.totalRows-offset,total_rows:before.totalRows}]});const primary=continuations[0];const continuationHint=primary?"; page --output-cursor":"";const budgetHint=bindingBudget.source==="session"?`Truncated by the remaining ${bindingBudget.tokens}-token session budget; start a new output session with a larger token_budget${continuationHint}.`:`${bindingBudget.tokens}-token: raise --output-budget${continuationHint}`;receipt.migration_hints=[budgetHint,...resolved.migration_hints];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});if(primary&&!continuationCursorRebased&&(typeof projected.next_cursor!=="string"||projected.continuation_kind==="output_cursor")){projected.next_cursor=primary.cursor}projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none";projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"recovery":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseBudgetCompactedCursor(projected,originalItemCount,cursorSource,cursorContinuesExistingPage){if(typeof cursorSource!=="string"||!Array.isArray(projected.items)){return false}const retainedCount=projected.items.length;if(retainedCount===0||retainedCount>=originalItemCount){return false}let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return false}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return false;const last=projected.items.at(-1);if(Object.prototype.toString.call(last)!=="[object Object]"){return false}const lastId=Reflect.get(last,"id");if(typeof lastId!=="string"||lastId.length===0)return false;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+retainedCount;if(afterIndex<0)return false;projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot);return true}function captureReadOutputContinuationState(projected,command,cursor,options){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length;const continued=cursor?.path===collection.path;return[collection.path,{rows,totalRows:continued?cursor.total_rows:rows,baseOffset:continued?cursor.offset:0,fingerprint:continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,collection.value,command)}]}));const cursorContinuesExistingPage=typeof projected.next_cursor==="string";return{collectionsBeforeBudget,originalItemCount:Array.isArray(projected.items)?projected.items.length:0,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after}}function compactReadOutputProjection(projected,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0;return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,assuranceMinimumRows>0?new Map([["assertions",assuranceMinimumRows]]):new Map,format,compacted=>{const continuationCursorRebased=rebaseBudgetCompactedCursor(compacted,continuationState.originalItemCount,continuationState.cursorSource,continuationState.cursorContinuesExistingPage);attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget);if(session!==void 0){Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))}})}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options);const session=parseReadOutputSession(options.outputSession??options.output_session);const rawCursor=options.outputCursor??options.output_cursor;const cursor=typeof rawCursor==="string"?decodeReadOutputContinuationCursor(rawCursor):void 0;const requested=requestedDimensions(resolved);const continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options)){return continuationReadyResult}const bindingBudget=resolveBindingReadOutputBudget(resolved,session);let projected=projectReadOutputRows(continuationReadyResult,resolved,session,cursor);preserveReadOutputRowContract(projected,projected,options.outputRowContract===false);const receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...bindingBudget?.source==="default"?{budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens}:{},precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:true,strings_compacted:false,rows_compacted:false,result_omitted:false};projected.read_output=receipt;projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format);updateReadOutputReceiptEstimate(projected,receipt,format);if(bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);if(brief!==void 0){receipt.applied_depth="brief";receipt.degradation_reason="output_budget_reached";preserveReadOutputRowContract(projected,brief);projected=stabilizeReadOutputReceiptEstimates(brief,options)}if(receipt.estimated_tokens>bindingBudget.tokens){projected=compactReadOutputProjection(projected,resolved,receipt,bindingBudget,session,captureReadOutputContinuationState(projected,resolved.command,cursor,options),receipt.estimated_tokens,format)}}if(bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){return omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format)}return projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===true&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const canonical=options.outputFormat??options.output_format;if(canonical==="json"||canonical==="toon")return canonical;const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
2
2
  //# sourceMappingURL=read-output-contracts.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]="fb87ff0c-88c8-52f9-9dc3-f37fec674425")}catch(e2){}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordClone}from"../core/shared/primitives.js";import{normalizeListOptions,normalizeUpdateOptions}from"./cli-contracts/registration-helpers.js";import{UPDATE_COMMANDER_STRING_OPTION_CONTRACTS}from"./cli-contracts/commander-mutation-options.js";import{normalizeBulkIdsValue}from"../core/io/bulk-ids-input.js";import{overlayMutationStdinTokenPolicy,preserveMutationStdinTokenLiterals,transferMutationStdinTokenPolicy}from"../core/item/parse.js";const MCP_MUTATION_TRANSPORT=Symbol("pm.mcp-mutation-transport");const WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function markMcpMutationTransportInput(input){Object.defineProperty(input,MCP_MUTATION_TRANSPORT,{value:true,enumerable:true});return input}function isMcpMutationTransportInput(input){return MCP_MUTATION_TRANSPORT in input}function preserveTransportLiteralOptions(source,options){return isMcpMutationTransportInput(source)?preserveMutationStdinTokenLiterals(options):transferMutationStdinTokenPolicy(source,options)}function mutationOptionsWithOverrides(source,overrides,omittedKeys=[]){const options=transferMutationStdinTokenPolicy(source,{...source,...overrides});for(const key of omittedKeys)Reflect.deleteProperty(options,key);return options}function readRuntimeString(args,key){const value=args[key];return typeof value==="string"&&value.trim().length>0?value:void 0}function readRuntimeScalarString(args,key){const value=args[key];if(typeof value==="string"){return value.trim().length>0?value:void 0}return typeof value==="number"&&Number.isFinite(value)?String(value):void 0}function readRuntimeScalarStringAllowBlank(args,key){const value=args[key];if(typeof value==="string"){return value}return typeof value==="number"&&Number.isFinite(value)?String(value):void 0}function isRuntimeRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function parseRuntimeInteger(value,label){if(typeof value==="number"){if(!Number.isInteger(value)){throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE)}return value}if(typeof value==="string"&&value.trim().length>0){const parsed=Number(value);if(!Number.isInteger(parsed)){throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE)}return parsed}return void 0}function resolveRuntimeLimit(args,options){if(typeof args.limit==="number"&&Number.isFinite(args.limit)){return args.limit}if(typeof options.limit==="number"&&Number.isFinite(options.limit)){return options.limit}return readRuntimeString(args,"limit")??readRuntimeString(options,"limit")}function actionGlobalOptions(args){const outputFormat=readRuntimeString(args,"outputFormat");return{json:true,quiet:true,author:readRuntimeString(args,"author"),path:readRuntimeString(args,"path"),noExtensions:args.noExtensions===true||args.no_extensions===true,noPager:true,outputInclude:readRuntimeString(args,"outputInclude"),outputLimit:readRuntimeScalarString(args,"outputLimit"),outputBudget:readRuntimeScalarString(args,"outputBudget"),outputSession:readRuntimeString(args,"outputSession"),outputCursor:readRuntimeString(args,"outputCursor"),outputFormat:outputFormat==="json"||outputFormat==="toon"?outputFormat:void 0}}const ARRAY_TO_CSV_FIELDS=new Set(["tags","blockedBy","blocked_by","skills","fields"]);const SCALAR_TO_ARRAY_FIELDS=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]);const ANNOTATION_SCALAR_TO_ARRAY_FIELDS=new Set([...SCALAR_TO_ARRAY_FIELDS].filter(field=>field!=="file"));const ARRAY_ADD_REMOVE_ACTIONS=new Set(["files","files-discover","docs","test","test-all"]);const SCALAR_ANNOTATION_SOURCE_ACTIONS=new Set(["comments","notes","learnings"]);function assertMcpAnnotationFileUnavailable(action,options){if(!SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)||!Object.prototype.hasOwnProperty.call(options,"file")){return}throw new PmCliError(`MCP ${action} does not accept options.file. Pass annotation text in options.add instead.`,EXIT_CODE.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}const LIFECYCLE_AUTHOR_ALIAS_ACTIONS=new Set(["claim","release","start-task","pause-task","close-task"]);const HOISTED_ACTION_OPTION_KEYS={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun"],package:["dryRun"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]};const UNIVERSAL_READ_OUTPUT_OPTION_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function normalizeMcpOptionsArrays(options,action=""){const result={};const promoteAddRemove=ARRAY_ADD_REMOVE_ACTIONS.has(action);const preserveStandaloneNote=action==="files"||action==="files-discover"||action==="docs";const scalarToArrayFields=SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)?ANNOTATION_SCALAR_TO_ARRAY_FIELDS:SCALAR_TO_ARRAY_FIELDS;for(const[key,value]of Object.entries(options)){if(Array.isArray(value)&&ARRAY_TO_CSV_FIELDS.has(key)){result[key]=value.join(",");continue}if(key==="note"&&preserveStandaloneNote){result[key]=value;continue}if(typeof value==="string"&&scalarToArrayFields.has(key)){result[key]=[value];continue}if(typeof value==="string"&&promoteAddRemove&&(key==="add"||key==="remove")){result[key]=[value];continue}result[key]=value}return result}function resolveMcpActionAuthor(args,options,action){const author=readRuntimeString(args,"author");if(author!==void 0){return author}return action!==void 0&&LIFECYCLE_AUTHOR_ALIAS_ACTIONS.has(action)?readRuntimeString(args,"assignee")??readRuntimeString(options,"assignee"):void 0}function withResolvedAuthor(options,author){return author!==void 0&&options.author===void 0?{...options,author}:options}function optionsWithAuthor(args,action){const sourceOptions=isRuntimeRecord(args.options)?args.options:void 0;const baseOptions=asRecordClone(args.options);const hoistedTopLevel={};const hoistKey=key=>{if(baseOptions[key]!==void 0||args[key]===void 0){return}hoistedTopLevel[key]=args[key]};for(const key of HOISTED_ACTION_OPTION_KEYS[action??""]??[]){hoistKey(key)}for(const key of UNIVERSAL_READ_OUTPUT_OPTION_KEYS){hoistKey(key)}if(action!==void 0&&isMcpMutationTransportInput(args)){assertMcpAnnotationFileUnavailable(action,baseOptions)}const options=normalizeMcpOptionsArrays({...hoistedTopLevel,...baseOptions},action);if(action==="history-attest"&&isMcpMutationTransportInput(args)){if(options.output!==void 0||typeof options.verify==="string"){throw new PmCliError("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",EXIT_CODE.USAGE)}}const stdinPolicySource=isMcpMutationTransportInput(args)?args:sourceOptions??args;return preserveTransportLiteralOptions(stdinPolicySource,withResolvedAuthor(options,resolveMcpActionAuthor(args,options,action)))}function withAddNoteOption(options){if(options.addNote===void 0){return options}const next={...options};if(next.note===void 0&&typeof next.addNote==="string"){next.note=next.addNote}delete next.addNote;return next}function withFilesDiscoveryOptions(options){const next={...options};if(next.discoveryNote!==void 0&&next.note===void 0&&typeof next.discoveryNote==="string"){next.note=next.discoveryNote}delete next.discover;delete next.discoveryNote;return next}function normalizeActionName(value){const chunks=[];let lastWasSeparator=true;for(const character of value.trim().toLowerCase()){const isAlphaNumeric=character>="a"&&character<="z"||character>="0"&&character<="9";if(isAlphaNumeric){chunks.push(character);lastWasSeparator=false;continue}if(!lastWasSeparator){chunks.push("-");lastWasSeparator=true}}if(chunks.at(-1)==="-"){chunks.pop()}return chunks.join("")}function shouldInvalidateWorkspaceContractsCacheAfterAction(action){return!WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS.has(normalizeActionName(action))}function normalizeCommandPath(value){return value.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function readRuntimeStringArray(value){if(!Array.isArray(value)){return[]}return value.map(entry=>String(entry)).filter(entry=>entry.length>0)}function extensionOptionsFromArgs(args,options){const reserved=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]);const passthrough={};for(const[key,value]of Object.entries(args)){if(!reserved.has(key)){passthrough[key]=value}}const normalizedOptions={...passthrough,...options};delete normalizedOptions.args;return normalizedOptions}function withMutationCompaction(args,options){const runnerOptions=preserveTransportLiteralOptions(options??{},{...options});return{changedFields:args.fullChangedFields===true?"full":"compact",idOnly:args.idOnly===true,runnerOptions}}function mutationListOptions(options){return{type:readRuntimeScalarString(options,"filterType"),tag:readRuntimeScalarString(options,"filterTag"),priority:readRuntimeScalarString(options,"filterPriority"),deadlineBefore:readRuntimeScalarString(options,"filterDeadlineBefore"),deadlineAfter:readRuntimeScalarString(options,"filterDeadlineAfter"),updatedAfter:readRuntimeScalarString(options,"filterUpdatedAfter"),updatedBefore:readRuntimeScalarString(options,"filterUpdatedBefore"),createdAfter:readRuntimeScalarString(options,"filterCreatedAfter"),createdBefore:readRuntimeScalarString(options,"filterCreatedBefore"),ids:normalizeBulkIdsValue(options.ids),assignee:readRuntimeScalarString(options,"filterAssignee"),assigneeFilter:readRuntimeScalarString(options,"filterAssigneeFilter")??readRuntimeScalarString(options,"filterAssignee_filter"),parent:readRuntimeScalarString(options,"filterParent"),sprint:readRuntimeScalarString(options,"filterSprint"),release:readRuntimeScalarString(options,"filterRelease"),limit:readRuntimeScalarString(options,"limit"),offset:readRuntimeScalarString(options,"offset")}}function readGraphIdListOption(value){if(typeof value==="string"&&value.trim().length>0)return value;if(Array.isArray(value))return readRuntimeStringArray(value);return void 0}function readGraphBoundOption(value){if(typeof value==="number"&&Number.isFinite(value))return value;if(typeof value==="string"&&value.trim().length>0)return value;return void 0}function graphOptionsFromFlat(options){const kind=readGraphIdListOption(options.kind);const exemptIsolate=readGraphIdListOption(options.exemptIsolate);const exemptIsolateType=readGraphIdListOption(options.exemptIsolateType);return{...kind===void 0?{}:{kind},maxDepth:readGraphBoundOption(options.maxDepth),limit:readGraphBoundOption(options.limit),after:readRuntimeString(options,"after"),direction:readRuntimeString(options,"direction"),maxPaths:readGraphBoundOption(options.maxPaths),sample:readGraphBoundOption(options.sample),...exemptIsolate===void 0?{}:{exemptIsolate},...exemptIsolateType===void 0?{}:{exemptIsolateType},saveBaseline:options.saveBaseline===true,rebuild:options.rebuild===true,clear:options.clear===true,summary:options.summary===true,...options.full===true?{full:true}:{}}}function normalizeBulkMutationListOptions(options){const normalized=normalizeListOptions(options);if(options.ids!==void 0){normalized.ids=normalizeBulkIdsValue(options.ids)}return normalized}function closeManyOptionsFromFlat(options){return{status:readRuntimeString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),reason:readRuntimeString(options,"reason"),resolution:readRuntimeString(options,"resolution"),expectedResult:readRuntimeString(options,"expectedResult")??readRuntimeString(options,"expected_result")??readRuntimeString(options,"expected"),actualResult:readRuntimeString(options,"actualResult")??readRuntimeString(options,"actual_result")??readRuntimeString(options,"actual"),validateClose:readRuntimeString(options,"validateClose")??readRuntimeString(options,"validate_close"),author:readRuntimeString(options,"author"),message:readRuntimeString(options,"message"),force:options.force===true?true:void 0,dryRun:options.dryRun===true||options.dry_run===true?true:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===false||options.noCheckpoint===true||options.no_checkpoint===true?false:void 0}}const UPDATE_MANY_FLAT_CONTROL_KEYS=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function updateManyUpdateOptionsFromFlat(options){const update={};for(const[key,value]of Object.entries(options)){if(UPDATE_MANY_FLAT_CONTROL_KEYS.has(key)){continue}update[key]=value}return normalizeMcpUpdateOptions(update)}function normalizeMcpUpdateOptions(options){const normalizedInput=normalizeMcpOptionsArrays(options,"update-many");for(const contract of UPDATE_COMMANDER_STRING_OPTION_CONTRACTS){for(const key of contract.keys){const value=normalizedInput[key];if(typeof value==="number"&&Number.isFinite(value)){normalizedInput[key]=String(value)}}}return normalizeUpdateOptions(normalizedInput)}function updateManyOptionsFromFlat(options){if(isRuntimeRecord(options.list)||isRuntimeRecord(options.update)){const updateSource=isRuntimeRecord(options.update)?options.update:updateManyUpdateOptionsFromFlat(options);const normalizedUpdate=preserveTransportLiteralOptions(options,normalizeMcpUpdateOptions(updateSource));return{status:readRuntimeScalarString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),update:overlayMutationStdinTokenPolicy(updateSource,normalizedUpdate),dryRun:options.dryRun===true||options.dry_run===true?true:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===false||options.noCheckpoint===true||options.no_checkpoint===true?false:void 0}}return{status:readRuntimeScalarString(options,"filterStatus"),list:mutationListOptions(options),update:preserveTransportLiteralOptions(options,updateManyUpdateOptionsFromFlat(options)),dryRun:options.dryRun===true||options.dry_run===true?true:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===false||options.noCheckpoint===true||options.no_checkpoint===true?false:void 0}}export{actionGlobalOptions,closeManyOptionsFromFlat,extensionOptionsFromArgs,graphOptionsFromFlat,isRuntimeRecord,markMcpMutationTransportInput,mutationListOptions,mutationOptionsWithOverrides,normalizeActionName,normalizeCommandPath,normalizeMcpOptionsArrays,normalizeMcpUpdateOptions,optionsWithAuthor,parseRuntimeInteger,readRuntimeScalarString,readRuntimeScalarStringAllowBlank,readRuntimeString,readRuntimeStringArray,resolveRuntimeLimit,shouldInvalidateWorkspaceContractsCacheAfterAction,updateManyOptionsFromFlat,updateManyUpdateOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction};
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]="17883200-00ba-51ef-8a6b-ab0ce2ad2029")}catch(e2){}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordClone}from"../core/shared/primitives.js";import{normalizeListOptions,normalizeUpdateOptions}from"./cli-contracts/registration-helpers.js";import{UPDATE_COMMANDER_STRING_OPTION_CONTRACTS}from"./cli-contracts/commander-mutation-options.js";import{normalizeBulkIdsValue}from"../core/io/bulk-ids-input.js";import{overlayMutationStdinTokenPolicy,preserveMutationStdinTokenLiterals,transferMutationStdinTokenPolicy}from"../core/item/parse.js";const MCP_MUTATION_TRANSPORT=Symbol("pm.mcp-mutation-transport");const WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function markMcpMutationTransportInput(input){Object.defineProperty(input,MCP_MUTATION_TRANSPORT,{value:true,enumerable:true});return input}function isMcpMutationTransportInput(input){return MCP_MUTATION_TRANSPORT in input}function preserveTransportLiteralOptions(source,options){return isMcpMutationTransportInput(source)?preserveMutationStdinTokenLiterals(options):transferMutationStdinTokenPolicy(source,options)}function mutationOptionsWithOverrides(source,overrides,omittedKeys=[]){const options=transferMutationStdinTokenPolicy(source,{...source,...overrides});for(const key of omittedKeys)Reflect.deleteProperty(options,key);return options}function readRuntimeString(args,key){const value=args[key];return typeof value==="string"&&value.trim().length>0?value:void 0}function readRuntimeScalarString(args,key){const value=args[key];if(typeof value==="string"){return value.trim().length>0?value:void 0}return typeof value==="number"&&Number.isFinite(value)?String(value):void 0}function readRuntimeScalarStringAllowBlank(args,key){const value=args[key];if(typeof value==="string"){return value}return typeof value==="number"&&Number.isFinite(value)?String(value):void 0}function isRuntimeRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function parseRuntimeInteger(value,label){if(typeof value==="number"){if(!Number.isInteger(value)){throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE)}return value}if(typeof value==="string"&&value.trim().length>0){const parsed=Number(value);if(!Number.isInteger(parsed)){throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE)}return parsed}return void 0}function resolveRuntimeLimit(args,options){if(typeof args.limit==="number"&&Number.isFinite(args.limit)){return args.limit}if(typeof options.limit==="number"&&Number.isFinite(options.limit)){return options.limit}return readRuntimeString(args,"limit")??readRuntimeString(options,"limit")}function actionGlobalOptions(args){const outputFormat=readRuntimeString(args,"outputFormat");return{json:true,quiet:true,author:readRuntimeString(args,"author"),path:readRuntimeString(args,"path"),noExtensions:args.noExtensions===true||args.no_extensions===true,noPager:true,outputInclude:readRuntimeString(args,"outputInclude"),outputLimit:readRuntimeScalarString(args,"outputLimit"),outputBudget:readRuntimeScalarString(args,"outputBudget"),outputSession:readRuntimeString(args,"outputSession"),outputCursor:readRuntimeString(args,"outputCursor"),outputFormat:outputFormat==="json"||outputFormat==="toon"?outputFormat:void 0}}const ARRAY_TO_CSV_FIELDS=new Set(["tags","blockedBy","blocked_by","skills","fields"]);const SCALAR_TO_ARRAY_FIELDS=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]);const ANNOTATION_SCALAR_TO_ARRAY_FIELDS=new Set([...SCALAR_TO_ARRAY_FIELDS].filter(field=>field!=="file"));const ARRAY_ADD_REMOVE_ACTIONS=new Set(["files","files-discover","docs","test","test-all"]);const SCALAR_ANNOTATION_SOURCE_ACTIONS=new Set(["comments","notes","learnings"]);function assertMcpAnnotationFileUnavailable(action,options){if(!SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)||!Object.prototype.hasOwnProperty.call(options,"file")){return}throw new PmCliError(`MCP ${action} does not accept options.file. Pass annotation text in options.add instead.`,EXIT_CODE.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}const LIFECYCLE_AUTHOR_ALIAS_ACTIONS=new Set(["claim","release","start-task","pause-task","close-task"]);const HOISTED_ACTION_OPTION_KEYS={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun"],package:["dryRun"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]};const UNIVERSAL_READ_OUTPUT_OPTION_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function normalizeMcpOptionsArrays(options,action=""){const result={};const promoteAddRemove=ARRAY_ADD_REMOVE_ACTIONS.has(action);const preserveStandaloneNote=action==="files"||action==="files-discover"||action==="docs";const scalarToArrayFields=SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)?ANNOTATION_SCALAR_TO_ARRAY_FIELDS:SCALAR_TO_ARRAY_FIELDS;for(const[key,value]of Object.entries(options)){if(Array.isArray(value)&&ARRAY_TO_CSV_FIELDS.has(key)){result[key]=value.join(",");continue}if(key==="note"&&preserveStandaloneNote){result[key]=value;continue}if(typeof value==="string"&&scalarToArrayFields.has(key)){result[key]=[value];continue}if(typeof value==="string"&&promoteAddRemove&&(key==="add"||key==="remove")){result[key]=[value];continue}result[key]=value}Object.assign(result,Object.fromEntries(Object.getOwnPropertySymbols(options).map(symbol=>[symbol,Reflect.get(options,symbol)])));return result}function resolveMcpActionAuthor(args,options,action){const author=readRuntimeString(args,"author");if(author!==void 0){return author}return action!==void 0&&LIFECYCLE_AUTHOR_ALIAS_ACTIONS.has(action)?readRuntimeString(args,"assignee")??readRuntimeString(options,"assignee"):void 0}function withResolvedAuthor(options,author){return author!==void 0&&options.author===void 0?{...options,author}:options}function optionsWithAuthor(args,action){const sourceOptions=isRuntimeRecord(args.options)?args.options:void 0;const baseOptions=asRecordClone(args.options);const hoistedTopLevel={};const hoistKey=key=>{if(baseOptions[key]!==void 0||args[key]===void 0){return}hoistedTopLevel[key]=args[key]};for(const key of HOISTED_ACTION_OPTION_KEYS[action??""]??[]){hoistKey(key)}for(const key of UNIVERSAL_READ_OUTPUT_OPTION_KEYS){hoistKey(key)}if(action!==void 0&&isMcpMutationTransportInput(args)){assertMcpAnnotationFileUnavailable(action,baseOptions)}const options=normalizeMcpOptionsArrays({...hoistedTopLevel,...baseOptions},action);if(action==="history-attest"&&isMcpMutationTransportInput(args)){if(options.output!==void 0||typeof options.verify==="string"){throw new PmCliError("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",EXIT_CODE.USAGE)}}const stdinPolicySource=isMcpMutationTransportInput(args)?args:sourceOptions??args;return preserveTransportLiteralOptions(stdinPolicySource,withResolvedAuthor(options,resolveMcpActionAuthor(args,options,action)))}function withAddNoteOption(options){if(options.addNote===void 0){return options}const next={...options};if(next.note===void 0&&typeof next.addNote==="string"){next.note=next.addNote}delete next.addNote;return next}function withFilesDiscoveryOptions(options){const next={...options};if(next.discoveryNote!==void 0&&next.note===void 0&&typeof next.discoveryNote==="string"){next.note=next.discoveryNote}delete next.discover;delete next.discoveryNote;return next}function normalizeActionName(value){const chunks=[];let lastWasSeparator=true;for(const character of value.trim().toLowerCase()){const isAlphaNumeric=character>="a"&&character<="z"||character>="0"&&character<="9";if(isAlphaNumeric){chunks.push(character);lastWasSeparator=false;continue}if(!lastWasSeparator){chunks.push("-");lastWasSeparator=true}}if(chunks.at(-1)==="-"){chunks.pop()}return chunks.join("")}function shouldInvalidateWorkspaceContractsCacheAfterAction(action){return!WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS.has(normalizeActionName(action))}function normalizeCommandPath(value){return value.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function readRuntimeStringArray(value){if(!Array.isArray(value)){return[]}return value.map(entry=>String(entry)).filter(entry=>entry.length>0)}function extensionOptionsFromArgs(args,options){const reserved=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]);const passthrough={};for(const[key,value]of Object.entries(args)){if(!reserved.has(key)){passthrough[key]=value}}const normalizedOptions={...passthrough,...options};delete normalizedOptions.args;return normalizedOptions}function withMutationCompaction(args,options){const runnerOptions=preserveTransportLiteralOptions(options??{},{...options});return{changedFields:args.fullChangedFields===true?"full":"compact",idOnly:args.idOnly===true,runnerOptions}}function mutationListOptions(options){return{type:readRuntimeScalarString(options,"filterType"),tag:readRuntimeScalarString(options,"filterTag"),priority:readRuntimeScalarString(options,"filterPriority"),deadlineBefore:readRuntimeScalarString(options,"filterDeadlineBefore"),deadlineAfter:readRuntimeScalarString(options,"filterDeadlineAfter"),updatedAfter:readRuntimeScalarString(options,"filterUpdatedAfter"),updatedBefore:readRuntimeScalarString(options,"filterUpdatedBefore"),createdAfter:readRuntimeScalarString(options,"filterCreatedAfter"),createdBefore:readRuntimeScalarString(options,"filterCreatedBefore"),ids:normalizeBulkIdsValue(options.ids),assignee:readRuntimeScalarString(options,"filterAssignee"),assigneeFilter:readRuntimeScalarString(options,"filterAssigneeFilter")??readRuntimeScalarString(options,"filterAssignee_filter"),parent:readRuntimeScalarString(options,"filterParent"),sprint:readRuntimeScalarString(options,"filterSprint"),release:readRuntimeScalarString(options,"filterRelease"),limit:readRuntimeScalarString(options,"limit"),offset:readRuntimeScalarString(options,"offset")}}function readGraphIdListOption(value){if(typeof value==="string"&&value.trim().length>0)return value;if(Array.isArray(value))return readRuntimeStringArray(value);return void 0}function readGraphBoundOption(value){if(typeof value==="number"&&Number.isFinite(value))return value;if(typeof value==="string"&&value.trim().length>0)return value;return void 0}function graphOptionsFromFlat(options){const kind=readGraphIdListOption(options.kind);const exemptIsolate=readGraphIdListOption(options.exemptIsolate);const exemptIsolateType=readGraphIdListOption(options.exemptIsolateType);return{...kind===void 0?{}:{kind},maxDepth:readGraphBoundOption(options.maxDepth),limit:readGraphBoundOption(options.limit),after:readRuntimeString(options,"after"),direction:readRuntimeString(options,"direction"),maxPaths:readGraphBoundOption(options.maxPaths),sample:readGraphBoundOption(options.sample),...exemptIsolate===void 0?{}:{exemptIsolate},...exemptIsolateType===void 0?{}:{exemptIsolateType},saveBaseline:options.saveBaseline===true,rebuild:options.rebuild===true,clear:options.clear===true,summary:options.summary===true,...options.full===true?{full:true}:{}}}function normalizeBulkMutationListOptions(options){const normalized=normalizeListOptions(options);if(options.ids!==void 0){normalized.ids=normalizeBulkIdsValue(options.ids)}return normalized}function closeManyOptionsFromFlat(options){return{status:readRuntimeString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),reason:readRuntimeString(options,"reason"),resolution:readRuntimeString(options,"resolution"),expectedResult:readRuntimeString(options,"expectedResult")??readRuntimeString(options,"expected_result")??readRuntimeString(options,"expected"),actualResult:readRuntimeString(options,"actualResult")??readRuntimeString(options,"actual_result")??readRuntimeString(options,"actual"),validateClose:readRuntimeString(options,"validateClose")??readRuntimeString(options,"validate_close"),author:readRuntimeString(options,"author"),message:readRuntimeString(options,"message"),force:options.force===true?true:void 0,dryRun:options.dryRun===true||options.dry_run===true?true:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===false||options.noCheckpoint===true||options.no_checkpoint===true?false:void 0}}const UPDATE_MANY_FLAT_CONTROL_KEYS=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function updateManyUpdateOptionsFromFlat(options){const update={};for(const[key,value]of Object.entries(options)){if(UPDATE_MANY_FLAT_CONTROL_KEYS.has(key)){continue}update[key]=value}return normalizeMcpUpdateOptions(update)}function normalizeMcpUpdateOptions(options){const normalizedInput=normalizeMcpOptionsArrays(options,"update-many");for(const contract of UPDATE_COMMANDER_STRING_OPTION_CONTRACTS){for(const key of contract.keys){const value=normalizedInput[key];if(typeof value==="number"&&Number.isFinite(value)){normalizedInput[key]=String(value)}}}return normalizeUpdateOptions(normalizedInput)}function updateManyOptionsFromFlat(options){if(isRuntimeRecord(options.list)||isRuntimeRecord(options.update)){const updateSource=isRuntimeRecord(options.update)?options.update:updateManyUpdateOptionsFromFlat(options);const normalizedUpdate=preserveTransportLiteralOptions(options,normalizeMcpUpdateOptions(updateSource));return{status:readRuntimeScalarString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),update:overlayMutationStdinTokenPolicy(updateSource,normalizedUpdate),dryRun:options.dryRun===true||options.dry_run===true?true:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===false||options.noCheckpoint===true||options.no_checkpoint===true?false:void 0}}return{status:readRuntimeScalarString(options,"filterStatus"),list:mutationListOptions(options),update:preserveTransportLiteralOptions(options,updateManyUpdateOptionsFromFlat(options)),dryRun:options.dryRun===true||options.dry_run===true?true:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===false||options.noCheckpoint===true||options.no_checkpoint===true?false:void 0}}export{actionGlobalOptions,closeManyOptionsFromFlat,extensionOptionsFromArgs,graphOptionsFromFlat,isRuntimeRecord,markMcpMutationTransportInput,mutationListOptions,mutationOptionsWithOverrides,normalizeActionName,normalizeCommandPath,normalizeMcpOptionsArrays,normalizeMcpUpdateOptions,optionsWithAuthor,parseRuntimeInteger,readRuntimeScalarString,readRuntimeScalarStringAllowBlank,readRuntimeString,readRuntimeStringArray,resolveRuntimeLimit,shouldInvalidateWorkspaceContractsCacheAfterAction,updateManyOptionsFromFlat,updateManyUpdateOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction};
2
2
  //# sourceMappingURL=runtime-input.js.map
@@ -192,3 +192,34 @@ command migration.
192
192
  Full discovery uses a uniform destination table. Its `reason` column contains
193
193
  the rationale for exceptions and an empty string where no exception applies,
194
194
  so adding a rationale does not expand every row into repeated field names.
195
+
196
+ ## Workspace customization and optional authoring
197
+
198
+ Tracked by [pm-npr3](../.agents/pm/tasks/pm-npr3.toon) and
199
+ [pm-uk9dwh](../.agents/pm/tasks/pm-uk9dwh.toon).
200
+
201
+ | Canonical command | Compatibility spelling | Responsibility |
202
+ | --- | --- | --- |
203
+ | `workspace init` | `init` | Bootstrap storage, settings, and optional guidance |
204
+ | `workspace config` | `config` | Read or change individual project/global settings |
205
+ | `workspace schema` | `schema` | Define types, statuses, fields, and validation contracts |
206
+ | `workspace profile` | `profile` | Apply reusable bundles of schema, settings, and templates |
207
+
208
+ These facets share workspace ownership. Schema defines what records mean;
209
+ configuration sets operating policy; profiles compose those primitives for a
210
+ domain; initialization creates their storage. The original SDK methods and MCP
211
+ actions keep their names and semantics. Root spellings remain permanent silent
212
+ aliases, including their arguments and flags.
213
+
214
+ `templates` remains owned by the optional templates package, within the workspace
215
+ authoring family. Its list/save/show operations provide reusable creation defaults;
216
+ they do not define schema or replace profiles. The destination census declares
217
+ these optional paths even when the package is inactive. `guide` remains owned by
218
+ `guide-shell` within the help family, so reading documentation is not a prerequisite
219
+ for core operation. `workspace position` and `workspace snapshot` retain their
220
+ existing state and recovery roles.
221
+
222
+ The bounded orientation sequence remains `pm context --for orient`, followed by
223
+ `pm contracts --command "workspace schema" --flags-only` (or the relevant command).
224
+ Use `pm workspace --help` to discover customization facets. No additional core noun
225
+ or mandatory package is introduced.
@@ -7,6 +7,14 @@ MCP server. Its cached runtime installs the exact version declared by the plugin
7
7
  audit, verified gaps, and phased remediation plan are documented in
8
8
  [Native ChatGPT and Codex Plugin Implementation Plan](CHATGPT_CODEX_PLUGIN_IMPLEMENTATION.md).
9
9
 
10
+ The portable package uses root `plugin.json` and `mcp.json`. The existing
11
+ `.codex-plugin/plugin.json` and `.mcp.json` remain compatibility manifests for
12
+ older hosts. The portable MCP entry launches the same exact-version cached
13
+ server as the compatibility entry. `pnpm version:check` and the release
14
+ provenance gate cover both versioned plugin manifests. The five portable skills
15
+ are generated from `templates/agent-skills/` into both plugin bundles, with
16
+ static drift checking before release.
17
+
10
18
  ## Install From This Repo
11
19
 
12
20
  ```bash
@@ -3,6 +3,24 @@
3
3
  Tracked by [pm-ig5cfe](../.agents/pm/issues/pm-ig5cfe.toon),
4
4
  [pm-495lkc](../.agents/pm/issues/pm-495lkc.toon), and
5
5
  [pm-miy5k6](../.agents/pm/issues/pm-miy5k6.toon).
6
+ Static inventory is tracked by [pm-lhhnx9](../.agents/pm/issues/pm-lhhnx9.toon).
7
+
8
+ ## Read-only configured inventory
9
+
10
+ Use `pm package inventory --project --json` (or `--global`) for a host GET route
11
+ or agent read. Pass a name to receive an explicit `absent` row. The public SDK
12
+ equivalent is `inspectStaticExtensionInventory({ pmRoot, scope, name })` from
13
+ `@unbrained/pm-cli/sdk`. Both read settings, managed metadata, and manifests
14
+ without importing package entrypoints, running hooks, checking for updates,
15
+ adopting installs, or writing workspace files. An absent managed-state file is
16
+ reported separately from an invalid one. `complete: false` and `errors` mean
17
+ the list must not be treated as authoritative; the CLI also exits nonzero.
18
+
19
+ `configured_enabled` is the effective saved enablement setting, while
20
+ `runtime_active` is always `null`. The static read does not prove that a package
21
+ will activate successfully. `pm package explore`, `manage`, `doctor`, and
22
+ `describe` probe runtime state and may execute installed package code. Run
23
+ those commands only when an activation probe is intended.
6
24
 
7
25
  ## Explicit Install-Source Identity
8
26
 
package/docs/RELEASING.md CHANGED
@@ -76,7 +76,52 @@ pnpm version:check
76
76
 
77
77
  `.github/workflows/auto-release.yml` runs once per day and can also be dispatched manually.
78
78
 
79
- Policy:
79
+ ### Independent morning dispatch
80
+
81
+ Tracked by [pm-9url9h](../.agents/pm/tasks/pm-9url9h.toon). An independent
82
+ operator-managed timer can invoke `scripts/release/dispatch-daily-release.mjs`
83
+ at **04:45 Europe/Vienna** (02:45 UTC in summer, 03:45 UTC in winter).
84
+ The aim is completion before 06:30–07:00 local time; host availability, GitHub
85
+ runner capacity and release gates can prevent that target. The host must be
86
+ awake, online and able to authenticate with `gh` unattended.
87
+
88
+ The existing **02:35 UTC GitHub cron remains enabled as a fallback**. Either
89
+ clock can arrive first. The dispatcher checks both release workflows for active
90
+ runs and skips an existing exact UTC-day tag. Tag existence is explicitly not
91
+ publication proof: incomplete publication still requires the normal immutable-tag
92
+ recovery procedure. Hosted concurrency and the one-release-per-UTC-day guard
93
+ remain the final protection if a native run races the external request.
94
+
95
+ The standalone dispatcher requires an absolute private state directory:
96
+
97
+ ```bash
98
+ node scripts/release/dispatch-daily-release.mjs --state-dir /absolute/private/state --check
99
+ ```
100
+
101
+ `--check` reads prerequisites without dispatching or writing state, including
102
+ outside the morning window. Without it, the dispatcher accepts only
103
+ 04:45–05:15 Vienna time and sends `workflow_dispatch` to `auto-release.yml` on
104
+ `main` with explicit `push=true`, `dry_run=false`, and `telemetry_mode=off`,
105
+ matching scheduled production policy. It never builds from the operator's
106
+ working branch, changes release secrets or bypasses hosted gates.
107
+
108
+ An exclusive daily intent file is written **before** sending the request. A
109
+ timeout can mean GitHub accepted the request, so an uncertain attempt is retained
110
+ and never automatically resent that UTC day. Inspect hosted run history before
111
+ any manual recovery. Pre-dispatch read failures leave no intent; a timer may
112
+ try again within the morning window. Late persistent-timer catch-up is a no-op.
113
+ Install a reviewed copy outside development checkouts so branch edits cannot
114
+ silently change an unattended service.
115
+
116
+ Keep dispatcher output in the service journal: `dispatch_accepted` proves only
117
+ API acceptance. Verify the hosted run, GitHub Release and exact npm version
118
+ separately. These runs remain `workflow_dispatch`; they do not improve or erase
119
+ the native `schedule` denominator in [Release Reliability](RELEASE_RELIABILITY.md).
120
+ Disable the independent timer to roll back; the original hosted schedule and
121
+ publication path continue unchanged. Host-specific unit files and authentication
122
+ configuration belong in private operator documentation.
123
+
124
+ ### Hosted release policy
80
125
 
81
126
  - release only when commits exist after the latest release tag
82
127
  - ignore tracker-governance-only commits for publish eligibility: `.agents/pm/**` and the mechanically generated `CHANGELOG.md` projection do not create a package release by themselves, while any product, test, documentation, workflow, or other changed path remains release-relevant
@@ -77,7 +77,7 @@
77
77
  {
78
78
  "task_id": "orientation-contracts-next",
79
79
  "command_count": 2,
80
- "estimated_tokens": 5180,
80
+ "estimated_tokens": 5203,
81
81
  "capabilities": [
82
82
  "actionable_work",
83
83
  "active_ownership",
@@ -120,11 +120,11 @@
120
120
  },
121
121
  {
122
122
  "id": "orientation-contracts-next",
123
- "max_estimated_tokens": 5180,
123
+ "max_estimated_tokens": 5203,
124
124
  "steps": [
125
125
  {
126
126
  "id": "contracts",
127
- "max_estimated_tokens": 4458,
127
+ "max_estimated_tokens": 4481,
128
128
  "accounting_mode": "self_reported"
129
129
  },
130
130
  {
@@ -261,5 +261,5 @@
261
261
  ]
262
262
  }
263
263
  ],
264
- "composite_max_estimated_tokens": 13011
264
+ "composite_max_estimated_tokens": 13034
265
265
  }
@@ -6,7 +6,7 @@ This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it ma
6
6
 
7
7
  | Capability family | Commands |
8
8
  | --- | --- |
9
- | workspace | `init`, `config`, `workspace merge`, `schema`, `profile`, `ops telemetry`, `ops health`, `ops gc`, `workspace` |
9
+ | workspace | `workspace init`, `workspace config`, `workspace merge`, `workspace schema`, `workspace profile`, `ops telemetry`, `ops health`, `ops gc`, `workspace` |
10
10
  | intake | `create`, `item`, `item copy`, `context focus`, `history restore` |
11
11
  | context | `list`, `aggregate`, `context`, `get`, `search`, `item duplicates`, `ops eval`, `context next`, `history activity`, `ops stats`, `help` |
12
12
  | lifecycle | `update`, `update many`, `close`, `close many`, `close delete`, `claim`, `release` |
@@ -5,7 +5,9 @@ This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it ma
5
5
  | Command | Minimum visibility tier | Capability family |
6
6
  | --- | --- | --- |
7
7
  | `init` | core | workspace |
8
+ | `workspace init` | core | workspace |
8
9
  | `config` | standard | workspace |
10
+ | `workspace config` | standard | workspace |
9
11
  | `extension` | full | extensions |
10
12
  | `package` | full | extensions |
11
13
  | `packages` | full | extensions |
@@ -54,7 +56,9 @@ This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it ma
54
56
  | `merge` | full | workspace |
55
57
  | `workspace merge` | full | workspace |
56
58
  | `schema` | standard | workspace |
59
+ | `workspace schema` | standard | workspace |
57
60
  | `profile` | standard | workspace |
61
+ | `workspace profile` | standard | workspace |
58
62
  | `activity` | full | context |
59
63
  | `history activity` | full | context |
60
64
  | `restore` | full | intake |
@@ -97,7 +101,7 @@ This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it ma
97
101
  | `assurance` | full | quality |
98
102
  | `gc` | full | workspace |
99
103
  | `ops gc` | full | workspace |
100
- | `workspace` | full | workspace |
104
+ | `workspace` | core | workspace |
101
105
  | `contracts` | standard | quality |
102
106
  | `claim` | core | lifecycle |
103
107
  | `release` | core | lifecycle |
@@ -95,6 +95,10 @@ This file is generated by `listPmFlagLexicon()`. Compatibility aliases do not co
95
95
  | `update many` | lifecycle | 146 | 146 |
96
96
  | `close many` | lifecycle | 72 | 72 |
97
97
  | `close delete` | lifecycle | 24 | 24 |
98
+ | `workspace init` | workspace | 30 | 30 |
99
+ | `workspace config` | workspace | 36 | 36 |
100
+ | `workspace schema` | workspace | 43 | 43 |
101
+ | `workspace profile` | workspace | 22 | 22 |
98
102
  | `item comments` | evidence | 31 | 31 |
99
103
  | `item notes` | evidence | 35 | 35 |
100
104
  | `item learnings` | evidence | 31 | 31 |