@unbrained/pm-cli 2026.11.15 → 2026.11.16

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 (181) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/error-guidance.js +2 -2
  3. package/dist/cli/help-content.js +2 -2
  4. package/dist/cli/register-operations.js +1 -1
  5. package/dist/cli-bundle/bundle-manifest.json +1 -1
  6. package/dist/cli-bundle/chunks/{chunk-TESRFVGF.js → chunk-2D26HRXB.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-VWKLTHYQ.js → chunk-2WNORBVN.js} +36 -25
  8. package/dist/cli-bundle/chunks/{chunk-J6L3Q5J4.js → chunk-4I7YG3VZ.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-QZNDEZYI.js → chunk-4WIVCOA7.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-A3WCP4TU.js +6 -0
  11. package/dist/cli-bundle/chunks/chunk-AB5S6TWE.js +124 -0
  12. package/dist/cli-bundle/chunks/{chunk-KLWGIEDC.js → chunk-BV7J3LRH.js} +3 -3
  13. package/dist/cli-bundle/chunks/{chunk-GCSKHCYK.js → chunk-DZWRNL6R.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-KSLPRST2.js → chunk-E4BQRZF2.js} +3 -3
  15. package/dist/cli-bundle/chunks/chunk-ERD2RYWM.js +31 -0
  16. package/dist/cli-bundle/chunks/chunk-F7P42FL5.js +9 -0
  17. package/dist/cli-bundle/chunks/{chunk-E4B2HWH7.js → chunk-FZ4XWWLO.js} +23 -23
  18. package/dist/cli-bundle/chunks/{chunk-7AODVNHX.js → chunk-I3T2FVUA.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-PMIGRSNZ.js → chunk-IGEBFNWE.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-YLPZE2TK.js → chunk-IYICNCK2.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-J257NZRD.js +20 -0
  22. package/dist/cli-bundle/chunks/{chunk-Q6GBRK27.js → chunk-JD3XWF66.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-FSE624WQ.js → chunk-JLHD7OQ2.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-DBUBX4DL.js → chunk-KGOGLKL2.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-ZWUS65LN.js → chunk-LC4DJVXR.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-LC6DL446.js → chunk-NHNM3GIP.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-ZVDXGAYV.js → chunk-NYN5OR2T.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-6UTBX62V.js → chunk-OFZQEQ6X.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-GAFALSR2.js → chunk-QGL5IAP4.js} +3 -3
  30. package/dist/cli-bundle/chunks/{chunk-HMVZSXB4.js → chunk-R24NZ2TB.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-S5UXBECQ.js → chunk-VJLZHOTP.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-YJNY5MKP.js → chunk-VO2HSB5F.js} +2 -2
  33. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-42Y2CSEQ.js → indexed-receipt-blobs-HNLN6UXH.js} +2 -2
  34. package/dist/cli-bundle/chunks/{item-revision-JCEDTAVX.js → item-revision-PSOL5I4H.js} +2 -2
  35. package/dist/cli-bundle/chunks/item-transaction-55QTCU2M.js +2 -0
  36. package/dist/cli-bundle/chunks/{mutation-actor-IQHBRFAJ.js → mutation-actor-BDBBH3ZS.js} +2 -2
  37. package/dist/cli-bundle/chunks/{mutation-admission-DF6BFGG6.js → mutation-admission-WUN7JYVJ.js} +2 -2
  38. package/dist/cli-bundle/chunks/{register-list-query-DNKPQB76.js → register-list-query-AESCVO6H.js} +2 -2
  39. package/dist/cli-bundle/chunks/{register-mutation-WVTDFLEF.js → register-mutation-SKCEP5QU.js} +2 -2
  40. package/dist/cli-bundle/chunks/register-operations-ZT4OYCF3.js +2 -0
  41. package/dist/cli-bundle/chunks/{register-setup-2RTG3LII.js → register-setup-JVWNS2TY.js} +2 -2
  42. package/dist/cli-bundle/chunks/{settlement-hook-W5ULPKIE.js → settlement-hook-MVVVUIVZ.js} +2 -2
  43. package/dist/cli-bundle/chunks/{stage-YFNK7U26.js → stage-RMU3JAWM.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-YZUBG4W2.js → chunk-3WVMEA2A.js} +3 -3
  45. package/dist/cli-bundle/focused-chunks/{chunk-CZZKAGHE.js → chunk-5UVJOAUP.js} +6 -6
  46. package/dist/cli-bundle/focused-chunks/{chunk-EALGFJRP.js → chunk-5WQ3LNUK.js} +3 -3
  47. package/dist/cli-bundle/focused-chunks/chunk-6E4X7MQA.js +26 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-JE3MFEQZ.js → chunk-7SEPCQV2.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-XQZKGTZV.js → chunk-7XHE335U.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-52H6AELE.js → chunk-BEHIMEV2.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-JXA77YIV.js → chunk-CZFZCSOX.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-W2KIQ7RF.js → chunk-DFBHW7HP.js} +3 -3
  53. package/dist/cli-bundle/focused-chunks/{chunk-WGYR3X6O.js → chunk-DZMP3VYQ.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-HHMMIHZP.js +2 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-LSWUTTE6.js → chunk-HPC2M6JD.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-2UQFFVQK.js → chunk-HR5FEUUL.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-S6GTALM4.js → chunk-J7ESCE7M.js} +3 -3
  58. package/dist/cli-bundle/focused-chunks/chunk-KRNF3WTC.js +3 -0
  59. package/dist/cli-bundle/focused-chunks/{chunk-DXMQ32EH.js → chunk-KWZLY35A.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-Z6HCQYSW.js → chunk-M4IA4LC6.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-YTNUUEY6.js → chunk-NASE6JC2.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/chunk-ONM2R32I.js +65 -0
  63. package/dist/cli-bundle/focused-chunks/{chunk-QXOFSZR6.js → chunk-PDXSMSO5.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{chunk-BSY6FZ3Y.js → chunk-PEL4SQXV.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-DRBXOAGY.js → chunk-QJ647CQE.js} +2 -2
  66. package/dist/cli-bundle/focused-chunks/chunk-SFATIM77.js +12 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-7GCAZJT4.js → chunk-UBBTBNUY.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{chunk-UPUIDGNJ.js → chunk-ZCN35TCK.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-ZSQ2FT22.js +44 -0
  70. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-LSBWMXKS.js → indexed-receipt-blobs-ADMQXF3N.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{item-revision-YO7YGQYE.js → item-revision-GNKYO6GZ.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/{item-transaction-7A3Q4CAJ.js → item-transaction-AUUQHR5Z.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{mutation-actor-UQHBNHOF.js → mutation-actor-OBRD7HFZ.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{mutation-admission-G565NLPE.js → mutation-admission-6TX3EOJX.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/{settlement-hook-UXN76GMA.js → settlement-hook-5U2M75BY.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/{stage-F3YJGNRK.js → stage-LERF2YJU.js} +2 -2
  77. package/dist/cli-bundle/main.js +6 -6
  78. package/dist/cli-bundle/sdk-authoring.js +1 -1
  79. package/dist/cli-bundle/sdk-contracts.js +2 -2
  80. package/dist/cli-bundle/sdk-core.js +1 -1
  81. package/dist/cli-bundle/sdk-governance.js +1 -1
  82. package/dist/cli-bundle/sdk-graph.js +1 -1
  83. package/dist/cli-bundle/sdk-merge.js +57 -57
  84. package/dist/cli-bundle/sdk-query.js +1 -1
  85. package/dist/cli-bundle/sdk-runtime.js +1 -1
  86. package/dist/cli-bundle/sdk-testing.js +1 -1
  87. package/dist/cli-bundle/sdk.js +11 -11
  88. package/dist/core/diagnostics/remediation.js +1 -1
  89. package/dist/core/output/mutation-projection.js +1 -1
  90. package/dist/core/shared/errors.d.ts +22 -0
  91. package/dist/core/shared/errors.js +1 -1
  92. package/dist/core/store/item-store.d.ts +15 -4
  93. package/dist/core/store/item-store.js +1 -1
  94. package/dist/core/telemetry/policy.d.ts +21 -2
  95. package/dist/core/telemetry/policy.js +1 -1
  96. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  97. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  98. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  99. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  100. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  101. package/dist/sdk/completion/bash.js +1 -1
  102. package/dist/sdk/completion/fish.js +2 -1
  103. package/dist/sdk/completion/zsh.js +12 -2
  104. package/dist/sdk/flag-invocation-contracts.js +1 -1
  105. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  106. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  107. package/dist/sdk/governance/health.js +2 -2
  108. package/dist/sdk/governance/in-progress-work-health.d.ts +49 -0
  109. package/dist/sdk/governance/in-progress-work-health.js +2 -0
  110. package/dist/sdk/governance/stale-work.d.ts +143 -2
  111. package/dist/sdk/governance/stale-work.js +1 -1
  112. package/dist/sdk/governance.d.ts +1 -1
  113. package/dist/sdk/governance.js +1 -1
  114. package/dist/sdk/history-compact.js +1 -1
  115. package/dist/sdk/index.d.ts +1 -1
  116. package/dist/sdk/index.js +1 -1
  117. package/dist/sdk/lifecycle/claim.d.ts +46 -3
  118. package/dist/sdk/lifecycle/claim.js +1 -1
  119. package/dist/sdk/lifecycle/task-composition.js +1 -1
  120. package/dist/sdk/ownership-source.d.ts +32 -0
  121. package/dist/sdk/ownership-source.js +1 -1
  122. package/dist/sdk/public-surface.json +1 -1
  123. package/dist/sdk/query/context.d.ts +5 -1
  124. package/dist/sdk/query/context.js +2 -2
  125. package/dist/sdk/query/next.d.ts +19 -3
  126. package/dist/sdk/query/next.js +1 -1
  127. package/dist/sdk/runtime-input.js +1 -1
  128. package/dist/sdk/runtime-primitives.d.ts +1 -1
  129. package/dist/sdk/runtime-primitives.js +1 -1
  130. package/docs/AGENT_GUIDE.md +2 -0
  131. package/docs/COMMANDS.md +22 -0
  132. package/docs/CONFIGURATION.md +20 -7
  133. package/docs/LIFECYCLE_COMMANDS.md +8 -1
  134. package/docs/MUTATION_INTEGRITY.md +79 -1
  135. package/docs/SDK.md +28 -0
  136. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  137. package/marketplace.json +1 -1
  138. package/node_modules/commander/Readme.md +6 -32
  139. package/node_modules/commander/index.js +1 -1
  140. package/node_modules/commander/lib/command.js +22 -9
  141. package/node_modules/commander/lib/help.js +6 -2
  142. package/node_modules/commander/lib/option.js +1 -1
  143. package/node_modules/commander/package.json +2 -1
  144. package/node_modules/commander/typings/index.d.ts +6 -3
  145. package/node_modules/semver/classes/range.js +2 -2
  146. package/node_modules/semver/internal/constants.js +30 -0
  147. package/node_modules/semver/internal/trim-comparator-whitespace.js +438 -0
  148. package/node_modules/semver/package.json +1 -1
  149. package/package.json +3 -3
  150. package/packages/pm-beads/package.json +1 -1
  151. package/packages/pm-calendar/package.json +1 -1
  152. package/packages/pm-command-kit/package.json +1 -1
  153. package/packages/pm-digital-twin/package.json +1 -1
  154. package/packages/pm-governance-audit/package.json +1 -1
  155. package/packages/pm-guide-shell/package.json +1 -1
  156. package/packages/pm-kanban/package.json +1 -1
  157. package/packages/pm-lifecycle-hooks/package.json +1 -1
  158. package/packages/pm-linked-test-adapters/package.json +1 -1
  159. package/packages/pm-search-advanced/package.json +1 -1
  160. package/packages/pm-templates/package.json +1 -1
  161. package/packages/pm-todos/package.json +1 -1
  162. package/packages/pm-vcs/package.json +1 -1
  163. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  164. package/plugins/pm-claude/package.json +1 -1
  165. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  166. package/plugins/pm-codex/package.json +1 -1
  167. package/plugins/pm-codex/plugin.json +1 -1
  168. package/runtime-dependencies.json +1 -1
  169. package/dist/cli-bundle/chunks/chunk-ASGAELBQ.js +0 -9
  170. package/dist/cli-bundle/chunks/chunk-E74OMFBZ.js +0 -6
  171. package/dist/cli-bundle/chunks/chunk-FYOIH56R.js +0 -20
  172. package/dist/cli-bundle/chunks/chunk-IXV5UM4U.js +0 -31
  173. package/dist/cli-bundle/chunks/chunk-NAX554KY.js +0 -124
  174. package/dist/cli-bundle/chunks/item-transaction-BSMGKZ4S.js +0 -2
  175. package/dist/cli-bundle/chunks/register-operations-NR5MTT5T.js +0 -2
  176. package/dist/cli-bundle/focused-chunks/chunk-63FM3TIG.js +0 -26
  177. package/dist/cli-bundle/focused-chunks/chunk-FK2X6MJY.js +0 -44
  178. package/dist/cli-bundle/focused-chunks/chunk-JRRHN2PZ.js +0 -12
  179. package/dist/cli-bundle/focused-chunks/chunk-LQZ5F6LE.js +0 -3
  180. package/dist/cli-bundle/focused-chunks/chunk-RMCODWHZ.js +0 -65
  181. package/dist/cli-bundle/focused-chunks/chunk-WVYXR3YX.js +0 -2
@@ -1,6 +1,24 @@
1
- import{type GlobalOptions}from "../runtime-primitives.js";import type{ItemMetadata,PmSettings}from "../../types/index.js";import type{RuntimeStatusRegistry}from "../../core/schema/runtime-schema.js";import{type NextRecommendation,type NextOptions}from "../query/next.js";
1
+ import{type GlobalOptions,PmCliError}from "../runtime-primitives.js";import{type ClaimActivityEvidence,type ItemOwnershipActivity}from "../ownership-source.js";import type{ItemMetadata,PmSettings}from "../../types/index.js";import type{RuntimeStatusRegistry}from "../../core/schema/runtime-schema.js";import{type NextRecommendation,type NextOptions}from "../query/next.js";
2
2
  /** Stable warning/error code for an exhausted atomic next-work walk. */
3
3
  export declare const NO_AVAILABLE_NEXT_ITEM_CODE="no_available_next_item";
4
+ /** Stable refusal code when `--takeover-stale` meets a claim the stale-work policy still treats as active (GH-1336). */
5
+ export declare const STALE_CLAIM_TAKEOVER_REFUSED_CODE="stale_claim_takeover_refused";
6
+ /** Audited evidence of a policy-permitted stale-claim takeover, recorded in the claim's history context (GH-1336). */
7
+ export interface StaleClaimTakeoverReceipt{
8
+ /** Holder whose idle claim was taken over, redacted like every echoed identity. */
9
+ previous_holder:string;
10
+ /** Author that took the claim. */
11
+ new_holder:string;
12
+ /** When the previous holder took the item, or null when history was silent. */
13
+ claimed_at:string|null;
14
+ /** Most recent recorded item activity the policy judged. */
15
+ last_activity_at:string;
16
+ /** Whole idle hours at the takeover. */
17
+ idle_hours:number;
18
+ /** Threshold the idle time met. */
19
+ threshold_hours:number;
20
+ /** Setting that owns the threshold. */
21
+ policy:ClaimActivityEvidence["stale_policy"]["setting"];}
4
22
  /** Documents the claim result payload exchanged by command, SDK, and package integrations. */
5
23
  export interface ClaimResult{
6
24
  /** Value that configures or reports item for this contract. */
@@ -20,7 +38,9 @@ warnings?:string[];
20
38
  /** Lifecycle transition applied inside the claim's locked mutation when `start` was requested. */
21
39
  start?:ClaimStartReceipt;
22
40
  /** What a post-commit warning left unrecorded and how to clear its cause; the claim itself is saved. */
23
- suggestions?:string[];}
41
+ suggestions?:string[];
42
+ /** Present when `takeoverStale` took over an idle claim; the same evidence is in the history entry. */
43
+ takeover?:StaleClaimTakeoverReceipt;}
24
44
  /** Status transition recorded by a claim that also started its item. */
25
45
  export interface ClaimStartReceipt{
26
46
  /** Lifecycle status observed under the item lock before the claim. */
@@ -95,6 +115,13 @@ author?:string;
95
115
  message?:string;
96
116
  /** Value that configures or reports if available for this contract. */
97
117
  ifAvailable?:boolean;
118
+ /**
119
+ * Take over another holder's claim only when its idle time meets
120
+ * `mutation_guard.stale_in_progress_hours`; an active claim is refused with
121
+ * `stale_claim_takeover_refused` (or skipped with `ifAvailable`). Explicit item only,
122
+ * never combined with `force` (GH-1336).
123
+ */
124
+ takeoverStale?:boolean;
98
125
  /** Maximum ranked candidates attempted by `claim --next`. */
99
126
  maxAttempts?:string|number;
100
127
  /**
@@ -112,6 +139,20 @@ handoff?:string;
112
139
  pause?:boolean;}
113
140
  /** Implements run claim for the public runtime surface of this module. */
114
141
  export declare function runClaim(id:string,force:boolean,global:GlobalOptions,options?:ClaimMutationOptions):Promise<ClaimResult>;
142
+ /** How a claim proceeds against another holder: skip it, or take it with a warning (and, for a stale takeover, a receipt). */
143
+ type HeldClaimDecision={kind:"skip";}|{kind:"take";warning:string;takeover?:StaleClaimTakeoverReceipt;};
144
+ /**
145
+ * Decide a claim on an item another principal holds. Runs under the item lock,
146
+ * so a holder's renewal (any recorded mutation) is either seen here or lands
147
+ * after this claim; it can never interleave with the stale judgement.
148
+ */
149
+ declare function decideHeldClaim(params:{pmRoot:string;
150
+ /** Storage identity whose history stream the store locks and appends to. */
151
+ storageId:string;metadata:Pick<ItemMetadata,"id"|"updated_at">;holder:string;author:string;thresholdHours:number;force:boolean;ifAvailable:boolean;takeoverStale:boolean;}):Promise<HeldClaimDecision>;
152
+ /** Build the takeover receipt when the conflict's activity meets the stale-work policy, else undefined. */
153
+ declare function staleTakeoverReceipt(ownership:ItemOwnershipActivity,author:string):StaleClaimTakeoverReceipt|undefined;
154
+ /** The typed refusal for a held item: plain contention, or a stale takeover the policy did not permit. */
155
+ declare function claimConflictRefusal(itemId:string,ownership:ItemOwnershipActivity,takeoverStale:boolean):PmCliError;
115
156
  /** Stable warning when session attribution could not be recorded for a claim that already committed. */
116
157
  export declare const CLAIM_ATTRIBUTION_UNRECORDED_WARNING="claim_semantic_attribution_unrecorded";
117
158
  /** Stable warning when session attribution could not be updated for a release that already committed (GH-1706). */
@@ -127,4 +168,6 @@ export declare function parseClaimNextAttempts(raw:string|number|undefined):numb
127
168
  /** Claims the first still-available row from a pre-ranked recommendation set. */
128
169
  export declare function claimNextFromRecommendations(recommendations:NextRecommendation[],force:boolean,global:GlobalOptions,options?:ClaimMutationOptions,claimRunner?:ClaimRunner):Promise<ClaimNextResult>;
129
170
  /** Implements run release for the public runtime surface of this module. */
130
- export declare function runRelease(id:string,force:boolean,global:GlobalOptions,options?:ReleaseMutationOptions):Promise<ReleaseResult>;export{};
171
+ export declare function runRelease(id:string,force:boolean,global:GlobalOptions,options?:ReleaseMutationOptions):Promise<ReleaseResult>;
172
+ /** Test-only access to the stale-takeover decision helpers. */
173
+ export declare const _testOnlyClaimCommand:{claimConflictRefusal:typeof claimConflictRefusal;decideHeldClaim:typeof decideHeldClaim;staleTakeoverReceipt:typeof staleTakeoverReceipt;};export{};
@@ -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]="d2ca6888-c757-5be9-84ca-15c97998945e")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{resolveRuntimeStatusRegistry,statusIsTerminal,EXIT_CODE,PmCliError,toItemRecord,mutateItem,resolvePmRoot,readSettings,resolveAuthor,resolveClaimPrincipal,normalizeStatusForRegistry}from"../runtime-primitives.js";import{wrapOwnershipConflict}from"../annotations.js";import{renderPmCommand,resolvePmCommandScopeArgs}from"../command-line.js";import{resolveItemOwnershipConflict}from"../ownership-source.js";import{applyReleaseHandoff,resolveReleaseHandoff}from"./release-handoff.js";import{enforceTypeWorkflowTransition}from"./workflow-transition.js";import{admitExplicitStartClaim,admitStartTransition,START_BLOCKED_REFUSAL_CODE}from"./start-blockers.js";import{resolveTypeWorkflows}from"../../core/schema/type-workflows.js";import{resolveStartTaskInProgressStatus}from"../start-task-status.js";import{runNext}from"../query/next.js";import{recordClaimSemanticAttribution,recordReleaseSemanticAttribution}from"../context/semantic-session-attribution.js";import{redactIdentityCredentials,redactIdentityFields,redactOptionalIdentityCredentials}from"../../core/shared/url-credentials.js";const NO_AVAILABLE_NEXT_ITEM_CODE="no_available_next_item";function refusalCode(error){if(!(error instanceof Error)||error.name!=="PmCliError")return;const context=error.context;if(typeof context!="object"||context===null)return;const code=context.code;return typeof code=="string"?code:void 0}function hasRefusalCode(error,code){return refusalCode(error)===code}function isAlreadyClaimedError(error){return hasRefusalCode(error,"already_claimed_by")}async function runClaim(id,force,global2,options={}){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),author=resolveAuthor(options.author,settings.author_default),claimPrincipal=resolveClaimPrincipal(author);let previousAssignee=null,skipped=!1,startEvidence={};const mutationWarnings=[],result=await mutateItem({pmRoot,settings,id,op:"claim",author,message:options.message,force,skipNoop:!0,async mutate(document){const currentAssigneeText=document.metadata.assignee??"",currentClaimPrincipal=document.metadata.claim_principal?.trim()||currentAssigneeText;if(previousAssignee=currentAssigneeText.trim().length>0?currentAssigneeText:null,statusIsTerminal(document.metadata.status,statusRegistry)&&!force)throw new PmCliError(`Cannot claim terminal item ${document.metadata.id} without --force`,EXIT_CODE.CONFLICT);if(previousAssignee!==null&&currentClaimPrincipal!==claimPrincipal){if(options.ifAvailable===!0)return skipped=!0,mutationWarnings.push(`claim_skipped_held_by:${redactOptionalIdentityCredentials(previousAssignee)}`),{changedFields:[]};if(!force){const ownership2=await resolveItemOwnershipConflict(pmRoot,document.metadata.id,currentAssigneeText);throw new PmCliError(`Item ${document.metadata.id} is already ${ownership2.phrase}. Use --force to take over, or --if-available to skip without failing.`,EXIT_CODE.CONFLICT,{code:"already_claimed_by",item_id:document.metadata.id,claimed_by:ownership2.holder,claimed_at:ownership2.since,claim_source:ownership2.source,why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}mutationWarnings.push(`claim_takeover:${redactOptionalIdentityCredentials(previousAssignee)}->${author}`)}const ownership={assignee:author,claim_principal:claimPrincipal},changedFields=["assignee","claim_principal"].filter(field=>document.metadata[field]!==ownership[field]);Object.assign(document.metadata,ownership);const fromStatus=document.metadata.status,{changedFields:startedFields,warnings:startWarnings,...started}=applyClaimStart(document.metadata,options.start===!0,settings,statusRegistry);return startWarnings.push(...await claimStartWarnings({pmRoot,settings,metadata:document.metadata,fromStatus,registry:statusRegistry,force,start:options.start===!0})),startEvidence=started,mutationWarnings.push(...startWarnings),{changedFields:[...changedFields,...startedFields],warnings:mutationWarnings}}}),attribution=attributionAdvice(await recordAttributionAfterCommit("claim",result.item.id,global2,skipped,()=>recordClaimSemanticAttribution({pmRoot,settings,principal:claimPrincipal,itemId:result.item.id})));return mutationWarnings.push(...attribution.warnings),{item:redactIdentityFields(toItemRecord(result.item)),changed_fields:result.changedFields,claimed_by:skipped&&previousAssignee!==null?redactIdentityCredentials(previousAssignee):author,previous_assignee:previousAssignee===null?null:redactIdentityCredentials(previousAssignee),forced:force,...skipped?{skipped:!0}:{},...mutationWarnings.length>0?{warnings:mutationWarnings}:{},...nonEmptyList("suggestions",attribution.suggestions),...startEvidence}}const CLAIM_ATTRIBUTION_UNRECORDED_WARNING="claim_semantic_attribution_unrecorded";function attributionAdvice(attribution){return attribution?{warnings:[attribution.warning],suggestions:[attribution.suggestion]}:{warnings:[],suggestions:[]}}function nonEmptyList(key,values){return values.length>0?{[key]:values}:{}}const RELEASE_ATTRIBUTION_UNRECORDED_WARNING="release_semantic_attribution_unrecorded";async function recordAttributionAfterCommit(operation,itemId,global2,skip,record){if(!skip)try{await record();return}catch(error){const cause=refusalCode(error)??"unexpected_error",scope=resolvePmCommandScopeArgs(global2);return{warning:operation==="claim"?CLAIM_ATTRIBUTION_UNRECORDED_WARNING:RELEASE_ATTRIBUTION_UNRECORDED_WARNING,suggestion:`The ${operation} of ${itemId} is saved, but the session attribution that names this agent's active work was not updated (${cause}); nothing needs a retry. If ${renderPmCommand([...scope,"health"])} reports a stale lock, remove it with ${renderPmCommand([...scope,"gc","--scope","locks"])}.`}}}function requireClaimTarget(id,next,start=!1){const startSuffix=start?" --start":"";if(!next&&!id)throw new PmCliError(start?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",EXIT_CODE.USAGE,{code:"missing_required_argument",field:"id",required:"Pass an item id, or --next to select the next available item.",nextSteps:[`Retry as pm claim <id>${startSuffix}, or pm claim --next${startSuffix}.`]});if(next&&id)throw new PmCliError("Specify either an item id or --next, not both",EXIT_CODE.USAGE,{code:"ambiguous_option_combination",required:"Pass either an item id or --next.",nextSteps:[`Retry as pm claim ${id}${startSuffix} to claim that item, or drop the id to select with --next.`]})}async function claimStartWarnings(params){return params.start?admitStartTransition(params):admitExplicitStartClaim(params)}function applyClaimStart(metadata,start,settings,registry){if(!start)return{changedFields:[],warnings:[]};if(statusIsTerminal(metadata.status,registry))throw new PmCliError(`Cannot start terminal item ${metadata.id}; reopen it with pm item reopen before starting it`,EXIT_CODE.CONFLICT,{code:"terminal_state_conflict",item_id:metadata.id,why:"Starting work moves an active item into progress; a terminal item must be reopened so its recurrence evidence is recorded.",nextSteps:[`Run pm item reopen ${metadata.id} "<reason>", then pm claim ${metadata.id} --start.`]});const startStatus=resolveStartTaskInProgressStatus(registry),enforcement=settings.governance.workflow_enforcement??"off",warning=enforceTypeWorkflowTransition({enforcement,typeWorkflows:enforcement==="off"?[]:resolveTypeWorkflows(settings.schema),statusRegistry:registry,typeName:metadata.type,fromStatus:metadata.status,toStatus:startStatus}),receipt={from_status:metadata.status,to_status:startStatus},changedFields=metadata.status===startStatus?[]:["status"];return metadata.status=startStatus,{start:receipt,changedFields,warnings:warning?[warning]:[]}}async function runClaimNext(force,global2,options={},nextOptions={}){const maxAttempts=parseClaimNextAttempts(options.maxAttempts),settings=await readSettings(resolvePmRoot(process.cwd(),global2.path)),claimOptions={...options,author:resolveAuthor(options.author,settings.author_default)},next=await runNext({...nextOptions,callerAuthor:claimOptions.author,limit:String(maxAttempts)},global2),recommendations=[next.recommended,...next.ready].filter(entry=>entry!==null).map(entry=>({...entry,reasons:"reasons"in entry?entry.reasons:["ranked ready candidate"]}));return claimNextFromRecommendations(recommendations.slice(0,maxAttempts),force,global2,claimOptions)}function parseClaimNextAttempts(raw){if(raw===void 0)return 10;const parsed=Number(raw);if(!Number.isSafeInteger(parsed)||parsed<1||parsed>100)throw new PmCliError("--max-attempts must be an integer from 1 to 100",EXIT_CODE.USAGE);return parsed}async function claimNextFromRecommendations(recommendations,force,global2,options={},claimRunner=runClaim){let attempts=0;const startRefused=[],refusals=()=>startRefused.length>0?{start_refused:[...startRefused]}:{};for(const recommendation of recommendations){attempts+=1;try{const claimed=await claimRunner(recommendation.id,force,global2,options),result={...claimed,recommendation,attempts,available:!0,...refusals()};if(!claimed.skipped)return result}catch(error){if(hasRefusalCode(error,START_BLOCKED_REFUSAL_CODE)){startRefused.push(recommendation.id);continue}if(!isAlreadyClaimedError(error))throw error}}if(options.ifAvailable===!0)return{available:!1,item:null,claimed_by:resolveAuthor(options.author,""),previous_assignee:null,forced:force,skipped:!0,recommendation:null,attempts,...refusals(),warnings:[NO_AVAILABLE_NEXT_ITEM_CODE]};throw noAvailableNextItemError(attempts,startRefused,options.start===!0)}function noAvailableNextItemError(attempts,startRefused,start){const noCandidatesMatched=attempts===0;let why="Every ranked candidate was claimed by another agent before this atomic selection completed.";return noCandidatesMatched?why="No ready items matched the specified filters or selection criteria.":startRefused.length>0&&(why=`${startRefused.length} of ${attempts} attempted candidates refused their start because a declared blocker is open (${startRefused.join(", ")}), and nothing was written to them; ${startRefused.length===attempts?"no other candidate was attempted":"every other attempted candidate was claimed by another agent"}.`),new PmCliError(noCandidatesMatched?"No actionable items matched the selection filters":"No actionable item remained available to claim",noCandidatesMatched?EXIT_CODE.NOT_FOUND:EXIT_CODE.CONFLICT,{code:NO_AVAILABLE_NEXT_ITEM_CODE,why,nextSteps:[noCandidatesMatched?"Verify the filters or run pm next to inspect all ready work.":`Run pm claim --next${start?" --start":""} again, with the same filters, to refresh the ranked candidate set.`],...startRefused.length>0?{details:{start_refused:[...startRefused]}}:{}})}async function runRelease(id,force,global2,options={}){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),author=resolveAuthor(options.author,settings.author_default),claimPrincipal=resolveClaimPrincipal(author),ownershipReleaseBypass=options.ownershipReleaseBypass===!0;let previousAssignee=null;const statusRegistry=resolveRuntimeStatusRegistry(settings.schema),handoffStatus=resolveReleaseHandoff(options,statusRegistry);if(handoffStatus!==void 0&&ownershipReleaseBypass)throw new PmCliError("Ownership-release bypass only clears ownership; it cannot change a handoff status.",EXIT_CODE.USAGE);let handoff,result;try{result=await mutateItem({pmRoot,settings,id,op:"release",author,message:options.message,force,bypassAssigneeConflict:ownershipReleaseBypass,mutate(document){previousAssignee=document.metadata.assignee??null;const transition=handoffStatus===void 0?void 0:applyReleaseHandoff(document.metadata,handoffStatus,settings,statusRegistry,options.message);return handoff=transition?.receipt,!previousAssignee&&!document.metadata.claim_principal?{changedFields:[]}:(delete document.metadata.assignee,delete document.metadata.claim_principal,{changedFields:["assignee","claim_principal",...transition?.changedFields??[]],warnings:transition?.warnings})}})}catch(error){wrapOwnershipConflict(error,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}const attribution=attributionAdvice(await recordAttributionAfterCommit("release",result.item.id,global2,!1,()=>recordReleaseSemanticAttribution({pmRoot,principal:claimPrincipal,itemId:result.item.id}))),handoffAdvice=releaseHandoffAdvice(result.item,statusRegistry);return{item:redactIdentityFields(toItemRecord(result.item)),released_by:author,changed_fields:result.changedFields,previous_assignee:previousAssignee===null?null:redactIdentityCredentials(previousAssignee),forced:force,...handoff===void 0?{}:{handoff},...nonEmptyList("warnings",[...result.warnings,...handoffAdvice.warnings,...attribution.warnings]),...nonEmptyList("suggestions",[...handoffAdvice.suggestions,...attribution.suggestions])}}function releaseHandoffAdvice(item,statusRegistry){return normalizeStatusForRegistry(item.status,statusRegistry)===normalizeStatusForRegistry(statusRegistry.in_progress_status,statusRegistry)?{warnings:["released_unclaimed_in_progress"],suggestions:[`${item.id} remains ${item.status} and unclaimed. If work is paused, run pm release ${item.id} --pause to move it to ${statusRegistry.open_status}.`]}:{warnings:[],suggestions:[]}}export{CLAIM_ATTRIBUTION_UNRECORDED_WARNING,NO_AVAILABLE_NEXT_ITEM_CODE,RELEASE_ATTRIBUTION_UNRECORDED_WARNING,applyClaimStart,claimNextFromRecommendations,isAlreadyClaimedError,parseClaimNextAttempts,requireClaimTarget,runClaim,runClaimNext,runRelease};
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]="0b2ea0f6-b501-5004-9daf-73538023fa9b")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{resolveRuntimeStatusRegistry,statusIsTerminal,EXIT_CODE,PmCliError,toItemRecord,mutateItem,resolvePmRoot,readSettings,resolveAuthor,resolveClaimPrincipal,normalizeStatusForRegistry}from"../runtime-primitives.js";import{wrapOwnershipConflict}from"../annotations.js";import{renderPmCommand,resolvePmCommandScopeArgs}from"../command-line.js";import{resolveItemOwnershipActivity}from"../ownership-source.js";import{mutateItemWithHistoryContextResolver}from"../../core/store/item-store.js";import{applyReleaseHandoff,resolveReleaseHandoff}from"./release-handoff.js";import{enforceTypeWorkflowTransition}from"./workflow-transition.js";import{admitExplicitStartClaim,admitStartTransition,START_BLOCKED_REFUSAL_CODE}from"./start-blockers.js";import{resolveTypeWorkflows}from"../../core/schema/type-workflows.js";import{resolveStartTaskInProgressStatus}from"../start-task-status.js";import{runNext}from"../query/next.js";import{recordClaimSemanticAttribution,recordReleaseSemanticAttribution}from"../context/semantic-session-attribution.js";import{redactIdentityCredentials,redactIdentityFields,redactOptionalIdentityCredentials}from"../../core/shared/url-credentials.js";const NO_AVAILABLE_NEXT_ITEM_CODE="no_available_next_item",STALE_CLAIM_TAKEOVER_REFUSED_CODE="stale_claim_takeover_refused";function refusalCode(error){if(!(error instanceof Error)||error.name!=="PmCliError")return;const context=error.context;if(typeof context!="object"||context===null)return;const code=context.code;return typeof code=="string"?code:void 0}function hasRefusalCode(error,code){return refusalCode(error)===code}function isAlreadyClaimedError(error){return hasRefusalCode(error,"already_claimed_by")}async function runClaim(id,force,global2,options={}){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),author=resolveAuthor(options.author,settings.author_default),claimPrincipal=resolveClaimPrincipal(author),takeoverStale=options.takeoverStale===!0;assertTakeoverStaleCombination(takeoverStale,force);let previousAssignee=null,skipped=!1,startEvidence={},takeover;const mutationWarnings=[],result=await mutateItemWithHistoryContextResolver({pmRoot,settings,id,op:"claim",author,message:options.message,force,skipNoop:!0,resolveHistoryContext:()=>takeover===void 0?void 0:{stale_claim_takeover:takeover},async mutate(document,location){const currentAssigneeText=document.metadata.assignee??"",currentClaimPrincipal=document.metadata.claim_principal?.trim()||currentAssigneeText;if(previousAssignee=currentAssigneeText.trim().length>0?currentAssigneeText:null,statusIsTerminal(document.metadata.status,statusRegistry)&&!force)throw new PmCliError(`Cannot claim terminal item ${document.metadata.id} without --force`,EXIT_CODE.CONFLICT);if(previousAssignee!==null&&currentClaimPrincipal!==claimPrincipal){const decision=await decideHeldClaim({pmRoot,storageId:location.storageId,metadata:document.metadata,holder:currentAssigneeText,author,thresholdHours:settings.mutation_guard.stale_in_progress_hours,force,ifAvailable:options.ifAvailable===!0,takeoverStale});if(decision.kind==="skip")return skipped=!0,mutationWarnings.push(`claim_skipped_held_by:${redactOptionalIdentityCredentials(currentAssigneeText)}`),{changedFields:[]};takeover=decision.takeover,mutationWarnings.push(decision.warning)}const ownership={assignee:author,claim_principal:claimPrincipal},changedFields=["assignee","claim_principal"].filter(field=>document.metadata[field]!==ownership[field]);Object.assign(document.metadata,ownership);const fromStatus=document.metadata.status,{changedFields:startedFields,warnings:startWarnings,...started}=applyClaimStart(document.metadata,options.start===!0,settings,statusRegistry);return startWarnings.push(...await claimStartWarnings({pmRoot,settings,metadata:document.metadata,fromStatus,registry:statusRegistry,force,start:options.start===!0})),startEvidence=started,mutationWarnings.push(...startWarnings),{changedFields:[...changedFields,...startedFields],warnings:mutationWarnings}}}),attribution=attributionAdvice(await recordAttributionAfterCommit("claim",result.item.id,global2,skipped,()=>recordClaimSemanticAttribution({pmRoot,settings,principal:claimPrincipal,itemId:result.item.id})));return mutationWarnings.push(...attribution.warnings),{item:redactIdentityFields(toItemRecord(result.item)),changed_fields:result.changedFields,claimed_by:skipped&&previousAssignee!==null?redactIdentityCredentials(previousAssignee):author,previous_assignee:previousAssignee===null?null:redactIdentityCredentials(previousAssignee),forced:force,...skipped?{skipped:!0}:{},...mutationWarnings.length>0?{warnings:mutationWarnings}:{},...nonEmptyList("suggestions",attribution.suggestions),...startEvidence,...takeover===void 0?{}:{takeover}}}async function decideHeldClaim(params){if(params.ifAvailable&&!params.takeoverStale)return{kind:"skip"};if(params.force)return{kind:"take",warning:`claim_takeover:${redactOptionalIdentityCredentials(params.holder)}->${params.author}`};const ownership=await resolveItemOwnershipActivity(params.pmRoot,params.storageId,params.holder,{updated_at:params.metadata.updated_at,threshold_hours:params.thresholdHours}),takeover=params.takeoverStale?staleTakeoverReceipt(ownership,params.author):void 0;if(takeover!==void 0)return{kind:"take",warning:`claim_stale_takeover:${takeover.previous_holder}->${params.author}:idle_hours=${takeover.idle_hours}`,takeover};if(params.takeoverStale&&params.ifAvailable)return{kind:"skip"};throw claimConflictRefusal(params.metadata.id,ownership,params.takeoverStale)}function assertTakeoverStaleCombination(takeoverStale,force){if(!(!takeoverStale||!force))throw new PmCliError("--takeover-stale cannot be combined with --force",EXIT_CODE.USAGE,{code:"ambiguous_option_combination",required:"Pass --takeover-stale to take over only an idle claim, or --force for a coordinated unconditional takeover.",nextSteps:["Drop --force to let the stale-work policy decide, or drop --takeover-stale for a coordinated override."]})}function staleTakeoverReceipt(ownership,author){const activity=ownership.activity;if(activity.stale_policy.stale)return{previous_holder:ownership.holder,new_holder:author,claimed_at:ownership.since,last_activity_at:activity.last_activity_at,idle_hours:activity.idle_hours,threshold_hours:activity.stale_policy.threshold_hours,policy:activity.stale_policy.setting}}const UNPROVEN_ACTIVITY_CAUSE={claim_record_unavailable:"no original history record shows when the holder took it",discarded_history_tail:"a history salvage after the claim discarded a record whose time is unknown",rewritten_history:"a history repair, redaction or merge reconcile after the claim rewrote its records",workspace_restored:"a workspace snapshot restore at or after the claim may have replaced the holder's work"};function describeNotStale(itemId,activity){return activity.history_unreadable===!0?{reason:"its history stream could not be read, so idleness cannot be established",nextStep:`Repair the history stream of ${itemId} (pm history ${itemId} --verify), then retry --takeover-stale.`}:activity.unproven_activity!==void 0?{reason:`${UNPROVEN_ACTIVITY_CAUSE[activity.unproven_activity]}, so idleness cannot be proven`,nextStep:`Ask the holder to release ${itemId} (pm release ${itemId}); a new claim starts a provable record.`}:activity.stale_policy.eligible_at===null?{reason:activity.idle_hours===null?"no valid activity time is recorded":`idle ${activity.idle_hours}h of ${activity.stale_policy.threshold_hours}h`,nextStep:`No eligibility time can be computed for ${itemId}; inspect pm history ${itemId}.`}:{reason:`idle ${activity.idle_hours}h of ${activity.stale_policy.threshold_hours}h`,nextStep:`Retry with --takeover-stale after ${activity.stale_policy.eligible_at} if nothing else is recorded on ${itemId}.`}}function claimConflictRefusal(itemId,ownership,takeoverStale){const activity=ownership.activity,policy=activity.stale_policy,evidence={item_id:itemId,claimed_by:ownership.holder,claimed_at:ownership.since,claim_source:ownership.source,claim_activity:activity},why="Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",forceStep="Re-run with --force only when taking over the item is coordinated.";if(takeoverStale){const notStale=describeNotStale(itemId,activity);return new PmCliError(`Item ${itemId} is ${ownership.phrase}, and its claim is not stale under ${policy.setting} (${notStale.reason}).`,EXIT_CODE.CONFLICT,{code:"stale_claim_takeover_refused",...evidence,required:`The claim must be idle for at least ${policy.threshold_hours}h (${policy.setting}) before --takeover-stale may take it.`,why:`${why} A stale takeover needs recorded evidence that the claim has been idle for the configured threshold, so an active claim is never taken over.`,nextSteps:[notStale.nextStep,"Run pm next to pick a different unclaimed item.",forceStep]})}return new PmCliError(`Item ${itemId} is already ${ownership.phrase}. Use --force to take over, or --if-available to skip without failing.`,EXIT_CODE.CONFLICT,{code:"already_claimed_by",...evidence,why,nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.",...policy.stale?[`Re-run with --takeover-stale: the claim has been idle ${activity.idle_hours}h, past ${policy.setting}=${policy.threshold_hours}.`]:[],forceStep]})}const CLAIM_ATTRIBUTION_UNRECORDED_WARNING="claim_semantic_attribution_unrecorded";function attributionAdvice(attribution){return attribution?{warnings:[attribution.warning],suggestions:[attribution.suggestion]}:{warnings:[],suggestions:[]}}function nonEmptyList(key,values){return values.length>0?{[key]:values}:{}}const RELEASE_ATTRIBUTION_UNRECORDED_WARNING="release_semantic_attribution_unrecorded";async function recordAttributionAfterCommit(operation,itemId,global2,skip,record){if(!skip)try{await record();return}catch(error){const cause=refusalCode(error)??"unexpected_error",scope=resolvePmCommandScopeArgs(global2);return{warning:operation==="claim"?CLAIM_ATTRIBUTION_UNRECORDED_WARNING:RELEASE_ATTRIBUTION_UNRECORDED_WARNING,suggestion:`The ${operation} of ${itemId} is saved, but the session attribution that names this agent's active work was not updated (${cause}); nothing needs a retry. If ${renderPmCommand([...scope,"health"])} reports a stale lock, remove it with ${renderPmCommand([...scope,"gc","--scope","locks"])}.`}}}function requireClaimTarget(id,next,start=!1){const startSuffix=start?" --start":"";if(!next&&!id)throw new PmCliError(start?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",EXIT_CODE.USAGE,{code:"missing_required_argument",field:"id",required:"Pass an item id, or --next to select the next available item.",nextSteps:[`Retry as pm claim <id>${startSuffix}, or pm claim --next${startSuffix}.`]});if(next&&id)throw new PmCliError("Specify either an item id or --next, not both",EXIT_CODE.USAGE,{code:"ambiguous_option_combination",required:"Pass either an item id or --next.",nextSteps:[`Retry as pm claim ${id}${startSuffix} to claim that item, or drop the id to select with --next.`]})}async function claimStartWarnings(params){return params.start?admitStartTransition(params):admitExplicitStartClaim(params)}function applyClaimStart(metadata,start,settings,registry){if(!start)return{changedFields:[],warnings:[]};if(statusIsTerminal(metadata.status,registry))throw new PmCliError(`Cannot start terminal item ${metadata.id}; reopen it with pm item reopen before starting it`,EXIT_CODE.CONFLICT,{code:"terminal_state_conflict",item_id:metadata.id,why:"Starting work moves an active item into progress; a terminal item must be reopened so its recurrence evidence is recorded.",nextSteps:[`Run pm item reopen ${metadata.id} "<reason>", then pm claim ${metadata.id} --start.`]});const startStatus=resolveStartTaskInProgressStatus(registry),enforcement=settings.governance.workflow_enforcement??"off",warning=enforceTypeWorkflowTransition({enforcement,typeWorkflows:enforcement==="off"?[]:resolveTypeWorkflows(settings.schema),statusRegistry:registry,typeName:metadata.type,fromStatus:metadata.status,toStatus:startStatus}),receipt={from_status:metadata.status,to_status:startStatus},changedFields=metadata.status===startStatus?[]:["status"];return metadata.status=startStatus,{start:receipt,changedFields,warnings:warning?[warning]:[]}}async function runClaimNext(force,global2,options={},nextOptions={}){if(options.takeoverStale===!0)throw new PmCliError("--takeover-stale cannot be combined with --next",EXIT_CODE.USAGE,{code:"ambiguous_option_combination",required:"Pass an explicit item id with --takeover-stale; --next only selects work no other author holds.",nextSteps:["Retry as pm claim <id> --takeover-stale for the held item, or drop --takeover-stale to select with --next."]});const maxAttempts=parseClaimNextAttempts(options.maxAttempts),settings=await readSettings(resolvePmRoot(process.cwd(),global2.path)),claimOptions={...options,author:resolveAuthor(options.author,settings.author_default)},next=await runNext({...nextOptions,callerAuthor:claimOptions.author,limit:String(maxAttempts)},global2),recommendations=[next.recommended,...next.ready].filter(entry=>entry!==null).map(entry=>({...entry,reasons:"reasons"in entry?entry.reasons:["ranked ready candidate"]}));return claimNextFromRecommendations(recommendations.slice(0,maxAttempts),force,global2,claimOptions)}function parseClaimNextAttempts(raw){if(raw===void 0)return 10;const parsed=Number(raw);if(!Number.isSafeInteger(parsed)||parsed<1||parsed>100)throw new PmCliError("--max-attempts must be an integer from 1 to 100",EXIT_CODE.USAGE);return parsed}async function claimNextFromRecommendations(recommendations,force,global2,options={},claimRunner=runClaim){let attempts=0;const startRefused=[],refusals=()=>startRefused.length>0?{start_refused:[...startRefused]}:{};for(const recommendation of recommendations){attempts+=1;try{const claimed=await claimRunner(recommendation.id,force,global2,options),result={...claimed,recommendation,attempts,available:!0,...refusals()};if(!claimed.skipped)return result}catch(error){if(hasRefusalCode(error,START_BLOCKED_REFUSAL_CODE)){startRefused.push(recommendation.id);continue}if(!isAlreadyClaimedError(error))throw error}}if(options.ifAvailable===!0)return{available:!1,item:null,claimed_by:resolveAuthor(options.author,""),previous_assignee:null,forced:force,skipped:!0,recommendation:null,attempts,...refusals(),warnings:[NO_AVAILABLE_NEXT_ITEM_CODE]};throw noAvailableNextItemError(attempts,startRefused,options.start===!0)}function noAvailableNextItemError(attempts,startRefused,start){const noCandidatesMatched=attempts===0;let why="Every ranked candidate was claimed by another agent before this atomic selection completed.";return noCandidatesMatched?why="No ready items matched the specified filters or selection criteria.":startRefused.length>0&&(why=`${startRefused.length} of ${attempts} attempted candidates refused their start because a declared blocker is open (${startRefused.join(", ")}), and nothing was written to them; ${startRefused.length===attempts?"no other candidate was attempted":"every other attempted candidate was claimed by another agent"}.`),new PmCliError(noCandidatesMatched?"No actionable items matched the selection filters":"No actionable item remained available to claim",noCandidatesMatched?EXIT_CODE.NOT_FOUND:EXIT_CODE.CONFLICT,{code:NO_AVAILABLE_NEXT_ITEM_CODE,why,nextSteps:[noCandidatesMatched?"Verify the filters or run pm next to inspect all ready work.":`Run pm claim --next${start?" --start":""} again, with the same filters, to refresh the ranked candidate set.`],...startRefused.length>0?{details:{start_refused:[...startRefused]}}:{}})}async function runRelease(id,force,global2,options={}){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),author=resolveAuthor(options.author,settings.author_default),claimPrincipal=resolveClaimPrincipal(author),ownershipReleaseBypass=options.ownershipReleaseBypass===!0;let previousAssignee=null;const statusRegistry=resolveRuntimeStatusRegistry(settings.schema),handoffStatus=resolveReleaseHandoff(options,statusRegistry);if(handoffStatus!==void 0&&ownershipReleaseBypass)throw new PmCliError("Ownership-release bypass only clears ownership; it cannot change a handoff status.",EXIT_CODE.USAGE);let handoff,result;try{result=await mutateItem({pmRoot,settings,id,op:"release",author,message:options.message,force,bypassAssigneeConflict:ownershipReleaseBypass,mutate(document){previousAssignee=document.metadata.assignee??null;const transition=handoffStatus===void 0?void 0:applyReleaseHandoff(document.metadata,handoffStatus,settings,statusRegistry,options.message);return handoff=transition?.receipt,!previousAssignee&&!document.metadata.claim_principal?{changedFields:[]}:(delete document.metadata.assignee,delete document.metadata.claim_principal,{changedFields:["assignee","claim_principal",...transition?.changedFields??[]],warnings:transition?.warnings})}})}catch(error){wrapOwnershipConflict(error,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}const attribution=attributionAdvice(await recordAttributionAfterCommit("release",result.item.id,global2,!1,()=>recordReleaseSemanticAttribution({pmRoot,principal:claimPrincipal,itemId:result.item.id}))),handoffAdvice=releaseHandoffAdvice(result.item,statusRegistry);return{item:redactIdentityFields(toItemRecord(result.item)),released_by:author,changed_fields:result.changedFields,previous_assignee:previousAssignee===null?null:redactIdentityCredentials(previousAssignee),forced:force,...handoff===void 0?{}:{handoff},...nonEmptyList("warnings",[...result.warnings,...handoffAdvice.warnings,...attribution.warnings]),...nonEmptyList("suggestions",[...handoffAdvice.suggestions,...attribution.suggestions])}}function releaseHandoffAdvice(item,statusRegistry){return normalizeStatusForRegistry(item.status,statusRegistry)===normalizeStatusForRegistry(statusRegistry.in_progress_status,statusRegistry)?{warnings:["released_unclaimed_in_progress"],suggestions:[`${item.id} remains ${item.status} and unclaimed. If work is paused, run pm release ${item.id} --pause to move it to ${statusRegistry.open_status}.`]}:{warnings:[],suggestions:[]}}const _testOnlyClaimCommand={claimConflictRefusal,decideHeldClaim,staleTakeoverReceipt};export{CLAIM_ATTRIBUTION_UNRECORDED_WARNING,NO_AVAILABLE_NEXT_ITEM_CODE,RELEASE_ATTRIBUTION_UNRECORDED_WARNING,STALE_CLAIM_TAKEOVER_REFUSED_CODE,_testOnlyClaimCommand,applyClaimStart,claimNextFromRecommendations,isAlreadyClaimedError,parseClaimNextAttempts,requireClaimTarget,runClaim,runClaimNext,runRelease};
2
2
  //# sourceMappingURL=claim.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]="35d9d28d-68f5-5a6d-b3e8-02424b81a4d4")}catch{}})();import{PmCliError}from"../../core/shared/errors.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{resolveRuntimeStatusRegistry}from"../../core/schema/runtime-schema.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{runClaim,runRelease}from"./claim.js";import{resolveReleaseHandoff}from"./release-handoff.js";import{runClose}from"./close.js";import{runUpdate}from"./update.js";import{resolveStartTaskInProgressStatus}from"../start-task-status.js";import{runAsExplicitStart,START_BLOCKED_REFUSAL_CODE}from"./start-blockers.js";import{runWithItemMutationPrecondition}from"../../core/store/item-mutation-precondition.js";import{mutationOptionsWithOverrides}from"../runtime-input.js";async function finishComposition(id,completed,operation){try{return await operation()}catch(error){const context=error instanceof PmCliError?error.context:{},failure=new PmCliError(error instanceof Error?error.message:String(error),error instanceof PmCliError?error.exitCode:EXIT_CODE.GENERIC_FAILURE,{...context,item_id:id,why:`${completed} completed for ${id} before the following step failed. No rollback was performed.${context.why?` ${context.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${id} and pm history ${id} before retrying the failed step.`,...context.nextSteps??[]]});throw failure.cause=error,failure}}async function runStartTask(id,options,global2){if(options.next===!0||options.ifAvailable===!0)throw new PmCliError("--start cannot be combined with --next or --if-available for an explicit item",EXIT_CODE.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});const settings=await readSettings(resolvePmRoot(process.cwd(),global2.path)),status=resolveStartTaskInProgressStatus(resolveRuntimeStatusRegistry(settings.schema));return runAsExplicitStart(async()=>{const claim=await runClaim(id,options.force===!0,global2,mutationOptionsWithOverrides(options,{},["start"])),canonicalId=claim.item.id,update=await finishComposition(canonicalId,"claim",()=>runUpdate(canonicalId,mutationOptionsWithOverrides(options,{status},["assignee","start","next","ifAvailable","maxAttempts"]),global2)).catch(async error=>{throw await releaseRefusedStartClaim(error,claim,global2,options.author)});return{id:canonicalId,action:"start_task",claim,update}})}async function releaseRefusedStartClaim(error,claim,global2,author){if(!(error instanceof PmCliError)||error.code!==START_BLOCKED_REFUSAL_CODE||claim.previous_assignee!==null)return error;const id=String(claim.item.id);try{await runWithItemMutationPrecondition({pmRoot:resolvePmRoot(process.cwd(),global2.path),id,validate:document=>{if(document.metadata.assignee!==claim.claimed_by||document.metadata.claim_principal!==claim.item.claim_principal)throw new PmCliError("The claim this start took is no longer its own.",EXIT_CODE.CONFLICT)}},()=>runRelease(id,!1,global2,{author,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return error}const refusal=error.cause instanceof PmCliError?error.cause:error;return new PmCliError(refusal.message,refusal.exitCode,{...refusal.context,why:`${refusal.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function runPauseTask(id,options,global2){const settings=await readSettings(resolvePmRoot(process.cwd(),global2.path)),registry=resolveRuntimeStatusRegistry(settings.schema);resolveReleaseHandoff({...options,pause:!0},registry);const status=registry.open_status,update=await runUpdate(id,mutationOptionsWithOverrides(options,{status},["assignee","pause"]),global2),canonicalId=update.item.id,release=await finishComposition(canonicalId,"update",()=>runRelease(canonicalId,options.force===!0,global2,options));return{id:canonicalId,action:"pause_task",update,release}}async function runCloseTask(id,reason,options,global2){const close=await runClose(id,reason,options,global2),canonicalId=close.item.id,release=await finishComposition(canonicalId,"close",()=>runRelease(canonicalId,options.force===!0,global2,options));return{id:canonicalId,action:"close_task",close,release}}export{finishComposition,releaseRefusedStartClaim,runCloseTask,runPauseTask,runStartTask};
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]="a2aa0bed-59f8-5199-a167-0283a8801595")}catch{}})();import{PmCliError}from"../../core/shared/errors.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{resolveRuntimeStatusRegistry}from"../../core/schema/runtime-schema.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{runClaim,runRelease}from"./claim.js";import{resolveReleaseHandoff}from"./release-handoff.js";import{runClose}from"./close.js";import{runUpdate}from"./update.js";import{resolveStartTaskInProgressStatus}from"../start-task-status.js";import{runAsExplicitStart,START_BLOCKED_REFUSAL_CODE}from"./start-blockers.js";import{runWithItemMutationPrecondition}from"../../core/store/item-mutation-precondition.js";import{mutationOptionsWithOverrides}from"../runtime-input.js";async function finishComposition(id,completed,operation){try{return await operation()}catch(error){const context=error instanceof PmCliError?error.context:{},failure=new PmCliError(error instanceof Error?error.message:String(error),error instanceof PmCliError?error.exitCode:EXIT_CODE.GENERIC_FAILURE,{...context,item_id:id,why:`${completed} completed for ${id} before the following step failed. No rollback was performed.${context.why?` ${context.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${id} and pm history ${id} before retrying the failed step.`,...context.nextSteps??[]]});throw failure.cause=error,failure}}async function runStartTask(id,options,global2){if(options.next===!0||options.ifAvailable===!0)throw new PmCliError("--start cannot be combined with --next or --if-available for an explicit item",EXIT_CODE.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});const settings=await readSettings(resolvePmRoot(process.cwd(),global2.path)),status=resolveStartTaskInProgressStatus(resolveRuntimeStatusRegistry(settings.schema));return runAsExplicitStart(async()=>{const claim=await runClaim(id,options.force===!0,global2,mutationOptionsWithOverrides(options,{},["start"])),canonicalId=claim.item.id,update=await finishComposition(canonicalId,"claim",()=>runUpdate(canonicalId,mutationOptionsWithOverrides(options,{status},["assignee","start","next","ifAvailable","maxAttempts","takeoverStale"]),global2)).catch(async error=>{throw await releaseRefusedStartClaim(error,claim,global2,options.author)});return{id:canonicalId,action:"start_task",claim,update}})}async function releaseRefusedStartClaim(error,claim,global2,author){if(!(error instanceof PmCliError)||error.code!==START_BLOCKED_REFUSAL_CODE||claim.previous_assignee!==null)return error;const id=String(claim.item.id);try{await runWithItemMutationPrecondition({pmRoot:resolvePmRoot(process.cwd(),global2.path),id,validate:document=>{if(document.metadata.assignee!==claim.claimed_by||document.metadata.claim_principal!==claim.item.claim_principal)throw new PmCliError("The claim this start took is no longer its own.",EXIT_CODE.CONFLICT)}},()=>runRelease(id,!1,global2,{author,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return error}const refusal=error.cause instanceof PmCliError?error.cause:error;return new PmCliError(refusal.message,refusal.exitCode,{...refusal.context,why:`${refusal.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function runPauseTask(id,options,global2){const settings=await readSettings(resolvePmRoot(process.cwd(),global2.path)),registry=resolveRuntimeStatusRegistry(settings.schema);resolveReleaseHandoff({...options,pause:!0},registry);const status=registry.open_status,update=await runUpdate(id,mutationOptionsWithOverrides(options,{status},["assignee","pause"]),global2),canonicalId=update.item.id,release=await finishComposition(canonicalId,"update",()=>runRelease(canonicalId,options.force===!0,global2,options));return{id:canonicalId,action:"pause_task",update,release}}async function runCloseTask(id,reason,options,global2){const close=await runClose(id,reason,options,global2),canonicalId=close.item.id,release=await finishComposition(canonicalId,"close",()=>runRelease(canonicalId,options.force===!0,global2,options));return{id:canonicalId,action:"close_task",close,release}}export{finishComposition,releaseRefusedStartClaim,runCloseTask,runPauseTask,runStartTask};
2
2
  //# sourceMappingURL=task-composition.js.map
@@ -1,3 +1,27 @@
1
+ import type{PmCliErrorContext}from "../core/shared/errors.js";import{type UnprovenActivityReason}from "./governance/stale-work.js";
2
+ /** Activity and stale-claim policy evidence behind a claim refusal or takeover (GH-1336). */
3
+ export type ClaimActivityEvidence=NonNullable<PmCliErrorContext["claim_activity"]>;
4
+ /** Inputs that let a claim conflict report the holder's activity under the stale-work policy. */
5
+ export interface ClaimActivityOptions{
6
+ /** The item's stored `updated_at`, read under the same lock as the conflict. */
7
+ updated_at:string|undefined;
8
+ /** Configured `mutation_guard.stale_in_progress_hours`. */
9
+ threshold_hours:number;
10
+ /** Evaluation instant, injectable for deterministic tests. */
11
+ now?:Date;
12
+ /**
13
+ * The item's history stream exists but could not be read (corrupt JSONL or
14
+ * conflict markers). Idleness then cannot be established, so the claim is
15
+ * never judged stale: recent activity may hide behind the unreadable lines.
16
+ */
17
+ history_unreadable?:boolean;
18
+ /**
19
+ * The readable stream cannot prove the holder's idleness: no original
20
+ * record sets the holder, or records after it were discarded, rewritten or
21
+ * replaced by a workspace restore; see `unprovenClaimActivity`. The claim is
22
+ * then never judged stale.
23
+ */
24
+ unproven_activity?:UnprovenActivityReason;}
1
25
  /** Typed holder evidence behind an `already_claimed_by` refusal (GH-1610). */
2
26
  export interface ItemOwnershipConflict{
3
27
  /** Prose used by the refusal message: `claimed by <holder>` or `assigned to <holder>`. */
@@ -13,7 +37,15 @@ holder:string;
13
37
  source:"claim"|"assignment"|"unknown";
14
38
  /** Timestamp of the latest assignee change, or null when history is unavailable or silent. */
15
39
  since:string|null;}
40
+ /** Holder evidence plus the holder's activity under the stale-work policy (GH-1336). */
41
+ export interface ItemOwnershipActivity extends ItemOwnershipConflict{
42
+ /** Claim age, last activity and stale-claim eligibility. */
43
+ activity:ClaimActivityEvidence;}
44
+ /** Evaluate claim age, last activity and stale-claim eligibility from one item's evidence. */
45
+ export declare function evaluateClaimActivity(claimedAt:string|null,latestHistoryAt:string|undefined,options:ClaimActivityOptions):ClaimActivityEvidence;
16
46
  /** Resolve the current holder, its source and its start time for an atomic claim conflict. */
17
47
  export declare function resolveItemOwnershipConflict(pmRoot:string,itemId:string,assignee:string):Promise<ItemOwnershipConflict>;
48
+ /** Resolve the holder evidence and judge the holder's activity under the stale-work policy, from one stream read. */
49
+ export declare function resolveItemOwnershipActivity(pmRoot:string,itemId:string,assignee:string,options:ClaimActivityOptions):Promise<ItemOwnershipActivity>;
18
50
  /** Describe the current ownership source for an atomic claim conflict. */
19
51
  export declare function describeItemOwnershipConflict(pmRoot:string,itemId:string,assignee:string):Promise<string>;
@@ -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]="6c6e6cae-87e6-58df-9f59-b9e74a80de38")}catch{}})();import{readHistoryEntries}from"../core/history/read.js";import{redactIdentityCredentials}from"../core/shared/url-credentials.js";import{getHistoryPath}from"../core/store/paths.js";function classifyOwnershipSource(operation){return operation===void 0?"unknown":operation==="claim"?"claim":"assignment"}async function resolveItemOwnershipConflict(pmRoot,itemId,assignee){const latestOwnershipEntry=[...await Promise.resolve().then(()=>readHistoryEntries(getHistoryPath(pmRoot,itemId),itemId)).catch(()=>[])].reverse().find(entry=>entry.patch.some(operation=>operation.path==="/metadata/assignee")),assigneeOperation=latestOwnershipEntry?.patch.find(operation=>operation.path==="/metadata/assignee"),evidence=assigneeOperation!==void 0&&typeof assigneeOperation.value=="string"&&assigneeOperation.value.trim()===assignee.trim()?latestOwnershipEntry:void 0,source=classifyOwnershipSource(evidence?.op),holder=redactIdentityCredentials(assignee);return{phrase:source==="claim"?`claimed by ${holder}`:`assigned to ${holder}`,holder,source,since:evidence?.ts??null}}async function describeItemOwnershipConflict(pmRoot,itemId,assignee){return(await resolveItemOwnershipConflict(pmRoot,itemId,assignee)).phrase}export{describeItemOwnershipConflict,resolveItemOwnershipConflict};
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]="498066a6-7936-539a-9da1-e3fe53197ae3")}catch{}})();import{readHistoryEntries}from"../core/history/read.js";import{getWorkspaceHistoryPath,WORKSPACE_HISTORY_ID}from"../core/history/workspace-history.js";import{redactIdentityCredentials}from"../core/shared/url-credentials.js";import{getHistoryPath}from"../core/store/paths.js";import{STALE_WORK_THRESHOLD_SETTING,isJudgeableHistoryRecord,isWellFormedHistoryRecord,latestHistoryTimestamp,normalizeStaleWorkThresholdHours,recordedBaselineActivity,resolveLastActivityAt,staleEligibleAt,unprovenClaimActivity,wholeHoursSince}from"./governance/stale-work.js";function evaluateClaimActivity(claimedAt,latestHistoryAt,options){const nowMs=(options.now??new Date).getTime(),thresholdHours=normalizeStaleWorkThresholdHours(options.threshold_hours),lastActivityAt=resolveLastActivityAt(options.updated_at,latestHistoryAt)??null,validClaimedAt=claimedAt!==null&&Number.isFinite(Date.parse(claimedAt))?claimedAt:null,idleHours=lastActivityAt===null?null:wholeHoursSince(lastActivityAt,nowMs),judgeable=lastActivityAt!==null&&options.history_unreadable!==!0&&options.unproven_activity===void 0;return{last_activity_at:lastActivityAt,...options.history_unreadable===!0?{history_unreadable:!0}:{},...options.unproven_activity===void 0?{}:{unproven_activity:options.unproven_activity},claim_age_hours:validClaimedAt===null?null:wholeHoursSince(validClaimedAt,nowMs),idle_hours:idleHours,stale_policy:{setting:STALE_WORK_THRESHOLD_SETTING,threshold_hours:thresholdHours,stale:judgeable&&idleHours>=thresholdHours,eligible_at:judgeable?staleEligibleAt(lastActivityAt,thresholdHours):null}}}function classifyOwnershipSource(operation){return operation===void 0?"unknown":operation==="claim"?"claim":"assignment"}const ASSIGNEE_PATH="/metadata/assignee",CLAIM_PRINCIPAL_PATH="/metadata/claim_principal";function changesOwnership(entry){return entry.patch.some(operation=>operation.path===ASSIGNEE_PATH||entry.op==="claim"&&operation.path===CLAIM_PRINCIPAL_PATH)}function holderNamedAt(history,index){for(let position=index;position>=0;position-=1){const operation=history[position].patch.find(candidate=>candidate.path===ASSIGNEE_PATH);if(operation!==void 0)return typeof operation.value=="string"?operation.value.trim():void 0}}async function readOwnershipEvidence(pmRoot,itemId,assignee){let readable=!0;const history=await Promise.resolve().then(()=>readHistoryEntries(getHistoryPath(pmRoot,itemId),itemId)).then(entries=>entries.every(isJudgeableHistoryRecord)?entries:(readable=!1,[])).catch(()=>(readable=!1,[]));let latestOwnershipIndex=history.length-1;for(;latestOwnershipIndex>=0&&!changesOwnership(history[latestOwnershipIndex]);)latestOwnershipIndex-=1;const latestOwnershipEntry=history[latestOwnershipIndex],evidence=holderNamedAt(history,latestOwnershipIndex)===assignee.trim()?latestOwnershipEntry:void 0,source=classifyOwnershipSource(evidence?.op),holder=redactIdentityCredentials(assignee);return{conflict:{phrase:source==="claim"?`claimed by ${holder}`:`assigned to ${holder}`,holder,source,since:evidence?.ts??null},history,readable,unproven:readable?unprovenClaimActivity(history,evidence===void 0?-1:latestOwnershipIndex):void 0}}function atOrAfter(timestamp,claimedMs){const ms=Date.parse(timestamp);return!Number.isFinite(ms)||ms>=claimedMs}const WORKSPACE_EVIDENCE_REWRITES=new Set(["history_salvage","history_repair","history_redact","merge_reconcile"]);async function workspaceRestoredSince(pmRoot,claimedAt){let entries;try{entries=await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID)}catch{return!0}const claimedMs=Date.parse(claimedAt);return entries.some(entry=>{if(!isWellFormedHistoryRecord(entry))return!0;if(entry.op==="workspace_snapshot_restore"||WORKSPACE_EVIDENCE_REWRITES.has(entry.op))return atOrAfter(entry.ts,claimedMs);if(entry.op!=="history_compact_baseline")return!1;const bound=recordedBaselineActivity(entry);return bound===void 0||atOrAfter(entry.ts,claimedMs)||bound!==null&&atOrAfter(bound,claimedMs)})}async function resolveItemOwnershipConflict(pmRoot,itemId,assignee){return(await readOwnershipEvidence(pmRoot,itemId,assignee)).conflict}async function resolveItemOwnershipActivity(pmRoot,itemId,assignee,options){const{conflict,history,readable,unproven}=await readOwnershipEvidence(pmRoot,itemId,assignee),judge=reason=>evaluateClaimActivity(conflict.since,latestHistoryTimestamp(history),{...options,...readable?{}:{history_unreadable:!0},...reason===void 0?{}:{unproven_activity:reason}}),activity=judge(unproven);return!activity.stale_policy.stale||!await workspaceRestoredSince(pmRoot,conflict.since)?{...conflict,activity}:{...conflict,activity:judge("workspace_restored")}}async function describeItemOwnershipConflict(pmRoot,itemId,assignee){return(await resolveItemOwnershipConflict(pmRoot,itemId,assignee)).phrase}export{describeItemOwnershipConflict,evaluateClaimActivity,resolveItemOwnershipActivity,resolveItemOwnershipConflict};
2
2
  //# sourceMappingURL=ownership-source.js.map