@unbrained/pm-cli 2026.10.23 → 2026.10.24

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 (137) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +21 -0
  3. package/dist/cli/error-guidance.js +2 -2
  4. package/dist/cli-bundle/bundle-manifest.json +1 -1
  5. package/dist/cli-bundle/chunks/{chunk-MTRYEVZR.js → chunk-3VI4XDP2.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-AAX7CNL7.js → chunk-4PNAUT2E.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-2UX2TAN2.js → chunk-CDR5ES7Q.js} +54 -54
  8. package/dist/cli-bundle/chunks/chunk-CNEUJHA4.js +2 -0
  9. package/dist/cli-bundle/chunks/{chunk-AXGFNNI3.js → chunk-CSE47ZAN.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-ZEI3DC5E.js → chunk-FASDGYQC.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-5DKCD4KV.js → chunk-HZNFNETE.js} +35 -34
  12. package/dist/cli-bundle/chunks/{chunk-KY34HTT2.js → chunk-KGZGXC7T.js} +29 -29
  13. package/dist/cli-bundle/chunks/{chunk-REXCO5AG.js → chunk-MA7SNKYK.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-ZNDYAZZ6.js → chunk-TZYQ4JDZ.js} +3 -3
  15. package/dist/cli-bundle/chunks/{chunk-F76ZUP73.js → chunk-URZB3USE.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-UY5UHI4I.js +2 -0
  17. package/dist/cli-bundle/chunks/{chunk-MMVX5L32.js → chunk-VPMQEVU6.js} +14 -14
  18. package/dist/cli-bundle/chunks/{chunk-ZMJF5HQW.js → chunk-VSSHB6XI.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-5V4HU6GK.js → chunk-YEI4N4A6.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-HDKY2YX3.js → chunk-Z62RXNHW.js} +2 -2
  21. package/dist/cli-bundle/chunks/{mutation-admission-P6LOBNLO.js → mutation-admission-NVTBZ7DH.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-list-query-JOB65KDN.js → register-list-query-2FE6K7FQ.js} +2 -2
  23. package/dist/cli-bundle/chunks/{register-mutation-QMNIN3RJ.js → register-mutation-KZXQUZUH.js} +2 -2
  24. package/dist/cli-bundle/chunks/{register-operations-Z4VET3I7.js → register-operations-BOCBWNKJ.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-setup-GNKWL3VL.js → register-setup-P3VLCTDY.js} +2 -2
  26. package/dist/cli-bundle/chunks/{stage-FW5OXCCR.js → stage-WRDTMCCF.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-LEHGCPZ6.js → chunk-3QYTS4OY.js} +4 -4
  28. package/dist/cli-bundle/focused-chunks/{chunk-I2USTQNQ.js → chunk-5MKNVJCM.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-CGL36F6I.js → chunk-6HJCSHBG.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-OMXMYTEX.js → chunk-7RQOFHMH.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/chunk-AGCEWJ27.js +21 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-BM652VCB.js → chunk-CEEOWDB7.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-NSMZY6IK.js → chunk-ES2NGVHZ.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/chunk-GXAXDPD4.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-P7DPS5M4.js → chunk-IUAYTD2S.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-DWQMYLFM.js → chunk-JYXA4JIP.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-XIZYJDYW.js → chunk-NFFPNMTH.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-MLET6I3I.js → chunk-NX7TVNUM.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-UNTCCJPL.js → chunk-POLMFGPQ.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-ZHMF34DT.js → chunk-RSEGFZTY.js} +52 -52
  41. package/dist/cli-bundle/focused-chunks/{chunk-4MNUQCGR.js → chunk-RVUGTIIU.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-6GTZ24YV.js → chunk-SBJ2IKTH.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-EDXTOAXP.js → chunk-SHUPX6G2.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-KI5YFKNN.js → chunk-TAHSXKAT.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/chunk-X5YRJMAY.js +2 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-XTYEASIY.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/chunk-ZMWLV2CE.js +91 -0
  48. package/dist/cli-bundle/focused-chunks/{mutation-admission-HTFAIHJL.js → mutation-admission-PB6YFY7S.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{stage-X3BUGEJT.js → stage-MQE4PFWT.js} +2 -2
  50. package/dist/cli-bundle/main.js +21 -21
  51. package/dist/cli-bundle/sdk-authoring.js +1 -1
  52. package/dist/cli-bundle/sdk-contracts.js +1 -1
  53. package/dist/cli-bundle/sdk-core.js +24 -24
  54. package/dist/cli-bundle/sdk-governance.js +1 -1
  55. package/dist/cli-bundle/sdk-graph.js +1 -1
  56. package/dist/cli-bundle/sdk-merge.js +53 -53
  57. package/dist/cli-bundle/sdk-query.js +1 -1
  58. package/dist/cli-bundle/sdk-runtime.js +1 -1
  59. package/dist/cli-bundle/sdk-testing.js +1 -1
  60. package/dist/cli-bundle/sdk.js +9 -9
  61. package/dist/core/checkpoint/mutation-checkpoint.d.ts +6 -3
  62. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  63. package/dist/core/checkpoint/mutation-context.d.ts +10 -0
  64. package/dist/core/checkpoint/mutation-context.js +2 -0
  65. package/dist/core/store/item-store.js +1 -1
  66. package/dist/sdk/agent/command-recovery.d.ts +1 -0
  67. package/dist/sdk/agent/command-recovery.js +1 -1
  68. package/dist/sdk/agent/linked-resource-recovery.d.ts +13 -0
  69. package/dist/sdk/agent/linked-resource-recovery.js +2 -0
  70. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  71. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +3 -2
  72. package/dist/sdk/core.d.ts +1 -1
  73. package/dist/sdk/core.js +1 -1
  74. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  75. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  76. package/dist/sdk/index.d.ts +1 -0
  77. package/dist/sdk/index.js +1 -1
  78. package/dist/sdk/lifecycle/checkpoint-rollback.d.ts +7 -0
  79. package/dist/sdk/lifecycle/checkpoint-rollback.js +2 -0
  80. package/dist/sdk/lifecycle/close-many.d.ts +1 -1
  81. package/dist/sdk/lifecycle/close-many.js +1 -1
  82. package/dist/sdk/lifecycle/update-many.d.ts +1 -1
  83. package/dist/sdk/lifecycle/update-many.js +1 -1
  84. package/dist/sdk/public-surface.json +1 -1
  85. package/dist/sdk/query/context.d.ts +2 -1
  86. package/dist/sdk/query/context.js +1 -1
  87. package/dist/sdk/query/get.d.ts +2 -1
  88. package/dist/sdk/query/get.js +1 -1
  89. package/dist/sdk/query/list.d.ts +2 -1
  90. package/dist/sdk/query/list.js +1 -1
  91. package/dist/sdk/query/search/types.d.ts +2 -1
  92. package/dist/sdk/query.d.ts +1 -0
  93. package/dist/sdk/query.js +1 -1
  94. package/dist/sdk/read-output-contracts.d.ts +10 -2
  95. package/dist/sdk/read-output-contracts.js +1 -1
  96. package/dist/sdk/runtime-input.js +1 -1
  97. package/dist/sdk/runtime-primitives.d.ts +1 -0
  98. package/dist/sdk/runtime-primitives.js +1 -1
  99. package/dist/sdk/runtime.d.ts +10 -10
  100. package/dist/sdk/runtime.js +1 -1
  101. package/dist/sdk/test/batch.js +2 -2
  102. package/dist/sdk/test/entry.d.ts +5 -1
  103. package/dist/sdk/test/entry.js +2 -1
  104. package/dist/sdk/test/execution.js +2 -2
  105. package/docs/COMMANDS.md +21 -2
  106. package/docs/READ_OUTPUT_CONTRACTS.md +15 -0
  107. package/docs/SDK.md +45 -0
  108. package/docs/TESTING.md +28 -0
  109. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +5 -3
  110. package/marketplace.json +1 -1
  111. package/package.json +1 -1
  112. package/packages/pm-beads/package.json +1 -1
  113. package/packages/pm-calendar/package.json +1 -1
  114. package/packages/pm-command-kit/package.json +1 -1
  115. package/packages/pm-digital-twin/package.json +1 -1
  116. package/packages/pm-governance-audit/package.json +1 -1
  117. package/packages/pm-guide-shell/package.json +1 -1
  118. package/packages/pm-kanban/package.json +1 -1
  119. package/packages/pm-lifecycle-hooks/package.json +1 -1
  120. package/packages/pm-linked-test-adapters/package.json +1 -1
  121. package/packages/pm-search-advanced/package.json +1 -1
  122. package/packages/pm-templates/package.json +1 -1
  123. package/packages/pm-todos/package.json +1 -1
  124. package/packages/pm-vcs/package.json +1 -1
  125. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  126. package/plugins/pm-claude/package.json +1 -1
  127. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  128. package/plugins/pm-codex/package.json +1 -1
  129. package/plugins/pm-codex/plugin.json +1 -1
  130. package/runtime-dependencies.json +1 -1
  131. package/dist/cli-bundle/chunks/chunk-2LTGJ5DL.js +0 -2
  132. package/dist/cli-bundle/chunks/chunk-QSY55FTA.js +0 -2
  133. package/dist/cli-bundle/focused-chunks/chunk-FO4U3FIP.js +0 -91
  134. package/dist/cli-bundle/focused-chunks/chunk-GXKP56W7.js +0 -2
  135. package/dist/cli-bundle/focused-chunks/chunk-JDN34LEZ.js +0 -2
  136. package/dist/cli-bundle/focused-chunks/chunk-Z5LDTMZ3.js +0 -2
  137. package/dist/cli-bundle/focused-chunks/chunk-ZR6ZKQUK.js +0 -20
@@ -25,7 +25,7 @@ export interface CheckpointRollbackRow {
25
25
  /** Stable identifier used to reference this record across commands and storage. */
26
26
  id:string;
27
27
  /** Lifecycle state reported for status. */
28
- status:"restored" | "failed";
28
+ status:"restored" | "failed" | "skipped";
29
29
  /** Value that configures or reports changed fields for this contract. */
30
30
  changed_fields?:string[];
31
31
  /** Value that configures or reports warnings for this contract. */
@@ -42,11 +42,14 @@ restored_ids:string[];
42
42
  /** Number of failed entries represented by this result. */
43
43
  failed_count:number;
44
44
  }
45
- /** Restore a single item to its captured pre-mutation timestamp. */
45
+ /** Recover one checkpointed item, or disclose that it has no remaining effect. */
46
46
  export type CheckpointRestoreFn = (id:string,targetUpdatedAt:string) => Promise<{
47
47
  changed_fields?:string[];
48
48
  warnings?:string[];
49
+ skipped?:boolean;
49
50
  }>;
51
+ /** Admit only a concrete checkpoint ID; invalid untyped values must never fall through to forward mutation. */
52
+ export declare function resolveCheckpointRollbackId(value:unknown):string | undefined;
50
53
  /** Implements normalize checkpoint id for the public runtime surface of this module. */
51
54
  export declare function normalizeCheckpointId(raw:string):string;
52
55
  /** Implements create checkpoint id for the public runtime surface of this module. */
@@ -59,5 +62,5 @@ export declare function checkpointFilePath(pmRoot:string,subdir:string,checkpoin
59
62
  export declare function writeMutationCheckpoint(pmRoot:string,subdir:string,checkpointId:string,payload:unknown):Promise<string>;
60
63
  /** Implements load mutation checkpoint for the public runtime surface of this module. */
61
64
  export declare function loadMutationCheckpoint(pmRoot:string,subdir:string,rawCheckpointId:string,schemaVersion:number):Promise<LoadedMutationCheckpoint>;
62
- /** Restore every checkpointed item to its captured pre-mutation timestamp, collecting per-item rows. A single item's failure is recorded and does not abort the remaining restores. */
65
+ /** Collect independent recovery results without allowing one row's refusal to hide other rows. */
63
66
  export declare function restoreCheckpointItems(items:MutationCheckpointItem[],restore:CheckpointRestoreFn):Promise<CheckpointRollbackResult>;
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="da661b46-841c-526d-88bc-976e007e8fbe")}catch{}})();import{readFile}from"node:fs/promises";import path from"node:path";import{pathExists,readFileIfExists}from"../fs/fs-utils.js";import{createFileAtomic}from"../fs/atomic-create.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{nowIso}from"../shared/time.js";function normalizeCheckpointId(raw){const trimmed=raw.trim();if(!trimmed)throw new PmCliError("--rollback requires a non-empty checkpoint ID",EXIT_CODE.USAGE);if(!/^[a-zA-Z0-9._-]+$/.test(trimmed))throw new PmCliError("--rollback checkpoint ID must match [a-zA-Z0-9._-]+",EXIT_CODE.USAGE);return trimmed}function createCheckpointId(prefix,nowValue){const compactTimestamp=nowValue.replace(/[-:.TZ]/g,"").slice(0,14),randomSuffix=Math.random().toString(36).slice(2,8);return`${prefix}-${compactTimestamp}-${randomSuffix}`}function checkpointDirectoryPath(pmRoot,subdir){return path.join(pmRoot,"checkpoints",subdir)}function checkpointFilePath(pmRoot,subdir,checkpointId){return path.join(checkpointDirectoryPath(pmRoot,subdir),`${checkpointId}.json`)}async function writeMutationCheckpoint(pmRoot,subdir,checkpointId,payload){const filePath=checkpointFilePath(pmRoot,subdir,checkpointId),raw=`${JSON.stringify(payload,null,2)}
2
- `;if(!await createFileAtomic(filePath,raw)&&await readFileIfExists(filePath)!==raw)throw new PmCliError(`Checkpoint ${checkpointId} already exists with different contents; use a new checkpoint ID.`,EXIT_CODE.CONFLICT);return filePath}function parseCheckpointItems(record,checkpointId){if(!Array.isArray(record.items))throw new PmCliError(`Checkpoint ${checkpointId} is missing items`,EXIT_CODE.GENERIC_FAILURE);return record.items.map(entry=>{if(!entry||typeof entry!="object")throw new PmCliError(`Checkpoint ${checkpointId} contains an invalid item entry`,EXIT_CODE.GENERIC_FAILURE);const row=entry;if(typeof row.id!="string"||row.id.trim().length===0)throw new PmCliError(`Checkpoint ${checkpointId} contains an item entry without ID`,EXIT_CODE.GENERIC_FAILURE);if(typeof row.target_updated_at!="string"||row.target_updated_at.trim().length===0)throw new PmCliError(`Checkpoint ${checkpointId} contains an item entry without target_updated_at`,EXIT_CODE.GENERIC_FAILURE);return{id:row.id.trim(),target_updated_at:row.target_updated_at.trim()}})}async function loadMutationCheckpoint(pmRoot,subdir,rawCheckpointId,schemaVersion){const normalizedId=normalizeCheckpointId(rawCheckpointId),filePath=checkpointFilePath(pmRoot,subdir,normalizedId);if(!await pathExists(filePath))throw new PmCliError(`Checkpoint ${normalizedId} not found`,EXIT_CODE.NOT_FOUND);const raw=await readFile(filePath,"utf8");let parsed;try{parsed=JSON.parse(raw)}catch(error){throw new PmCliError(`Checkpoint ${normalizedId} contains invalid JSON: ${toErrorMessage(error)}`,EXIT_CODE.GENERIC_FAILURE)}if(!parsed||typeof parsed!="object")throw new PmCliError(`Checkpoint ${normalizedId} is invalid`,EXIT_CODE.GENERIC_FAILURE);const record=parsed;if(record.schema_version!==schemaVersion)throw new PmCliError(`Checkpoint ${normalizedId} has unsupported schema version`,EXIT_CODE.GENERIC_FAILURE);const items=parseCheckpointItems(record,normalizedId);return{record,items,path:filePath,id:typeof record.id=="string"?record.id:normalizedId,created_at:typeof record.created_at=="string"?record.created_at:nowIso(),author:typeof record.author=="string"?record.author:"unknown"}}async function restoreCheckpointItems(items,restore){const rows=[],restoredIds=[];for(const entry of items)try{const restored=await restore(entry.id,entry.target_updated_at);rows.push({id:entry.id,status:"restored",changed_fields:restored.changed_fields,warnings:restored.warnings}),restoredIds.push(entry.id)}catch(error){rows.push({id:entry.id,status:"failed",error:toErrorMessage(error)})}return{rows,restored_ids:restoredIds,failed_count:rows.filter(row=>row.status==="failed").length}}export{checkpointDirectoryPath,checkpointFilePath,createCheckpointId,loadMutationCheckpoint,normalizeCheckpointId,restoreCheckpointItems,writeMutationCheckpoint};
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]="7cc00705-c03e-5a18-9bec-af2585939ed8")}catch{}})();import{readFile}from"node:fs/promises";import path from"node:path";import{pathExists,readFileIfExists}from"../fs/fs-utils.js";import{createFileAtomic}from"../fs/atomic-create.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{nowIso}from"../shared/time.js";function resolveCheckpointRollbackId(value){if(value!==void 0){if(typeof value!="string")throw new PmCliError("--rollback requires a non-empty checkpoint ID string",EXIT_CODE.USAGE);return normalizeCheckpointId(value)}}function normalizeCheckpointId(raw){const trimmed=raw.trim();if(!trimmed)throw new PmCliError("--rollback requires a non-empty checkpoint ID",EXIT_CODE.USAGE);if(!/^[a-zA-Z0-9._-]+$/.test(trimmed))throw new PmCliError("--rollback checkpoint ID must match [a-zA-Z0-9._-]+",EXIT_CODE.USAGE);return trimmed}function createCheckpointId(prefix,nowValue){const compactTimestamp=nowValue.replace(/[-:.TZ]/g,"").slice(0,14),randomSuffix=Math.random().toString(36).slice(2,8);return`${prefix}-${compactTimestamp}-${randomSuffix}`}function checkpointDirectoryPath(pmRoot,subdir){return path.join(pmRoot,"checkpoints",subdir)}function checkpointFilePath(pmRoot,subdir,checkpointId){return path.join(checkpointDirectoryPath(pmRoot,subdir),`${checkpointId}.json`)}async function writeMutationCheckpoint(pmRoot,subdir,checkpointId,payload){const filePath=checkpointFilePath(pmRoot,subdir,checkpointId),raw=`${JSON.stringify(payload,null,2)}
2
+ `;if(!await createFileAtomic(filePath,raw)&&await readFileIfExists(filePath)!==raw)throw new PmCliError(`Checkpoint ${checkpointId} already exists with different contents; use a new checkpoint ID.`,EXIT_CODE.CONFLICT);return filePath}function parseCheckpointItems(record,checkpointId){if(!Array.isArray(record.items))throw new PmCliError(`Checkpoint ${checkpointId} is missing items`,EXIT_CODE.GENERIC_FAILURE);return record.items.map(entry=>{if(!entry||typeof entry!="object")throw new PmCliError(`Checkpoint ${checkpointId} contains an invalid item entry`,EXIT_CODE.GENERIC_FAILURE);const row=entry;if(typeof row.id!="string"||row.id.trim().length===0)throw new PmCliError(`Checkpoint ${checkpointId} contains an item entry without ID`,EXIT_CODE.GENERIC_FAILURE);if(typeof row.target_updated_at!="string"||row.target_updated_at.trim().length===0)throw new PmCliError(`Checkpoint ${checkpointId} contains an item entry without target_updated_at`,EXIT_CODE.GENERIC_FAILURE);return{id:row.id.trim(),target_updated_at:row.target_updated_at.trim()}})}async function loadMutationCheckpoint(pmRoot,subdir,rawCheckpointId,schemaVersion){const normalizedId=normalizeCheckpointId(rawCheckpointId),filePath=checkpointFilePath(pmRoot,subdir,normalizedId);if(!await pathExists(filePath))throw new PmCliError(`Checkpoint ${normalizedId} not found`,EXIT_CODE.NOT_FOUND);const raw=await readFile(filePath,"utf8");let parsed;try{parsed=JSON.parse(raw)}catch(error){throw new PmCliError(`Checkpoint ${normalizedId} contains invalid JSON: ${toErrorMessage(error)}`,EXIT_CODE.GENERIC_FAILURE)}if(!parsed||typeof parsed!="object")throw new PmCliError(`Checkpoint ${normalizedId} is invalid`,EXIT_CODE.GENERIC_FAILURE);const record=parsed;if(record.schema_version!==schemaVersion)throw new PmCliError(`Checkpoint ${normalizedId} has unsupported schema version. Inspect pm history and use an explicit pm restore only after reviewing later edits.`,EXIT_CODE.GENERIC_FAILURE);const items=parseCheckpointItems(record,normalizedId);return{record,items,path:filePath,id:typeof record.id=="string"?record.id:normalizedId,created_at:typeof record.created_at=="string"?record.created_at:nowIso(),author:typeof record.author=="string"?record.author:"unknown"}}async function restoreCheckpointItems(items,restore){const rows=[],restoredIds=[];for(const entry of items)try{const restored=await restore(entry.id,entry.target_updated_at);rows.push({id:entry.id,status:restored.skipped?"skipped":"restored",changed_fields:restored.changed_fields,warnings:restored.warnings}),restored.skipped||restoredIds.push(entry.id)}catch(error){rows.push({id:entry.id,status:"failed",error:toErrorMessage(error)})}return{rows,restored_ids:restoredIds,failed_count:rows.filter(row=>row.status==="failed").length}}export{checkpointDirectoryPath,checkpointFilePath,createCheckpointId,loadMutationCheckpoint,normalizeCheckpointId,resolveCheckpointRollbackId,restoreCheckpointItems,writeMutationCheckpoint};
3
3
  //# sourceMappingURL=mutation-checkpoint.js.map
@@ -0,0 +1,10 @@
1
+ interface CheckpointMutationContext {
2
+ pmRoot:string;
3
+ itemId:string;
4
+ checkpointId:string;
5
+ }
6
+ /** Carry checkpoint identity through nested lifecycle writers in this async operation only. */
7
+ export declare function withCheckpointMutation<T>(context:CheckpointMutationContext,operation:() => Promise<T>):Promise<T>;
8
+ /** Read checkpoint attribution only for the matching tracker and item at commit time. */
9
+ export declare function checkpointMutationHistoryContext(pmRoot:string,itemId:string):Record<string,unknown> | undefined;
10
+ export {};
@@ -0,0 +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]="c343ed33-0135-5d3a-94a4-67314b295168")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";const checkpointContext=new AsyncLocalStorage;function withCheckpointMutation(context,operation){return checkpointContext.run({...context,pmRoot:path.resolve(context.pmRoot)},operation)}function checkpointMutationHistoryContext(pmRoot,itemId){const context=checkpointContext.getStore();return context?.pmRoot===path.resolve(pmRoot)&&context.itemId===itemId?{bulk_checkpoint:context.checkpointId}:void 0}export{checkpointMutationHistoryContext,withCheckpointMutation};
2
+ //# sourceMappingURL=mutation-context.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]="3ecac03b-7dfe-5ce3-a93d-6b9f948c68fe")}catch{}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import{assertItemMutationPreconditions}from"./item-mutation-precondition.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{effectiveItemFormatVersion,requiredItemFormatVersion}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease}from"../lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS,resolveWorkspaceRoot}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{nowIso}from"../shared/time.js";async function fileExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){warnings&&(warnings.includes(warning)||warnings.push(warning))}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){return preferredFormat==="toon"?["toon","json_markdown"]:preferredFormat==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim(),exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0)return null;const normalizedId=normalizeItemId(rawId,idPrefix),rawNormalizedId=normalizeRawItemId(rawId),candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0),entries=Object.entries(typeToFolder),searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries)for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);await fileExists(itemPath)&&matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes))throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:!1});const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,requireSupportedFormat:!0,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_format_version_unsupported")throw new PmCliError(`Item ${item.id}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath});if(error instanceof PmCliError&&error.code==="item_document_invalid")return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})};throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!0,forceSourceScan:options.forceSourceScan});return recordItemMetadataEnumeration(candidates.length),candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder)),allIds=[];return await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries)for(const ext of ITEM_FILE_EXTENSIONS)if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}catch{}})),allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix),ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));return ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id)}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder),nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return suggestions.length>0&&nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`),new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===!0&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder);const lease=await acquireLockLease(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const warnings=[],{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings}),assigned=document.metadata.assignee?.trim(),assignedPrincipal=document.metadata.claim_principal?.trim()||assigned,callerPrincipal=resolveClaimPrincipal(params.author),governance=resolveGovernanceKnobs(params.settings);if(assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict)){if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);governance.ownership_enforcement==="warn"&&warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}return{typeToFolder,located,originalRaw,document,warnings,releaseLock,lease}}catch(error){throw await releaseLock(),error}}async function commitLockedItemWrite(lease,located,originalRaw,commit){return lease.fence(async()=>{let currentRaw;try{currentRaw=await fs.readFile(located.itemPath,"utf8")}catch(error){if(!isFileMissingError(error))throw error;currentRaw=null}if(currentRaw!==originalRaw)throw new PmCliError(`Item ${located.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,EXIT_CODE.CONFLICT,{code:"stale_revision",item_id:located.id,reason:currentRaw===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return commit()})}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!="object"||serviceWriteOverride.result===null)return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:!1};const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path=="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents=="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===!0}}async function resolveItemStoreDeleteOverride(payload){const override=await runActiveServiceOverride("item_store_delete",payload),record=override.handled&&typeof override.result=="object"&&override.result!==null?override.result:{};return{effectiveItemPath:typeof record.item_path=="string"&&record.item_path.trim().length>0?record.item_path:payload.item_path,skipDelete:record.skip_delete===!0,warnings:override.warnings}}async function rollbackMutatedItemWrite(params){if(!params.skipItemWrite){if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw),await fs.rm(params.effectiveTargetItemPath,{force:!0});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder}),{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutation=await params.mutate(mutableDocument);if(params.skipNoop===!0&&mutation.changedFields.length===0)return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]};const historyContext=params.resolveHistoryContext?.(),requiredFormat=Math.max(requiredItemFormatVersion(beforeDocument.metadata),requiredItemFormatVersion(mutableDocument.metadata));assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(params.pmRoot),requiredFormat),requiredFormat>effectiveItemFormatVersion(mutableDocument.metadata)&&(mutableDocument.metadata.pm_format_version=requiredFormat,mutation.changedFields.push("pm_format_version")),mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op}),targetItemFormat="toon",serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder),historyPath=getHistoryPath(params.pmRoot,located.id),committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter}),{effectiveTargetItemPath:effectiveTargetItemPath2,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipItemWrite||await writeFileAtomic(effectiveTargetItemPath2,effectiveSerializedAfter),!skipItemWrite&&effectiveTargetItemPath2!==located.itemPath&&await fs.rm(located.itemPath);const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:workflowPolicy.decisions.length===0?historyContext:{...historyContext,workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(historyPath,entry)}catch(error){throw await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath:effectiveTargetItemPath2,originalItemPath:located.itemPath,originalRaw}),error}skipItemWrite||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath2,previousItemPath:located.itemPath,document:afterDocument}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveTargetItemPath:effectiveTargetItemPath2,overrideWarnings:serviceWriteOverride.warnings}}),{derivedIndexWarnings,effectiveTargetItemPath}=committed,hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];return recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields}),{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force}),{located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{const extensionFieldNames=resolveActiveExtensionFieldNames(void 0),beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"}),deletionTimestamp=nowIso(),tombstoneDocument=EMPTY_CANONICAL_DOCUMENT,historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}}),historyPath=getHistoryPath(params.pmRoot,located.id),runDeleteOverride=()=>resolveItemStoreDeleteOverride({op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});if(params.dryRun===!0){const preview=await runDeleteOverride();return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:preview.effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...preview.warnings]}}const committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const{effectiveItemPath:effectiveItemPath2,skipDelete,warnings}=await runDeleteOverride(),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipDelete||await fs.rm(effectiveItemPath2);try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw skipDelete||await writeFileAtomic(effectiveItemPath2,originalRaw),error}skipDelete||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath2,document:null}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveItemPath:effectiveItemPath2,overrideWarnings:warnings}}),{derivedIndexWarnings,effectiveItemPath}=committed,hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];return recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]}),{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
1
+ (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]="3a19f8b4-d2d8-5133-b320-281980d64da6")}catch{}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import{assertItemMutationPreconditions}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext}from"../checkpoint/mutation-context.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{effectiveItemFormatVersion,requiredItemFormatVersion}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease}from"../lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS,resolveWorkspaceRoot}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{nowIso}from"../shared/time.js";async function fileExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){warnings&&(warnings.includes(warning)||warnings.push(warning))}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){return preferredFormat==="toon"?["toon","json_markdown"]:preferredFormat==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim(),exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0)return null;const normalizedId=normalizeItemId(rawId,idPrefix),rawNormalizedId=normalizeRawItemId(rawId),candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0),entries=Object.entries(typeToFolder),searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries)for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);await fileExists(itemPath)&&matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes))throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:!1});const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,requireSupportedFormat:!0,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_format_version_unsupported")throw new PmCliError(`Item ${item.id}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath});if(error instanceof PmCliError&&error.code==="item_document_invalid")return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})};throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!0,forceSourceScan:options.forceSourceScan});return recordItemMetadataEnumeration(candidates.length),candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder)),allIds=[];return await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries)for(const ext of ITEM_FILE_EXTENSIONS)if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}catch{}})),allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix),ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));return ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id)}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder),nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return suggestions.length>0&&nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`),new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===!0&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder);const lease=await acquireLockLease(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const warnings=[],{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings}),assigned=document.metadata.assignee?.trim(),assignedPrincipal=document.metadata.claim_principal?.trim()||assigned,callerPrincipal=resolveClaimPrincipal(params.author),governance=resolveGovernanceKnobs(params.settings);if(assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict)){if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);governance.ownership_enforcement==="warn"&&warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}return{typeToFolder,located,originalRaw,document,warnings,releaseLock,lease}}catch(error){throw await releaseLock(),error}}async function commitLockedItemWrite(lease,located,originalRaw,commit){return lease.fence(async()=>{let currentRaw;try{currentRaw=await fs.readFile(located.itemPath,"utf8")}catch(error){if(!isFileMissingError(error))throw error;currentRaw=null}if(currentRaw!==originalRaw)throw new PmCliError(`Item ${located.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,EXIT_CODE.CONFLICT,{code:"stale_revision",item_id:located.id,reason:currentRaw===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return commit()})}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!="object"||serviceWriteOverride.result===null)return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:!1};const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path=="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents=="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===!0}}async function resolveItemStoreDeleteOverride(payload){const override=await runActiveServiceOverride("item_store_delete",payload),record=override.handled&&typeof override.result=="object"&&override.result!==null?override.result:{};return{effectiveItemPath:typeof record.item_path=="string"&&record.item_path.trim().length>0?record.item_path:payload.item_path,skipDelete:record.skip_delete===!0,warnings:override.warnings}}async function rollbackMutatedItemWrite(params){if(!params.skipItemWrite){if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw),await fs.rm(params.effectiveTargetItemPath,{force:!0});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder}),{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutation=await params.mutate(mutableDocument);if(params.skipNoop===!0&&mutation.changedFields.length===0)return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]};const historyContext={...params.resolveHistoryContext?.(),...checkpointMutationHistoryContext(params.pmRoot,located.id)},requiredFormat=Math.max(requiredItemFormatVersion(beforeDocument.metadata),requiredItemFormatVersion(mutableDocument.metadata));assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(params.pmRoot),requiredFormat),requiredFormat>effectiveItemFormatVersion(mutableDocument.metadata)&&(mutableDocument.metadata.pm_format_version=requiredFormat,mutation.changedFields.push("pm_format_version")),mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op}),targetItemFormat="toon",serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder),historyPath=getHistoryPath(params.pmRoot,located.id),committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter}),{effectiveTargetItemPath:effectiveTargetItemPath2,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipItemWrite||await writeFileAtomic(effectiveTargetItemPath2,effectiveSerializedAfter),!skipItemWrite&&effectiveTargetItemPath2!==located.itemPath&&await fs.rm(located.itemPath);const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:workflowPolicy.decisions.length===0?Object.keys(historyContext).length===0?void 0:historyContext:{...historyContext,workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(historyPath,entry)}catch(error){throw await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath:effectiveTargetItemPath2,originalItemPath:located.itemPath,originalRaw}),error}skipItemWrite||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath2,previousItemPath:located.itemPath,document:afterDocument}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveTargetItemPath:effectiveTargetItemPath2,overrideWarnings:serviceWriteOverride.warnings}}),{derivedIndexWarnings,effectiveTargetItemPath}=committed,hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];return recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields}),{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force}),{located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{const extensionFieldNames=resolveActiveExtensionFieldNames(void 0),beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"}),deletionTimestamp=nowIso(),tombstoneDocument=EMPTY_CANONICAL_DOCUMENT,historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}}),historyPath=getHistoryPath(params.pmRoot,located.id),runDeleteOverride=()=>resolveItemStoreDeleteOverride({op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});if(params.dryRun===!0){const preview=await runDeleteOverride();return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:preview.effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...preview.warnings]}}const committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const{effectiveItemPath:effectiveItemPath2,skipDelete,warnings}=await runDeleteOverride(),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipDelete||await fs.rm(effectiveItemPath2);try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw skipDelete||await writeFileAtomic(effectiveItemPath2,originalRaw),error}skipDelete||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath2,document:null}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveItemPath:effectiveItemPath2,overrideWarnings:warnings}}),{derivedIndexWarnings,effectiveItemPath}=committed,hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];return recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]}),{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
2
2
  //# sourceMappingURL=item-store.js.map
@@ -1,3 +1,4 @@
1
+ export { resolveLinkedResourcePositionalRecovery } from "./linked-resource-recovery.js";
1
2
  /** Derive a same-command read retry for known completeness and encoding mistakes without discarding intent. */
2
3
  export declare function resolveReadOptionRetryArgs(commandName:string,invocationArgv:readonly string[],unknownOption:string):string[] | undefined;
3
4
  /** Identify presentation intent that must not be silently dropped from an unknown-option retry. */
@@ -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]="54d81daa-9e2e-5b4d-b9f2-93f8d11f9fbc")}catch{}})();import{renderPmCommand}from"../command-line.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"../read-output/options.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";const READ_PROJECTION_FLAGS=new Set([...Object.values(READ_OUTPUT_DIMENSION_FLAGS),...READ_OUTPUT_COMPOSITION_FLAGS,"--full","--brief","--compact","--summary","--fields","--section","--token-budget"]),MUTATION_RECEIPT_FLAGS=new Set(["--full-changed-fields","--no-changed-fields","--id-only"]);function readOptionCorrection(command,flag,token,next){if(flag==="--full"&&command==="context"&&token===flag)return{consumed:1,replacement:["--depth","full"],conflicts:["--depth","--output-include","--fields","--section","--for"]};if(flag==="--depth"&&["list","search"].includes(command)){const inline=token.includes("=");return(inline?token.slice(token.indexOf("=")+1):next)!=="full"?void 0:{consumed:inline?1:2,replacement:["--full"],conflicts:["--full","--brief","--compact","--output-include","--fields","--for"]}}return flag==="--toon"&&token===flag?{consumed:1,replacement:["--output-format","toon"],conflicts:["--json","--format","--output-format","--stream"]}:void 0}function resolveReadOptionRetryArgs(commandName,invocationArgv,unknownOption){const command=commandName==="ctx"?"context":resolvePmCommandOperation(commandName);if(!["context","list","search","get"].includes(command)||invocationArgv.includes("--"))return;const invoked=parseBootstrapCommandName(invocationArgv);if((invoked==="ctx"?"context":invoked)!==command)return;const flag=unknownOption.split("=",1)[0],indices=invocationArgv.flatMap((token,index2)=>token===flag||token.startsWith(`${flag}=`)?[index2]:[]);if(indices.length!==1)return;const index=indices[0],correction=readOptionCorrection(command,flag,invocationArgv[index],invocationArgv[index+1]);if(!correction)return;const{replacement,consumed,conflicts}=correction;if(!invocationArgv.some(argument=>conflicts.includes(argument.split("=",1)[0])))return[...invocationArgv.slice(0,index),...replacement,...invocationArgv.slice(index+consumed)]}function isReadProjectionRecoveryFlag(flag){const normalized=flag.split("=",1)[0].replaceAll("_","-");return READ_PROJECTION_FLAGS.has(normalized)||normalized.length>=5&&[...READ_PROJECTION_FLAGS].some(candidate=>candidate.startsWith(normalized))}function isCompatibleRecoveryFlag(requested,candidate){const unknownFlag=requested.split("=",1)[0].replaceAll("_","-");return isReadProjectionRecoveryFlag(unknownFlag)?!MUTATION_RECEIPT_FLAGS.has(candidate):MUTATION_RECEIPT_FLAGS.has(unknownFlag)?!isReadProjectionRecoveryFlag(candidate):!0}function normalizeMissingFlag(label){return label.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!(!Array.isArray(invocationArgv)||invocationArgv.length===0))return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));return contract?contract.value_type==="boolean"?null:`<${contract.value_name??"value"}>`:"<value>"}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv],terminatorIndex=retry.indexOf("--");let insertionIndex=terminatorIndex<0?retry.length:terminatorIndex;for(const label of missingLabels){const flag=normalizeMissingFlag(label);if(!flag||retry.slice(0,insertionIndex).some(token=>token===flag||token.startsWith(`${flag}=`)))continue;const placeholder=resolveMissingOptionPlaceholder(commandName,flag),recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption),insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{isCompatibleRecoveryFlag,isReadProjectionRecoveryFlag,renderMissingOptionRetry,resolveMissingOptionPlaceholder,resolveReadOptionRetryArgs,resolveRecoveryCommandName};
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]="acba78bd-59c7-5bc2-b0ef-1d9d41ff0975")}catch{}})();import{renderPmCommand}from"../command-line.js";import{resolveLinkedResourcePositionalRecovery}from"./linked-resource-recovery.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"../read-output/options.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";const READ_PROJECTION_FLAGS=new Set([...Object.values(READ_OUTPUT_DIMENSION_FLAGS),...READ_OUTPUT_COMPOSITION_FLAGS,"--full","--brief","--compact","--summary","--fields","--section","--token-budget"]),MUTATION_RECEIPT_FLAGS=new Set(["--full-changed-fields","--no-changed-fields","--id-only"]);function readOptionCorrection(command,flag,token,next){if(flag==="--full"&&command==="context"&&token===flag)return{consumed:1,replacement:["--depth","full"],conflicts:["--depth","--output-include","--fields","--section","--for"]};if(flag==="--depth"&&["list","search"].includes(command)){const inline=token.includes("=");return(inline?token.slice(token.indexOf("=")+1):next)!=="full"?void 0:{consumed:inline?1:2,replacement:["--full"],conflicts:["--full","--brief","--compact","--output-include","--fields","--for"]}}return flag==="--toon"&&token===flag?{consumed:1,replacement:["--output-format","toon"],conflicts:["--json","--format","--output-format","--stream"]}:void 0}function resolveReadOptionRetryArgs(commandName,invocationArgv,unknownOption){const command=commandName==="ctx"?"context":resolvePmCommandOperation(commandName);if(!["context","list","search","get"].includes(command)||invocationArgv.includes("--"))return;const invoked=parseBootstrapCommandName(invocationArgv);if((invoked==="ctx"?"context":invoked)!==command)return;const flag=unknownOption.split("=",1)[0],indices=invocationArgv.flatMap((token,index2)=>token===flag||token.startsWith(`${flag}=`)?[index2]:[]);if(indices.length!==1)return;const index=indices[0],correction=readOptionCorrection(command,flag,invocationArgv[index],invocationArgv[index+1]);if(!correction)return;const{replacement,consumed,conflicts}=correction;if(!invocationArgv.some(argument=>conflicts.includes(argument.split("=",1)[0])))return[...invocationArgv.slice(0,index),...replacement,...invocationArgv.slice(index+consumed)]}function isReadProjectionRecoveryFlag(flag){const normalized=flag.split("=",1)[0].replaceAll("_","-");return READ_PROJECTION_FLAGS.has(normalized)||normalized.length>=5&&[...READ_PROJECTION_FLAGS].some(candidate=>candidate.startsWith(normalized))}function isCompatibleRecoveryFlag(requested,candidate){const unknownFlag=requested.split("=",1)[0].replaceAll("_","-");return isReadProjectionRecoveryFlag(unknownFlag)?!MUTATION_RECEIPT_FLAGS.has(candidate):MUTATION_RECEIPT_FLAGS.has(unknownFlag)?!isReadProjectionRecoveryFlag(candidate):!0}function normalizeMissingFlag(label){return label.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!(!Array.isArray(invocationArgv)||invocationArgv.length===0))return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));return contract?contract.value_type==="boolean"?null:`<${contract.value_name??"value"}>`:"<value>"}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv],terminatorIndex=retry.indexOf("--");let insertionIndex=terminatorIndex<0?retry.length:terminatorIndex;for(const label of missingLabels){const flag=normalizeMissingFlag(label);if(!flag||retry.slice(0,insertionIndex).some(token=>token===flag||token.startsWith(`${flag}=`)))continue;const placeholder=resolveMissingOptionPlaceholder(commandName,flag),recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption),insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{isCompatibleRecoveryFlag,isReadProjectionRecoveryFlag,renderMissingOptionRetry,resolveLinkedResourcePositionalRecovery,resolveMissingOptionPlaceholder,resolveReadOptionRetryArgs,resolveRecoveryCommandName};
2
2
  //# sourceMappingURL=command-recovery.js.map
@@ -0,0 +1,13 @@
1
+ /** Recovery retains supplied values; missing test commands never become executable placeholders. */
2
+ export interface LinkedResourcePositionalRecovery {
3
+ /** Item operand retained in templates when the actual test command is missing. */
4
+ itemId:string;
5
+ /** Misplaced path, command or metadata value. */
6
+ value:string;
7
+ /** Exact retry, absent when the caller must supply the actual test command. */
8
+ retryArgs?:string[];
9
+ /** Original-scope template whose actual-command placeholder must be filled before replay. */
10
+ templateArgs?:string[];
11
+ }
12
+ /** Repair object-first resource syntax without guessing command names or combining mutations. */
13
+ export declare function resolveLinkedResourcePositionalRecovery(command:string | undefined,argv:readonly string[]):LinkedResourcePositionalRecovery | undefined;
@@ -0,0 +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]="b58016fa-9817-5421-a4a3-78d1b1d22937")}catch{}})();import{findBootstrapCommandTokenIndex,GLOBAL_VALUE_CONSUMING_FLAGS,BOOTSTRAP_BOOLEAN_FLAGS}from"../cli-contracts/bootstrap-command-scanner.js";import{findPmNamespacedCommand}from"../cli-contracts/command-aliases.js";import{assertLinkedTestCommand,normalizeStructuredLinkedTestEntry,STRUCTURED_LINKED_TEST_KEYS}from"../test/entry.js";import{parseCsvKv}from"../../core/item/parse.js";function hasAdmittedTestCommand(command){if(!command?.trim())return!1;try{return assertLinkedTestCommand(command.trim()),!0}catch{return!1}}function structuredTestReplacement(value){try{const{command,...metadata}=normalizeStructuredLinkedTestEntry(parseCsvKv(value,"--add"),"--add");return hasAdmittedTestCommand(command)?["--add",value]:["command=<actual command>",...Object.entries(metadata).map(([key,entry])=>`${key}=${JSON.stringify(entry)}`)].join(",")}catch{return}}function hasOnlyPresentationSuffix(args){for(let index=0;index<args.length;index+=1){const token=args[index];if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)&&token!=="--all")continue;const flag=token.split("=",1)[0];if(!GLOBAL_VALUE_CONSUMING_FLAGS.has(flag)||["--author","--path","--pm-path"].includes(flag))return!1;if(!token.includes("=")){const value=args[++index];if(value===void 0||value.startsWith("-"))return!1}}return!0}function positionalOperands(command,argv){const start=findBootstrapCommandTokenIndex(argv);if(start===void 0)return;const namespaced=findPmNamespacedCommand(argv.slice(start));if((namespaced?.alias??argv[start])!==command)return;const idIndex=start+(namespaced?.canonical_argv.length??1),id=argv[idIndex],value=argv[idIndex+1];if(!(!id||id==="add"||id.startsWith("-"))&&!(!value||value.startsWith("-"))&&hasOnlyPresentationSuffix(argv.slice(idIndex+2)))return{idIndex,value}}function replacementArgs(command,value){const key=/^[A-Za-z_][A-Za-z0-9_]*=/u.exec(value)?.[0];if(command==="test")return key?["command=","cmd="].includes(key)?structuredTestReplacement(value):STRUCTURED_LINKED_TEST_KEYS.includes(key.slice(0,-1))?`command=<actual command>,${value}`:void 0:hasAdmittedTestCommand(value)?["--add-json",JSON.stringify({command:value})]:"command=<actual command>";if(!(key&&key!=="path="))return["--add",key?value:`path=${JSON.stringify(value)}`]}function resolveLinkedResourcePositionalRecovery(command,argv){if(command===void 0||!["files","docs","test"].includes(command))return;const operands=positionalOperands(command,argv);if(!operands)return;const{idIndex,value}=operands,itemId=argv[idIndex],replacement=replacementArgs(command,value);if(replacement!==void 0)return typeof replacement=="string"?{itemId,value,templateArgs:[...argv.slice(0,idIndex+1),"--add",replacement,...argv.slice(idIndex+2)]}:{itemId,value,retryArgs:[...argv.slice(0,idIndex+1),...replacement,...argv.slice(idIndex+2)]}}export{resolveLinkedResourcePositionalRecovery};
2
+ //# sourceMappingURL=linked-resource-recovery.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]="e69bd52d-7844-5de6-ade5-c4c3a6713df2")}catch{}})();import{resolvePmCommandAlias,PM_HISTORY_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,resolvePmHistoryOperation}from"./command-aliases.js";const PM_CLI_GRAMMAR_NOUNS=["item","list","context","search","graph","history","workspace","package","ops","plan","contracts","help"],PM_CLI_SHARED_VERBS=["acknowledge","activate","add","adopt","adopt-all","catalog","compact","complete","create","deactivate","delete","describe","doctor","edit","explore","import","init","inspect","install","list","manage","migrate","mutate","read","redact","reload","remove","reopen","repair","restore","run","show","uninstall","upgrade","verify"];function positionalSlot(name,valueKind,required,options={}){return{name,required,variadic:options.variadic===!0,value_kind:valueKind,polymorphic:options.polymorphic===!0}}function positionalActionVerb(action){const phrase=action.replaceAll("-"," ");return`${phrase.charAt(0).toUpperCase()}${phrase.slice(1)}`}const ITEM_ID=positionalSlot("id","item_id",!0),OPTIONAL_ITEM_ID=positionalSlot("id","item_id",!1),OPTIONAL_TEXT=positionalSlot("text","string",!1),PLAN_ITEM_ID=positionalSlot("plan-id","item_id",!0),PLAN_STEP=positionalSlot("step","string",!0),PLAN_CREATE_FLAGS=["--acceptance-criteria","--actual-result","--affected-version","--assignee","--blocked-by","--blocked-reason","--blocks","--body","--claim","--comment","--component","--confidence","--create-mode","--customer-impact","--deadline","--definition-of-ready","--description","--doc","--environment","--estimate","--event","--expected-result","--fixed-version","--file","--from-search","--goal","--harness","--impact","--learning","--message","--mode","--note","--objective","--order","--outcome","--parent","--priority","--rank","--related","--release","--reminder","--reporter","--repro-steps","--resolution","--resume-context","--reviewer","--risk","--scope","--severity","--sprint","--status","--step","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-replacement","--step-status","--step-title","--tags","--template","--test","--title","--type-option","--unblock-note","--value","--why-now"],PLAN_STEP_FLAGS=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"],PLAN_STEP_ACTION_DESCRIPTIONS={"update-step":"Update one declared Plan step.","complete-step":"Complete one declared Plan step.","block-step":"Block one declared Plan step.","remove-step":"Remove one declared Plan step.",link:"Link one dependency to a declared Plan step.",unlink:"Unlink one dependency from a declared Plan step."},PM_POSITIONAL_ACTION_CONTRACTS=[{command:"plan create",parent:"plan",action:"create",slots:[positionalSlot("title","string",!1,{polymorphic:!0})],accepted_flags:PLAN_CREATE_FLAGS,description:"Create a Plan item and optionally seed its ordered steps.",example:'pm plan create --title "Refactor lock retry"'},{command:"plan show",parent:"plan",action:"show",slots:[PLAN_ITEM_ID],accepted_flags:["--depth","--fields"],description:"Read one Plan item with a bounded plan projection.",example:"pm plan show pm-a1b2 --depth standard"},{command:"plan add-step",parent:"plan",action:"add-step",slots:[PLAN_ITEM_ID],accepted_flags:PLAN_STEP_FLAGS,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(PLAN_STEP_ACTION_DESCRIPTIONS).map(([action,description])=>({command:`plan ${action}`,parent:"plan",action,slots:[PLAN_ITEM_ID,PLAN_STEP],accepted_flags:PLAN_STEP_FLAGS,description,example:`pm plan ${action} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[PLAN_ITEM_ID,PLAN_STEP,positionalSlot("new-order","integer",!0)],accepted_flags:["--force","--message"],description:"Move one Plan step to a declared integer order.",example:"pm plan reorder-step pm-a1b2 plan-step-001 2"},...["decision","discovery","validation","resume","approve","materialize"].map(action=>({command:`plan ${action}`,parent:"plan",action,slots:[PLAN_ITEM_ID],accepted_flags:PLAN_STEP_FLAGS,description:`${positionalActionVerb(action)} for one Plan item.`,example:`pm plan ${action} pm-a1b2`})),...["list","show","put","remove"].map(action=>({command:`assurance ${action}`,parent:"assurance",action,slots:[positionalSlot("kind","string",!0),...action==="list"?[]:[positionalSlot("id","string",!0)]],accepted_flags:action==="put"?["--author","--definition","--message"]:action==="remove"?["--author","--message"]:[],description:`${positionalActionVerb(action)} assurance declarations by kind.`,example:action==="list"?"pm assurance list measurement":`pm assurance ${action} measurement example-id`})),{command:"assurance run",parent:"assurance",action:"run",slots:[positionalSlot("gate-id","string",!0)],accepted_flags:["--dry-run","--trigger","--tree"],description:"Evaluate one assurance gate for a lifecycle trigger.",example:"pm assurance run tracker-context-quality --trigger ci --dry-run"},{command:"assurance verdicts",parent:"assurance",action:"verdicts",slots:[positionalSlot("gate-id","string",!1)],accepted_flags:["--gate","--limit"],description:"List bounded assurance verdict history.",example:"pm assurance verdicts --limit 20"},...["presets","apply"].map(action=>({command:`assurance ${action}`,parent:"assurance",action,slots:[positionalSlot("preset","string",action==="apply")],accepted_flags:["--author","--message","--owner"],description:action==="apply"?"Apply one assurance adoption preset.":"List available assurance adoption presets.",example:action==="apply"?"pm assurance apply software-delivery --owner <pm-item-id>":"pm assurance presets"})),{command:"assurance derive",parent:"assurance",action:"derive",slots:[],accepted_flags:["--apply","--author","--message","--owner"],description:"Derive assurance proposals from current project context.",example:"pm assurance derive --owner pm-a1b2"},{command:"assurance promote",parent:"assurance",action:"promote",slots:[positionalSlot("assertion-id","string",!0)],accepted_flags:["--author","--enforcement","--message"],description:"Promote one assertion into a warning or blocking gate.",example:"pm assurance promote assertion-id --enforcement warn"},{command:"assurance risk",parent:"assurance",action:"risk",slots:[],accepted_flags:["--definition"],description:"Analyze bounded defect-recurrence risk for a proposed change.",example:`pm assurance risk --definition '{"policy":{"version":1,"evidence_epoch":"2026-01-01T00:00:00.000Z","families":[]},"change":{"files":[]}}'`},{command:"assurance lineages",parent:"assurance",action:"lineages",slots:[],accepted_flags:["--definition"],description:"Measure all recorded recurrence lineages with bounded evidence rows.",example:`pm assurance lineages --definition '{"policy":{"version":1,"evidence_epoch":"2026-01-01T00:00:00.000Z","families":[]}}'`},{command:"workspace position",parent:"workspace",action:"position",slots:[],accepted_flags:[],description:"Read bounded merge-fence, receipt, history-drift, and next-action readiness.",example:"pm workspace position"},{command:"workspace snapshot create",parent:"workspace snapshot",action:"create",slots:[positionalSlot("name","string",!1)],accepted_flags:[],description:"Capture authoritative tracker state as an immutable snapshot.",example:"pm workspace snapshot create before-migration"},{command:"workspace snapshot list",parent:"workspace snapshot",action:"list",slots:[],accepted_flags:[],description:"List immutable workspace snapshots and named references.",example:"pm workspace snapshot list"},{command:"workspace snapshot inspect",parent:"workspace snapshot",action:"inspect",slots:[positionalSlot("target","string",!0)],accepted_flags:[],description:"Inspect one workspace snapshot target.",example:"pm workspace snapshot inspect before-migration"},{command:"workspace snapshot restore",parent:"workspace snapshot",action:"restore",slots:[positionalSlot("target","string",!0)],accepted_flags:["--author","--dry-run","--force","--message"],description:"Restore an immutable workspace snapshot with explicit recovery controls.",example:"pm workspace snapshot restore before-migration --dry-run"},{command:"workspace snapshot delete",parent:"workspace snapshot",action:"delete",slots:[positionalSlot("target","string",!0)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}],POSITIONAL_ACTION_CONTRACTS_BY_SPECIFICITY=[...PM_POSITIONAL_ACTION_CONTRACTS].sort((left,right)=>right.command.length-left.command.length),EXPLICIT_POSITIONAL_SLOTS=new Map([["append",[ITEM_ID,OPTIONAL_TEXT]],["assurance",[positionalSlot("action","action",!0),positionalSlot("kind","string",!1),positionalSlot("id","string",!1)]],["beads import",[positionalSlot("file","string",!1)]],["cal",[positionalSlot("view","string",!1,{polymorphic:!0})]],["calendar",[positionalSlot("view","string",!1,{polymorphic:!0})]],["changelog export",[positionalSlot("file","string",!1)]],["claim",[OPTIONAL_ITEM_ID]],["close",[ITEM_ID,OPTIONAL_TEXT]],["close-task",[ITEM_ID,positionalSlot("reason","string",!1)]],["comments",[ITEM_ID,OPTIONAL_TEXT]],["completion",[positionalSlot("shell","string",!1)]],["config",[positionalSlot("scope","string",!1,{polymorphic:!0}),positionalSlot("action","action",!1),positionalSlot("key","string",!1),positionalSlot("value","string",!1,{polymorphic:!0})]],["copy",[ITEM_ID]],["create",[positionalSlot("type-or-title","string",!1,{polymorphic:!0}),positionalSlot("title","string",!1)]],["delete",[ITEM_ID]],["deps",[ITEM_ID]],["docs",[ITEM_ID]],["event",[positionalSlot("title","string",!0)]],["files",[ITEM_ID]],["files discover",[ITEM_ID]],["files lookup",[positionalSlot("paths","string",!0,{variadic:!0})]],["focus",[OPTIONAL_ITEM_ID]],["get",[ITEM_ID]],["graph",[positionalSlot("subcommand","action",!0),OPTIONAL_ITEM_ID,positionalSlot("target","item_id",!1)]],["guide",[positionalSlot("topic","string",!1)]],["history",[ITEM_ID]],["history-compact",[OPTIONAL_ITEM_ID]],["history-redact",[ITEM_ID]],["history-repair",[OPTIONAL_ITEM_ID]],["init",[positionalSlot("prefix-or-path","string",!1,{polymorphic:!0})]],["item complete",[ITEM_ID,positionalSlot("reason","string",!1)]],["item reopen",[ITEM_ID,positionalSlot("reason","string",!0)]],["learnings",[ITEM_ID,OPTIONAL_TEXT]],["meet",[positionalSlot("title","string",!0)]],["merge",[positionalSlot("subcommand","action",!0),positionalSlot("artifact","string",!1),positionalSlot("base","string",!1),positionalSlot("ours","string",!1),positionalSlot("theirs","string",!1)]],["notes",[ITEM_ID,OPTIONAL_TEXT]],["package",[positionalSlot("target","string",!1,{polymorphic:!0})]],["package list",[]],["package inventory",[positionalSlot("name","string",!1)]],["package scaffold",[positionalSlot("target","string",!0)]],["package upgrade",[positionalSlot("target","string",!1)]],["packages",[positionalSlot("target","string",!1,{polymorphic:!0})]],["packages list",[]],["packages inventory",[positionalSlot("name","string",!1)]],["packages scaffold",[positionalSlot("target","string",!0)]],["packages upgrade",[positionalSlot("target","string",!1)]],["pause-task",[ITEM_ID]],["plan",[positionalSlot("subcommand","action",!0),positionalSlot("id","item_id",!1,{polymorphic:!0}),positionalSlot("step","string",!1),positionalSlot("new-order","integer",!1)]],["profile",[positionalSlot("subcommand","action",!0),positionalSlot("name","string",!1)]],["release",[ITEM_ID]],["remind",[positionalSlot("title","string",!0)]],["restore",[ITEM_ID,positionalSlot("target","string",!0)]],["schema",[positionalSlot("subcommand","action",!0),positionalSlot("name","string",!1)]],["search-advanced",[positionalSlot("keywords","string",!0,{variadic:!0})]],["search",[positionalSlot("keywords","string",!0,{variadic:!0})]],["start-task",[ITEM_ID]],["templates save",[positionalSlot("name","string",!0)]],["templates show",[positionalSlot("name","string",!0)]],["telemetry",[positionalSlot("namespace-or-subcommand","action",!1,{polymorphic:!0}),positionalSlot("subcommand","action",!1)]],["test",[ITEM_ID]],["test-runs-worker",[positionalSlot("runId","string",!0)]],["update",[ITEM_ID]],["workspace snapshot",[positionalSlot("action","action",!0),positionalSlot("target","string",!1)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("target","string",!0)]])),...["describe"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("target","string",!1)]])),...["install"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("targets","string",!1,{variadic:!0})]])),["vcs abandon",[ITEM_ID]],["vcs create",[positionalSlot("title","string",!0)]],["vcs merge",[ITEM_ID]],["vcs propose",[ITEM_ID]],["vcs ref-create",[positionalSlot("name","string",!0)]],["vcs show",[ITEM_ID]]]);function normalizePositionalCommandPath(command){return command.trim().toLowerCase().replace(/\s+/gu," ")}function resolvePmCommandPositionalContract(command){const normalized=normalizePositionalCommandPath(command),direct=PM_COMMAND_POSITIONAL_CONTRACTS.find(contract=>contract.command===normalized);if(direct)return direct;const canonical=resolvePmCommandAlias(normalized)?.canonical;if(canonical)return PM_COMMAND_POSITIONAL_CONTRACTS.find(contract=>contract.command===canonical)}function resolvePmPositionalActionContract(command){const normalized=normalizePositionalCommandPath(command);return POSITIONAL_ACTION_CONTRACTS_BY_SPECIFICITY.find(contract=>contract.command===normalized||normalized.startsWith(`${contract.command} `))}function formatPmPositionalActionFlagTip(acceptedFlags){return`Applicable flags: ${acceptedFlags.length>0?acceptedFlags.join(", "):"none"}.`}function destinationRows(noun,target,disposition,owner,commands){return commands.map(command=>({command,noun,target,disposition,owner}))}const PM_COMMAND_DESTINATION_CONTRACTS=[...destinationRows("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...destinationRows("item","item","consolidation","pm-yql1",["append","close-many","close-task","comments","copy","delete","deps","docs","files","learnings","notes","pause-task","start-task","test","update-many"]),...["claim","close","create","get","release","update"].map(command=>({command,noun:"item",target:command,disposition:"keep_as_is",owner:"pm-pbyu",reason:"Permanent high-frequency item operations retain concise root spellings under the accepted hot-path grammar policy."})),...destinationRows("item","item files","target_noun","pm-yql1",["files discover","files lookup","item files discover","item files lookup"]),...destinationRows("item","item test worker","consolidation","pm-lp4j",["test-runs-worker"]),...destinationRows("list","list","target_noun","pm-pfqi",["list"]),...destinationRows("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...destinationRows("context","context","target_noun","pm-pbyu",["context"]),...destinationRows("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...destinationRows("context","context next","consolidation","pm-kcs4",["ctx next"]),...destinationRows("context","context focus","consolidation","pm-kcs4",["ctx focus"]),...destinationRows("search","search","target_noun","pm-pbyu",["search"]),...destinationRows("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...destinationRows("item","item duplicates","consolidation","pm-fmy9ih",["duplicates"]),...destinationRows("item","item duplicates","package_owned","pm-fmy9ih",["dedupe-audit","dedupe-merge","comments-audit"]),...destinationRows("graph","graph","target_noun","pm-pbyu",["graph"]),...destinationRows("history","history","target_noun","pm-pbyu",["history"]),...destinationRows("history","history attest","target_noun","pm-3z0k",["history attest"]),...destinationRows("history","history attest","consolidation","pm-3z0k",["history-attest"]),...PM_HISTORY_COMMAND_ALIASES.flatMap(({alias,canonical})=>[...destinationRows("history",canonical,"target_noun","pm-tqel",[canonical]),...destinationRows("history",canonical,"consolidation","pm-tqel",[alias])]),...destinationRows("history","history","consolidation","pm-tqel",["events","merge"]),...destinationRows("history","history acknowledge","consolidation","pm-djyvbk",["history-author-acknowledge"]),...destinationRows("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...destinationRows("workspace","workspace","target_noun","pm-pbyu",["workspace","workspace position","workspace snapshot","workspace snapshot create","workspace snapshot delete","workspace snapshot inspect","workspace snapshot list","workspace snapshot restore"]),...destinationRows("workspace","workspace init","consolidation","pm-npr3",["init"]),...destinationRows("package","package","target_noun","pm-pbyu",["package","package activate","package adopt","package adopt-all","package catalog","package deactivate","package describe","package doctor","package explore","package init","package install","package inventory","package list","package manage","package migrate","package reload","package scaffold","package uninstall","package upgrade"]),...destinationRows("package","package","consolidation","pm-tnud",["extension activate","extension adopt","extension adopt-all","extension catalog","extension deactivate","extension describe","extension doctor","extension explore","extension init","extension install","extension manage","extension migrate","extension reload","extension uninstall","packages","packages activate","packages adopt","packages adopt-all","packages catalog","packages deactivate","packages describe","packages doctor","packages explore","packages init","packages install","packages inventory","packages list","packages manage","packages migrate","packages reload","packages scaffold","packages uninstall","packages upgrade"]),...destinationRows("package","package","package_owned","package:beads",["beads import"]),...destinationRows("package","package","package_owned","package:pm-changelog",["changelog export","changelog generate"]),...destinationRows("package","package calendar","package_owned","pm-o3fh",["cal","calendar","event","meet","remind"]),...destinationRows("ops","ops","target_noun","pm-6apl",["ops"]),...destinationRows("ops","ops normalize","package_owned","package:pm-governance-audit",["normalize"]),...destinationRows("ops","ops","consolidation","pm-6apl",["eval","gc","health","stats","telemetry","test-all","validate"]),...destinationRows("workspace","workspace","consolidation","pm-npr3",["config","profile","schema"]),...["assurance",...PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent})=>parent==="assurance").map(({command})=>command)].map(command=>({command,noun:"ops",target:command,disposition:"keep_as_is",owner:"pm-djyvbk",reason:"Assurance manages durable measurement, assertion, gate, and verdict data; retain its established domain surface independently of operational diagnostics."})),...destinationRows("plan","plan","target_noun","pm-pbyu",["plan"]),...destinationRows("plan","plan","target_noun","pm-2tan",PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent})=>parent==="plan").map(({command})=>command)),...destinationRows("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...destinationRows("help","help","target_noun","pm-pbyu",["help"]),...destinationRows("workspace","templates","package_owned","package:builtin-templates",["templates","templates list","templates save","templates show"]),...destinationRows("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])].flatMap(entry=>{const alias=PM_RELOCATED_COMMAND_ALIASES.find(candidate=>candidate.alias===entry.command);if(!alias)return[entry];const noun=PM_CLI_GRAMMAR_NOUNS.find(candidate=>candidate===alias.canonical_argv[0])??entry.noun;return[{...entry,noun,target:alias.canonical,owner:alias.owner},{...entry,command:alias.canonical,noun,target:alias.canonical,owner:alias.owner,disposition:entry.disposition==="package_owned"?"package_owned":"target_noun"}]}),PM_COMMAND_POSITIONAL_CONTRACTS=[...new Set(PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command))].map(command=>({command,slots:resolvePmPositionalActionContract(command)?.slots??EXPLICIT_POSITIONAL_SLOTS.get(resolvePmHistoryOperation(command))??[]})),PM_CLI_GRAMMAR_CONTRACT={nouns:PM_CLI_GRAMMAR_NOUNS,shared_verbs:PM_CLI_SHARED_VERBS,scope_before_verb:!0,visible_top_level_ceiling:69,ceiling_raise_requires_pm_item:!0,positional_shape_budget:21};function verifyExplicitPositionalSlotCensus(explicitCommands,destinationCommands){const destinations=new Set(destinationCommands);return[...new Set(explicitCommands)].filter(command=>!destinations.has(command)).map(command=>({code:"positional_signature_mismatch",command,detail:`Positional signature ${command} has no destination declaration.`}))}function positionalShapeKey(slots){return slots.map(({required,variadic,value_kind:valueKind,polymorphic})=>`${required?"r":"o"}:${variadic?"v":"s"}:${valueKind}:${polymorphic?"p":"m"}`).join("|")}function positionalSignatureKey(slots){return slots.map(({name,required,variadic,value_kind:valueKind,polymorphic})=>`${name}:${required?"r":"o"}:${variadic?"v":"s"}:${valueKind}:${polymorphic?"p":"m"}`).join("|")}function duplicatePositionalSignatureFindings(contracts,surface){const counts=new Map;for(const{command}of contracts){const normalized=normalizePositionalCommandPath(command);counts.set(normalized,(counts.get(normalized)??0)+1)}return[...counts.entries()].filter(([,count])=>count>1).map(([command,count])=>({code:"positional_signature_mismatch",command,detail:`${count} ${surface} positional signatures exist for ${command}; exactly one is required.`}))}function verifyPmCommandPositionalContracts(observed,options={}){const declared=options.declared??PM_COMMAND_POSITIONAL_CONTRACTS,positionalShapeBudget=options.positionalShapeBudget??PM_CLI_GRAMMAR_CONTRACT.positional_shape_budget,declaredByCommand=new Map(declared.map(contract=>[normalizePositionalCommandPath(contract.command),contract])),observedByCommand=new Map(observed.map(contract=>[normalizePositionalCommandPath(contract.command),contract])),findings=[...duplicatePositionalSignatureFindings(declared,"declared"),...duplicatePositionalSignatureFindings(observed,"observed"),...options.declared===void 0?[...verifyExplicitPositionalSlotCensus(EXPLICIT_POSITIONAL_SLOTS.keys(),PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command)),...verifyExplicitPositionalSlotCensus(PM_POSITIONAL_ACTION_CONTRACTS.map(({command})=>command),PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command))]:[]];for(const contract of declaredByCommand.values()){const normalizedCommand=normalizePositionalCommandPath(contract.command),actual=observedByCommand.get(normalizedCommand);actual?positionalSignatureKey(actual.slots)!==positionalSignatureKey(contract.slots)&&findings.push({code:"positional_signature_mismatch",command:contract.command,detail:`Observed positional signature for ${contract.command} differs from its declared SDK contract: observed=${positionalSignatureKey(actual.slots)||"<none>"}; declared=${positionalSignatureKey(contract.slots)||"<none>"}.`}):findings.push({code:"missing_observed_signature",command:contract.command,detail:`No observed positional signature exists for ${contract.command}.`})}for(const contract of observedByCommand.values())declaredByCommand.has(normalizePositionalCommandPath(contract.command))||findings.push({code:"stale_observed_signature",command:contract.command,detail:`Observed positional signature ${contract.command} has no declaration.`});const positionalShapeCount=new Set(declared.map(({slots})=>positionalShapeKey(slots))).size;return positionalShapeCount>positionalShapeBudget&&findings.push({code:"positional_shape_budget_exceeded",command:"*",detail:`Distinct positional shape count ${positionalShapeCount} exceeds budget ${positionalShapeBudget}.`}),findings.sort((left,right)=>left.command!==right.command?left.command.localeCompare(right.command):left.code.localeCompare(right.code)),{ok:findings.length===0,declared_command_count:declared.length,observed_command_count:observed.length,positional_shape_count:positionalShapeCount,positional_shape_budget:positionalShapeBudget,findings}}function validateCommandDestinations(commands,destinationsByCommand,nounSet){return commands.flatMap(command=>{const destinations=destinationsByCommand.get(command)??[];if(destinations.length===0){const separatorIndex=command.indexOf(" "),root=separatorIndex===-1?command:command.slice(0,separatorIndex);return[{code:"missing_destination",spelling:command,message:`Command \`${command}\` has no destination census row.`,nearest_target:nounSet.has(root)?root:`ops ${command}`}]}const duplicateFinding=destinations.length>1?[{code:"duplicate_destination",spelling:command,message:`Command \`${command}\` has ${destinations.length} destination rows.`,nearest_target:destinations[0].target}]:[];return destinations.reduce((findings,destination)=>(destination.disposition==="keep_as_is"&&(destination.reason?.trim().length??0)===0&&findings.push({code:"missing_destination",spelling:command,message:`Command \`${command}\` is kept as-is without a documented reason.`,nearest_target:destination.target}),nounSet.has(destination.noun)||findings.push({code:"unknown_noun",spelling:command,message:`Command \`${command}\` names undeclared noun \`${destination.noun}\`.`,nearest_target:destination.target}),findings),duplicateFinding)})}function validateDestinationCensus(commandSet,destinations){return destinations.filter(destination=>destination.disposition!=="package_owned"&&!commandSet.has(destination.command)).map(destination=>({code:"stale_destination",spelling:destination.command,message:`Destination row \`${destination.command}\` is absent from live contracts.`,nearest_target:destination.target}))}function validateAliasTargets(aliases,commandSet){return aliases.filter(alias=>!commandSet.has(alias.canonical)).map(alias=>({code:"alias_target_missing",spelling:alias.alias,message:`Alias \`${alias.alias}\` targets missing canonical command \`${alias.canonical}\`.`,nearest_target:alias.canonical_argv.join(" ")}))}function verifyPmCliGrammar(commands,aliases=[],destinations=PM_COMMAND_DESTINATION_CONTRACTS){const normalizedCommands=[...new Set(commands.map(command=>command.trim()))].filter(command=>command.length>0).sort((left,right)=>left.localeCompare(right)),commandSet=new Set(normalizedCommands),nounSet=new Set(PM_CLI_GRAMMAR_NOUNS),destinationsByCommand=new Map;for(const destination of destinations){const entries=destinationsByCommand.get(destination.command)??[];entries.push(destination),destinationsByCommand.set(destination.command,entries)}const findings=[...validateCommandDestinations(normalizedCommands,destinationsByCommand,nounSet),...validateDestinationCensus(commandSet,destinations),...validateAliasTargets(aliases.filter(alias=>commandSet.has(alias.alias)||!(destinationsByCommand.get(alias.canonical)??[]).some(destination=>destination.disposition==="package_owned")),commandSet)],hiddenAliasNames=new Set(aliases.filter(alias=>alias.hidden).map(alias=>alias.alias)),visibleTopLevelCount=new Set(normalizedCommands.filter(command=>!command.includes(" ")&&!hiddenAliasNames.has(command)&&!(destinationsByCommand.get(command)??[]).some(destination=>destination.disposition==="package_owned"))).size;return visibleTopLevelCount>PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling&&findings.push({code:"visible_surface_ceiling_exceeded",spelling:String(visibleTopLevelCount),message:`Visible non-package top-level command count ${visibleTopLevelCount} exceeds ceiling ${PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling}.`,nearest_target:"Declare the noun placement and tracked waiver before raising the ceiling."}),{ok:findings.length===0,command_count:normalizedCommands.length,destination_count:destinations.length,hidden_alias_count:aliases.filter(alias=>alias.hidden).length,visible_top_level_count:visibleTopLevelCount,visible_top_level_ceiling:PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling,findings}}export{PM_CLI_GRAMMAR_CONTRACT,PM_CLI_GRAMMAR_NOUNS,PM_CLI_SHARED_VERBS,PM_COMMAND_DESTINATION_CONTRACTS,PM_COMMAND_POSITIONAL_CONTRACTS,PM_POSITIONAL_ACTION_CONTRACTS,formatPmPositionalActionFlagTip,positionalShapeKey,positionalSignatureKey,resolvePmCommandPositionalContract,resolvePmPositionalActionContract,verifyExplicitPositionalSlotCensus,verifyPmCliGrammar,verifyPmCommandPositionalContracts};
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]="32173550-b687-53ee-b51e-f66ab42958fd")}catch{}})();import{resolvePmCommandAlias,PM_HISTORY_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,resolvePmHistoryOperation}from"./command-aliases.js";const PM_CLI_GRAMMAR_NOUNS=["item","list","context","search","graph","history","workspace","package","ops","plan","contracts","help"],PM_CLI_SHARED_VERBS=["acknowledge","activate","add","adopt","adopt-all","catalog","compact","complete","create","deactivate","delete","describe","doctor","edit","explore","import","init","inspect","install","list","manage","migrate","mutate","read","redact","reload","remove","reopen","repair","restore","run","show","uninstall","upgrade","verify"];function positionalSlot(name,valueKind,required,options={}){return{name,required,variadic:options.variadic===!0,value_kind:valueKind,polymorphic:options.polymorphic===!0}}function positionalActionVerb(action){const phrase=action.replaceAll("-"," ");return`${phrase.charAt(0).toUpperCase()}${phrase.slice(1)}`}const ITEM_ID=positionalSlot("id","item_id",!0),OPTIONAL_ITEM_ID=positionalSlot("id","item_id",!1),OPTIONAL_TEXT=positionalSlot("text","string",!1),PLAN_ITEM_ID=positionalSlot("plan-id","item_id",!0),PLAN_STEP=positionalSlot("step","string",!0),PLAN_CREATE_FLAGS=["--acceptance-criteria","--actual-result","--affected-version","--assignee","--blocked-by","--blocked-reason","--blocks","--body","--claim","--comment","--component","--confidence","--create-mode","--customer-impact","--deadline","--definition-of-ready","--description","--doc","--environment","--estimate","--event","--expected-result","--fixed-version","--file","--from-search","--goal","--harness","--impact","--learning","--message","--mode","--note","--objective","--order","--outcome","--parent","--priority","--rank","--related","--release","--reminder","--reporter","--repro-steps","--resolution","--resume-context","--reviewer","--risk","--scope","--severity","--sprint","--status","--step","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-replacement","--step-status","--step-title","--tags","--template","--test","--title","--type-option","--unblock-note","--value","--why-now"],PLAN_STEP_FLAGS=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"],PLAN_STEP_ACTION_DESCRIPTIONS={"update-step":"Update one declared Plan step.","complete-step":"Complete one declared Plan step.","block-step":"Block one declared Plan step.","remove-step":"Remove one declared Plan step.",link:"Link one dependency to a declared Plan step.",unlink:"Unlink one dependency from a declared Plan step."},PM_POSITIONAL_ACTION_CONTRACTS=[{command:"plan create",parent:"plan",action:"create",slots:[positionalSlot("title","string",!1,{polymorphic:!0})],accepted_flags:PLAN_CREATE_FLAGS,description:"Create a Plan item and optionally seed its ordered steps.",example:'pm plan create --title "Refactor lock retry"'},{command:"plan show",parent:"plan",action:"show",slots:[PLAN_ITEM_ID],accepted_flags:["--depth","--fields"],description:"Read one Plan item with a bounded plan projection.",example:"pm plan show pm-a1b2 --depth standard"},{command:"plan add-step",parent:"plan",action:"add-step",slots:[PLAN_ITEM_ID],accepted_flags:PLAN_STEP_FLAGS,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(PLAN_STEP_ACTION_DESCRIPTIONS).map(([action,description])=>({command:`plan ${action}`,parent:"plan",action,slots:[PLAN_ITEM_ID,PLAN_STEP],accepted_flags:PLAN_STEP_FLAGS,description,example:`pm plan ${action} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[PLAN_ITEM_ID,PLAN_STEP,positionalSlot("new-order","integer",!0)],accepted_flags:["--force","--message"],description:"Move one Plan step to a declared integer order.",example:"pm plan reorder-step pm-a1b2 plan-step-001 2"},...["decision","discovery","validation","resume","approve","materialize"].map(action=>({command:`plan ${action}`,parent:"plan",action,slots:[PLAN_ITEM_ID],accepted_flags:PLAN_STEP_FLAGS,description:`${positionalActionVerb(action)} for one Plan item.`,example:`pm plan ${action} pm-a1b2`})),...["list","show","put","remove"].map(action=>({command:`assurance ${action}`,parent:"assurance",action,slots:[positionalSlot("kind","string",!0),...action==="list"?[]:[positionalSlot("id","string",!0)]],accepted_flags:action==="put"?["--author","--definition","--message"]:action==="remove"?["--author","--message"]:[],description:`${positionalActionVerb(action)} assurance declarations by kind.`,example:action==="list"?"pm assurance list measurement":`pm assurance ${action} measurement example-id`})),{command:"assurance run",parent:"assurance",action:"run",slots:[positionalSlot("gate-id","string",!0)],accepted_flags:["--dry-run","--trigger","--tree"],description:"Evaluate one assurance gate for a lifecycle trigger.",example:"pm assurance run tracker-context-quality --trigger ci --dry-run"},{command:"assurance verdicts",parent:"assurance",action:"verdicts",slots:[positionalSlot("gate-id","string",!1)],accepted_flags:["--gate","--limit"],description:"List bounded assurance verdict history.",example:"pm assurance verdicts --limit 20"},...["presets","apply"].map(action=>({command:`assurance ${action}`,parent:"assurance",action,slots:[positionalSlot("preset","string",action==="apply")],accepted_flags:["--author","--message","--owner"],description:action==="apply"?"Apply one assurance adoption preset.":"List available assurance adoption presets.",example:action==="apply"?"pm assurance apply software-delivery --owner <pm-item-id>":"pm assurance presets"})),{command:"assurance derive",parent:"assurance",action:"derive",slots:[],accepted_flags:["--apply","--author","--message","--owner"],description:"Derive assurance proposals from current project context.",example:"pm assurance derive --owner pm-a1b2"},{command:"assurance promote",parent:"assurance",action:"promote",slots:[positionalSlot("assertion-id","string",!0)],accepted_flags:["--author","--enforcement","--message"],description:"Promote one assertion into a warning or blocking gate.",example:"pm assurance promote assertion-id --enforcement warn"},{command:"assurance risk",parent:"assurance",action:"risk",slots:[],accepted_flags:["--definition"],description:"Analyze bounded defect-recurrence risk for a proposed change.",example:`pm assurance risk --definition '{"policy":{"version":1,"evidence_epoch":"2026-01-01T00:00:00.000Z","families":[]},"change":{"files":[]}}'`},{command:"assurance lineages",parent:"assurance",action:"lineages",slots:[],accepted_flags:["--definition"],description:"Measure all recorded recurrence lineages with bounded evidence rows.",example:`pm assurance lineages --definition '{"policy":{"version":1,"evidence_epoch":"2026-01-01T00:00:00.000Z","families":[]}}'`},{command:"workspace position",parent:"workspace",action:"position",slots:[],accepted_flags:[],description:"Read bounded merge-fence, receipt, history-drift, and next-action readiness.",example:"pm workspace position"},{command:"workspace snapshot create",parent:"workspace snapshot",action:"create",slots:[positionalSlot("name","string",!1)],accepted_flags:[],description:"Capture authoritative tracker state as an immutable snapshot.",example:"pm workspace snapshot create before-migration"},{command:"workspace snapshot list",parent:"workspace snapshot",action:"list",slots:[],accepted_flags:[],description:"List immutable workspace snapshots and named references.",example:"pm workspace snapshot list"},{command:"workspace snapshot inspect",parent:"workspace snapshot",action:"inspect",slots:[positionalSlot("target","string",!0)],accepted_flags:[],description:"Inspect one workspace snapshot target.",example:"pm workspace snapshot inspect before-migration"},{command:"workspace snapshot restore",parent:"workspace snapshot",action:"restore",slots:[positionalSlot("target","string",!0)],accepted_flags:["--author","--dry-run","--force","--message"],description:"Restore an immutable workspace snapshot with explicit recovery controls.",example:"pm workspace snapshot restore before-migration --dry-run"},{command:"workspace snapshot delete",parent:"workspace snapshot",action:"delete",slots:[positionalSlot("target","string",!0)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}],POSITIONAL_ACTION_CONTRACTS_BY_SPECIFICITY=[...PM_POSITIONAL_ACTION_CONTRACTS].sort((left,right)=>right.command.length-left.command.length),EXPLICIT_POSITIONAL_SLOTS=new Map([["append",[ITEM_ID,OPTIONAL_TEXT]],["assurance",[positionalSlot("action","action",!0),positionalSlot("kind","string",!1),positionalSlot("id","string",!1)]],["beads import",[positionalSlot("file","string",!1)]],["cal",[positionalSlot("view","string",!1,{polymorphic:!0})]],["calendar",[positionalSlot("view","string",!1,{polymorphic:!0})]],["changelog export",[positionalSlot("file","string",!1)]],["changelog milestone create",[positionalSlot("name","string",!0)]],["claim",[OPTIONAL_ITEM_ID]],["close",[ITEM_ID,OPTIONAL_TEXT]],["close-task",[ITEM_ID,positionalSlot("reason","string",!1)]],["comments",[ITEM_ID,OPTIONAL_TEXT]],["completion",[positionalSlot("shell","string",!1)]],["config",[positionalSlot("scope","string",!1,{polymorphic:!0}),positionalSlot("action","action",!1),positionalSlot("key","string",!1),positionalSlot("value","string",!1,{polymorphic:!0})]],["copy",[ITEM_ID]],["create",[positionalSlot("type-or-title","string",!1,{polymorphic:!0}),positionalSlot("title","string",!1)]],["delete",[ITEM_ID]],["deps",[ITEM_ID]],["docs",[ITEM_ID]],["event",[positionalSlot("title","string",!0)]],["files",[ITEM_ID]],["files discover",[ITEM_ID]],["files lookup",[positionalSlot("paths","string",!0,{variadic:!0})]],["focus",[OPTIONAL_ITEM_ID]],["get",[ITEM_ID]],["graph",[positionalSlot("subcommand","action",!0),OPTIONAL_ITEM_ID,positionalSlot("target","item_id",!1)]],["guide",[positionalSlot("topic","string",!1)]],["history",[ITEM_ID]],["history-compact",[OPTIONAL_ITEM_ID]],["history-redact",[ITEM_ID]],["history-repair",[OPTIONAL_ITEM_ID]],["init",[positionalSlot("prefix-or-path","string",!1,{polymorphic:!0})]],["item complete",[ITEM_ID,positionalSlot("reason","string",!1)]],["item reopen",[ITEM_ID,positionalSlot("reason","string",!0)]],["learnings",[ITEM_ID,OPTIONAL_TEXT]],["meet",[positionalSlot("title","string",!0)]],["merge",[positionalSlot("subcommand","action",!0),positionalSlot("artifact","string",!1),positionalSlot("base","string",!1),positionalSlot("ours","string",!1),positionalSlot("theirs","string",!1)]],["notes",[ITEM_ID,OPTIONAL_TEXT]],["package",[positionalSlot("target","string",!1,{polymorphic:!0})]],["package list",[]],["package inventory",[positionalSlot("name","string",!1)]],["package scaffold",[positionalSlot("target","string",!0)]],["package upgrade",[positionalSlot("target","string",!1)]],["packages",[positionalSlot("target","string",!1,{polymorphic:!0})]],["packages list",[]],["packages inventory",[positionalSlot("name","string",!1)]],["packages scaffold",[positionalSlot("target","string",!0)]],["packages upgrade",[positionalSlot("target","string",!1)]],["pause-task",[ITEM_ID]],["plan",[positionalSlot("subcommand","action",!0),positionalSlot("id","item_id",!1,{polymorphic:!0}),positionalSlot("step","string",!1),positionalSlot("new-order","integer",!1)]],["profile",[positionalSlot("subcommand","action",!0),positionalSlot("name","string",!1)]],["release",[ITEM_ID]],["remind",[positionalSlot("title","string",!0)]],["restore",[ITEM_ID,positionalSlot("target","string",!0)]],["schema",[positionalSlot("subcommand","action",!0),positionalSlot("name","string",!1)]],["search-advanced",[positionalSlot("keywords","string",!0,{variadic:!0})]],["search",[positionalSlot("keywords","string",!0,{variadic:!0})]],["start-task",[ITEM_ID]],["templates save",[positionalSlot("name","string",!0)]],["templates show",[positionalSlot("name","string",!0)]],["telemetry",[positionalSlot("namespace-or-subcommand","action",!1,{polymorphic:!0}),positionalSlot("subcommand","action",!1)]],["test",[ITEM_ID]],["test-runs-worker",[positionalSlot("runId","string",!0)]],["update",[ITEM_ID]],["workspace snapshot",[positionalSlot("action","action",!0),positionalSlot("target","string",!1)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("target","string",!0)]])),...["describe"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("target","string",!1)]])),...["install"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("targets","string",!1,{variadic:!0})]])),["vcs abandon",[ITEM_ID]],["vcs create",[positionalSlot("title","string",!0)]],["vcs merge",[ITEM_ID]],["vcs propose",[ITEM_ID]],["vcs ref-create",[positionalSlot("name","string",!0)]],["vcs show",[ITEM_ID]]]);function normalizePositionalCommandPath(command){return command.trim().toLowerCase().replace(/\s+/gu," ")}function resolvePmCommandPositionalContract(command){const normalized=normalizePositionalCommandPath(command),direct=PM_COMMAND_POSITIONAL_CONTRACTS.find(contract=>contract.command===normalized);if(direct)return direct;const canonical=resolvePmCommandAlias(normalized)?.canonical;if(canonical)return PM_COMMAND_POSITIONAL_CONTRACTS.find(contract=>contract.command===canonical)}function resolvePmPositionalActionContract(command){const normalized=normalizePositionalCommandPath(command);return POSITIONAL_ACTION_CONTRACTS_BY_SPECIFICITY.find(contract=>contract.command===normalized||normalized.startsWith(`${contract.command} `))}function formatPmPositionalActionFlagTip(acceptedFlags){return`Applicable flags: ${acceptedFlags.length>0?acceptedFlags.join(", "):"none"}.`}function destinationRows(noun,target,disposition,owner,commands){return commands.map(command=>({command,noun,target,disposition,owner}))}const PM_COMMAND_DESTINATION_CONTRACTS=[...destinationRows("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...destinationRows("item","item","consolidation","pm-yql1",["append","close-many","close-task","comments","copy","delete","deps","docs","files","learnings","notes","pause-task","start-task","test","update-many"]),...["claim","close","create","get","release","update"].map(command=>({command,noun:"item",target:command,disposition:"keep_as_is",owner:"pm-pbyu",reason:"Permanent high-frequency item operations retain concise root spellings under the accepted hot-path grammar policy."})),...destinationRows("item","item files","target_noun","pm-yql1",["files discover","files lookup","item files discover","item files lookup"]),...destinationRows("item","item test worker","consolidation","pm-lp4j",["test-runs-worker"]),...destinationRows("list","list","target_noun","pm-pfqi",["list"]),...destinationRows("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...destinationRows("context","context","target_noun","pm-pbyu",["context"]),...destinationRows("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...destinationRows("context","context next","consolidation","pm-kcs4",["ctx next"]),...destinationRows("context","context focus","consolidation","pm-kcs4",["ctx focus"]),...destinationRows("search","search","target_noun","pm-pbyu",["search"]),...destinationRows("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...destinationRows("item","item duplicates","consolidation","pm-fmy9ih",["duplicates"]),...destinationRows("item","item duplicates","package_owned","pm-fmy9ih",["dedupe-audit","dedupe-merge","comments-audit"]),...destinationRows("graph","graph","target_noun","pm-pbyu",["graph"]),...destinationRows("history","history","target_noun","pm-pbyu",["history"]),...destinationRows("history","history attest","target_noun","pm-3z0k",["history attest"]),...destinationRows("history","history attest","consolidation","pm-3z0k",["history-attest"]),...PM_HISTORY_COMMAND_ALIASES.flatMap(({alias,canonical})=>[...destinationRows("history",canonical,"target_noun","pm-tqel",[canonical]),...destinationRows("history",canonical,"consolidation","pm-tqel",[alias])]),...destinationRows("history","history","consolidation","pm-tqel",["events","merge"]),...destinationRows("history","history acknowledge","consolidation","pm-djyvbk",["history-author-acknowledge"]),...destinationRows("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...destinationRows("workspace","workspace","target_noun","pm-pbyu",["workspace","workspace position","workspace snapshot","workspace snapshot create","workspace snapshot delete","workspace snapshot inspect","workspace snapshot list","workspace snapshot restore"]),...destinationRows("workspace","workspace init","consolidation","pm-npr3",["init"]),...destinationRows("package","package","target_noun","pm-pbyu",["package","package activate","package adopt","package adopt-all","package catalog","package deactivate","package describe","package doctor","package explore","package init","package install","package inventory","package list","package manage","package migrate","package reload","package scaffold","package uninstall","package upgrade"]),...destinationRows("package","package","consolidation","pm-tnud",["extension activate","extension adopt","extension adopt-all","extension catalog","extension deactivate","extension describe","extension doctor","extension explore","extension init","extension install","extension manage","extension migrate","extension reload","extension uninstall","packages","packages activate","packages adopt","packages adopt-all","packages catalog","packages deactivate","packages describe","packages doctor","packages explore","packages init","packages install","packages inventory","packages list","packages manage","packages migrate","packages reload","packages scaffold","packages uninstall","packages upgrade"]),...destinationRows("package","package","package_owned","package:beads",["beads import"]),...destinationRows("package","package","package_owned","package:pm-changelog",["changelog audit","changelog export","changelog generate","changelog milestone create"]),...destinationRows("package","package calendar","package_owned","pm-o3fh",["cal","calendar","event","meet","remind"]),...destinationRows("ops","ops","target_noun","pm-6apl",["ops"]),...destinationRows("ops","ops normalize","package_owned","package:pm-governance-audit",["normalize"]),...destinationRows("ops","ops","consolidation","pm-6apl",["eval","gc","health","stats","telemetry","test-all","validate"]),...destinationRows("workspace","workspace","consolidation","pm-npr3",["config","profile","schema"]),...["assurance",...PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent})=>parent==="assurance").map(({command})=>command)].map(command=>({command,noun:"ops",target:command,disposition:"keep_as_is",owner:"pm-djyvbk",reason:"Assurance manages durable measurement, assertion, gate, and verdict data; retain its established domain surface independently of operational diagnostics."})),...destinationRows("plan","plan","target_noun","pm-pbyu",["plan"]),...destinationRows("plan","plan","target_noun","pm-2tan",PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent})=>parent==="plan").map(({command})=>command)),...destinationRows("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...destinationRows("help","help","target_noun","pm-pbyu",["help"]),...destinationRows("workspace","templates","package_owned","package:builtin-templates",["templates","templates list","templates save","templates show"]),...destinationRows("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])].flatMap(entry=>{const alias=PM_RELOCATED_COMMAND_ALIASES.find(candidate=>candidate.alias===entry.command);if(!alias)return[entry];const noun=PM_CLI_GRAMMAR_NOUNS.find(candidate=>candidate===alias.canonical_argv[0])??entry.noun;return[{...entry,noun,target:alias.canonical,owner:alias.owner},{...entry,command:alias.canonical,noun,target:alias.canonical,owner:alias.owner,disposition:entry.disposition==="package_owned"?"package_owned":"target_noun"}]}),PM_COMMAND_POSITIONAL_CONTRACTS=[...new Set(PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command))].map(command=>({command,slots:resolvePmPositionalActionContract(command)?.slots??EXPLICIT_POSITIONAL_SLOTS.get(resolvePmHistoryOperation(command))??[]})),PM_CLI_GRAMMAR_CONTRACT={nouns:PM_CLI_GRAMMAR_NOUNS,shared_verbs:PM_CLI_SHARED_VERBS,scope_before_verb:!0,visible_top_level_ceiling:69,ceiling_raise_requires_pm_item:!0,positional_shape_budget:21};function verifyExplicitPositionalSlotCensus(explicitCommands,destinationCommands){const destinations=new Set(destinationCommands);return[...new Set(explicitCommands)].filter(command=>!destinations.has(command)).map(command=>({code:"positional_signature_mismatch",command,detail:`Positional signature ${command} has no destination declaration.`}))}function positionalShapeKey(slots){return slots.map(({required,variadic,value_kind:valueKind,polymorphic})=>`${required?"r":"o"}:${variadic?"v":"s"}:${valueKind}:${polymorphic?"p":"m"}`).join("|")}function positionalSignatureKey(slots){return slots.map(({name,required,variadic,value_kind:valueKind,polymorphic})=>`${name}:${required?"r":"o"}:${variadic?"v":"s"}:${valueKind}:${polymorphic?"p":"m"}`).join("|")}function duplicatePositionalSignatureFindings(contracts,surface){const counts=new Map;for(const{command}of contracts){const normalized=normalizePositionalCommandPath(command);counts.set(normalized,(counts.get(normalized)??0)+1)}return[...counts.entries()].filter(([,count])=>count>1).map(([command,count])=>({code:"positional_signature_mismatch",command,detail:`${count} ${surface} positional signatures exist for ${command}; exactly one is required.`}))}function verifyPmCommandPositionalContracts(observed,options={}){const declared=options.declared??PM_COMMAND_POSITIONAL_CONTRACTS,positionalShapeBudget=options.positionalShapeBudget??PM_CLI_GRAMMAR_CONTRACT.positional_shape_budget,declaredByCommand=new Map(declared.map(contract=>[normalizePositionalCommandPath(contract.command),contract])),observedByCommand=new Map(observed.map(contract=>[normalizePositionalCommandPath(contract.command),contract])),findings=[...duplicatePositionalSignatureFindings(declared,"declared"),...duplicatePositionalSignatureFindings(observed,"observed"),...options.declared===void 0?[...verifyExplicitPositionalSlotCensus(EXPLICIT_POSITIONAL_SLOTS.keys(),PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command)),...verifyExplicitPositionalSlotCensus(PM_POSITIONAL_ACTION_CONTRACTS.map(({command})=>command),PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command))]:[]];for(const contract of declaredByCommand.values()){const normalizedCommand=normalizePositionalCommandPath(contract.command),actual=observedByCommand.get(normalizedCommand);actual?positionalSignatureKey(actual.slots)!==positionalSignatureKey(contract.slots)&&findings.push({code:"positional_signature_mismatch",command:contract.command,detail:`Observed positional signature for ${contract.command} differs from its declared SDK contract: observed=${positionalSignatureKey(actual.slots)||"<none>"}; declared=${positionalSignatureKey(contract.slots)||"<none>"}.`}):findings.push({code:"missing_observed_signature",command:contract.command,detail:`No observed positional signature exists for ${contract.command}.`})}for(const contract of observedByCommand.values())declaredByCommand.has(normalizePositionalCommandPath(contract.command))||findings.push({code:"stale_observed_signature",command:contract.command,detail:`Observed positional signature ${contract.command} has no declaration.`});const positionalShapeCount=new Set(declared.map(({slots})=>positionalShapeKey(slots))).size;return positionalShapeCount>positionalShapeBudget&&findings.push({code:"positional_shape_budget_exceeded",command:"*",detail:`Distinct positional shape count ${positionalShapeCount} exceeds budget ${positionalShapeBudget}.`}),findings.sort((left,right)=>left.command!==right.command?left.command.localeCompare(right.command):left.code.localeCompare(right.code)),{ok:findings.length===0,declared_command_count:declared.length,observed_command_count:observed.length,positional_shape_count:positionalShapeCount,positional_shape_budget:positionalShapeBudget,findings}}function validateCommandDestinations(commands,destinationsByCommand,nounSet){return commands.flatMap(command=>{const destinations=destinationsByCommand.get(command)??[];if(destinations.length===0){const separatorIndex=command.indexOf(" "),root=separatorIndex===-1?command:command.slice(0,separatorIndex);return[{code:"missing_destination",spelling:command,message:`Command \`${command}\` has no destination census row.`,nearest_target:nounSet.has(root)?root:`ops ${command}`}]}const duplicateFinding=destinations.length>1?[{code:"duplicate_destination",spelling:command,message:`Command \`${command}\` has ${destinations.length} destination rows.`,nearest_target:destinations[0].target}]:[];return destinations.reduce((findings,destination)=>(destination.disposition==="keep_as_is"&&(destination.reason?.trim().length??0)===0&&findings.push({code:"missing_destination",spelling:command,message:`Command \`${command}\` is kept as-is without a documented reason.`,nearest_target:destination.target}),nounSet.has(destination.noun)||findings.push({code:"unknown_noun",spelling:command,message:`Command \`${command}\` names undeclared noun \`${destination.noun}\`.`,nearest_target:destination.target}),findings),duplicateFinding)})}function validateDestinationCensus(commandSet,destinations){return destinations.filter(destination=>destination.disposition!=="package_owned"&&!commandSet.has(destination.command)).map(destination=>({code:"stale_destination",spelling:destination.command,message:`Destination row \`${destination.command}\` is absent from live contracts.`,nearest_target:destination.target}))}function validateAliasTargets(aliases,commandSet){return aliases.filter(alias=>!commandSet.has(alias.canonical)).map(alias=>({code:"alias_target_missing",spelling:alias.alias,message:`Alias \`${alias.alias}\` targets missing canonical command \`${alias.canonical}\`.`,nearest_target:alias.canonical_argv.join(" ")}))}function verifyPmCliGrammar(commands,aliases=[],destinations=PM_COMMAND_DESTINATION_CONTRACTS){const normalizedCommands=[...new Set(commands.map(command=>command.trim()))].filter(command=>command.length>0).sort((left,right)=>left.localeCompare(right)),commandSet=new Set(normalizedCommands),nounSet=new Set(PM_CLI_GRAMMAR_NOUNS),destinationsByCommand=new Map;for(const destination of destinations){const entries=destinationsByCommand.get(destination.command)??[];entries.push(destination),destinationsByCommand.set(destination.command,entries)}const findings=[...validateCommandDestinations(normalizedCommands,destinationsByCommand,nounSet),...validateDestinationCensus(commandSet,destinations),...validateAliasTargets(aliases.filter(alias=>commandSet.has(alias.alias)||!(destinationsByCommand.get(alias.canonical)??[]).some(destination=>destination.disposition==="package_owned")),commandSet)],hiddenAliasNames=new Set(aliases.filter(alias=>alias.hidden).map(alias=>alias.alias)),visibleTopLevelCount=new Set(normalizedCommands.filter(command=>!command.includes(" ")&&!hiddenAliasNames.has(command)&&!(destinationsByCommand.get(command)??[]).some(destination=>destination.disposition==="package_owned"))).size;return visibleTopLevelCount>PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling&&findings.push({code:"visible_surface_ceiling_exceeded",spelling:String(visibleTopLevelCount),message:`Visible non-package top-level command count ${visibleTopLevelCount} exceeds ceiling ${PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling}.`,nearest_target:"Declare the noun placement and tracked waiver before raising the ceiling."}),{ok:findings.length===0,command_count:normalizedCommands.length,destination_count:destinations.length,hidden_alias_count:aliases.filter(alias=>alias.hidden).length,visible_top_level_count:visibleTopLevelCount,visible_top_level_ceiling:PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling,findings}}export{PM_CLI_GRAMMAR_CONTRACT,PM_CLI_GRAMMAR_NOUNS,PM_CLI_SHARED_VERBS,PM_COMMAND_DESTINATION_CONTRACTS,PM_COMMAND_POSITIONAL_CONTRACTS,PM_POSITIONAL_ACTION_CONTRACTS,formatPmPositionalActionFlagTip,positionalShapeKey,positionalSignatureKey,resolvePmCommandPositionalContract,resolvePmPositionalActionContract,verifyExplicitPositionalSlotCensus,verifyPmCliGrammar,verifyPmCommandPositionalContracts};
2
2
  //# sourceMappingURL=grammar-contracts.js.map
@@ -14,6 +14,7 @@ import type { ToolOptionFlagContract } from "./flag-contracts.js";
14
14
  import type { CloseCommandOptions } from "../lifecycle/close.js";
15
15
  import type { CreateCommandOptions } from "../lifecycle/create.js";
16
16
  import type { UpdateCommandOptions } from "../lifecycle/update.js";
17
+ import type { UpdateManyCommandOptions } from "../lifecycle/update-many.js";
17
18
  import type { TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE } from "./tool-option-contracts.js";
18
19
  /** JSON-compatible scalar the SDK option-normalization layer accepts for one flag value (CLI flags arrive as strings; MCP and SDK callers may pass native numbers and booleans). */
19
20
  export type PmOptionScalar = string | number | boolean;
@@ -62,8 +63,8 @@ ids?:string | number | readonly (string | number)[];
62
63
  export type PmBulkMutationControlOptions = {
63
64
  /** Preview the bulk mutation without writing changes. */
64
65
  dryRun?:boolean;
65
- /** Roll back a previously checkpointed bulk mutation. */
66
- rollback?:boolean;
66
+ /** ID of the checkpoint whose committed bulk effects should be reversed. */
67
+ rollback?:UpdateManyCommandOptions["rollback"];
67
68
  /** Skip writing the crash-recovery checkpoint for this bulk mutation. */
68
69
  noCheckpoint?:boolean;
69
70
  };
@@ -11,7 +11,7 @@ export * from "./agent-session-context.js";
11
11
  export { isAlreadyClaimedError } from "./lifecycle/claim.js";
12
12
  export { PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions,} from "./read-output-contracts.js";
13
13
  export { applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,isReadOutputSessionReference,} from "./read-output-session.js";
14
- export type { PmReadOutputBudgetExceeded,PmReadOutputContinuation,PmReadOutputCursorEnvelope,PmReadOutputDimension,PmReadOutputLegacyAlias,PmReadOutputOptions,PmReadOutputProducerContinuation,PmReadOutputReceipt,PmReadOutputResult,PmReadOutputResultFor,PmReadOutputSessionResult,PmReadOutputSurface,PmReadOutputSurfaceContract,} from "./read-output-contracts.js";
14
+ export type { PmReadOutputBudgetExceeded,PmReadOutputContinuation,PmReadOutputCursorEnvelope,PmReadOutputDimension,PmReadOutputLegacyAlias,PmReadOutputOptions,PmReadOutputProducerContinuation,PmReadOutputReceipt,PmReadOutputMetadata,PmReadOutputResult,PmReadOutputResultFor,PmReadOutputSessionResult,PmReadOutputSurface,PmReadOutputSurfaceContract,} from "./read-output-contracts.js";
15
15
  export type { PmReadOutputSessionReceipt,PmReadOutputSessionReference,PmReadOutputSessionState,} from "./read-output-session.js";
16
16
  export type { ItemDocument,ItemMetadata,ItemStatus,ItemType,PmSettings,} from "../types/index.js";
17
17
  export type { CloseEvidenceFollowUp } from "./lifecycle-policy.js";
package/dist/sdk/core.js CHANGED
@@ -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]="3156fd3f-6fa1-53e3-9ef8-a63433f4bc1f")}catch{}})();import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,listAllComplete}from"./runtime.js";export*from"./core-governance.js";import{updateLinkedTest}from"./test/update.js";import{isItemAlreadyExistsError,isPmTokenBudgetRecovery}from"./errors.js";export*from"./agent-session-context.js";import{isAlreadyClaimedError}from"./lifecycle/claim.js";import{PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions}from"./read-output-contracts.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,isReadOutputSessionReference}from"./read-output-session.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,aggregate,append,applyReadOutputDimensions,applyReadOutputSessionReferences,attachReadOutputSessionReceipt,canonicalDocument,claim,claimNext,classifyItemFormatVersion,close,comments,context,copy,create,createPmCliExpectedError,decodeReadOutputContinuationCursor,deleteItem,deps,docs,effectiveItemFormatVersion,emptyImportedDocument,encodeReadOutputContinuationCursor,files,filesDiscover,focus,get,graph,isAlreadyClaimedError,isItemAlreadyExistsError,isPmCliExpectedError,isPmTokenBudgetRecovery,isReadOutputBudgetExceeded,isReadOutputSessionReference,learnings,list,listAllComplete,next,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,notes,nowIso,parseReadOutputSession,readOutputSessionRemainingTokens,release,reopen,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,restore,runAction,search,serializeItemDocument,update,updateLinkedTest,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]="8aaf0090-c67a-540b-b631-800aa480fb0b")}catch{}})();import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,listAllComplete}from"./runtime.js";export*from"./core-governance.js";import{updateLinkedTest}from"./test/update.js";import{isItemAlreadyExistsError,isPmTokenBudgetRecovery}from"./errors.js";export*from"./agent-session-context.js";import{isAlreadyClaimedError}from"./lifecycle/claim.js";import{PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions}from"./read-output-contracts.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,isReadOutputSessionReference}from"./read-output-session.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,aggregate,append,applyReadOutputDimensions,applyReadOutputSessionReferences,attachReadOutputSessionReceipt,canonicalDocument,claim,claimNext,classifyItemFormatVersion,close,comments,context,copy,create,createPmCliExpectedError,decodeReadOutputContinuationCursor,deleteItem,deps,docs,effectiveItemFormatVersion,emptyImportedDocument,encodeReadOutputContinuationCursor,files,filesDiscover,focus,get,graph,isAlreadyClaimedError,isItemAlreadyExistsError,isPmCliExpectedError,isPmTokenBudgetRecovery,isReadOutputBudgetExceeded,isReadOutputSessionReference,learnings,list,listAllComplete,next,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,notes,nowIso,parseReadOutputSession,readOutputSessionRemainingTokens,release,reopen,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,restore,runAction,search,serializeItemDocument,update,updateLinkedTest,validateReadOutputOptions};
2
2
  //# sourceMappingURL=core.js.map