@unbrained/pm-cli 2026.10.5 → 2026.10.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +26 -1
  3. package/dist/cli/register-setup.js +1 -1
  4. package/dist/cli/runtime/projection-retry.js +1 -1
  5. package/dist/cli-bundle/bundle-manifest.json +158 -158
  6. package/dist/cli-bundle/chunks/{chunk-Z66DWDAU.js → chunk-25EW53VO.js} +39 -38
  7. package/dist/cli-bundle/chunks/{chunk-YVBRASXO.js → chunk-3CCVTV6Q.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-5MNOWZPN.js → chunk-3REXBTST.js} +2 -2
  9. package/dist/cli-bundle/chunks/chunk-4WB55TBC.js +80 -0
  10. package/dist/cli-bundle/chunks/{chunk-OOLYASYJ.js → chunk-6STTPXOC.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-AJ7H6XUF.js → chunk-ATB4ZZBQ.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-N4YGSG6F.js → chunk-D4G43LBV.js} +38 -38
  13. package/dist/cli-bundle/chunks/{chunk-HRJ6G6ZG.js → chunk-K6D6DMRT.js} +28 -28
  14. package/dist/cli-bundle/chunks/chunk-KIRHWPZB.js +2 -0
  15. package/dist/cli-bundle/chunks/chunk-O67BH435.js +6 -0
  16. package/dist/cli-bundle/chunks/{chunk-3CYOBJUK.js → chunk-RJHLD64E.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-WFZ4UEOB.js → chunk-TUKO5NF7.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-VZ63DEVJ.js → chunk-XJD47LUH.js} +2 -2
  19. package/dist/cli-bundle/chunks/{register-list-query-75QXHIFH.js → register-list-query-53WYLNZT.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-mutation-YS54SCHG.js → register-mutation-34XXUBVI.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-operations-6KHZQSYJ.js → register-operations-WANO6EIM.js} +2 -2
  22. package/dist/cli-bundle/chunks/register-setup-WT37UPBQ.js +2 -0
  23. package/dist/cli-bundle/focused-chunks/{chunk-GITOYRUW.js → chunk-6KFKQD2D.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-UDYRVBOZ.js → chunk-FOHRPFIT.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-DDRN42PB.js → chunk-GRQXL5G5.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-ABV67XCC.js → chunk-JZ4WGUVH.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-B5RSLVE6.js → chunk-NM3PM6O6.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/chunk-OT7HK7SG.js +2 -0
  29. package/dist/cli-bundle/focused-chunks/{chunk-2CVX3KR3.js → chunk-PCLU34KB.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-5C3IDDW7.js → chunk-QQIE4L42.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/chunk-RPUNVKXK.js +2 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-LE4JUCRR.js → chunk-RXSVJPZ7.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-SPN5QTZ3.js +30 -0
  34. package/dist/cli-bundle/focused-chunks/{chunk-CLDPTMQY.js → chunk-SUZJNPGB.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-YMU42COG.js → chunk-W4BG5HHS.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-C224METM.js → chunk-Y5HXFDTZ.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-ECBOPEJE.js → chunk-ZK5SOOPC.js} +61 -61
  38. package/dist/cli-bundle/focused-chunks/chunk-ZQK2XUSS.js +12 -0
  39. package/dist/cli-bundle/main.js +21 -21
  40. package/dist/cli-bundle/sdk-authoring.js +1 -1
  41. package/dist/cli-bundle/sdk-contracts.js +1 -1
  42. package/dist/cli-bundle/sdk-core.js +31 -30
  43. package/dist/cli-bundle/sdk-governance.js +1 -1
  44. package/dist/cli-bundle/sdk-graph.js +1 -1
  45. package/dist/cli-bundle/sdk-merge.js +42 -42
  46. package/dist/cli-bundle/sdk-query.js +1 -1
  47. package/dist/cli-bundle/sdk-runtime.js +1 -1
  48. package/dist/cli-bundle/sdk-testing.js +1 -1
  49. package/dist/cli-bundle/sdk.js +2 -2
  50. package/dist/core/extensions/extension-types.d.ts +2 -0
  51. package/dist/core/extensions/extension-types.js +1 -1
  52. package/dist/sdk/cli-bootstrap.d.ts +5 -1
  53. package/dist/sdk/cli-bootstrap.js +1 -1
  54. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  55. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  56. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  57. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  58. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  59. package/dist/sdk/extension/managed-state.d.ts +2 -0
  60. package/dist/sdk/extension/managed-state.js +1 -1
  61. package/dist/sdk/extension/managed-update-status.d.ts +3 -0
  62. package/dist/sdk/extension/managed-update-status.js +2 -0
  63. package/dist/sdk/extension/source-resolution.d.ts +2 -6
  64. package/dist/sdk/extension/source-resolution.js +1 -1
  65. package/dist/sdk/extension/update-check.d.ts +10 -0
  66. package/dist/sdk/extension/update-check.js +1 -1
  67. package/dist/sdk/extension-command-context.js +2 -1
  68. package/dist/sdk/extension.d.ts +4 -0
  69. package/dist/sdk/extension.js +1 -1
  70. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  71. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  72. package/dist/sdk/public-surface.json +1 -1
  73. package/dist/sdk/query/get.js +1 -1
  74. package/dist/sdk/read-output-contracts.js +1 -1
  75. package/dist/sdk/runtime-input.js +1 -1
  76. package/dist/sdk/test/execution.d.ts +2 -1
  77. package/dist/sdk/test/execution.js +3 -3
  78. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +36 -0
  79. package/docs/GET_READ_EVIDENCE.md +17 -1
  80. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
  81. package/docs/PR_REVIEW_LOOP.md +21 -4
  82. package/docs/README.md +1 -0
  83. package/docs/RELEASING.md +18 -0
  84. package/docs/SDK_CONFIGURATION_SAFETY.md +123 -0
  85. package/docs/generated/FLAG_LEXICON_BUDGETS.md +3 -3
  86. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  87. package/marketplace.json +2 -2
  88. package/package.json +3 -3
  89. package/packages/pm-beads/package.json +1 -1
  90. package/packages/pm-calendar/package.json +1 -1
  91. package/packages/pm-command-kit/package.json +1 -1
  92. package/packages/pm-digital-twin/package.json +1 -1
  93. package/packages/pm-governance-audit/package.json +1 -1
  94. package/packages/pm-guide-shell/package.json +1 -1
  95. package/packages/pm-kanban/package.json +1 -1
  96. package/packages/pm-lifecycle-hooks/package.json +1 -1
  97. package/packages/pm-linked-test-adapters/package.json +1 -1
  98. package/packages/pm-search-advanced/package.json +1 -1
  99. package/packages/pm-templates/package.json +1 -1
  100. package/packages/pm-todos/package.json +1 -1
  101. package/packages/pm-vcs/package.json +1 -1
  102. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  103. package/plugins/pm-claude/package.json +2 -2
  104. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  105. package/plugins/pm-codex/package.json +2 -2
  106. package/plugins/pm-codex/plugin.json +1 -1
  107. package/dist/cli-bundle/chunks/chunk-D332RXZ7.js +0 -80
  108. package/dist/cli-bundle/chunks/chunk-KRVI56QE.js +0 -6
  109. package/dist/cli-bundle/chunks/chunk-TGMONGWX.js +0 -2
  110. package/dist/cli-bundle/chunks/register-setup-RTATEN2M.js +0 -2
  111. package/dist/cli-bundle/focused-chunks/chunk-DOVTUKJQ.js +0 -2
  112. package/dist/cli-bundle/focused-chunks/chunk-GUIF3WVC.js +0 -30
  113. package/dist/cli-bundle/focused-chunks/chunk-RHIH6XIW.js +0 -12
  114. package/dist/cli-bundle/focused-chunks/chunk-XV5RV4ZT.js +0 -2
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4280f121-31b0-55e3-9e3b-964ba97e43b4")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,toItemRecord,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,TYPE_TO_FOLDER,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,getHistoryPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{renderPmCommand}from"../command-line.js";import{recordContextUsageTouches}from"../context-usage.js";import{collectBlockedByIds,resolveItemBlockers}from"../actionability.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"../../core/item/dependency-reference.js";import{buildItemChildrenRollup}from"../item-children.js";import{buildItemSchedule}from"../item-schedule.js";import{getItemAt}from"../history-read.js";import{parseIntegerLimit}from"./parsers.js";import{runList}from"./list.js";import{registerOutputMaterialFieldGroups}from"../output-projection.js";import{GET_DEPTH_VALUES,listGetProjectionFields}from"./projection-contracts.js";import{GET_DEPTH_VALUES as GET_DEPTH_VALUES2,listGetProjectionFields as listGetProjectionFields2}from"./projection-contracts.js";const AUTOMATIC_CHILD_ROLLUP_TYPES=new Set(["epic","feature","milestone","plan"]),BUILTIN_ITEM_TYPES=new Set(Object.keys(TYPE_TO_FOLDER).map(type=>type.toLowerCase()));function itemCollectionCounts(item){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(key=>[key,item[key]?.length??0]))}function hasOmittedDependencyProvenance(item,projection){return!projection.fieldProjection&&projection.full||fieldsInclude(projection.fields,"dependencies")?!1:item.dependencies?.some(({id:_id,kind:_kind,...provenance})=>Object.values(provenance).some(value=>value!==void 0))??!1}function itemMaterialFieldGroups(item,body,children,currentSnapshot,projection){const collectionCounts=itemCollectionCounts(item);return[...body.length>0?["body"]:[],...Object.entries(collectionCounts).flatMap(([name,count])=>count>0?[name]:[]),...collectionCounts.files+collectionCounts.tests+collectionCounts.docs>0?["linked"]:[],...children===void 0?["children"]:children.count>0?["children"]:[],...typeof item.assignee=="string"&&item.assignee.trim().length>0?["claim_state"]:[],...buildItemSchedule(item)?["schedule"]:[],...currentSnapshot&&collectBlockedByIds(item).length>0?["blockers"]:[],...hasOmittedDependencyProvenance(item,projection)?["dependency_provenance"]:[]]}function shouldAutoIncludeGetChildren(itemType){const normalizedType=itemType.trim().toLowerCase();return normalizedType.length>0&&(AUTOMATIC_CHILD_ROLLUP_TYPES.has(normalizedType)||!BUILTIN_ITEM_TYPES.has(normalizedType))}function toClaimHistoryContext(entry){return{ts:entry.ts,author:entry.author,message:entry.message??null}}function resolveClaimStateContext(assigneeValue,history){const assignee=assigneeValue?.trim(),normalizedAssignee=assignee&&assignee.length>0?assignee:null,lastClaim=[...history].reverse().find(entry=>entry.op==="claim"),lastRelease=[...history].reverse().find(entry=>entry.op==="release");return{claimed:normalizedAssignee!==null,assignee:normalizedAssignee,last_claim:lastClaim?toClaimHistoryContext(lastClaim):null,last_release:lastRelease?toClaimHistoryContext(lastRelease):null}}function parseGetDepth(raw){if(raw===void 0||raw.trim().length===0)return"standard";const normalized=raw.trim().toLowerCase();if(normalized==="full")return"deep";if(GET_DEPTH_VALUES.includes(normalized))return normalized;throw new PmCliError("Get --depth must be one of brief|standard|deep|full",EXIT_CODE.USAGE,{field:"depth",value:raw,recovery:{allowed_values:[...GET_DEPTH_VALUES,"full"]}})}function projectItemForDepth(item,depth,full){const collectionCounts=itemCollectionCounts(item),projectedItem={...item};if(!full&&item.dependencies!==void 0&&(projectedItem.dependencies=item.dependencies.map(({id,kind})=>({id,kind}))),depth==="deep")return{...projectedItem,comments:item.comments??[],notes:item.notes??[],learnings:item.learnings??[],files:item.files??[],tests:item.tests??[],docs:item.docs??[],reminders:item.reminders??[],events:item.events??[],notes_count:collectionCounts.notes,tests_count:collectionCounts.tests,collection_counts:collectionCounts};const{comments:_comments,notes:_notes,learnings:_learnings,files:_files,tests:_tests,docs:_docs,reminders:_reminders,events:_events,...projected}=projectedItem;return{...projected,notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:collectionCounts}}function parseGetFields(raw){if(raw===void 0)return null;const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0)throw new PmCliError("Get --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return fields}function normalizeGetField(field){return field.startsWith("item.")?field.slice(5):field}function validateGetFields(fields,runtimeMetadataKeys,id){if(fields===null)return;const allowedValues=listGetProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues),unknown=fields.filter(field=>{const normalized=normalizeGetField(field);return!allowed.has(field)&&!allowed.has(normalized)});if(unknown.length>0){const suggestedRetryArguments=["get",id,"--fields",fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown get --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const EMPTY_PROJECTED_COLLECTION_FIELDS=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function projectedMetadataValue(source,counts,field){return Object.hasOwn(counts,field)?counts[field]:source[field]!==void 0?source[field]:EMPTY_PROJECTED_COLLECTION_FIELDS.has(field)?[]:void 0}function projectItemForFields(item,fields){const source=toItemRecord(item),omittedCounts={notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:itemCollectionCounts(item)},projected={id:item.id};for(const field of fields){const normalized=normalizeGetField(field);normalized==="body"||normalized==="linked"||normalized.startsWith("linked.")||normalized==="claim_state"||normalized.startsWith("claim_state.")||normalized==="children"||normalized.startsWith("children.")||normalized==="schedule"||normalized.startsWith("schedule.")||normalized==="blockers"||(projected[normalized]=projectedMetadataValue(source,omittedCounts,normalized))}return projected}function fieldsInclude(fields,name){return fields?.some(field=>field===name||field===`item.${name}`)??!1}function fieldsIncludeRoot(fields,name){return fields.some(field=>{const normalized=normalizeGetField(field);return normalized===name||normalized.startsWith(`${name}.`)})}function resolveGetProjection(options,id){if(options.full&&(options.fields!==void 0||options.depth!==void 0))throw new PmCliError("Get projection options are mutually exclusive; remove the extra projection flag and retry.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:renderPmCommand(["get",id,"--full"]),suggested_retry_args:["get",id,"--full"]}});if(options.tree!==!0&&options.treeDepth!==void 0)throw new PmCliError("Get --tree-depth requires --tree",EXIT_CODE.USAGE);if(options.at!==void 0&&options.tree===!0)throw new PmCliError("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",EXIT_CODE.USAGE);return{depth:options.full?"deep":parseGetDepth(options.depth),full:options.full===!0||options.depth?.trim().toLowerCase()==="full",treeDepth:options.tree===!0?parseIntegerLimit(options.treeDepth,"--tree-depth"):void 0,fields:parseGetFields(options.fields),fieldProjection:options.fields!==void 0}}async function loadGetItemContext(id,global2,at){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());if(at!==void 0){const historical=await getItemAt(id,at,{pmRoot:global2.path});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:historical.document.metadata.id,metadata:historical.document.metadata,body:historical.document.body,historical}}const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeRegistry.type_to_folder);const loaded=await readLocatedItem(located,{schema:settings.schema});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:located.id,metadata:loaded.document.metadata,body:loaded.document.body}}function validateGetProjectionFields(fields,settings,historical,id){const runtimeMetadataKeys=resolveRuntimeFieldRegistry(settings.schema).definitions.map(field=>field.metadata_key);if(validateGetFields(fields,runtimeMetadataKeys,id),historical&&fieldsIncludeRoot(fields??[],"children"))throw new PmCliError("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",EXIT_CODE.USAGE);if(historical&&fieldsIncludeRoot(fields??[],"blockers"))throw new PmCliError("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",EXIT_CODE.USAGE)}function shouldIncludeGetField(params){const{fieldProjection,depth,fields,field}=params;return fieldProjection?field==="body"||field==="linked"?fieldsInclude(fields,field):fieldsIncludeRoot(fields,field):depth!=="brief"}async function resolveGetClaimState(context,includeClaimState){if(!includeClaimState)return;const historyPath=getHistoryPath(context.pmRoot,context.locatedId),history=await readHistoryEntries(historyPath,context.locatedId);return resolveClaimStateContext(context.metadata.assignee,context.historical?history.slice(0,context.historical.target.historyIndex+1):history)}function attachGetLinked(result,context,fields,includeLinked){const includeLinkedFiles=includeLinked||fieldsInclude(fields,"linked.files"),includeLinkedTests=includeLinked||fieldsInclude(fields,"linked.tests"),includeLinkedDocs=includeLinked||fieldsInclude(fields,"linked.docs");!includeLinked&&!includeLinkedFiles&&!includeLinkedTests&&!includeLinkedDocs||(result.linked={files:includeLinkedFiles?context.metadata.files??[]:[],tests:includeLinkedTests?context.metadata.tests??[]:[],docs:includeLinkedDocs?context.metadata.docs??[]:[]})}async function buildGetChildrenRollup(context,includeChildren){if(!includeChildren)return;const statusRegistry=resolveRuntimeStatusRegistry(context.settings.schema),corpus=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,context.typeToFolder,void 0,context.settings.schema);return buildItemChildrenRollup(context.locatedId,corpus,statusRegistry)}function canonicalizeDeclaredBlockers(blockers,targets){const canonical=new Map;for(const blocker of blockers){const id=blocker.external?blocker.id:targets.get(blocker.id.toLowerCase())?.id??blocker.id;canonical.set(blocker.external?`external:${id}`:`local:${id.toLowerCase()}`,{...blocker,id})}return[...canonical.values()]}async function attachGetBlockers(result,context,projection){if(context.historical!==void 0||!(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"blockers"):projection.depth!=="brief"))return;const ids=collectBlockedByIds(context.metadata);if(ids.length===0)return;const targets=new Map;for(const id of ids){if(isExternalDependencyReference(id)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(id)||context.metadata.dependencies?.some(dependency=>dependency.id.trim()===id&&dependency.kind==="blocked_by"&&isExternalDependencySourceKind(dependency.source_kind)))continue;const located=await locateItem(context.pmRoot,id,context.settings.id_prefix,context.settings.item_format,context.typeToFolder);if(located!==null){const loaded=await readLocatedItem(located,{schema:context.settings.schema});if(loaded.document.metadata.id!==located.id)throw new PmCliError(`Blocker identity differs from its canonical file: ${located.id}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});targets.set(id.toLowerCase(),loaded.document.metadata)}}const resolved=canonicalizeDeclaredBlockers(resolveItemBlockers({blocked_by:context.metadata.blocked_by,dependencies:context.metadata.dependencies,updated_at:context.metadata.updated_at},targets,resolveRuntimeStatusRegistry(context.settings.schema)),targets);result.blockers={scope:"declared",open:resolved.filter(blocker=>!blocker.resolved).map(({resolved:_resolved,...blocker})=>blocker),closed_count:resolved.filter(blocker=>blocker.resolved).length},!projection.fieldProjection&&!projection.full&&delete result.item.blocked_by}function attachGetSchedule(result,context,fields,includeSchedule){if(!includeSchedule)return;const schedule=buildItemSchedule(context.metadata);if(schedule){if(fields===null||fieldsInclude(fields,"schedule")){result.schedule=schedule;return}result.schedule=Object.fromEntries(Object.entries(schedule).filter(([key])=>fields.some(field=>normalizeGetField(field)===`schedule.${key}`)))}}async function buildGetTree(context,options,treeDepth,global2){if(options.tree!==!0)return;const subtree=await runList(void 0,{parent:context.locatedId,tree:!0,treeDepth:treeDepth===void 0?void 0:String(treeDepth),full:!0},global2);return{root_id:context.locatedId,root_title:context.metadata.title,depth_limit:treeDepth??null,count:subtree.count,items:subtree.items.map(entry=>toItemRecord(entry))}}async function runGet(id,global2,options={}){const projection=resolveGetProjection(options,id),context=await loadGetItemContext(id,global2,options.at);validateGetProjectionFields(projection.fields,context.settings,context.historical!==void 0,context.locatedId);const includeBody=shouldIncludeGetField({...projection,field:"body"}),includeLinked=shouldIncludeGetField({...projection,field:"linked"}),includeClaimState=shouldIncludeGetField({...projection,field:"claim_state"}),includeChildren=context.historical===void 0&&(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"children"):projection.depth==="deep"&&(projection.full||shouldAutoIncludeGetChildren(context.metadata.type))),includeSchedule=projection.fieldProjection?fieldsIncludeRoot(projection.fields,"schedule"):projection.depth!=="brief",claimState=await resolveGetClaimState(context,includeClaimState),result={item:projection.fieldProjection?projectItemForFields(context.metadata,projection.fields):projectItemForDepth(context.metadata,projection.depth,projection.full)};includeBody&&(result.item.body=context.body),attachGetLinked(result,context,projection.fields,includeLinked),claimState&&(result.claim_state=claimState),attachGetSchedule(result,context,projection.fields,includeSchedule),await attachGetBlockers(result,context,projection);const children=await buildGetChildrenRollup(context,includeChildren);children!==void 0&&(result.children=children);const tree=await buildGetTree(context,options,projection.treeDepth,global2);if(tree!==void 0&&(result.tree=tree),context.historical&&(result.reconstructed=!0,result.as_of_version=context.historical.as_of_version,result.as_of_timestamp=context.historical.as_of_timestamp),context.historical===void 0)try{await recordContextUsageTouches({pmRoot:context.pmRoot,author:resolveAuthor(void 0,context.settings.author_default),itemIds:[context.locatedId],intent:"get"})}catch{}return registerOutputMaterialFieldGroups(result,itemMaterialFieldGroups(context.metadata,context.body,children,context.historical===void 0,projection)),result}const _testOnlyGetCommand={shouldAutoIncludeGetChildren};export{GET_DEPTH_VALUES2 as GET_DEPTH_VALUES,_testOnlyGetCommand,listGetProjectionFields2 as listGetProjectionFields,runGet};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e2c03bb3-e603-579b-bb44-0b3757a00ea8")}catch{}})();import{readdir}from"node:fs/promises";import path from"node:path";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,toItemRecord,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,TYPE_TO_FOLDER,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,getHistoryPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{renderPmCommand}from"../command-line.js";import{recordContextUsageTouches}from"../context-usage.js";import{createPmCliExpectedError}from"../errors.js";import{collectBlockedByIds,resolveItemBlockers}from"../actionability.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"../../core/item/dependency-reference.js";import{buildItemChildrenRollup}from"../item-children.js";import{buildItemSchedule}from"../item-schedule.js";import{getItemAt}from"../history-read.js";import{parseIntegerLimit}from"./parsers.js";import{runList}from"./list.js";import{registerOutputMaterialFieldGroups}from"../output-projection.js";import{GET_DEPTH_VALUES,listGetProjectionFields}from"./projection-contracts.js";import{GET_DEPTH_VALUES as GET_DEPTH_VALUES2,listGetProjectionFields as listGetProjectionFields2}from"./projection-contracts.js";const AUTOMATIC_CHILD_ROLLUP_TYPES=new Set(["epic","feature","milestone","plan"]),BUILTIN_ITEM_TYPES=new Set(Object.keys(TYPE_TO_FOLDER).map(type=>type.toLowerCase()));function itemCollectionCounts(item){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(key=>[key,item[key]?.length??0]))}function itemMaterialFieldGroups(item,body,children,currentSnapshot,projection){const collectionCounts=itemCollectionCounts(item);return[...body.length>0?["body"]:[],...Object.entries(collectionCounts).flatMap(([name,count])=>count>0?[name]:[]),...collectionCounts.files+collectionCounts.tests+collectionCounts.docs>0?["linked"]:[],...children===void 0?["children"]:children.count>0?["children"]:[],...typeof item.assignee=="string"&&item.assignee.trim().length>0?["claim_state"]:[],...buildItemSchedule(item)?["schedule"]:[],...currentSnapshot&&collectBlockedByIds(item).length>0?["blockers"]:[],...!projection.full&&item.dependencies?.some(({id:_id,kind:_kind,...provenance})=>Object.values(provenance).some(value=>value!==void 0))?["dependency_provenance"]:[]]}function shouldAutoIncludeGetChildren(itemType){const normalizedType=itemType.trim().toLowerCase();return normalizedType.length>0&&(AUTOMATIC_CHILD_ROLLUP_TYPES.has(normalizedType)||!BUILTIN_ITEM_TYPES.has(normalizedType))}function toClaimHistoryContext(entry){return{ts:entry.ts,author:entry.author,message:entry.message??null}}function resolveClaimStateContext(assigneeValue,history){const assignee=assigneeValue?.trim(),normalizedAssignee=assignee&&assignee.length>0?assignee:null,lastClaim=[...history].reverse().find(entry=>entry.op==="claim"),lastRelease=[...history].reverse().find(entry=>entry.op==="release");return{claimed:normalizedAssignee!==null,assignee:normalizedAssignee,last_claim:lastClaim?toClaimHistoryContext(lastClaim):null,last_release:lastRelease?toClaimHistoryContext(lastRelease):null}}function parseGetDepth(raw){if(raw===void 0||raw.trim().length===0)return"standard";const normalized=raw.trim().toLowerCase();if(normalized==="full")return"deep";if(GET_DEPTH_VALUES.includes(normalized))return normalized;throw new PmCliError("Get --depth must be one of brief|standard|deep|full",EXIT_CODE.USAGE,{field:"depth",value:raw,recovery:{allowed_values:[...GET_DEPTH_VALUES,"full"]}})}function projectItemForDepth(item,depth,full){const collectionCounts=itemCollectionCounts(item),projectedItem={...item};if(!full&&item.dependencies!==void 0&&(projectedItem.dependencies=item.dependencies.map(({id,kind})=>({id,kind}))),depth==="deep")return{...projectedItem,comments:item.comments??[],notes:item.notes??[],learnings:item.learnings??[],files:item.files??[],tests:item.tests??[],docs:item.docs??[],reminders:item.reminders??[],events:item.events??[],notes_count:collectionCounts.notes,tests_count:collectionCounts.tests,collection_counts:collectionCounts};const{comments:_comments,notes:_notes,learnings:_learnings,files:_files,tests:_tests,docs:_docs,reminders:_reminders,events:_events,...projected}=projectedItem;return{...projected,notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:collectionCounts}}function parseGetFields(raw){if(raw===void 0)return null;const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0)throw new PmCliError("Get --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return fields}function normalizeGetField(field){return field.startsWith("item.")?field.slice(5):field}function validateGetFields(fields,runtimeMetadataKeys,id){if(fields===null)return;const allowedValues=listGetProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues),unknown=fields.filter(field=>{const normalized=normalizeGetField(field);return!allowed.has(field)&&!allowed.has(normalized)});if(unknown.length>0){const suggestedRetryArguments=["get",id,"--fields",fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown get --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const EMPTY_PROJECTED_COLLECTION_FIELDS=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function projectedMetadataValue(source,counts,field){return Object.hasOwn(counts,field)?counts[field]:source[field]!==void 0?source[field]:EMPTY_PROJECTED_COLLECTION_FIELDS.has(field)?[]:void 0}function projectItemForFields(item,fields){const source=toItemRecord(item),omittedCounts={notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:itemCollectionCounts(item)},projected={id:item.id};for(const field of fields){const normalized=normalizeGetField(field);normalized==="body"||normalized==="linked"||normalized.startsWith("linked.")||normalized==="claim_state"||normalized.startsWith("claim_state.")||normalized==="children"||normalized.startsWith("children.")||normalized==="schedule"||normalized.startsWith("schedule.")||normalized==="blockers"||(projected[normalized]=projectedMetadataValue(source,omittedCounts,normalized))}return projected}function fieldsInclude(fields,name){return fields?.some(field=>field===name||field===`item.${name}`)??!1}function fieldsIncludeRoot(fields,name){return fields.some(field=>{const normalized=normalizeGetField(field);return normalized===name||normalized.startsWith(`${name}.`)})}function resolveGetProjection(options,id){if(options.full&&(options.fields!==void 0||options.depth!==void 0))throw new PmCliError("Get projection options are mutually exclusive; remove the extra projection flag and retry.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:renderPmCommand(["get",id,"--full"]),suggested_retry_args:["get",id,"--full"]}});if(options.tree!==!0&&options.treeDepth!==void 0)throw new PmCliError("Get --tree-depth requires --tree",EXIT_CODE.USAGE);if(options.at!==void 0&&options.tree===!0)throw new PmCliError("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",EXIT_CODE.USAGE);return{depth:options.full?"deep":parseGetDepth(options.depth),full:options.full===!0||options.depth?.trim().toLowerCase()==="full",treeDepth:options.tree===!0?parseIntegerLimit(options.treeDepth,"--tree-depth"):void 0,fields:parseGetFields(options.fields),fieldProjection:options.fields!==void 0}}async function loadGetItemContext(id,global2,at){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());if(at!==void 0){const historical=await getItemAt(id,at,{pmRoot:global2.path});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:historical.document.metadata.id,metadata:historical.document.metadata,body:historical.document.body,historical}}const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeRegistry.type_to_folder);const loaded=await readLocatedItem(located,{schema:settings.schema});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:located.id,metadata:loaded.document.metadata,body:loaded.document.body}}function validateGetProjectionFields(fields,settings,historical,id){const runtimeMetadataKeys=resolveRuntimeFieldRegistry(settings.schema).definitions.map(field=>field.metadata_key);if(validateGetFields(fields,runtimeMetadataKeys,id),historical&&fieldsIncludeRoot(fields??[],"children"))throw new PmCliError("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",EXIT_CODE.USAGE);if(historical&&fieldsIncludeRoot(fields??[],"blockers"))throw new PmCliError("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",EXIT_CODE.USAGE)}function shouldIncludeGetField(params){const{fieldProjection,depth,fields,field}=params;return fieldProjection?field==="body"||field==="linked"?fieldsInclude(fields,field):fieldsIncludeRoot(fields,field):depth!=="brief"}async function resolveGetClaimState(context,includeClaimState){if(!includeClaimState)return;const historyPath=getHistoryPath(context.pmRoot,context.locatedId),history=await readHistoryEntries(historyPath,context.locatedId);return resolveClaimStateContext(context.metadata.assignee,context.historical?history.slice(0,context.historical.target.historyIndex+1):history)}function attachGetLinked(result,context,fields,includeLinked){const includeLinkedFiles=includeLinked||fieldsInclude(fields,"linked.files"),includeLinkedTests=includeLinked||fieldsInclude(fields,"linked.tests"),includeLinkedDocs=includeLinked||fieldsInclude(fields,"linked.docs");!includeLinked&&!includeLinkedFiles&&!includeLinkedTests&&!includeLinkedDocs||(result.linked={files:includeLinkedFiles?context.metadata.files??[]:[],tests:includeLinkedTests?context.metadata.tests??[]:[],docs:includeLinkedDocs?context.metadata.docs??[]:[]})}async function buildGetChildrenRollup(context,includeChildren){if(!includeChildren)return;const statusRegistry=resolveRuntimeStatusRegistry(context.settings.schema),corpus=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,context.typeToFolder,void 0,context.settings.schema);return buildItemChildrenRollup(context.locatedId,corpus,statusRegistry)}function canonicalizeDeclaredBlockers(blockers,targets){const canonical=new Map;for(const blocker of blockers){const id=blocker.external?blocker.id:targets.get(blocker.id.toLowerCase())?.id??blocker.id;canonical.set(blocker.external?`external:${id}`:`local:${id.toLowerCase()}`,{...blocker,id})}return[...canonical.values()]}async function resolvePhysicalBlockerId(itemPath,probedId){const filename=path.basename(itemPath),physicalId=(await readdir(path.dirname(itemPath)).catch(error=>{throw createPmCliExpectedError("Cannot verify the blocker's physical file identity",{exitCode:EXIT_CODE.GENERIC_FAILURE,context:{code:"blocker_identity_read_failed",required:"Restore access to the blocker item directory, then retry the item read."},cause:error})})).filter(name=>name.toLowerCase()===filename.toLowerCase()).sort((left,right)=>+(right===filename)-+(left===filename)||left.localeCompare(right)).map(name=>path.parse(name).name)[0];if(physicalId===void 0)throw new PmCliError(`Blocker canonical file disappeared during identity verification: ${probedId}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker file and validate storage integrity before retrying the item read."});return physicalId}async function attachGetBlockers(result,context,projection){if(context.historical!==void 0||!(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"blockers"):projection.depth!=="brief"))return;const ids=collectBlockedByIds(context.metadata);if(ids.length===0)return;const declaredIds=new Map([context.metadata.blocked_by,...(context.metadata.dependencies??[]).filter(dependency=>dependency.kind==="blocked_by").map(dependency=>dependency.id)].filter(id=>typeof id=="string").map(id=>[id.trim().toLowerCase(),id.trim()])),targets=new Map;for(const id of ids){if(isExternalDependencyReference(id)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(id)||context.metadata.dependencies?.some(dependency=>dependency.id.trim()===id&&dependency.kind==="blocked_by"&&isExternalDependencySourceKind(dependency.source_kind)))continue;const located=await locateItem(context.pmRoot,declaredIds.get(id),context.settings.id_prefix,context.settings.item_format,context.typeToFolder);if(located===null)continue;const loaded=await readLocatedItem(located,{schema:context.settings.schema});if(located.id=await resolvePhysicalBlockerId(located.itemPath,located.id),loaded.document.metadata.id!==located.id)throw new PmCliError(`Blocker identity differs from its canonical file: ${located.id}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});targets.set(id.toLowerCase(),loaded.document.metadata)}const resolved=canonicalizeDeclaredBlockers(resolveItemBlockers({blocked_by:context.metadata.blocked_by,dependencies:context.metadata.dependencies,updated_at:context.metadata.updated_at},targets,resolveRuntimeStatusRegistry(context.settings.schema)),targets);result.blockers={scope:"declared",open:resolved.filter(blocker=>!blocker.resolved).map(({resolved:_resolved,...blocker})=>blocker),closed_count:resolved.filter(blocker=>blocker.resolved).length},!projection.fieldProjection&&!projection.full&&delete result.item.blocked_by}function attachGetSchedule(result,context,fields,includeSchedule){if(!includeSchedule)return;const schedule=buildItemSchedule(context.metadata);if(schedule){if(fields===null||fieldsInclude(fields,"schedule")){result.schedule=schedule;return}result.schedule=Object.fromEntries(Object.entries(schedule).filter(([key])=>fields.some(field=>normalizeGetField(field)===`schedule.${key}`)))}}async function buildGetTree(context,options,treeDepth,global2){if(options.tree!==!0)return;const subtree=await runList(void 0,{parent:context.locatedId,tree:!0,treeDepth:treeDepth===void 0?void 0:String(treeDepth),full:!0},global2);return{root_id:context.locatedId,root_title:context.metadata.title,depth_limit:treeDepth??null,count:subtree.count,items:subtree.items.map(entry=>toItemRecord(entry))}}async function runGet(id,global2,options={}){const projection=resolveGetProjection(options,id),context=await loadGetItemContext(id,global2,options.at);validateGetProjectionFields(projection.fields,context.settings,context.historical!==void 0,context.locatedId);const includeBody=shouldIncludeGetField({...projection,field:"body"}),includeLinked=shouldIncludeGetField({...projection,field:"linked"}),includeClaimState=shouldIncludeGetField({...projection,field:"claim_state"}),includeChildren=context.historical===void 0&&(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"children"):projection.depth==="deep"&&(projection.full||shouldAutoIncludeGetChildren(context.metadata.type))),includeSchedule=projection.fieldProjection?fieldsIncludeRoot(projection.fields,"schedule"):projection.depth!=="brief",claimState=await resolveGetClaimState(context,includeClaimState),result={item:projection.fieldProjection?projectItemForFields(context.metadata,projection.fields):projectItemForDepth(context.metadata,projection.depth,projection.full)};includeBody&&(result.item.body=context.body),attachGetLinked(result,context,projection.fields,includeLinked),claimState&&(result.claim_state=claimState),attachGetSchedule(result,context,projection.fields,includeSchedule),await attachGetBlockers(result,context,projection);const children=await buildGetChildrenRollup(context,includeChildren);children!==void 0&&(result.children=children);const tree=await buildGetTree(context,options,projection.treeDepth,global2);if(tree!==void 0&&(result.tree=tree),context.historical&&(result.reconstructed=!0,result.as_of_version=context.historical.as_of_version,result.as_of_timestamp=context.historical.as_of_timestamp),context.historical===void 0)try{await recordContextUsageTouches({pmRoot:context.pmRoot,author:resolveAuthor(void 0,context.settings.author_default),itemIds:[context.locatedId],intent:"get"})}catch{}return registerOutputMaterialFieldGroups(result,projection.fieldProjection?[]:itemMaterialFieldGroups(context.metadata,context.body,children,context.historical===void 0,projection)),result}const _testOnlyGetCommand={shouldAutoIncludeGetChildren};export{GET_DEPTH_VALUES2 as GET_DEPTH_VALUES,_testOnlyGetCommand,listGetProjectionFields2 as listGetProjectionFields,runGet};
2
2
  //# sourceMappingURL=get.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f339a0cc-ca55-5953-9ab7-fb766e9b7e36")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"./read-output/options.js";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,refreshReadOutputDeliveredCounts}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"],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"],READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"],CANONICAL_OPTIONS=READ_OUTPUT_DIMENSION_FLAGS,PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension])),PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=READ_OUTPUT_COMPOSITION_FLAGS,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:{}},VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]),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],dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:!0,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)),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()),root=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===!0||options.target==="catalog"||options.action==="catalog")?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0],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"],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),!0),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]!==!1))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);return surface?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)])):new Map}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[],modeOptions=readOutputIncludeModeOptions(command),selectors=[],modes=[],optionsWithProvenance=commandOptions,existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE],canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]),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("_","-")}`;isRequestedOption(readOption(commandOptions,legacyFlag))&&explicitLegacyAliases.add(legacyFlag),commandOptions[option]=!0,modes.push(token),canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[],forwardedGetFields=forwardedGetFieldSelectors.length>0;return forwardedGetFields&&(commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(","),canonicalModes.add("fields")),(modes.length>0||forwardedGetFields)&&(optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{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,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===!1)return!0}function isRequestedOption(value){return value!==void 0&&value!==!1&&value!==null}function stringList(value){const normalized=(Array.isArray(value)?value:[value]).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),candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(legacy)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;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;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 legacy.flag==="--stream"||legacy.flag==="--follow"?{source:"legacy",value:"stream"}:legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return!1;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===!0||provenance.sdk_invocation_observed===!0)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){return command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===!0}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;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand),invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE],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)},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))])),legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]}),migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag).migration_hint]:[]}),encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding),include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include),amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount),explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost),completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance),budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon",cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed({include,amount,cost,encoding},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"]),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:{},itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right)),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),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"),itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice(5)]: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))),projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));fullItem?projected.item=vocabulary.item: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}`}))],combinedOmittedFieldGroups=[...isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[],...omittedFieldGroups];return projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups},projected}function countPopulatedRows(result){let populated=0;return mapReadOutputRows({...result},entry=>(isRecord(entry)&&Object.keys(entry).length>0&&(populated+=1),entry)),populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0)return;const modes=[...readOutputIncludeModeOptions(command).keys()],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),qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[])),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},rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors,shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);return rejectEmptyIncludeProjection(command,result,shaped,rowSelectors),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;if(bounded.has_more=!0,bounded.truncated=!0,typeof bounded.count=="number"){const activeRowKey=isRecord(bounded.projection)?bounded.projection.row_key:void 0;bounded.count=typeof activeRowKey=="string"&&Array.isArray(bounded[activeRowKey])?bounded[activeRowKey].length:countReadOutputRows(bounded)}return bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount},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,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),receipt=result.read_output,session=parseReadOutputSession(options.outputSession??options.output_session);return session===void 0?(updateReadOutputReceiptEstimate(result,receipt,format),result):attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;if(!(Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[]).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)))],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:{},existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry=="string"):[],existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry=="string"):[],rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys,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)),resolved.command==="assurance"&&(projected=prioritizeAssuranceAssertions(projected)),refreshReadOutputDeliveredCounts(projected,result),projected=applyReadOutputContinuation(projected,resolved.command,cursor),resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];if(projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path)),isRecord(projected.projection)&&(projected.projection={...projected.projection,row_key:cursor.path}),isRecord(projected.row_contract)){const rowContract=projected.row_contract;projected.row_contract={...rowContract,row_keys:[cursor.path],...Array.isArray(rowContract.continuation_row_keys)?{continuation_row_keys:[cursor.path]}:{}}}projected.count=Object.keys(projected[cursor.path]).length}const continuationSource=result.count_only===!0?{...projected,count_only:!0,count:result.count}:projected;return resolved.amount?.source==="canonical"&&(projected=applyAmountBound(projected,resolved.amount.value)),refreshReadOutputDeliveredCounts(projected,continuationSource),session===void 0?projected:applyReadOutputSessionReferences(projected,session)}function resolveBindingReadOutputBudget(resolved,session){return[...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)}]].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:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}},omitted={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt},boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0&&updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format),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===!0||options.output_row_contract===!0||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===!0}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||requiresReadOutputAudit(resolved,options))return!1;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!1}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"||estimateReadOutputTokens(options.outputRowContract===!1?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"]:[],afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length])),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}]}),primary=continuations[0],continuationHint=primary?"; page --output-cursor":"",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});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!1;const retainedCount=projected.items.length;if(retainedCount===0||retainedCount>=originalItemCount)return!1;let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return!1}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return!1;const last=projected.items.at(-1);if(Object.prototype.toString.call(last)!=="[object Object]")return!1;const lastId=Reflect.get(last,"id");if(typeof lastId!="string"||lastId.length===0)return!1;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+retainedCount;return afterIndex<0?!1:(projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot),!0)}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,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)}]})),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,source,countOnly,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const deliveredSource={...source,count_only:countOnly},assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0,minimumRowsByPath=new Map;if(assuranceMinimumRows>0&&minimumRowsByPath.set("assertions",assuranceMinimumRows),resolved.command==="history"&&Array.isArray(projected.diff))for(const collection of readOutputBudgetCollections(projected))collection.path.startsWith("diff.")&&minimumRowsByPath.set(collection.path,Object.keys(collection.value).length);return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{refreshReadOutputDeliveredCounts(compacted,deliveredSource);const continuationCursorRebased=rebaseBudgetCompactedCursor(compacted,continuationState.originalItemCount,continuationState.cursorSource,continuationState.cursorContinuesExistingPage);if(attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget),resolved.command==="history"&&isRecord(compacted.projection)){compacted.has_more=typeof compacted.next_cursor=="string"||compacted.applied_bound?.kind==="output_limit";const rowKey=compacted.projection.row_key;typeof rowKey=="string"&&Array.isArray(compacted[rowKey])&&(compacted.count=compacted[rowKey].length)}session!==void 0&&Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))},resolved.command==="history"&&Array.isArray(projected.diff))}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options),session=parseReadOutputSession(options.outputSession??options.output_session),rawCursor=options.outputCursor??options.output_cursor,cursor=typeof rawCursor=="string"?decodeReadOutputContinuationCursor(rawCursor):void 0,requested=requestedDimensions(resolved),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===!1);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:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};if(projected.read_output=receipt,projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format),updateReadOutputReceiptEstimate(projected,receipt,format),bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);brief!==void 0&&(receipt.applied_depth="brief",receipt.degradation_reason="output_budget_reached",preserveReadOutputRowContract(projected,brief),projected=stabilizeReadOutputReceiptEstimates(brief,options)),receipt.estimated_tokens>bindingBudget.tokens&&(projected=compactReadOutputProjection(projected,projected,continuationReadyResult.count_only===!0,resolved,receipt,bindingBudget,session,captureReadOutputContinuationState(projected,resolved.command,cursor,options),receipt.estimated_tokens,format))}return bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens?omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format):projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===!0&&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=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2c49208d-1cb1-583b-82c3-15d06c273c48")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"./read-output/options.js";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,refreshReadOutputDeliveredCounts}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"],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"],READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"],CANONICAL_OPTIONS=READ_OUTPUT_DIMENSION_FLAGS,PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension])),PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=READ_OUTPUT_COMPOSITION_FLAGS,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:{}},VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]),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],dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:!0,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)),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()),root=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===!0||options.target==="catalog"||options.action==="catalog")?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0],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"],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),!0),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]!==!1))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);return surface?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)])):new Map}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[],modeOptions=readOutputIncludeModeOptions(command),selectors=[],modes=[],optionsWithProvenance=commandOptions,existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE],canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]),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("_","-")}`;isRequestedOption(readOption(commandOptions,legacyFlag))&&explicitLegacyAliases.add(legacyFlag),commandOptions[option]=!0,modes.push(token),canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[],forwardedGetFields=forwardedGetFieldSelectors.length>0;return forwardedGetFields&&(commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(","),canonicalModes.add("fields")),(modes.length>0||forwardedGetFields)&&(optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{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,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===!1)return!0}function isRequestedOption(value){return value!==void 0&&value!==!1&&value!==null}function stringList(value){const normalized=(Array.isArray(value)?value:[value]).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),candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(legacy)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;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;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 legacy.flag==="--stream"||legacy.flag==="--follow"?{source:"legacy",value:"stream"}:legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return!1;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===!0||provenance.sdk_invocation_observed===!0)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){return command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===!0}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;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand),invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE],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)},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))])),legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]}),migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag).migration_hint]:[]}),encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding),include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include),amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount),explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost),completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance),budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon",cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed({include,amount,cost,encoding},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"]),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:{},itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right)),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),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"),itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice(5)]: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))),projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));fullItem?projected.item=vocabulary.item: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}`}))],combinedOmittedFieldGroups=[...isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[],...omittedFieldGroups];return projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups},projected}function countPopulatedRows(result){let populated=0;return mapReadOutputRows({...result},entry=>(isRecord(entry)&&Object.keys(entry).length>0&&(populated+=1),entry)),populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0)return;const modes=[...readOutputIncludeModeOptions(command).keys()],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),qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[])),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},rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors,shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);return rejectEmptyIncludeProjection(command,result,shaped,rowSelectors),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;if(bounded.has_more=!0,bounded.truncated=!0,typeof bounded.count=="number"){const activeRowKey=isRecord(bounded.projection)?bounded.projection.row_key:void 0;bounded.count=typeof activeRowKey=="string"&&Array.isArray(bounded[activeRowKey])?bounded[activeRowKey].length:countReadOutputRows(bounded)}return bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount},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,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),receipt=result.read_output,session=parseReadOutputSession(options.outputSession??options.output_session);return session===void 0?(updateReadOutputReceiptEstimate(result,receipt,format),result):attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;if(!(Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[]).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)))],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:{},existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry=="string"):[],existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry=="string"):[],rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys,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,options){let projected={...result};if(resolved.include?.source==="canonical"&&(projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)),resolved.command==="assurance"&&(projected=prioritizeAssuranceAssertions(projected)),refreshReadOutputDeliveredCounts(projected,result),projected=applyReadOutputContinuation(projected,resolved.command,cursor),resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];if(projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path)),isRecord(projected.projection)&&(projected.projection={...projected.projection,row_key:cursor.path}),isRecord(projected.row_contract)){const rowContract=projected.row_contract;projected.row_contract={...rowContract,row_keys:[cursor.path],...Array.isArray(rowContract.continuation_row_keys)?{continuation_row_keys:[cursor.path]}:{}}}projected.count=Object.keys(projected[cursor.path]).length}const continuationSource=result.count_only===!0?{...projected,count_only:!0,count:result.count}:projected,continuationState=captureReadOutputContinuationState(projected,resolved.command,cursor,options);return resolved.amount?.source==="canonical"&&(projected=applyAmountBound(projected,resolved.amount.value)),refreshReadOutputDeliveredCounts(projected,continuationSource),{projected:session===void 0?projected:applyReadOutputSessionReferences(projected,session),continuationState}}function resolveBindingReadOutputBudget(resolved,session){return[...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)}]].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:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}},omitted={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt},boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0&&updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format),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===!0||options.output_row_contract===!0||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===!0}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||requiresReadOutputAudit(resolved,options))return!1;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!1}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"||estimateReadOutputTokens(options.outputRowContract===!1?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"]:[],afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length])),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}]}),primary=continuations[0],continuationHint=primary?"; page --output-cursor":"",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});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!1;const retainedCount=projected.items.length;if(retainedCount===0||retainedCount>=originalItemCount)return!1;let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return!1}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return!1;const last=projected.items.at(-1);if(Object.prototype.toString.call(last)!=="[object Object]")return!1;const lastId=Reflect.get(last,"id");if(typeof lastId!="string"||lastId.length===0)return!1;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+retainedCount;return afterIndex<0?!1:(projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot),!0)}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,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)}]})),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,source,countOnly,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const deliveredSource={...source,count_only:countOnly},assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0,minimumRowsByPath=new Map;if(assuranceMinimumRows>0&&minimumRowsByPath.set("assertions",assuranceMinimumRows),resolved.command==="history"&&Array.isArray(projected.diff))for(const collection of readOutputBudgetCollections(projected))collection.path.startsWith("diff.")&&minimumRowsByPath.set(collection.path,Object.keys(collection.value).length);return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{refreshReadOutputDeliveredCounts(compacted,deliveredSource);const continuationCursorRebased=rebaseBudgetCompactedCursor(compacted,continuationState.originalItemCount,continuationState.cursorSource,continuationState.cursorContinuesExistingPage);if(attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget),resolved.command==="history"&&isRecord(compacted.projection)){compacted.has_more=typeof compacted.next_cursor=="string"||compacted.applied_bound?.kind==="output_limit";const rowKey=compacted.projection.row_key;typeof rowKey=="string"&&Array.isArray(compacted[rowKey])&&(compacted.count=compacted[rowKey].length)}session!==void 0&&Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))},resolved.command==="history"&&Array.isArray(projected.diff))}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options),session=parseReadOutputSession(options.outputSession??options.output_session),rawCursor=options.outputCursor??options.output_cursor,cursor=typeof rawCursor=="string"?decodeReadOutputContinuationCursor(rawCursor):void 0,requested=requestedDimensions(resolved),continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options))return continuationReadyResult;const bindingBudget=resolveBindingReadOutputBudget(resolved,session),projection=projectReadOutputRows(continuationReadyResult,resolved,session,cursor,options);let projected=projection.projected;preserveReadOutputRowContract(projected,projected,options.outputRowContract===!1);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:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};if(projected.read_output=receipt,projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format),updateReadOutputReceiptEstimate(projected,receipt,format),bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);brief!==void 0&&(receipt.applied_depth="brief",receipt.degradation_reason="output_budget_reached",preserveReadOutputRowContract(projected,brief),projected=stabilizeReadOutputReceiptEstimates(brief,options)),receipt.estimated_tokens>bindingBudget.tokens&&(projected=compactReadOutputProjection(projected,projected,continuationReadyResult.count_only===!0,resolved,receipt,bindingBudget,session,projection.continuationState,receipt.estimated_tokens,format))}return bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens?omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format):projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===!0&&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=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2b0a2979-accd-55f8-be45-db54f1528f86")}catch{}})();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"),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){return Object.defineProperty(input,MCP_MUTATION_TRANSPORT,{value:!0,enumerable:!0}),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];return typeof value=="string"?value.trim().length>0?value:void 0:typeof value=="number"&&Number.isFinite(value)?String(value):void 0}function readRuntimeScalarStringAllowBlank(args,key){const value=args[key];return typeof value=="string"?value: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}}function resolveRuntimeLimit(args,options){return typeof args.limit=="number"&&Number.isFinite(args.limit)?args.limit:typeof options.limit=="number"&&Number.isFinite(options.limit)?options.limit:readRuntimeString(args,"limit")??readRuntimeString(options,"limit")}function actionGlobalOptions(args){const outputFormat=readRuntimeString(args,"outputFormat");return{json:!0,quiet:!0,author:readRuntimeString(args,"author"),path:readRuntimeString(args,"path"),noExtensions:args.noExtensions===!0||args.no_extensions===!0,noPager:!0,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"]),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"]),ANNOTATION_SCALAR_TO_ARRAY_FIELDS=new Set([...SCALAR_TO_ARRAY_FIELDS].filter(field=>field!=="file")),ARRAY_ADD_REMOVE_ACTIONS=new Set(["files","files-discover","docs","test","test-all"]),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")))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"]),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"]},UNIVERSAL_READ_OUTPUT_OPTION_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function normalizeMcpOptionsArrays(options,action=""){const result={},promoteAddRemove=ARRAY_ADD_REMOVE_ACTIONS.has(action),preserveStandaloneNote=action==="files"||action==="files-discover"||action==="docs",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 Object.assign(result,Object.fromEntries(Object.getOwnPropertySymbols(options).map(symbol=>[symbol,Reflect.get(options,symbol)]))),result}function resolveMcpActionAuthor(args,options,action){const author=readRuntimeString(args,"author");return author!==void 0?author: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,baseOptions=asRecordClone(args.options),hoistedTopLevel={},hoistKey=key=>{baseOptions[key]!==void 0||args[key]===void 0||(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);action!==void 0&&isMcpMutationTransportInput(args)&&assertMcpAnnotationFileUnavailable(action,baseOptions);const options=normalizeMcpOptionsArrays({...hoistedTopLevel,...baseOptions},action);if(action==="history-attest"&&isMcpMutationTransportInput(args)&&(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};return next.note===void 0&&typeof next.addNote=="string"&&(next.note=next.addNote),delete next.addNote,next}function withFilesDiscoveryOptions(options){const next={...options};return next.discoveryNote!==void 0&&next.note===void 0&&typeof next.discoveryNote=="string"&&(next.note=next.discoveryNote),delete next.discover,delete next.discoveryNote,next}function normalizeActionName(value){const chunks=[];let lastWasSeparator=!0;for(const character of value.trim().toLowerCase()){if(character>="a"&&character<="z"||character>="0"&&character<="9"){chunks.push(character),lastWasSeparator=!1;continue}lastWasSeparator||(chunks.push("-"),lastWasSeparator=!0)}return chunks.at(-1)==="-"&&chunks.pop(),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){return Array.isArray(value)?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"]),passthrough={};for(const[key,value]of Object.entries(args))reserved.has(key)||(passthrough[key]=value);const normalizedOptions={...passthrough,...options};return delete normalizedOptions.args,normalizedOptions}function withMutationCompaction(args,options){const runnerOptions=preserveTransportLiteralOptions(options??{},{...options});return{changedFields:args.fullChangedFields===!0?"full":"compact",idOnly:args.idOnly===!0,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)}function readGraphBoundOption(value){if(typeof value=="number"&&Number.isFinite(value)||typeof value=="string"&&value.trim().length>0)return value}function graphOptionsFromFlat(options){const kind=readGraphIdListOption(options.kind),exemptIsolate=readGraphIdListOption(options.exemptIsolate),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===!0,rebuild:options.rebuild===!0,clear:options.clear===!0,summary:options.summary===!0,...options.full===!0?{full:!0}:{}}}function normalizeBulkMutationListOptions(options){const normalized=normalizeListOptions(options);return options.ids!==void 0&&(normalized.ids=normalizeBulkIdsValue(options.ids)),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===!0?!0:void 0,dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1: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))UPDATE_MANY_FLAT_CONTROL_KEYS.has(key)||(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];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),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===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}return{status:readRuntimeScalarString(options,"filterStatus"),list:mutationListOptions(options),update:preserveTransportLiteralOptions(options,updateManyUpdateOptionsFromFlat(options)),dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}export{actionGlobalOptions,closeManyOptionsFromFlat,extensionOptionsFromArgs,graphOptionsFromFlat,isMcpMutationTransportInput,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=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bd5ef423-5675-585c-ac2f-0b7548636596")}catch{}})();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"),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){return Object.defineProperty(input,MCP_MUTATION_TRANSPORT,{value:!0,enumerable:!0}),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];return typeof value=="string"?value.trim().length>0?value:void 0:typeof value=="number"&&Number.isFinite(value)?String(value):void 0}function readRuntimeScalarStringAllowBlank(args,key){const value=args[key];return typeof value=="string"?value: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}}function resolveRuntimeLimit(args,options){return typeof args.limit=="number"&&Number.isFinite(args.limit)?args.limit:typeof options.limit=="number"&&Number.isFinite(options.limit)?options.limit:readRuntimeString(args,"limit")??readRuntimeString(options,"limit")}function actionGlobalOptions(args){const outputFormat=readRuntimeString(args,"outputFormat");return{json:!0,quiet:!0,author:readRuntimeString(args,"author"),path:readRuntimeString(args,"path"),noExtensions:args.noExtensions===!0||args.no_extensions===!0,noPager:!0,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"]),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"]),ANNOTATION_SCALAR_TO_ARRAY_FIELDS=new Set([...SCALAR_TO_ARRAY_FIELDS].filter(field=>field!=="file")),ARRAY_ADD_REMOVE_ACTIONS=new Set(["files","files-discover","docs","test","test-all"]),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")))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"]),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","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},UNIVERSAL_READ_OUTPUT_OPTION_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function normalizeMcpOptionsArrays(options,action=""){const result={},promoteAddRemove=ARRAY_ADD_REMOVE_ACTIONS.has(action),preserveStandaloneNote=action==="files"||action==="files-discover"||action==="docs",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 Object.assign(result,Object.fromEntries(Object.getOwnPropertySymbols(options).map(symbol=>[symbol,Reflect.get(options,symbol)]))),result}function resolveMcpActionAuthor(args,options,action){const author=readRuntimeString(args,"author");return author!==void 0?author: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,baseOptions=asRecordClone(args.options),hoistedTopLevel={},hoistKey=key=>{baseOptions[key]!==void 0||args[key]===void 0||(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);action!==void 0&&isMcpMutationTransportInput(args)&&assertMcpAnnotationFileUnavailable(action,baseOptions);const options=normalizeMcpOptionsArrays({...hoistedTopLevel,...baseOptions},action);if(action==="history-attest"&&isMcpMutationTransportInput(args)&&(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};return next.note===void 0&&typeof next.addNote=="string"&&(next.note=next.addNote),delete next.addNote,next}function withFilesDiscoveryOptions(options){const next={...options};return next.discoveryNote!==void 0&&next.note===void 0&&typeof next.discoveryNote=="string"&&(next.note=next.discoveryNote),delete next.discover,delete next.discoveryNote,next}function normalizeActionName(value){const chunks=[];let lastWasSeparator=!0;for(const character of value.trim().toLowerCase()){if(character>="a"&&character<="z"||character>="0"&&character<="9"){chunks.push(character),lastWasSeparator=!1;continue}lastWasSeparator||(chunks.push("-"),lastWasSeparator=!0)}return chunks.at(-1)==="-"&&chunks.pop(),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){return Array.isArray(value)?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"]),passthrough={};for(const[key,value]of Object.entries(args))reserved.has(key)||(passthrough[key]=value);const normalizedOptions={...passthrough,...options};return delete normalizedOptions.args,normalizedOptions}function withMutationCompaction(args,options){const runnerOptions=preserveTransportLiteralOptions(options??{},{...options});return{changedFields:args.fullChangedFields===!0?"full":"compact",idOnly:args.idOnly===!0,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)}function readGraphBoundOption(value){if(typeof value=="number"&&Number.isFinite(value)||typeof value=="string"&&value.trim().length>0)return value}function graphOptionsFromFlat(options){const kind=readGraphIdListOption(options.kind),exemptIsolate=readGraphIdListOption(options.exemptIsolate),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===!0,rebuild:options.rebuild===!0,clear:options.clear===!0,summary:options.summary===!0,...options.full===!0?{full:!0}:{}}}function normalizeBulkMutationListOptions(options){const normalized=normalizeListOptions(options);return options.ids!==void 0&&(normalized.ids=normalizeBulkIdsValue(options.ids)),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===!0?!0:void 0,dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1: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))UPDATE_MANY_FLAT_CONTROL_KEYS.has(key)||(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];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),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===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}return{status:readRuntimeScalarString(options,"filterStatus"),list:mutationListOptions(options),update:preserveTransportLiteralOptions(options,updateManyUpdateOptionsFromFlat(options)),dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}export{actionGlobalOptions,closeManyOptionsFromFlat,extensionOptionsFromArgs,graphOptionsFromFlat,isMcpMutationTransportInput,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
@@ -250,7 +250,8 @@ export declare function countFailureCategories(runResults: TestRunResult[]): Rec
250
250
  declare function copyIntoSandboxIfPresent(sourcePath: string, targetPath: string, recursive?: boolean, makeDirectory?: (targetPath: string, options: {
251
251
  recursive: true;
252
252
  }) => Promise<unknown>): Promise<void>;
253
- declare function seedLinkedTestSandbox(sandboxPmPath: string, sandboxGlobalPath: string, sourceRoots: LinkedTestSandboxSourceRoots): Promise<void>;
253
+ /** Seed settings and extension configuration, auditing schema-only copies against their own initialized history. */
254
+ declare function seedLinkedTestSandbox(sandboxPmPath: string, sandboxGlobalPath: string, sourceRoots: LinkedTestSandboxSourceRoots, auditSettings?: boolean): Promise<void>;
254
255
  declare function seedLinkedTestTrackerData(sourceRoot: string, sandboxRoot: string): Promise<void>;
255
256
  /**
256
257
  * Create an audited settings snapshot only for source trackers that predate