mandrel 2.91.0 → 2.93.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.
@@ -506,7 +506,7 @@ number of keys.
506
506
  | `delivery.quality.gates.maintainability.targetDirs` | `[".agents/scripts", "tests"]` | `["src"]` | Root scans the framework's own source tree; consumer template scans the conventional `src/`. |
507
507
  | `delivery.quality.gates.crap.targetDirs` | `[".agents/scripts"]` | `["src"]` | Same reason as maintainability above. |
508
508
  | `github.owner` / `.repo` / `.projectNumber` | Populated for `dsj1984/mandrel` | `[OWNER]` / `[REPO]` / `null` | Shared repo identifiers; placeholders in the template are replaced by `node .agents/scripts/bootstrap.js` (or by hand). |
509
- | `github.operatorHandle` | Committed as the `@[USERNAME]` placeholder; each contributor overrides it in gitignored `.agentrc.local.json` | `@[USERNAME]` | Schema-required, but per-contributor: the committed placeholder resolves to null and the lease guards fail closed until you set your own handle locally (see [Per-machine local overrides](#per-machine-local-overrides)). |
509
+ | `github.operatorHandle` | Committed as the `@[USERNAME]` placeholder; each contributor overrides it in gitignored `.agentrc.local.json`, or with `GH_OPERATOR_HANDLE` where there is no overlay (cloud sessions) | `@[USERNAME]` | Schema-required, but per-contributor: the committed placeholder resolves to null and the lease guards fail closed until you set your own handle locally (see [Per-machine local overrides](#per-machine-local-overrides)). |
510
510
  | `delivery.worktreeIsolation.nodeModulesStrategy` | `clone` | `clone` | Platform default on darwin/linux (copy-on-write clone of donor `node_modules`); Windows dogfood/template use `per-worktree`. |
511
511
 
512
512
  When a consumer runs `/mandrel-update`, the
@@ -664,6 +664,39 @@ makes one developer the fallback identity for everyone else.
664
664
  Otherwise a developer without an overlay silently seeds Story branches from,
665
665
  and opens PRs against, `main`.
666
666
 
667
+ **Environment override.** `GH_OPERATOR_HANDLE` beats both files: when it is
668
+ set, the resolver uses it as `github.operatorHandle`, so precedence is
669
+ `GH_OPERATOR_HANDLE` → `.agentrc.local.json` → `.agentrc.json`. A bare login
670
+ gets its `@` prefix added, an empty value is ignored, and a `.env` entry
671
+ works too. The override only applies when the config already has a `github`
672
+ block. It is the same variable `bootstrap.js` reads for the handle.
673
+
674
+ #### Claude Code cloud environments
675
+
676
+ A cloud session clones the repo without the gitignored `.agentrc.local.json`,
677
+ so it has only the committed `@[USERNAME]` placeholder, or whatever handle
678
+ the team committed. Each person has their own cloud environment, so one
679
+ environment variable identifies one person:
680
+
681
+ - Add `GH_OPERATOR_HANDLE=your-github-login` to your cloud environment's
682
+ **Environment variables**. Use your own user login, never an Organization
683
+ or team. Don't write `.agentrc.local.json` from a setup script instead: the
684
+ script runs once, and later sessions start from a cached snapshot that
685
+ skips it.
686
+ - Leave `GITHUB_TOKEN` and `GH_TOKEN` unset. Every GitHub request from a
687
+ hosted cloud session goes through the Claude Code GitHub proxy, which
688
+ supplies your connected GitHub account's credential for REST calls.
689
+
690
+ The proxy answers **all** GitHub GraphQL with HTTP 403, even when you set
691
+ your own token. Projects v2 is GraphQL-only, so board Status never syncs
692
+ from a cloud session. Labels stay authoritative, and each skipped Status flip
693
+ is reported as a warning.
694
+
695
+ The handle has to be a user who can be assigned. GitHub's add-assignees
696
+ endpoint silently ignores a login it cannot assign, such as an Organization,
697
+ a team, or a user with no access to the repo. When that happens the Story
698
+ lease refuses with `not-assignable` rather than running a Story nobody holds.
699
+
667
700
  ### Adding a new top-level key (framework change)
668
701
 
669
702
  This is a framework-level change, not a project-level one. The path is:
@@ -699,6 +732,7 @@ Claude Code web environment-variables UI for web sessions.
699
732
  | Variable | Required? | Purpose |
700
733
  | -------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
701
734
  | `GITHUB_TOKEN` | Yes\* | GitHub API auth for all ticketing operations. `GH_TOKEN` is accepted as a synonym. `gh auth token` is a fallback for local sessions. |
735
+ | `GH_OPERATOR_HANDLE` | No | Overrides `github.operatorHandle` (the lease owner and @mention handle). Set it where there is no `.agentrc.local.json`, such as a Claude Code cloud environment. See [Claude Code cloud environments](#claude-code-cloud-environments). |
702
736
  | `NOTIFICATION_WEBHOOK_URL` | No | POST target for in-band Notifier events (Make.com / Slack / Discord). Unset disables the webhook channel; the GitHub comment channel still fires. |
703
737
  | `WEBHOOK_SECRET` | No | Shared secret used to sign outbound webhook payloads as `X-Signature-256: sha256=<hmac>`. Unset ships unsigned payloads. |
704
738
  | `MANDREL_ALLOW_TEST_WEBHOOKS` | No | Set to `1` to keep `NOTIFICATION_WEBHOOK_URL` live inside `npm test` / `npm run test:profile`. Default behaviour scrubs the env var from the test child so no URL resolves and the webhook never fires (see below). |
@@ -3,6 +3,8 @@
3
3
  * `/agents-bootstrap-github` registers as required-status checks.
4
4
  */
5
5
 
6
+ import { isObject } from '../json-utils.js';
7
+
6
8
  /** Keep in sync with the job names in `.github/workflows/ci.yml`. */
7
9
  export const DEFAULT_REQUIRED_CHECKS = Object.freeze([
8
10
  Object.freeze({
@@ -107,3 +109,19 @@ export function getGitHub(config) {
107
109
  },
108
110
  };
109
111
  }
112
+
113
+ /**
114
+ * `GH_OPERATOR_HANDLE` beats `github.operatorHandle` (cloud sessions have no
115
+ * `.agentrc.local.json`). Only an existing `github` block is touched: a lone
116
+ * handle would fail its required `owner` / `repo`.
117
+ */
118
+ export function applyOperatorHandleEnv(read, env = process.env) {
119
+ const handle = String(env.GH_OPERATOR_HANDLE ?? '').trim();
120
+ const github = read.raw?.github;
121
+ if (handle.length === 0 || !isObject(github)) return read;
122
+ const operatorHandle = handle.startsWith('@') ? handle : `@${handle}`;
123
+ return {
124
+ ...read,
125
+ raw: { ...read.raw, github: { ...github, operatorHandle } },
126
+ };
127
+ }
@@ -13,7 +13,7 @@ import {
13
13
  import { getCiDelivery } from './config/ci.js';
14
14
  import { getCommands } from './config/commands.js';
15
15
  import { overlayRoot, resolveAgentrcRoot } from './config/git-roots.js';
16
- import { getGitHub } from './config/github.js';
16
+ import { applyOperatorHandleEnv, getGitHub } from './config/github.js';
17
17
  import { resolvePaths } from './config/paths.js';
18
18
  import { validateOrchestrationConfig } from './config/validate-orchestration.js';
19
19
  import { getWorktreeIsolation } from './config/worktree-isolation.js';
@@ -217,7 +217,7 @@ export function resolveConfig(opts) {
217
217
  }
218
218
  ensureEnvLoaded(root);
219
219
  const resolved = finalizeConfig(
220
- readRawConfig(injectedFs ?? fs, root),
220
+ applyOperatorHandleEnv(readRawConfig(injectedFs ?? fs, root)),
221
221
  validate,
222
222
  );
223
223
  if (!injectedFs) _cacheByKey.set(key, resolved);
@@ -37,7 +37,7 @@ export function resolveOperatorFromCandidates({
37
37
 
38
38
  /**
39
39
  * Acquire a lease; a foreign claim without `steal` throws the surface's
40
- * refusal.
40
+ * refusal; a result's own `message` wins.
41
41
  *
42
42
  * @param {object} opts
43
43
  * @param {object} opts.provider
@@ -62,7 +62,7 @@ export async function acquireLeaseFailClosed({
62
62
  steal,
63
63
  });
64
64
  if (!result.acquired) {
65
- throw new Error(renderRefusal(result, ticketId));
65
+ throw new Error(result.message ?? renderRefusal(result, ticketId));
66
66
  }
67
67
  return result;
68
68
  }
@@ -113,7 +113,10 @@ export async function finishWithMergeWait(prCtx, deps) {
113
113
  injectedNotify: deps.injectedNotify,
114
114
  runPostLandTailFn: (args) => {
115
115
  deps.setPhase('post-land');
116
- return runPostLandTail(args);
116
+ return runPostLandTail({
117
+ ...args,
118
+ releaseStoryLeaseFn: deps.releaseLease,
119
+ });
117
120
  },
118
121
  });
119
122
  const terminal = terminalFromWaitOutcome({
@@ -51,35 +51,9 @@ import { discardHeldReview } from './review-overlap.js';
51
51
 
52
52
  const progress = Logger.createProgress('single-story-close', { stderr: true });
53
53
 
54
- async function releaseLease({ storyId }, deps) {
55
- try {
56
- const outcome = await deps.releaseLease({
57
- provider: deps.provider,
58
- storyId,
59
- config: deps.config,
60
- });
61
- progress(
62
- 'LEASE',
63
- outcome.released
64
- ? `🔓 Story #${storyId} lease released.`
65
- : `🔓 Story #${storyId} lease not released (${outcome.reason}).`,
66
- );
67
- return outcome.released;
68
- } catch (err) {
69
- progress(
70
- 'LEASE',
71
- `⚠️ lease release failed (close continues): ${err?.message ?? err}`,
72
- );
73
- return false;
74
- }
75
- }
76
-
77
54
  /**
78
- * Re-take the Story lease before any gate, push or PR write: a block released
79
- * it, and init is the only other acquirer, so a re-close would otherwise run
80
- * unassigned and unguarded. No steal — a foreign holder throws init's
81
- * refusal. No configured operator handle skips the acquire (release is
82
- * best-effort for the same reason), so close never newly hard-fails on it.
55
+ * Re-affirm the Story lease before any write; normally `already-held`, since
56
+ * only the post-land tail releases it. No steal; no operator handle skips it.
83
57
  */
84
58
  async function acquireLease({ storyId }, deps) {
85
59
  const operator = resolveOperatorFromCandidates({
@@ -105,24 +79,6 @@ async function acquireLease({ storyId }, deps) {
105
79
  return lease;
106
80
  }
107
81
 
108
- /**
109
- * Release the lease best-effort before re-throwing a blocked-prone phase's
110
- * error verbatim. The lease has no TTL, so a stranded claim would refuse the
111
- * next operator who picks up the blocked Story.
112
- *
113
- * @template T
114
- * @param {() => Promise<T>} run
115
- * @returns {Promise<T>}
116
- */
117
- async function releaseLeaseOnBlock(run, ctx, deps) {
118
- try {
119
- return await run();
120
- } catch (err) {
121
- await releaseLease(ctx, deps);
122
- throw err;
123
- }
124
- }
125
-
126
82
  /**
127
83
  * Tests mock these at their module URLs and re-import only this module, so
128
84
  * they are bound here and handed to the phases rather than imported there.
@@ -161,6 +117,21 @@ function resolveCloseDeps(options, injected) {
161
117
  };
162
118
  }
163
119
 
120
+ function assertStoryId(options) {
121
+ if (!options.storyId) {
122
+ throw new Error(
123
+ 'Usage: node single-story-close.js --story <STORY_ID> [--cwd <main-repo>] [--skip-validation] [--skip-sync] [--no-auto-merge] [--wait-merge|--no-wait-merge] [--max-wait-seconds <n>] [--merge-watch-mode <sync|async>] [--rerun-advisory <n>] [--override-review-block <reason>] [--worker-tokens <n>] [--worker-model <model>] [--worker-effort <level>]',
124
+ );
125
+ }
126
+ }
127
+
128
+ function tagCloseError(err, { phaseTimer, phase, observedGates }) {
129
+ if (!err || typeof err !== 'object') return;
130
+ err.closePhaseDurations = phaseTimer.finish();
131
+ if (!err.closePhase) err.closePhase = phase;
132
+ if (!err.closeGates && observedGates) err.closeGates = observedGates;
133
+ }
134
+
164
135
  export async function runSingleStoryClose({
165
136
  storyId: storyIdParam,
166
137
  cwd: cwdParam,
@@ -194,11 +165,7 @@ export async function runSingleStoryClose({
194
165
  workerModelParam,
195
166
  workerEffortParam,
196
167
  });
197
- if (!options.storyId) {
198
- throw new Error(
199
- 'Usage: node single-story-close.js --story <STORY_ID> [--cwd <main-repo>] [--skip-validation] [--skip-sync] [--no-auto-merge] [--wait-merge|--no-wait-merge] [--max-wait-seconds <n>] [--merge-watch-mode <sync|async>] [--rerun-advisory <n>] [--override-review-block <reason>] [--worker-tokens <n>] [--worker-model <model>] [--worker-effort <level>]',
200
- );
201
- }
168
+ assertStoryId(options);
202
169
 
203
170
  // The runner keeps THROWING; it only tags the error with its phase and the
204
171
  // gates it observed (null until validation reports), and the CLI boundary
@@ -236,11 +203,7 @@ export async function runSingleStoryClose({
236
203
  deps,
237
204
  );
238
205
  } catch (err) {
239
- if (err && typeof err === 'object') {
240
- err.closePhaseDurations = phaseTimer.finish();
241
- if (!err.closePhase) err.closePhase = phase;
242
- if (!err.closeGates && observedGates) err.closeGates = observedGates;
243
- }
206
+ tagCloseError(err, { phaseTimer, phase, observedGates });
244
207
  throw err;
245
208
  }
246
209
  }
@@ -271,7 +234,6 @@ async function graphqlPreflightPhase(ctx, deps) {
271
234
  probe: deps.graphqlProbe,
272
235
  });
273
236
  if (!preflight) return null;
274
- await releaseLease(ctx, deps);
275
237
  return await preflightBlockedResult({
276
238
  storyId: ctx.storyId,
277
239
  preflight,
@@ -396,11 +358,7 @@ function landedPr(ctx) {
396
358
  }
397
359
 
398
360
  async function prePushPhase(ctx, deps) {
399
- ctx.prePush = await releaseLeaseOnBlock(
400
- () => runPrePushPhases(ctx, deps),
401
- ctx,
402
- deps,
403
- );
361
+ ctx.prePush = await runPrePushPhases(ctx, deps);
404
362
  if (!ctx.prePush.pending) return null;
405
363
  discardHeldReview(ctx.heldReview, 'validation pending', progress);
406
364
  return await finishDeferred(ctx.prePush.lockWait, {
@@ -415,11 +373,7 @@ async function prePushPhase(ctx, deps) {
415
373
  }
416
374
 
417
375
  async function openPrPhase(ctx, deps) {
418
- ctx.pr = await releaseLeaseOnBlock(
419
- () => openAndReviewPr(ctx, deps),
420
- ctx,
421
- deps,
422
- );
376
+ ctx.pr = await openAndReviewPr(ctx, deps);
423
377
  return null;
424
378
  }
425
379
 
@@ -460,22 +414,9 @@ async function armPhase(ctx, deps) {
460
414
  return null;
461
415
  }
462
416
 
463
- /** Wait-for-merge needs the arm outcome, so it is resolved here. */
464
- async function finishPhase(ctx, deps) {
417
+ function buildPrContext(ctx, deps) {
465
418
  const { options, arm } = ctx;
466
- const { waitForMerge, reason: waitForMergeReason } = resolveWaitForMerge({
467
- waitForMergeExplicit: options.waitForMergeExplicit,
468
- noWaitForMerge: options.noWaitForMerge,
469
- config: deps.config,
470
- autoMergeReason: arm.autoMergeReason,
471
- });
472
- reportOperatorMergeSkip({
473
- waitForMergeReason,
474
- autoMergeReason: arm.autoMergeReason,
475
- storyId: ctx.storyId,
476
- waitForMergeExplicit: options.waitForMergeExplicit,
477
- });
478
- const prCtx = {
419
+ return {
479
420
  storyId: ctx.storyId,
480
421
  storyBranch: ctx.storyBranch,
481
422
  baseBranch: ctx.baseBranch,
@@ -500,8 +441,32 @@ async function finishPhase(ctx, deps) {
500
441
  ctx.pr.reviewDegraded,
501
442
  ),
502
443
  };
444
+ }
445
+
446
+ function decideWaitForMerge(ctx, deps) {
447
+ const { options, arm } = ctx;
448
+ const decision = resolveWaitForMerge({
449
+ waitForMergeExplicit: options.waitForMergeExplicit,
450
+ noWaitForMerge: options.noWaitForMerge,
451
+ config: deps.config,
452
+ autoMergeReason: arm.autoMergeReason,
453
+ });
454
+ reportOperatorMergeSkip({
455
+ waitForMergeReason: decision.reason,
456
+ autoMergeReason: arm.autoMergeReason,
457
+ storyId: ctx.storyId,
458
+ waitForMergeExplicit: options.waitForMergeExplicit,
459
+ });
460
+ return decision;
461
+ }
462
+
463
+ /** Wait-for-merge needs the arm outcome, so it is resolved here. */
464
+ async function finishPhase(ctx, deps) {
465
+ const { options } = ctx;
466
+ const { waitForMerge, reason } = decideWaitForMerge(ctx, deps);
467
+ const prCtx = buildPrContext(ctx, deps);
503
468
  if (!waitForMerge) {
504
- return await finishWithoutMergeWait(prCtx, waitForMergeReason);
469
+ return await finishWithoutMergeWait(prCtx, reason);
505
470
  }
506
471
  return await finishWithMergeWait(prCtx, {
507
472
  cwd: options.cwd,
@@ -513,6 +478,7 @@ async function finishPhase(ctx, deps) {
513
478
  injectedGh: deps.gh,
514
479
  injectedNotify: deps.notify,
515
480
  runConfirmMergePhase: deps.runConfirmMergePhase,
481
+ releaseLease: deps.releaseLease,
516
482
  });
517
483
  }
518
484
 
@@ -26,7 +26,8 @@ export function resolveOperator(config) {
26
26
  'github.operatorHandle is unset or still the shipped `@[USERNAME]` ' +
27
27
  'placeholder, so the standalone Story lease has no owner. Set your own ' +
28
28
  'handle in .agentrc.local.json (e.g. { "github": { "operatorHandle": ' +
29
- '"@your-login" } }) and re-run.',
29
+ '"@your-login" } }), or GH_OPERATOR_HANDLE in the environment where ' +
30
+ 'there is no .agentrc.local.json (cloud sessions), and re-run.',
30
31
  });
31
32
  }
32
33
 
@@ -25,6 +25,7 @@ const INSTALL_FLAGS = Object.freeze({ installed: 'true', failed: 'false' });
25
25
  * @param {boolean} args.dryRun
26
26
  * @param {{ remoteVerified: boolean, remoteUrl?: string, detail?: string }} args.remote
27
27
  * @param {string|null} args.checklistPath
28
+ * @param {{ status: string, reason?: string }|null} [args.boardSync]
28
29
  * @returns {{ result: object, summary: object }}
29
30
  */
30
31
  export function composeStoryInitResult({
@@ -41,6 +42,7 @@ export function composeStoryInitResult({
41
42
  dryRun,
42
43
  remote,
43
44
  checklistPath,
45
+ boardSync = null,
44
46
  }) {
45
47
  const dependenciesInstalled =
46
48
  INSTALL_FLAGS[installStatus.status] ?? 'skipped';
@@ -68,6 +70,7 @@ export function composeStoryInitResult({
68
70
  // Footprint-matched write-time checklist (null when no lens matches) —
69
71
  // the same Story-scoped path a multi-Story dispatch prompt names.
70
72
  checklistPath,
73
+ boardSync,
71
74
  };
72
75
  const summary = {
73
76
  storyId,
@@ -78,6 +81,14 @@ export function composeStoryInitResult({
78
81
  remoteVerified: remote.remoteVerified,
79
82
  checklistPath,
80
83
  dryRun,
84
+ boardSync: summarizeBoardSync(boardSync),
81
85
  };
82
86
  return { result, summary };
83
87
  }
88
+
89
+ /** The status, plus its reason when the board did not move. */
90
+ function summarizeBoardSync(boardSync) {
91
+ if (!boardSync) return null;
92
+ if (!boardSync.reason) return boardSync.status;
93
+ return `${boardSync.status} (${boardSync.reason})`;
94
+ }
@@ -42,6 +42,12 @@ export function currentOwner(assignees) {
42
42
  return assignees[0];
43
43
  }
44
44
 
45
+ /** GitHub returns the canonical-case login; the configured handle may differ. */
46
+ function sameLogin(a, b) {
47
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
48
+ return a.toLowerCase() === b.toLowerCase();
49
+ }
50
+
45
51
  /**
46
52
  * @param {string} op
47
53
  * @param {object} opts
@@ -74,9 +80,10 @@ function normaliseOpts(op, opts) {
74
80
  * @param {boolean} [opts.steal=false] Transfer a foreign claim.
75
81
  * @returns {Promise<{
76
82
  * acquired: boolean,
77
- * owner: string,
83
+ * owner: string|null,
78
84
  * previousOwner: string|null,
79
- * reason: 'unclaimed'|'already-held'|'stolen'|'held'|'lost-race',
85
+ * reason: 'unclaimed'|'already-held'|'stolen'|'held'|'lost-race'|'not-assignable',
86
+ * message?: string,
80
87
  * }>}
81
88
  */
82
89
  export async function acquireLease(opts) {
@@ -96,7 +103,7 @@ export async function acquireLease(opts) {
96
103
  });
97
104
  }
98
105
 
99
- if (owner === operator) {
106
+ if (sameLogin(owner, operator)) {
100
107
  return {
101
108
  acquired: true,
102
109
  owner: operator,
@@ -123,18 +130,6 @@ export async function acquireLease(opts) {
123
130
  });
124
131
  }
125
132
 
126
- /**
127
- * Write, then re-read with `fresh: true`; on a foreign co-assignee, back out
128
- * and report `lost-race` so the loser never builds the winner's worktree.
129
- *
130
- * @param {object} args
131
- * @param {object} args.provider
132
- * @param {number} args.ticketId
133
- * @param {string} args.operator
134
- * @param {string|null} args.previousOwner
135
- * @param {string} args.reason Success reason when the claim holds.
136
- * @returns {Promise<{ acquired: boolean, owner: string, previousOwner: string|null, reason: string }>}
137
- */
138
133
  /**
139
134
  * Additive for an unowned ticket — a replacing PATCH would evict a
140
135
  * simultaneous claimer, hiding the collision verify keys on. Replacing only
@@ -149,6 +144,55 @@ function claimMutation(operator, previousOwner) {
149
144
  return { assignees: [operator] };
150
145
  }
151
146
 
147
+ function notAssignableMessage(operator, ticketId) {
148
+ return (
149
+ `ticket lease: GitHub silently dropped @${operator} as an assignee of ` +
150
+ `#${ticketId} — the handle is an Organization or team, or has no access ` +
151
+ 'to the repo, so the lease cannot be held. Set github.operatorHandle (or ' +
152
+ 'GH_OPERATOR_HANDLE in a cloud environment) to the GitHub user who runs ' +
153
+ 'this session, and re-run.'
154
+ );
155
+ }
156
+
157
+ /** No foreign login: an empty re-read means GitHub dropped the operator. */
158
+ async function settleUncontested({
159
+ provider,
160
+ ticketId,
161
+ operator,
162
+ previousOwner,
163
+ reason,
164
+ assignees,
165
+ }) {
166
+ if (assignees.length > 0) {
167
+ return { acquired: true, owner: operator, previousOwner, reason };
168
+ }
169
+ if (previousOwner !== null) {
170
+ await provider
171
+ .updateTicket(ticketId, { assignees: [previousOwner] })
172
+ .catch(() => undefined);
173
+ }
174
+ return {
175
+ acquired: false,
176
+ owner: null,
177
+ previousOwner,
178
+ reason: 'not-assignable',
179
+ message: notAssignableMessage(operator, ticketId),
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Write, then re-read with `fresh: true`; on a foreign co-assignee, back out
185
+ * and report `lost-race` so the loser never builds the winner's worktree. An
186
+ * empty re-read is `not-assignable`: GitHub ignores an unassignable login.
187
+ *
188
+ * @param {object} args
189
+ * @param {object} args.provider
190
+ * @param {number} args.ticketId
191
+ * @param {string} args.operator
192
+ * @param {string|null} args.previousOwner
193
+ * @param {string} args.reason Success reason when the claim holds.
194
+ * @returns {Promise<{ acquired: boolean, owner: string|null, previousOwner: string|null, reason: string }>}
195
+ */
152
196
  async function claimAndVerify({
153
197
  provider,
154
198
  ticketId,
@@ -160,10 +204,17 @@ async function claimAndVerify({
160
204
 
161
205
  const after = await provider.getTicket(ticketId, { fresh: true });
162
206
  const assignees = Array.isArray(after?.assignees) ? after.assignees : [];
163
- const foreign = assignees.filter((login) => login !== operator);
207
+ const foreign = assignees.filter((login) => !sameLogin(login, operator));
164
208
 
165
209
  if (foreign.length === 0) {
166
- return { acquired: true, owner: operator, previousOwner, reason };
210
+ return settleUncontested({
211
+ provider,
212
+ ticketId,
213
+ operator,
214
+ previousOwner,
215
+ reason,
216
+ assignees,
217
+ });
167
218
  }
168
219
 
169
220
  // Lost the race: leave the winner as sole assignee.
@@ -196,7 +247,7 @@ export async function releaseLease(opts) {
196
247
  const ticket = await provider.getTicket(ticketId);
197
248
  const owner = currentOwner(ticket?.assignees);
198
249
 
199
- if (owner !== operator) {
250
+ if (!sameLogin(owner, operator)) {
200
251
  return { released: false, owner, reason: 'not-held' };
201
252
  }
202
253
 
@@ -106,15 +106,49 @@ async function loadTicketSnapshot(provider, opts, ticketId, needFromState) {
106
106
  }
107
107
  }
108
108
 
109
+ const BOARD_SYNC_REMEDIES = Object.freeze({
110
+ 'insufficient-scope': 'gh auth refresh -h github.com -s project',
111
+ 'not-on-project': 'node .agents/scripts/board-backfill.js',
112
+ });
113
+
114
+ const SILENT_BOARD_SKIPS = new Set(['no-project']);
115
+
116
+ /** Warns on every flip, never latched: agents read the flip's own output. */
117
+ function reportBoardSync(ticketId, newState, boardSync) {
118
+ if (boardSync.status === 'synced') return;
119
+ if (SILENT_BOARD_SKIPS.has(boardSync.reason)) return;
120
+ Logger.warn(boardSyncMessage(ticketId, newState, boardSync));
121
+ }
122
+
123
+ function boardSyncMessage(ticketId, newState, { status, reason, detail }) {
124
+ const why = detail ? `${reason}: ${detail}` : reason;
125
+ const remedy = BOARD_SYNC_REMEDIES[reason];
126
+ const fix = remedy ? ` — fix: \`${remedy}\`` : '';
127
+ return `[Ticketing] board Status not synced for #${ticketId} → ${newState} (${status}, ${why})${fix}`;
128
+ }
129
+
130
+ /** First instance per provider wins, so a later `config` is ignored. */
131
+ function columnSyncFor(provider, _makeColumnSync, config) {
132
+ if (_makeColumnSync) return _makeColumnSync({ provider, logger: Logger });
133
+ if (!_columnSyncRegistry.has(provider)) {
134
+ _columnSyncRegistry.set(
135
+ provider,
136
+ new ColumnSync({ provider, logger: Logger, config }),
137
+ );
138
+ }
139
+ return _columnSyncRegistry.get(provider);
140
+ }
141
+
109
142
  /**
110
143
  * Mirror the new state onto the Projects v2 Status column. Best-effort: a
111
- * board failure is logged and never blocks the label transition. An injected
112
- * `_makeColumnSync` bypasses the registry so test stubs are never cached.
144
+ * board failure never blocks the label transition; the outcome is returned.
145
+ * An injected `_makeColumnSync` bypasses the registry.
113
146
  *
114
147
  * @param {object} provider
115
148
  * @param {number} ticketId
116
149
  * @param {string} newState
117
150
  * @param {(opts: object) => { sync: (id: number, labels: string[]) => Promise<object> }} [_makeColumnSync]
151
+ * @returns {Promise<{ status: string, reason?: string, column?: string, detail?: string }>}
118
152
  */
119
153
  async function syncProjectStatusColumn(
120
154
  provider,
@@ -124,25 +158,14 @@ async function syncProjectStatusColumn(
124
158
  config,
125
159
  ) {
126
160
  try {
127
- let sync;
128
- if (_makeColumnSync) {
129
- sync = _makeColumnSync({ provider, logger: Logger });
130
- } else {
131
- // `config` is read at construction only; the first instance per
132
- // provider wins, so a later transition's config is ignored.
133
- if (!_columnSyncRegistry.has(provider)) {
134
- _columnSyncRegistry.set(
135
- provider,
136
- new ColumnSync({ provider, logger: Logger, config }),
137
- );
138
- }
139
- sync = _columnSyncRegistry.get(provider);
140
- }
141
- await sync.sync(ticketId, [newState]);
161
+ const sync = columnSyncFor(provider, _makeColumnSync, config);
162
+ return await sync.sync(ticketId, [newState]);
142
163
  } catch (err) {
143
- Logger.warn(
144
- `[Ticketing] column sync failed for #${ticketId} → ${newState}: ${err?.message ?? err}`,
145
- );
164
+ return {
165
+ status: 'failed',
166
+ reason: 'error',
167
+ detail: String(err?.message ?? err),
168
+ };
146
169
  }
147
170
  }
148
171
 
@@ -250,6 +273,7 @@ async function emitBlockedFriction(ticketId, fromState, newState, opts) {
250
273
  * `cascade: false` suppresses the upward parent cascade.
251
274
  * `ticketSnapshot` is a pre-fetched ticket that saves the `fromState` read
252
275
  * and the provider's label-merge read. `_makeColumnSync` is a test seam.
276
+ * @returns {Promise<{ boardSync: { status: string, reason?: string, column?: string, detail?: string } }>}
253
277
  */
254
278
  export async function transitionTicketState(
255
279
  provider,
@@ -285,13 +309,14 @@ export async function transitionTicketState(
285
309
 
286
310
  await emitBlockedFriction(ticketId, fromState, newState, opts);
287
311
 
288
- await syncProjectStatusColumn(
312
+ const boardSync = await syncProjectStatusColumn(
289
313
  provider,
290
314
  ticketId,
291
315
  newState,
292
316
  opts._makeColumnSync,
293
317
  opts.config,
294
318
  );
319
+ reportBoardSync(ticketId, newState, boardSync);
295
320
 
296
321
  // Every transition re-derives parent state from children (not just `done`),
297
322
  // keeping the board accurate when work starts or a child blocks.
@@ -310,6 +335,7 @@ export async function transitionTicketState(
310
335
  newState,
311
336
  });
312
337
  }
338
+ return { boardSync };
313
339
  }
314
340
 
315
341
  /**
@@ -143,25 +143,27 @@ export async function assertNotForeignExecuting({
143
143
  }
144
144
 
145
145
  /**
146
- * Best-effort: the lease is the real guard, so a failed flip only logs.
147
- *
148
- * @param {object} provider
149
- * @param {number} storyId
150
- * @param {object} story Prefetched snapshot.
151
- * @returns {Promise<void>}
146
+ * A failed flip rolls the claim back and throws: a ready, assigned Story
147
+ * reads as a stalled dispatch. Returns the flip's board-sync outcome.
152
148
  */
153
- async function flipStoryToExecuting(provider, storyId, story) {
149
+ async function flipStoryToExecuting(provider, storyId, story, config) {
150
+ let flip;
154
151
  try {
155
- await transitionTicketState(provider, storyId, STATE_LABELS.EXECUTING, {
156
- ticketSnapshot: story,
157
- cascade: false,
158
- });
159
- progress('LABELS', `🏷️ Story #${storyId} → agent::executing`);
152
+ flip = await transitionTicketState(
153
+ provider,
154
+ storyId,
155
+ STATE_LABELS.EXECUTING,
156
+ { ticketSnapshot: story, cascade: false, config },
157
+ );
160
158
  } catch (err) {
161
159
  Logger.error(
162
- `[single-story-init] ⚠️ Failed to flip Story labels: ${err?.message ?? err}`,
160
+ `[single-story-init] ⚠️ Failed to flip Story #${storyId} to agent::executing; rolling the claim back: ${err?.message ?? err}`,
163
161
  );
162
+ await rollbackClaimOnInitFailure(provider, storyId, config);
163
+ throw err;
164
164
  }
165
+ progress('LABELS', `🏷️ Story #${storyId} → agent::executing`);
166
+ return flip?.boardSync ?? null;
165
167
  }
166
168
 
167
169
  /**
@@ -647,6 +649,7 @@ export async function runSingleStoryInit({
647
649
  let worktreeCreated = false;
648
650
  let installStatus = { status: 'skipped', reason: 'dry-run' };
649
651
  let worktreeSweep = null;
652
+ let boardSync = null;
650
653
 
651
654
  if (!dryRun) {
652
655
  const acquire = injectedAcquireLease ?? acquireStoryLease;
@@ -671,7 +674,7 @@ export async function runSingleStoryInit({
671
674
  });
672
675
 
673
676
  // Before the install, so a concurrent probe cannot double-dispatch.
674
- await flipStoryToExecuting(provider, storyId, story);
677
+ boardSync = await flipStoryToExecuting(provider, storyId, story, config);
675
678
 
676
679
  // After the flip (the rollup reads it), before the install window.
677
680
  await rollUpContainerEpic(provider, storyId, config);
@@ -723,6 +726,7 @@ export async function runSingleStoryInit({
723
726
  dryRun,
724
727
  remote,
725
728
  checklistPath,
729
+ boardSync,
726
730
  });
727
731
 
728
732
  // The envelope (stdout + disk) is the only record; no ticket comment. Full
@@ -36,8 +36,15 @@ foreign claim is stale — a foreign assignee is treated as a _live_ claim:
36
36
  the current owner. Coordinate with that operator, or pass **`--steal`** to
37
37
  forcibly transfer the claim once you have confirmed the other run is dead.
38
38
 
39
- `--dry-run` skips the lease (no assignee mutation). The matching release
40
- runs in `single-story-close.js` (Step 3).
39
+ `--dry-run` skips the lease (no assignee mutation). The claim lives for the
40
+ Story's whole delivery: it is released only by close's post-land tail once
41
+ the merge is confirmed (Step 3), or by init's own rollback when provisioning
42
+ fails or the `agent::executing` flip does not land — that flip is not
43
+ best-effort, so init exits non-zero rather than leave a ready Story assigned.
44
+ A blocked or failed close **keeps** the claim. The flip's Projects v2 outcome
45
+ is reported as `boardSync` in the init envelope; a Status that did not move
46
+ logs one warning naming the fix (`gh auth refresh -h github.com -s project`
47
+ for a token without the `project` scope).
41
48
 
42
49
  ### Branch reuse
43
50
 
@@ -339,12 +346,16 @@ The `single-story-close.js` script, in order:
339
346
  `blocked` or `failed` close keeps its working copy. A missing worktree is
340
347
  recreated from `story-<id>` before close's first git operation — and the
341
348
  `--wait` resume's — never falling back to the main checkout.
342
- 7. **Releases the Story lease** — a no-op when the operator no longer holds
343
- the claim, so a late close never yanks a live claim. Best-effort: a
344
- release failure is logged, not fatal, and reported as
345
- `leaseReleased: <boolean>`. The fail-closed lease never expires on its
346
- own, so a claim stranded by a failed release is cleared only by `--steal`
347
- or by de-assigning the ticket.
349
+ 7. **Releases the Story lease only after the merge is confirmed** — the
350
+ post-land tail's step, a no-op when the operator no longer holds the
351
+ claim, so a late close never yanks a live claim. Every other ending keeps
352
+ it: a red gate, a review-critical halt, a base-sync conflict, a blocked
353
+ GraphQL preflight, `pending` and `blocked` all leave the Story assigned,
354
+ because its label still says it is owned; the next close re-affirms the
355
+ claim as `already-held`. Best-effort: a release failure is logged, not
356
+ fatal, and reported as `leaseReleased: <boolean>`. The fail-closed lease
357
+ never expires on its own, so a claim stranded by a failed release is
358
+ cleared only by `--steal` or by de-assigning the ticket.
348
359
 
349
360
  The merge wait recovers on its own when `main` moves under the queued PR. A
350
361
  `DIRTY` PR is merged with `origin/<base>` in the Story worktree in that same
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,20 @@ All notable changes to this project will be documented in this file.
15
15
  -->
16
16
  <!-- markdownlint-disable-file MD004 MD012 MD037 -->
17
17
 
18
+ ## [2.93.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.92.0...mandrel-v2.93.0) (2026-10-19)
19
+
20
+
21
+ ### Added
22
+
23
+ * fail the Story lease closed when GitHub silently drops the operator, and let cloud sessions supply the operator handle via GH_OPERATOR_HANDLE ([#5788](https://github.com/dsj1984/mandrel/issues/5788)) ([#5789](https://github.com/dsj1984/mandrel/issues/5789)) ([6acb901](https://github.com/dsj1984/mandrel/commit/6acb901cf34ef312f7eb18e0f3eb3053697f65f0))
24
+
25
+ ## [2.92.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.91.0...mandrel-v2.92.0) (2026-10-18)
26
+
27
+
28
+ ### Fixed
29
+
30
+ * keep the Story assignee until the merge lands, and report every board-Status sync that did not happen ([#5784](https://github.com/dsj1984/mandrel/issues/5784)) ([#5785](https://github.com/dsj1984/mandrel/issues/5785)) ([8ca2b61](https://github.com/dsj1984/mandrel/commit/8ca2b611adb70a4bb53ec3b35dcdfe42dc1528bc))
31
+
18
32
  ## [2.91.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.90.0...mandrel-v2.91.0) (2026-10-18)
19
33
 
20
34
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mandrel",
3
- "version": "2.91.0",
3
+ "version": "2.93.0",
4
4
  "description": "Claude Code-first opinionated workflow framework: instructions, skills, rules, and SDLC workflows that govern AI coding assistants.",
5
5
  "files": [
6
6
  ".agents/",