@codyswann/lisa 4.110.2 → 4.111.0

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 (146) hide show
  1. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  2. package/dist/core/upstream-evidence-manifest.d.ts.map +1 -1
  3. package/dist/core/upstream-evidence-manifest.js +74 -6
  4. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  5. package/package.json +4 -4
  6. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  7. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  8. package/plugins/lisa/.codex-plugin/scripts/human-gate-lift.mjs +148 -0
  9. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/SKILL.md +69 -4
  10. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/references/runbook-template.md +3 -0
  11. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/cli-cycle.mjs +16 -0
  12. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/cli-orphans.mjs +162 -0
  13. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/cli-usage.mjs +40 -0
  14. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/ledger.mjs +15 -3
  15. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/orphan-buckets.mjs +233 -0
  16. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/orphan-holds.mjs +252 -0
  17. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/orphan-sweep.mjs +335 -0
  18. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/session-manager.mjs +12 -1
  19. package/plugins/lisa/skills/lisa-session-manager/SKILL.md +69 -4
  20. package/plugins/lisa/skills/lisa-session-manager/references/runbook-template.md +3 -0
  21. package/plugins/lisa/skills/lisa-session-manager/scripts/cli-cycle.mjs +16 -0
  22. package/plugins/lisa/skills/lisa-session-manager/scripts/cli-orphans.mjs +162 -0
  23. package/plugins/lisa/skills/lisa-session-manager/scripts/cli-usage.mjs +40 -0
  24. package/plugins/lisa/skills/lisa-session-manager/scripts/ledger.mjs +15 -3
  25. package/plugins/lisa/skills/lisa-session-manager/scripts/orphan-buckets.mjs +233 -0
  26. package/plugins/lisa/skills/lisa-session-manager/scripts/orphan-holds.mjs +252 -0
  27. package/plugins/lisa/skills/lisa-session-manager/scripts/orphan-sweep.mjs +335 -0
  28. package/plugins/lisa/skills/lisa-session-manager/scripts/session-manager.mjs +12 -1
  29. package/plugins/lisa-agy/plugin.json +1 -1
  30. package/plugins/lisa-agy/skills/lisa-session-manager/SKILL.md +69 -4
  31. package/plugins/lisa-agy/skills/lisa-session-manager/references/runbook-template.md +3 -0
  32. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/cli-cycle.mjs +16 -0
  33. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/cli-orphans.mjs +162 -0
  34. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/cli-usage.mjs +40 -0
  35. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/ledger.mjs +15 -3
  36. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/orphan-buckets.mjs +233 -0
  37. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/orphan-holds.mjs +252 -0
  38. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/orphan-sweep.mjs +335 -0
  39. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/session-manager.mjs +12 -1
  40. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  41. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  42. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  43. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  44. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  45. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  46. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  47. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  48. package/plugins/lisa-copilot/skills/lisa-session-manager/SKILL.md +69 -4
  49. package/plugins/lisa-copilot/skills/lisa-session-manager/references/runbook-template.md +3 -0
  50. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/cli-cycle.mjs +16 -0
  51. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/cli-orphans.mjs +162 -0
  52. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/cli-usage.mjs +40 -0
  53. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/ledger.mjs +15 -3
  54. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/orphan-buckets.mjs +233 -0
  55. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/orphan-holds.mjs +252 -0
  56. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/orphan-sweep.mjs +335 -0
  57. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/session-manager.mjs +12 -1
  58. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  59. package/plugins/lisa-cursor/skills/lisa-session-manager/SKILL.md +69 -4
  60. package/plugins/lisa-cursor/skills/lisa-session-manager/references/runbook-template.md +3 -0
  61. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/cli-cycle.mjs +16 -0
  62. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/cli-orphans.mjs +162 -0
  63. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/cli-usage.mjs +40 -0
  64. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/ledger.mjs +15 -3
  65. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/orphan-buckets.mjs +233 -0
  66. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/orphan-holds.mjs +252 -0
  67. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/orphan-sweep.mjs +335 -0
  68. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/session-manager.mjs +12 -1
  69. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  70. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  71. package/plugins/lisa-devin/skills/lisa-session-manager/SKILL.md +69 -4
  72. package/plugins/lisa-devin/skills/lisa-session-manager/references/runbook-template.md +3 -0
  73. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/cli-cycle.mjs +16 -0
  74. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/cli-orphans.mjs +162 -0
  75. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/cli-usage.mjs +40 -0
  76. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/ledger.mjs +15 -3
  77. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/orphan-buckets.mjs +233 -0
  78. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/orphan-holds.mjs +252 -0
  79. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/orphan-sweep.mjs +335 -0
  80. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/session-manager.mjs +12 -1
  81. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  82. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  83. package/plugins/lisa-expo-agy/plugin.json +1 -1
  84. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  85. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  86. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  87. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  88. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  89. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  90. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  91. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  92. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  93. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  94. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  95. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  96. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  97. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  98. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  99. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  100. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  101. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  102. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  103. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  104. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  105. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  106. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  107. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  108. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  109. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  110. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  111. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  112. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  113. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  114. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  115. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  116. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  117. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  118. package/plugins/lisa-rails-agy/plugin.json +1 -1
  119. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  120. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  121. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  122. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  123. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  124. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  125. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  126. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  127. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  128. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  129. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  130. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  131. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  132. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  133. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  134. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  135. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  136. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  137. package/plugins/src/base/skills/lisa-session-manager/SKILL.md +69 -4
  138. package/plugins/src/base/skills/lisa-session-manager/references/runbook-template.md +3 -0
  139. package/plugins/src/base/skills/lisa-session-manager/scripts/cli-cycle.mjs +16 -0
  140. package/plugins/src/base/skills/lisa-session-manager/scripts/cli-orphans.mjs +162 -0
  141. package/plugins/src/base/skills/lisa-session-manager/scripts/cli-usage.mjs +40 -0
  142. package/plugins/src/base/skills/lisa-session-manager/scripts/ledger.mjs +15 -3
  143. package/plugins/src/base/skills/lisa-session-manager/scripts/orphan-buckets.mjs +233 -0
  144. package/plugins/src/base/skills/lisa-session-manager/scripts/orphan-holds.mjs +252 -0
  145. package/plugins/src/base/skills/lisa-session-manager/scripts/orphan-sweep.mjs +335 -0
  146. package/plugins/src/base/skills/lisa-session-manager/scripts/session-manager.mjs +12 -1
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Plan the session manager's "Orphans and holds" sweep (CodySwannGT/lisa#4722).
3
+ * Pure: no I/O, no config reads; the clock arrives as `now`.
4
+ *
5
+ * Reconcile used to look only at the manager's own ledger, so items left in
6
+ * the `claimed` (or `review`) role by an earlier manager session, a worker
7
+ * that died or was stopped, or a completion step that never ran were never
8
+ * revisited. On a live project most claimed items had no live worker, some
9
+ * for days. This planner buckets each such orphan:
10
+ *
11
+ * - `doneReady`: its pull request merged; only completion is missing.
12
+ * - `return`: no open or merged pull request; back to the `ready` role.
13
+ * - `redispatch`: an open pull request and no owner; spawn a fresh attempt.
14
+ * - `parked`: held for a person; leave it, but make sure it says why.
15
+ * - `lookup`: the pull request is not known yet; the manager finds it first.
16
+ *
17
+ * It never touches an item the ledger shows live, one assigned to someone
18
+ * other than "me" or an operator, or one updated within `staleHours`, which
19
+ * protects a person running `/lisa:implement` by hand outside the manager.
20
+ * The hold half lives in orphan-holds.mjs. Writes per cycle are capped at
21
+ * `max`, shared across orphans and hold lifts, and the rest are `deferred`.
22
+ * @module session-manager/orphan-sweep
23
+ */
24
+ import {
25
+ entryMatches,
26
+ idComparableValues,
27
+ parseIdEntries,
28
+ } from "../../../scripts/operator-id-kinds.mjs";
29
+ import { holdDigest, judgeHold } from "./orphan-holds.mjs";
30
+ import { FINISH_RETRY_HOURS, classifyOrphan } from "./orphan-buckets.mjs";
31
+
32
+ export {
33
+ FINISH_REFUSED_PREFIX,
34
+ FINISH_RETRY_HOURS,
35
+ SWEEP_COMMENT_PREFIX,
36
+ } from "./orphan-buckets.mjs";
37
+
38
+ /** At most this many writes per cycle unless the caller says otherwise. */
39
+ export const DEFAULT_ORPHAN_MAX = 10;
40
+
41
+ /** An item updated more recently than this many hours is left alone. */
42
+ export const DEFAULT_STALE_HOURS = 6;
43
+
44
+ /** The order buckets spend the cap in. */
45
+ const CAPPED_BUCKETS = ["doneReady", "return", "redispatch", "parked"];
46
+
47
+ /**
48
+ * A trimmed id string, or null. Numeric ids become strings.
49
+ * @param {unknown} value - Raw id
50
+ * @returns {string | null} Comparable id
51
+ */
52
+ function idOrNull(value) {
53
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
54
+ return Number.isSafeInteger(value) ? String(value) : null;
55
+ }
56
+
57
+ /**
58
+ * The fields one assignee is compared on, the way `queue` compares them: a
59
+ * plain string is the tracker's normalized id (GitHub login, Jira accountId,
60
+ * Linear user id); a `{login, id}` object adds the kind-keyed fields.
61
+ * @param {unknown} assignee - One assignee as the tracker gave it
62
+ * @returns {{plain: string|null, login: string|null, id: string|null}} Fields
63
+ */
64
+ function assigneeFields(assignee) {
65
+ if (assignee !== null && typeof assignee === "object") {
66
+ const login = idOrNull(assignee.login);
67
+ const id = idOrNull(assignee.id ?? assignee.accountId);
68
+ return { plain: login ?? id, login, id };
69
+ }
70
+ return { plain: idOrNull(assignee), login: null, id: null };
71
+ }
72
+
73
+ /**
74
+ * Whether any assignee is neither "me" nor an operator.
75
+ * @param {unknown} assignees - The item's assignees
76
+ * @param {{me: string|null, operators: object[]}} who - Identities
77
+ * @returns {boolean} True when someone else holds the item
78
+ */
79
+ function heldBySomeoneElse(assignees, who) {
80
+ return (Array.isArray(assignees) ? assignees : []).some(assignee => {
81
+ const fields = assigneeFields(assignee);
82
+ if (fields.plain === null) return false;
83
+ if (who.me !== null && fields.plain === who.me) return false;
84
+ return !who.operators.some(entry => entryMatches(entry, fields));
85
+ });
86
+ }
87
+
88
+ /**
89
+ * Resolve and check the options.
90
+ * @param {object} opts - Caller options
91
+ * @returns {object} Resolved policy
92
+ */
93
+ function resolveOptions(opts = {}) {
94
+ const now = new Date(opts.now ?? Number.NaN).getTime();
95
+ if (!Number.isFinite(now)) throw new Error("now must be a valid time");
96
+ const max = opts.max ?? DEFAULT_ORPHAN_MAX;
97
+ if (!Number.isInteger(max) || max < 0) {
98
+ throw new Error("max must be a non-negative integer");
99
+ }
100
+ const staleHours = opts.staleHours ?? DEFAULT_STALE_HOURS;
101
+ if (typeof staleHours !== "number" || !(staleHours >= 0)) {
102
+ throw new Error("staleHours must be a non-negative number");
103
+ }
104
+ return {
105
+ now,
106
+ max,
107
+ staleMs: staleHours * 3_600_000,
108
+ live: new Set(Array.isArray(opts.liveRefs) ? opts.liveRefs : []),
109
+ who: {
110
+ me: idOrNull(opts.me),
111
+ operators: parseIdEntries(opts.operatorIds),
112
+ },
113
+ trustedHumanActorIds: idComparableValues(opts.trustedAuthorIds),
114
+ humanNeededLabel: opts.humanNeededLabel,
115
+ humanOnly: opts.humanOnly,
116
+ readyLabel: opts.readyLabel,
117
+ lifecycleLabels: opts.lifecycleLabels,
118
+ roleLabels: opts.roleLabels ?? {},
119
+ rolesAreStates: opts.rolesAreStates === true,
120
+ finishRetryMs: FINISH_RETRY_HOURS * 3_600_000,
121
+ previousDigest: opts.previousDigest ?? null,
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Why an orphan candidate is left alone, or null when the sweep may act.
127
+ * @param {object} item - Candidate with a ref
128
+ * @param {object} policy - Resolved policy
129
+ * @returns {string | null} Skip reason
130
+ */
131
+ function skipReason(item, policy) {
132
+ if (policy.live.has(item.ref)) return "live";
133
+ if (heldBySomeoneElse(item.assignees, policy.who)) return "foreign";
134
+ const updated = new Date(item.updatedAt ?? Number.NaN).getTime();
135
+ if (!Number.isFinite(updated)) return "undated";
136
+ return policy.now - updated < policy.staleMs ? "fresh" : null;
137
+ }
138
+
139
+ /**
140
+ * The canonical ref of a raw entry, or empty.
141
+ * @param {unknown} raw - Raw entry
142
+ * @returns {string} Trimmed ref
143
+ */
144
+ const refOf = raw => (typeof raw?.ref === "string" ? raw.ref.trim() : "");
145
+
146
+ /**
147
+ * Sort orphan candidates into skips and buckets, uncapped.
148
+ * @param {unknown} items - Raw candidates
149
+ * @param {object} policy - Resolved policy
150
+ * @returns {{skipped: object[], buckets: Record<string, object[]>}} Sorted
151
+ */
152
+ function sortOrphans(items, policy) {
153
+ const skipped = [];
154
+ const buckets = {
155
+ lookup: [],
156
+ doneReady: [],
157
+ return: [],
158
+ redispatch: [],
159
+ parked: [],
160
+ };
161
+ for (const raw of Array.isArray(items) ? items : []) {
162
+ const ref = refOf(raw);
163
+ const reason = ref === "" ? "no ref" : skipReason({ ...raw, ref }, policy);
164
+ if (reason !== null) {
165
+ skipped.push({ ref: ref === "" ? null : ref, reason });
166
+ continue;
167
+ }
168
+ const { bucket, entry } = classifyOrphan({ ...raw, ref }, policy);
169
+ buckets[bucket].push(entry);
170
+ }
171
+ return { skipped, buckets };
172
+ }
173
+
174
+ /** Guards that only hold back a lift: the hold is still listed for a person. */
175
+ const LIFT_ONLY_GUARDS = new Set(["fresh", "undated"]);
176
+
177
+ /**
178
+ * Judge every hold, once per ref.
179
+ *
180
+ * A live or foreign hold is skipped outright: not ours to judge. A fresh or
181
+ * undated one is still judged, but only its kept reasons are used; its lift
182
+ * waits. Otherwise any comment, the sweep's own partial-lift comment
183
+ * included, would bump `updatedAt`, drop the hold from the operator's list
184
+ * for `staleHours`, and churn the digest.
185
+ * @param {unknown} holds - Raw hold candidates
186
+ * @param {object} policy - Resolved policy
187
+ * @returns {{lift: object[], keep: object[], skipped: object[]}} Judged
188
+ */
189
+ function sortHolds(holds, policy) {
190
+ const judged = { lift: [], keep: [], skipped: [] };
191
+ const seen = new Set();
192
+ for (const raw of Array.isArray(holds) ? holds : []) {
193
+ const ref = refOf(raw);
194
+ if (ref === "" || seen.has(ref)) continue;
195
+ seen.add(ref);
196
+ const guard = skipReason({ ...raw, ref }, policy);
197
+ if (guard !== null && !LIFT_ONLY_GUARDS.has(guard)) {
198
+ judged.skipped.push({ ref, reason: guard });
199
+ continue;
200
+ }
201
+ const { kind, entry, keep } = judgeHold({ ...raw, ref }, policy);
202
+ if (kind === "lift" && guard !== null) {
203
+ judged.skipped.push({ ref, reason: guard });
204
+ } else {
205
+ judged[kind === "skip" ? "skipped" : kind].push(entry);
206
+ }
207
+ if (keep) judged.keep.push(keep);
208
+ }
209
+ return judged;
210
+ }
211
+
212
+ /**
213
+ * Whether an entry spends the cap: a parked item already explaining its hold
214
+ * needs no write, so it never does.
215
+ * @param {string} bucket - Bucket name
216
+ * @param {object} entry - Bucket entry
217
+ * @returns {boolean} True when it costs a write
218
+ */
219
+ const costs = (bucket, entry) =>
220
+ bucket !== "parked" || entry.reasonOnItem === false;
221
+
222
+ /**
223
+ * Spend the cap across buckets in order, deferring the overflow.
224
+ * @param {[string, object[]][]} queue - Buckets in spending order
225
+ * @param {number} max - Cap
226
+ * @returns {{kept: Record<string, object[]>, deferred: object[]}} Capped
227
+ */
228
+ function spendCap(queue, max) {
229
+ let spent = 0;
230
+ const kept = {};
231
+ const deferred = [];
232
+ for (const [bucket, entries] of queue) {
233
+ kept[bucket] = [];
234
+ for (const entry of entries) {
235
+ if (costs(bucket, entry) && spent >= max) {
236
+ deferred.push({ ref: entry.ref, bucket });
237
+ continue;
238
+ }
239
+ if (costs(bucket, entry)) spent += 1;
240
+ kept[bucket].push(entry);
241
+ }
242
+ }
243
+ return { kept, deferred };
244
+ }
245
+
246
+ /**
247
+ * One orphan the sweep acts on, or asks a PR lookup for.
248
+ * @typedef {object} OrphanEntry
249
+ * @property {string} ref - Canonical item ref
250
+ * @property {string} reason - Plain-English reason for the bucket
251
+ * @property {string} [prUrl] - The pull request (`doneReady`, `redispatch`)
252
+ * @property {string} [comment] - The comment to post (`return`, and `parked`
253
+ * when `reasonOnItem` is false); starts with `[lisa-session-manager]`
254
+ * @property {boolean} [reasonOnItem] - `parked` only: the item already says
255
+ * why it is held
256
+ */
257
+
258
+ /**
259
+ * One hold the sweep lifts.
260
+ * @typedef {object} HoldLift
261
+ * @property {string} ref - Canonical item ref
262
+ * @property {string} reason - Plain-English reason
263
+ * @property {string[]} comments - Lift comments, each ending with `decision`
264
+ * when there is one
265
+ * @property {{removeHumanNeededLabel: boolean, addReadyLabel: string|null}}
266
+ * actions - Label writes after the comments
267
+ * @property {string|null} decision - The `Decision:` line; null for a lift
268
+ * that only re-lanes an item an earlier cycle already lifted
269
+ */
270
+
271
+ /**
272
+ * The plan `planOrphanSweep` returns; it writes nothing.
273
+ * @typedef {object} OrphanSweepPlan
274
+ * @property {OrphanEntry[]} doneReady - Merged PR; finish completion
275
+ * @property {OrphanEntry[]} return - Back to the `ready` role
276
+ * @property {OrphanEntry[]} redispatch - Open PR; spawn a fresh attempt
277
+ * @property {OrphanEntry[]} parked - Held for a person; leave it
278
+ * @property {OrphanEntry[]} lookup - Find the PR, then plan again
279
+ * @property {{ref: string|null, reason: string}[]} skipped - Left alone
280
+ * @property {{lift: HoldLift[], keep: {ref: string, reason: string}[],
281
+ * digest: {fingerprint: string|null, text: string, changed: boolean}}}
282
+ * holds - Lifts, truly-human holds and the operator's list
283
+ * @property {{ref: string, bucket: string}[]} deferred - Over the cap
284
+ */
285
+
286
+ /**
287
+ * Plan this cycle's orphan and hold sweep.
288
+ * @param {{items?: unknown, holds?: unknown}} input - Items in the `claimed`
289
+ * (and configured `review`) role as `{ref, role, labels, body, comments,
290
+ * assignees, updatedAt, pr}` (`pr` undefined when not looked up, null when
291
+ * none was found, else `{url, state}`), and held items as
292
+ * `{ref, role?, labels, body, comments, assignees, updatedAt}`
293
+ * @param {{liveRefs?: string[], me?: string|null, operatorIds?: unknown,
294
+ * now: string|number|Date, staleHours?: number, max?: number,
295
+ * trustedAuthorIds?: unknown, humanNeededLabel?: string, humanOnly?: unknown,
296
+ * readyLabel?: string, lifecycleLabels?: string[],
297
+ * roleLabels?: Record<string, string | string[]>,
298
+ * rolesAreStates?: boolean,
299
+ * previousDigest?: string|null}} opts - Ledger-derived live refs,
300
+ * identities, the clock, the cap and the hold policy
301
+ * @returns {OrphanSweepPlan} Plan; it writes nothing
302
+ */
303
+ export function planOrphanSweep(input = {}, opts = {}) {
304
+ const policy = resolveOptions(opts);
305
+ const orphans = sortOrphans(input.items, policy);
306
+ const holds = sortHolds(input.holds, policy);
307
+ const lookup = orphans.buckets.lookup;
308
+ const capped = spendCap(
309
+ [
310
+ ...CAPPED_BUCKETS.map(bucket => [bucket, orphans.buckets[bucket]]),
311
+ ["lift", holds.lift],
312
+ ],
313
+ policy.max
314
+ );
315
+ return {
316
+ doneReady: capped.kept.doneReady,
317
+ return: capped.kept.return,
318
+ redispatch: capped.kept.redispatch,
319
+ parked: capped.kept.parked,
320
+ lookup: lookup.slice(0, policy.max),
321
+ skipped: [...orphans.skipped, ...holds.skipped],
322
+ holds: {
323
+ lift: capped.kept.lift,
324
+ keep: holds.keep,
325
+ digest: holdDigest(holds.keep, policy.previousDigest),
326
+ },
327
+ deferred: [
328
+ ...capped.deferred,
329
+ ...lookup.slice(policy.max).map(entry => ({
330
+ ref: entry.ref,
331
+ bucket: "lookup",
332
+ })),
333
+ ],
334
+ };
335
+ }
@@ -48,6 +48,7 @@ import {
48
48
  } from "./cli-cycle.mjs";
49
49
  import { answer, itemAnswer, markPlan } from "./cli-human.mjs";
50
50
  import { cycle } from "./cyclers.mjs";
51
+ import { orphanPlan } from "./cli-orphans.mjs";
51
52
  import { overruledPlan } from "./cli-overruled.mjs";
52
53
  import { repoDir, start, status, stop, validate } from "./cli-manager.mjs";
53
54
  import { queue } from "./cli-queue.mjs";
@@ -129,6 +130,11 @@ const COMMANDS = {
129
130
  options: { input: text, max: text },
130
131
  positionals: 0,
131
132
  },
133
+ "orphan-plan": {
134
+ run: orphanPlan,
135
+ options: { input: text, max: text, "stale-hours": text },
136
+ positionals: 0,
137
+ },
132
138
  answer: { run: answer, options: {}, positionals: 1 },
133
139
  "item-answer": { run: itemAnswer, options: {}, positionals: 1 },
134
140
  "channel-answer": { run: channelAnswer, options: {}, positionals: 1 },
@@ -171,7 +177,12 @@ const LEDGER_SPECS = {
171
177
  "validation-cleared": { options: {}, positionals: 1 },
172
178
  "clear-setup-gap": { options: {}, positionals: 1 },
173
179
  control: {
174
- options: { paused: text, "max-workers": text, me: text },
180
+ options: {
181
+ paused: text,
182
+ "max-workers": text,
183
+ me: text,
184
+ "hold-digest": text,
185
+ },
175
186
  positionals: 0,
176
187
  },
177
188
  };
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: lisa-session-manager
3
- description: "Runs the local session manager for a project: a long-lived Claude Code session in tmux that dispatches Ready work items to fresh background worker sessions (`/lisa:implement <REF> managedBy=<manager>`), relays worker questions and operator answers over the project's own Telegram bot when one is configured (Telegram is optional; without it questions stay pending in the ledger), reconciles stalled and blocked items, and records one automation run outcome per cycle. Tracker-neutral (GitHub, Jira, Linear); lifecycle states always come from config. Requires Claude Code (background sessions, channels, cross-session messaging). Set it up with lisa-setup-session-manager."
3
+ description: "Runs the local session manager for a project: a long-lived Claude Code session in tmux that dispatches Ready work items to fresh background worker sessions (`/lisa:implement <REF> managedBy=<manager>`), relays worker questions and operator answers over the project's own Telegram bot when one is configured (Telegram is optional; without it questions stay pending in the ledger), reconciles stalled, blocked and orphaned items, re-judges human holds, and records one automation run outcome per cycle. Tracker-neutral (GitHub, Jira, Linear); lifecycle states always come from config. Requires Claude Code (background sessions, channels, cross-session messaging). Set it up with lisa-setup-session-manager."
4
4
  ---
5
5
 
6
6
  # Session manager
@@ -456,7 +456,7 @@ shows them.
456
456
  not valid JSON): report its message
457
457
  to the operator and leave the item; it never means the reply was a credential.
458
458
 
459
- **In Progress (ledger-driven).** Run `classify`. Items not in the ledger are not yours: leave them.
459
+ **In Progress (ledger-driven).** Run `classify`. Items not in the ledger are handled by "Orphans and holds" below, never here.
460
460
 
461
461
  | Classification | Action |
462
462
  |---|---|
@@ -473,6 +473,69 @@ covers a plain Bash call (lisa#4522). So `blocked-on-prompt` detection is the gu
473
473
  `resume` passes the same permission flags as `spawn`, so a relayed answer or nudge never drops
474
474
  the bypass.
475
475
 
476
+ **Orphans and holds** (CodySwannGT/lisa#4722). Items get left in the `claimed` role (or the
477
+ `review` role) by an earlier manager session, a worker that died or was stopped, or a completion
478
+ step that never ran, and nothing else revisits them. Holds an agent may decide sit in the queue
479
+ just as long. Sweep both every cycle, after `classify` and before Dispatch:
480
+
481
+ 1. **List** the items in the `claimed` role and, only when `resolve-lifecycle-role.mjs` resolves
482
+ the optional `review` role, the `review` role; plus the open items carrying the human-needed
483
+ label or a `[lisa-human-gate]` body marker, in any role. Page every list to completion (GitHub:
484
+ `gh`, with `--limit 10000`; Jira / Linear: `lisa-atlassian-access` or `lisa-linear-access`).
485
+ Write `{"complete":true,"items":[{ref,role,labels,body,comments,assignees,updatedAt}],"holds":[{ref,role,labels,body,comments,assignees,updatedAt}]}`
486
+ to `.lisa/session-manager/orphan-input.json`: refs canonical as dispatch uses them, comments
487
+ as `{id,author,body,createdAt}` with the author's stable id and the comment's own posting
488
+ time (a refusal comment with no `createdAt` never ages out of its 24-hour park), assignees as `{login,id}` objects on GitHub (the REST
489
+ `.assignees[].id`) and as the account or user id on Jira and Linear, and each hold's `role` as
490
+ the lifecycle role it is in (`ready`, `claimed`, `review`, `blocked`, `done`), so a lift never
491
+ moves an item that is in a lane back to the `ready` role. On Jira and Linear a hold with no
492
+ known role is lifted but never moved. Set `complete` to `true`
493
+ only when every list reached its last page; the CLI refuses anything else. Run
494
+ `node "$SM/session-manager.mjs" orphan-plan --input .lisa/session-manager/orphan-input.json --project-root "$ROOT"`.
495
+ For each ref in `lookup`, find its pull request in the item's repo dir
496
+ (`gh pr list --state all --search <ref>`); when several match, prefer the merged one, then an
497
+ open one, then a closed one. Set that item's `pr` to `null` or
498
+ `{"url":…,"state":"open"|"merged"|"closed"}`, and run it again. The live refs, "me", the
499
+ operators and the trusted authors come from the ledger and config, never from the input. It
500
+ skips refs the ledger shows running or asking (their holds too, so an item waiting on a
501
+ person's answer is never on the operator's list twice), items assigned to anyone but "me" or an
502
+ operator, and items updated within `--stale-hours` (default 6) or with no `updatedAt`, which
503
+ protects a person running `/lisa:implement` by hand. A live or foreign hold is skipped the
504
+ same way; a fresh or undated one is not lifted this cycle, but its human reasons still reach
505
+ the operator's list, so a new comment never makes the list change.
506
+ 2. **Act** per bucket. **Before every write** in this sweep (a finish, a return, a re-dispatch
507
+ claim, a parked comment, a hold lift), re-read the item with `lisa-tracker-read`. Skip it for
508
+ this cycle, with one transcript line and no write, when its role is no longer the one the plan
509
+ saw, it gained an assignee who is neither "me" nor an operator, or its `updatedAt` is newer than
510
+ the snapshot the plan used, apart from this sweep's own earlier write on that item. The plan is
511
+ a snapshot; someone may have moved the item since. Every write goes through `lisa-tracker-write`
512
+ and is read back with `lisa-tracker-read`; every comment is the planner's, which starts with
513
+ `[lisa-session-manager]`.
514
+ - `doneReady`: the pull request merged. In the item's repo dir run
515
+ `node scripts/lisa-work-item.mjs finish --ref <ref> --pr-url <prUrl>`. If it refuses, post
516
+ one comment that starts `[lisa-session-manager] Cannot complete:` and says, in plain words,
517
+ why the item cannot complete yet. Later cycles see that comment and park the item, then retry
518
+ finishing once it is more than 24 hours old.
519
+ - `return`: move it to the `ready` role with the entry's `comment`.
520
+ - `redispatch`: an open pull request and no worker. Claim it (`reused`) and `spawn` it exactly
521
+ as Dispatch steps 2.3 and 2.4, ahead of new items, while `capacity` says `can_spawn`. A
522
+ spawn that reaches `stall.maxAttempts` follows the `exhausted` row above.
523
+ - `parked`: post the entry's `comment` only when `reasonOnItem` is false. An item in the
524
+ `review` role with an open pull request is parked, never re-dispatched: it is waiting on
525
+ review or merge.
526
+ - `holds.lift`: post each of its `comments` (each ends with its `Decision:` line; `decision` is null for a lift an earlier cycle
527
+ already posted, which only re-lanes the item); a partial
528
+ lift is also in `holds.keep` with the reasons still left for a person. Then remove
529
+ the human-needed label and move it to the `ready` role as its `actions` say.
530
+ - `holds.keep`: when `holds.digest.changed` is true, send `holds.digest.text` to the operator
531
+ once (Telegram when configured, else the cycle summary; nothing when the text is empty), then
532
+ record it with `ledger control --hold-digest <fingerprint>` (`none` when `fingerprint` is
533
+ null). An unchanged list is never re-sent.
534
+ - `deferred`: the next cycle takes them.
535
+
536
+ A failure anywhere in this sweep is one transcript line: it never holds dispatch and never makes
537
+ the cycle `recovery-required`.
538
+
476
539
  **Blocked.** List the items in the `blocked` role (paged to completion, same access paths as the
477
540
  queue below). For each:
478
541
 
@@ -650,7 +713,7 @@ session `start` creates), every cycle ends in **exactly one** of the six outcome
650
713
  | This cycle | Run outcome |
651
714
  |---|---|
652
715
  | No dispatch, no state change, no question relayed or newly pending. The summary still states the denominator: "swept N ready, 0 dispatchable; R running/C cap". | `nothing-needed` |
653
- | At least one of: a worker spawned and seen live in `status`; a Blocked→Ready release written and read back; an answer delivered and its marker removed (`SendMessage` acknowledged, or `resume` returned a session id), or recorded on the item and read back before its marker was removed; a stalled or `blocked-on-prompt` item retried. | `change-proved` |
716
+ | At least one of: a worker spawned and seen live in `status`; a Blocked→Ready release written and read back; an orphan finished, returned or re-dispatched, or a hold lifted, written and read back; an answer delivered and its marker removed (`SendMessage` acknowledged, or `resume` returned a session id), or recorded on the item and read back before its marker was removed; a stalled or `blocked-on-prompt` item retried. | `change-proved` |
654
717
  | An item was marked human-needed ("Mark and move on": marker and question comment written and read back), in any of the four cases, including an `exhausted` item moved to the `blocked` role, or a marked item whose question comment was re-posted after `item-answer` reported `no-question-comment`; or a worker `FAILED` moved the item to the `blocked` role with its reason comment, both read back. The summary names each ref and where to answer it. | `candidate-proposed` |
655
718
  | No item was newly marked, but a pending question was re-sent on Telegram (`requestion`) and awaits the operator, and nothing else changed. | `approval-requested` |
656
719
  | The tracker, a configured Telegram or `claude` was unreachable; Telegram is configured but was unavailable or unpaired (a question stayed pending with no Telegram message id); a human-needed mark could not be written or read back, or no marker is configured; an answer for a finished worker, an `exhausted` item or a `decision` no worker has picked up could not be posted on the item or read back (its question stays pending); a worker `FAILED`'s move to the `blocked` role could not be written or read back; a spawn failed after the claim (the item went back to Ready); a worker classified `setup-gap` (the item went back to Ready); the capacity probe failed. | `recovery-required` |
@@ -668,7 +731,9 @@ other candidates. The planning-miss candidate a mark routes (step 6 of "Mark and
668
731
  one: it runs in the background, and whatever it does — a learning PR, a drop note, a failure —
669
732
  never moves the cycle's outcome. The same holds for the overruled-escalation sweep in Reconcile,
670
733
  including its `[lisa-escalation-overruled]` marker comment: it is never a state change for the run
671
- outcome. When several rows apply, the most urgent wins: `recovery-required`, then
734
+ outcome. In the "Orphans and holds" sweep, a completion, return, re-dispatch or hold lift
735
+ written and read back counts as `change-proved`; a failure in that sweep is one transcript line and
736
+ never `recovery-required`, and a parked comment or the operator's hold list is never a state change. When several rows apply, the most urgent wins: `recovery-required`, then
672
737
  `candidate-proposed`, then `approval-requested`, then `change-proved`.
673
738
  A missing channel is never a reason for `recovery-required`: with `notify` `none`, a cycle ends
674
739
  `nothing-needed`, `change-proved` or `candidate-proposed` on its work alone.
@@ -9,6 +9,9 @@ the project: edit the prose to match how you run it. The loop follows the
9
9
 
10
10
  Keeps Ready work moving on this machine: each Ready item gets its own fresh coding session, and the
11
11
  operator answers that session's questions, from their phone when the project has a Telegram bot.
12
+ Each cycle it also sweeps items left claimed with no live worker (finishing, returning or
13
+ re-dispatching them) and re-judges human holds: it lifts the ones an agent may decide and sends the
14
+ operator one list of the rest, only when that list changes.
12
15
 
13
16
  ## Sources of truth
14
17
 
@@ -57,6 +57,21 @@ function pausedFlag(value) {
57
57
  return value === "true";
58
58
  }
59
59
 
60
+ /**
61
+ * Parse `--hold-digest <fingerprint>`: the sha256 `orphan-plan` reported.
62
+ * @param {string} value - Flag value
63
+ * @returns {string} Fingerprint
64
+ */
65
+ function holdDigestFlag(value) {
66
+ if (!/^[0-9a-f]{64}$/u.test(value)) {
67
+ throw new CliError(
68
+ "--hold-digest must be a sha256 fingerprint or none.",
69
+ 2
70
+ );
71
+ }
72
+ return value;
73
+ }
74
+
60
75
  /**
61
76
  * Parse a flag where `none` clears the value.
62
77
  * @param {string | undefined} value - Flag value
@@ -173,6 +188,7 @@ const LEDGER_ACTIONS = {
173
188
  intFlag(value, "--max-workers")
174
189
  ),
175
190
  me: clearable(ctx.values.me, value => value),
191
+ holdDigest: clearable(ctx.values["hold-digest"], holdDigestFlag),
176
192
  }).filter(([, value]) => value !== undefined)
177
193
  )
178
194
  ),
@@ -0,0 +1,162 @@
1
+ /**
2
+ * `orphan-plan`: the session manager's per-cycle "Orphans and holds" sweep
3
+ * (CodySwannGT/lisa#4722). The plan writes nothing: the manager finishes,
4
+ * returns, re-dispatches or parks each orphan and lifts or keeps each hold
5
+ * through `lisa-tracker-write`, as the skill says.
6
+ *
7
+ * Who the manager is and who may release a hold come from the ledger and
8
+ * config only, never from the input: the input is assembled from items'
9
+ * own (untrusted) bodies and comments, so ids carried beside them would let
10
+ * an item vouch for itself, and a live ref an input could drop would let the
11
+ * sweep return an item a worker is still on.
12
+ *
13
+ * Item bodies and comments arrive on stdin or in a file, never in argv.
14
+ * @module session-manager/cli-orphans
15
+ */
16
+ import {
17
+ readPath,
18
+ resolveRole,
19
+ } from "../../../scripts/resolve-lifecycle-role.mjs";
20
+ import {
21
+ CliError,
22
+ asSetupError,
23
+ humanNeededLabel,
24
+ intFlag,
25
+ loadProject,
26
+ stdinText,
27
+ validOrAbsent,
28
+ } from "./cli-runtime.mjs";
29
+ import { parseJson, readJsonFile } from "./json-input.mjs";
30
+ import { readLedger } from "./ledger.mjs";
31
+ import { planOrphanSweep } from "./orphan-sweep.mjs";
32
+
33
+ /** The roles whose labels count as "in a lane" for a hold release. */
34
+ const LANE_ROLES = ["ready", "claimed", "blocked", "review", "human_needed"];
35
+
36
+ /** Ledger statuses that mean a worker is on the item, or a person is asked. */
37
+ const LIVE_STATUSES = new Set(["running", "question"]);
38
+
39
+ /**
40
+ * The tracker this project uses.
41
+ * @param {ReturnType<typeof loadProject>} project - Loaded project
42
+ * @returns {string | undefined} `github`, `jira` or `linear`
43
+ */
44
+ const trackerOf = project => project.local?.tracker ?? project.global?.tracker;
45
+
46
+ /**
47
+ * One lifecycle role's configured value, empty when unset.
48
+ * @param {ReturnType<typeof loadProject>} project - Loaded project
49
+ * @param {string} name - Role name
50
+ * @returns {string} Label or state
51
+ */
52
+ function roleValue(project, name) {
53
+ return resolveRole({
54
+ role: name,
55
+ vendor: trackerOf(project),
56
+ local: project.local,
57
+ global: project.global,
58
+ }).value;
59
+ }
60
+
61
+ /**
62
+ * Every configured `done` value: the env-keyed map's values, or one string.
63
+ * @param {ReturnType<typeof loadProject>} project - Loaded project
64
+ * @returns {string[]} Done labels or states
65
+ */
66
+ function doneValues(project) {
67
+ const roots = { jira: "jira.workflow", linear: "linear.workflow" };
68
+ const root = roots[trackerOf(project)] ?? "github.labels.build";
69
+ for (const config of [project.local, project.global]) {
70
+ const done = readPath(config, `${root}.done`);
71
+ if (typeof done === "string" && done !== "") return [done];
72
+ if (done && typeof done === "object") {
73
+ return Object.values(done).filter(value => typeof value === "string");
74
+ }
75
+ }
76
+ return [];
77
+ }
78
+
79
+ /**
80
+ * The hold policy from config: labels, lanes and human-only classes.
81
+ * @param {ReturnType<typeof loadProject>} project - Loaded project
82
+ * @returns {object} Policy fields for planOrphanSweep
83
+ */
84
+ function holdPolicy(project) {
85
+ const humanOnly =
86
+ readPath(project.local, "humanGate.humanOnly") ??
87
+ readPath(project.global, "humanGate.humanOnly");
88
+ return {
89
+ humanNeededLabel: humanNeededLabel(project, undefined),
90
+ humanOnly,
91
+ readyLabel: roleValue(project, "ready"),
92
+ // A hold's role is its lane: on Jira and Linear the lane is a state, so
93
+ // the lift's lane check reads it as one more label.
94
+ roleLabels: {
95
+ ...Object.fromEntries(
96
+ LANE_ROLES.map(name => [name, roleValue(project, name)]).filter(
97
+ ([, value]) => value !== ""
98
+ )
99
+ ),
100
+ done: doneValues(project),
101
+ },
102
+ // Where roles are states, a hold with no known lane is lifted but never
103
+ // re-laned (fail closed).
104
+ rolesAreStates: trackerOf(project) !== "github",
105
+ lifecycleLabels: [
106
+ ...LANE_ROLES.map(name => roleValue(project, name)),
107
+ ...doneValues(project),
108
+ ].filter(value => value !== ""),
109
+ };
110
+ }
111
+
112
+ /**
113
+ * Read the envelope and refuse one not paged to completion.
114
+ * @param {object} ctx - CLI context
115
+ * @returns {{items: unknown, holds: unknown}} The listed items and holds
116
+ */
117
+ function readEnvelope(ctx) {
118
+ const envelope = ctx.values.input
119
+ ? readJsonFile(ctx.values.input)
120
+ : parseJson(stdinText(ctx, "orphan JSON"), "stdin");
121
+ if (envelope?.complete !== true) {
122
+ throw new CliError(
123
+ "The orphan listing was not paged to completion (complete !== true); " +
124
+ "refusing to plan from a partial list.",
125
+ 2
126
+ );
127
+ }
128
+ return { items: envelope.items, holds: envelope.holds };
129
+ }
130
+
131
+ /**
132
+ * `orphan-plan [--input <file>] [--max <n>] [--stale-hours <n>]` (stdin
133
+ * without --input: `{"complete":true,"items":[...],"holds":[...]}`).
134
+ * @param {object} ctx - CLI context
135
+ * @returns {Promise<{ json: object }>} The plan from planOrphanSweep
136
+ */
137
+ export async function orphanPlan(ctx) {
138
+ const input = readEnvelope(ctx);
139
+ const max = intFlag(ctx.values.max, "--max");
140
+ const staleHours = intFlag(ctx.values["stale-hours"], "--stale-hours");
141
+ const project = loadProject(ctx.root);
142
+ const config = validOrAbsent(project);
143
+ const ledger = await readLedger(ctx.root);
144
+ const liveRefs = Object.entries(ledger.items)
145
+ .filter(([, item]) => LIVE_STATUSES.has(item.status))
146
+ .map(([ref]) => ref);
147
+ return {
148
+ json: asSetupError(() =>
149
+ planOrphanSweep(input, {
150
+ liveRefs,
151
+ me: ledger.control.me ?? null,
152
+ operatorIds: config?.operatorIds ?? [],
153
+ trustedAuthorIds: config?.trustedAuthorIds ?? [],
154
+ now: new Date(),
155
+ ...(max === undefined ? {} : { max }),
156
+ ...(staleHours === undefined ? {} : { staleHours }),
157
+ previousDigest: ledger.control.holdDigest ?? null,
158
+ ...holdPolicy(project),
159
+ })
160
+ ),
161
+ };
162
+ }