claude-code-session-manager 0.144.0 → 0.145.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 (57) hide show
  1. package/dist/assets/{AppSettings-Z68gQiVE.js → AppSettings-BR5b6oof.js} +2 -2
  2. package/dist/assets/{History-C3E6y_7t.js → History-B4U0mCdK.js} +1 -1
  3. package/dist/assets/HomeClaudeConfig-DQqG7lFE.js +5 -0
  4. package/dist/assets/{Panel-CnfWs46Z.js → Panel-CwsOJ0nI.js} +1 -1
  5. package/dist/assets/{ProjectClaudeConfig-CP0Wsg-H.js → ProjectClaudeConfig-BzRowu8x.js} +1 -1
  6. package/dist/assets/{Scheduler-D8un7N3B.js → Scheduler-dr7CNOcL.js} +1 -1
  7. package/dist/assets/{SkillReferenceGraph-DRtZV1Al.js → SkillReferenceGraph-CroBPY4C.js} +1 -1
  8. package/dist/assets/{Skills-Bg5O2Hyn.js → Skills-BiW2lCnD.js} +1 -1
  9. package/dist/assets/{TiptapBody-BdzoBmqu.js → TiptapBody-CYTkQiva.js} +1 -1
  10. package/dist/assets/{Toggle-Dt5K1OXt.js → Toggle-WFBYo8JI.js} +1 -1
  11. package/dist/assets/{VoiceButton-CTLyRgdF.js → VoiceButton-DZu8dTpO.js} +1 -1
  12. package/dist/assets/{historyTotals-B2_KWBga.js → historyTotals-B7KeXLSE.js} +1 -1
  13. package/dist/assets/{index-446b69rr.js → index-hXRNm0UJ.js} +128 -128
  14. package/dist/index.html +1 -1
  15. package/dist-web/app.js +394 -394
  16. package/package.json +1 -1
  17. package/plugins/session-manager-dev/skills/develop/SKILL.md +11 -6
  18. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +1 -1
  19. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +8 -4
  20. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +9 -6
  21. package/src/main/build-info.json +4 -4
  22. package/src/main/chatRunner.cjs +35 -5
  23. package/src/main/config.cjs +12 -0
  24. package/src/main/index.cjs +2 -2
  25. package/src/main/ipcSchemas.cjs +5 -0
  26. package/src/main/lib/claude/headlessMcpServers.cjs +1 -1
  27. package/src/main/lib/claude/personaToolScope.cjs +23 -8
  28. package/src/main/lib/demo-video-kit/resumableRun.cjs +21 -14
  29. package/src/main/lib/demo-video-kit/seedKit.cjs +2 -2
  30. package/src/main/lib/epic/epicOutsideRead.cjs +43 -8
  31. package/src/main/lib/epic/planReviewInput.cjs +2 -0
  32. package/src/main/lib/epic/scriptStartedBy.cjs +19 -4
  33. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +84 -12
  34. package/src/main/lib/feedback-remote/localAdminHttp.cjs +5 -1
  35. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +6 -3
  36. package/src/main/lib/feedback-remote/servicePairings.cjs +48 -0
  37. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +11 -6
  38. package/src/main/lib/mcpToolCatalog.cjs +4 -2
  39. package/src/main/lib/opsOwnership.cjs +2 -0
  40. package/src/main/lib/prd/prdCreate.cjs +2 -1
  41. package/src/main/lib/prd/prdMcpReachWarnings.cjs +3 -1
  42. package/src/main/lib/prd/prdSandboxWarnings.cjs +1 -1
  43. package/src/main/lib/scheduler/planReviewStore.cjs +24 -2
  44. package/src/main/lib/scheduler/reviewNotice.cjs +3 -1
  45. package/src/main/lib/tasks/memoryConsolidation.cjs +21 -12
  46. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +131 -11
  47. package/src/main/runVerify.cjs +77 -3
  48. package/src/main/scheduler/gitTreeGuard.cjs +6 -0
  49. package/src/main/scheduler/planReviewHold.cjs +11 -5
  50. package/src/main/scheduler/prdPaths.cjs +10 -1
  51. package/src/main/scheduler.cjs +170 -18
  52. package/src/main/templates/PRD_AUTHORING.md +2 -2
  53. package/src/main/webRemote.cjs +22 -0
  54. package/src/preload/api.d.ts +8 -0
  55. package/src/preload/apiSurface.json +11 -0
  56. package/src/preload/index.cjs +2 -0
  57. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +0 -5
@@ -69,6 +69,7 @@ const { headlessPermissionArgs, ensureCliCapsProbed } = require('./lib/claude/cl
69
69
  // as the authoritative guarantee.
70
70
  ensureCliCapsProbed().catch(() => {});
71
71
  const launchFailure = require('./lib/scheduler/launchFailure.cjs');
72
+ const { isProtectedClaudePath, sandboxWarnings } = require('./lib/prd/prdSandboxWarnings.cjs');
72
73
  const { sandboxLimitFromStreamJson, environmentLimitStamp, ENVIRONMENT_LIMIT_MESSAGE } = require('./lib/scheduler/sandboxEnvironmentLimit.cjs');
73
74
  const { decideVerifyDowngrade } = require('./lib/scheduler/refireCap.cjs');
74
75
  const { finalizeReasonFor } = require('./lib/scheduler/finalizeReason.cjs');
@@ -140,7 +141,8 @@ const { verifyRun, captureArtifactEvidence, parseLog, scanSentinel, scanForeignW
140
141
  const { latestTerminalOutcomeForSlug, COMPLETED_EQUIVALENT_VERDICTS } = require('./lib/scheduler/terminalRunOutcome.cjs');
141
142
  const { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan, fixPlanRecordPath } = require('./lib/scheduler/fixPlanSlug.cjs');
142
143
  const { landedSinceRun, landedOnMainSince } = require('./lib/scheduler/landedSinceRun.cjs');
143
- const { declaredPathsForPrd, issuedAtForPrd } = require('./lib/prd/prdDeclaredPaths.cjs');
144
+ const { declaredPathsForPrd, issuedAtForPrd, extractDeclaredPaths } = require('./lib/prd/prdDeclaredPaths.cjs');
145
+ const { extractSection: extractPrdSection } = require('./lib/scheduler/definitionOfDone.cjs');
144
146
  const { identity: procIdentityOf, isDifferentProcess } = require('./lib/process/procIdentity.cjs');
145
147
  const jobLeftovers = require('./lib/scheduler/jobLeftovers.cjs');
146
148
  const planReviewHold = require('./scheduler/planReviewHold.cjs');
@@ -195,7 +197,8 @@ const { resolveEpicEffort, effortArgs } = require('./lib/claude/agentEffortResol
195
197
  const { transitionJob, emitJobEvent, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = require('./lib/scheduler/scheduleJobTransitions.cjs');
196
198
  const { buildContextDigest, composeExecutorPrompt } = require('./lib/epic/epicContextDigest.cjs');
197
199
  const { JOB_STATUSES } = require('./lib/scheduler/scheduleJobSchema.cjs');
198
- const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
200
+ const auditLogModule = require('./lib/telemetry/auditLog.cjs');
201
+ const { appendAuditEvent } = auditLogModule;
199
202
  const heldSchedulerTurns = require('./lib/scheduler/heldSchedulerTurns.cjs');
200
203
  const autoStartedSession = require('./lib/feedback-remote/autoStartedSession.cjs');
201
204
  const preflightCheck = require('./lib/scheduler/preflightCheck.cjs');
@@ -2662,6 +2665,29 @@ async function reconcilePass(state) {
2662
2665
  const parent = healTargetForFix(slug, state.jobs);
2663
2666
  entry.investigationDepth = parent ? (parent.investigationDepth ?? 1) + 1 : 2;
2664
2667
  }
2668
+ // A scheduler-authored fix plan whose # Files names a protected .claude path can never pass: the job
2669
+ // sandbox refuses every write there. Minted parked (born directly, like quarantine — not a transition)
2670
+ // with an environment limit so reviewLadder never auto-fixes it.
2671
+ if (entry.isFixPlan && Array.isArray(p.files)) {
2672
+ const protectedFiles = p.files.filter(isProtectedClaudePath);
2673
+ if (protectedFiles.length > 0) {
2674
+ const joined = protectedFiles.join(', ');
2675
+ const bornAt = new Date().toISOString();
2676
+ entry.status = 'needs_review';
2677
+ entry.environmentLimit = { kind: 'claude-dir-write', evidence: `${joined} in # Files` };
2678
+ entry.error = ENVIRONMENT_LIMIT_MESSAGE;
2679
+ entry.statusHistory = [{
2680
+ from: null,
2681
+ to: 'needs_review',
2682
+ reason: `fix plan lists protected path ${joined}; the job sandbox refuses writes there — architect-inline work`,
2683
+ source: 'reconcile',
2684
+ at: bornAt,
2685
+ }];
2686
+ entry.reviewNotice = buildReviewNotice({ job: entry, report: null, epicId: entry.sourcePromptId ?? null, now: bornAt });
2687
+ console.warn(`[scheduler] reconcile: parking fix plan ${slug} — # Files lists protected .claude path(s) ${joined}`);
2688
+ appendAuditEvent('fix_plan_sandbox_refused', { slug, cwd: p.cwd, path: p.path, files: protectedFiles });
2689
+ }
2690
+ }
2665
2691
  // Provenance gate (PRD-authoring lockdown): a PRD discovered with no
2666
2692
  // `createdVia` stamp was never written through scheduler_create_prd/
2667
2693
  // chat:create-prd (prdCreate.cjs always stamps 'scheduler-api') or the
@@ -7417,6 +7443,7 @@ ${logTail}
7417
7443
  the scheduler's commit guard and post-run verifier read git state from this path, and a
7418
7444
  non-repo cwd parks even a fully green, committed run in \`needs_review\`.
7419
7445
  List each file under \`# Files\` as \`- <repo-relative path>\` with nothing else on the line; put any note about a file in the Implementation notes, never on its path line.
7446
+ The job sandbox refuses every write under \`.claude/agents\`, \`.claude/commands\`, \`.claude/skills\`, \`.claude/hooks\` and \`.claude/settings*.json\` (Edit and Write too), so the fix plan must NEVER list such a path in \`# Files\`. If the only fix is there, write no fix plan and report that the edit is architect-inline work in the Epic chat (see PRD_AUTHORING.md #job-sandbox-limits).
7420
7447
  6. The PRD body MUST be self-contained — \`claude -p\` runs it on a fresh Sonnet session with NO conversation context. Include:
7421
7448
  - Root-cause analysis (what went wrong and why)
7422
7449
  - Concrete fix steps (specific files / commands / edits)
@@ -7491,7 +7518,9 @@ function readRunOutcomeSidecars(runDir, slug) {
7491
7518
  */
7492
7519
  const INVESTIGATION_LAUNCH_KEY = 'investigation';
7493
7520
 
7494
- async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {}) {
7521
+ function spawnInvestigation(failedJob, runDir, opts) { return trackInFlight(spawnInvestigationUntracked(failedJob, runDir, opts)); }
7522
+
7523
+ async function spawnInvestigationUntracked(failedJob, runDir, { deadChild = null } = {}) {
7495
7524
  // Auto-dispatch hold first — before anything below can spawn a process
7496
7525
  // (probeClaudeVersion included). A held needs_review row stays eligible for
7497
7526
  // the periodic auto-fix pass; a plain 'failed' row (never a
@@ -8291,24 +8320,38 @@ async function applyPlanReviewHolds(state, deps = {}) {
8291
8320
  const recordRelease = deps.recordRelease || ((a) => planReviewStore.recordPlanRelease(a));
8292
8321
  const notify = deps.notify || ((cwd, epicId, text, extra) => appendResponseEventIfKnown(cwd, epicId, text, extra));
8293
8322
  const gitHead = deps.gitHead || (async (cwd) => { try { return String(await execGitAt(cwd, ['rev-parse', 'HEAD'])).trim() || null; } catch { return null; } });
8294
- const readPrdTexts = deps.readPrdTexts || ((cwd, epicId, slugs) => prdPaths.readEpicPrdTexts(cwd, epicId, slugs));
8295
- const audit = deps.audit || ((k, d) => { try { appendAuditEvent(k, d); } catch { /* audit never breaks dispatch */ } });
8323
+ const readPrdFiles = deps.readPrdFiles || ((cwd, epicId, slugs) => prdPaths.readEpicPrdFiles(cwd, epicId, slugs));
8324
+ const readPrdTexts = deps.readPrdTexts || (async (cwd, epicId, slugs) => {
8325
+ const files = await readPrdFiles(cwd, epicId, slugs);
8326
+ return new Map([...files].map(([k, v]) => [k, v.text]));
8327
+ });
8328
+ const audit = deps.audit || ((k, d) => { try { auditLogModule.appendAuditEvent(k, d); } catch { /* audit never breaks dispatch */ } });
8296
8329
  const readEpicGoal = deps.readEpicGoal || ((cwd, epicId) => {
8297
8330
  try {
8298
8331
  const sessions = readActiveIndex(cwd).sessions;
8299
8332
  const sess = sessions && Object.prototype.hasOwnProperty.call(sessions, epicId) ? sessions[epicId] : null;
8300
- const t = sess && typeof sess.goalText === 'string' ? sess.goalText.trim() : '';
8301
- return t;
8333
+ if (!sess) return '';
8334
+ const title = typeof sess.title === 'string' && sess.title.trim() ? sess.title.trim()
8335
+ : (typeof sess.goalText === 'string' ? sess.goalText.trim().split(/\n\s*\n/)[0].trim() : '');
8336
+ const objective = typeof sess.openingPrompt === 'string' ? sess.openingPrompt.trim().slice(0, 2000) : '';
8337
+ return [title, objective].filter(Boolean).join('\n\n');
8302
8338
  } catch { return ''; }
8303
8339
  });
8304
8340
  const resolvePrdPath = deps.resolvePrdPath || (async (m, cwd, epicId) => {
8305
8341
  try {
8306
- const dir = await prdPaths.findPrdDirForJob({ ...m, cwd: m.cwd || cwd, epicId: m.epicId || epicId });
8307
- if (dir) return path.join(dir, `${m.slug}.md`);
8308
- } catch { /* fall through to the canonical live path */ }
8342
+ const files = await readPrdFiles(m.cwd || cwd, m.epicId || epicId, [m.slug]);
8343
+ const hit = files.get(m.slug);
8344
+ if (hit && hit.path) return path.resolve(hit.path);
8345
+ } catch { /* fall through */ }
8309
8346
  return opsPath(cwd, 'scheduler', 'epics', epicId, 'prds', `${m.slug}.md`);
8310
8347
  });
8348
+ const markCreateRefused = deps.markCreateRefused || ((cwd, epicId, slug, round) => planReviewStore.markCreateRefused(cwd, epicId, slug, round));
8311
8349
  const heldReasons = new Map();
8350
+ const notifyCreateFailed = async (v, epicId, vslug, err) => {
8351
+ try {
8352
+ await notify(v.cwd, epicId, `PLAN REVIEW NOT STARTED — the independent review job for plan ${bareSlug(vslug)} could not be created: ${err}. Its PRDs stay held until the review lands, you release it with scheduler_release_plan, or the hold times out.`, { prdSlug: v.slug, notice: 'plan-review-create-failed', allowInactive: true });
8353
+ } catch { /* notice never breaks the tick */ }
8354
+ };
8312
8355
 
8313
8356
  const reviews = {};
8314
8357
  const validators = rows.filter((r) => r && r.status === 'pending' && r.agentType === 'validator' && r.planReview === 'required');
@@ -8316,7 +8359,7 @@ async function applyPlanReviewHolds(state, deps = {}) {
8316
8359
  const epicId = v.sourcePromptId || v.epicId;
8317
8360
  if (!epicId || !v.cwd) continue;
8318
8361
  const rec = readReview(v.cwd, epicId, v.slug);
8319
- if (rec) reviews[bareSlug(v.slug)] = { ...rec, released: !!rec.release || rec.released === true };
8362
+ if (rec) reviews[bareSlug(v.slug)] = rec;
8320
8363
  }
8321
8364
  const { held: holds, needsReview, expired } = planReviewHold.computePlanReviewHolds(rows, reviews, { now, holdMs });
8322
8365
  const expiredSet = new Set(expired);
@@ -8372,21 +8415,41 @@ async function applyPlanReviewHolds(state, deps = {}) {
8372
8415
  const baseSha = await gitHead(v.cwd);
8373
8416
  const input = buildPlanReviewInput({ epicId, cwd: v.cwd, epicGoal, validateSlug: v.slug, members, baseSha, round });
8374
8417
  const res = await createPrd(input);
8375
- if (res && res.ok === false) console.warn('[scheduler] plan review PRD not created', reviewSlug, res.error || res.reason || '');
8418
+ if (res && res.ok === false) {
8419
+ const err = String(res.error || res.reason || '');
8420
+ console.warn('[scheduler] plan review PRD not created', reviewSlug, err);
8421
+ if (await markCreateRefused(v.cwd, epicId, v.slug, round)) {
8422
+ audit('plan_review_create_refused', { validateSlug: vslug, round, error: err });
8423
+ await notifyCreateFailed(v, epicId, vslug, err);
8424
+ }
8425
+ }
8376
8426
  } catch (e) {
8377
8427
  console.error('[scheduler] plan review PRD create failed', reviewSlug, e?.message || e);
8428
+ try {
8429
+ const err = String(e?.message || e);
8430
+ if (await markCreateRefused(v.cwd, epicId, v.slug, round)) {
8431
+ audit('plan_review_create_refused', { validateSlug: vslug, round, error: err });
8432
+ await notifyCreateFailed(v, epicId, vslug, err);
8433
+ }
8434
+ } catch { /* never breaks the tick */ }
8378
8435
  }
8379
8436
  }
8380
8437
 
8381
8438
  // Stamp / clear heldReason on pending rows so settle + starvation see a known wait.
8382
8439
  const mutateRows = deps.mutateRows || ((fn) => mutate((s) => fn(s.jobs)));
8383
- const dirty = rows.some((r) => r && r.status === 'pending' && (
8440
+ const stampSlugs = new Set();
8441
+ for (const v of validators) {
8442
+ if (expiredSet.has(v.slug) || v.queuedAt || v.createdAt || v.planReviewHeldAt) continue;
8443
+ if (needsReview.includes(v.slug) || planReviewHold.planMembers(v, rows).some((m) => held.has(m.slug))) stampSlugs.add(v.slug);
8444
+ }
8445
+ const dirty = stampSlugs.size > 0 || rows.some((r) => r && r.status === 'pending' && (
8384
8446
  (heldReasons.has(r.slug) && !r.preflightHold && r.heldReason !== heldReasons.get(r.slug))
8385
8447
  || (!heldReasons.has(r.slug) && typeof r.heldReason === 'string' && r.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX))));
8386
8448
  if (dirty) {
8387
8449
  await mutateRows((list) => {
8388
8450
  for (const r of list) {
8389
8451
  if (!r || r.status !== 'pending') continue;
8452
+ if (stampSlugs.has(r.slug) && !r.queuedAt && !r.createdAt && !r.planReviewHeldAt) r.planReviewHeldAt = new Date(now).toISOString();
8390
8453
  if (heldReasons.has(r.slug) && !r.preflightHold) r.heldReason = heldReasons.get(r.slug);
8391
8454
  else if (typeof r.heldReason === 'string' && r.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX)) delete r.heldReason;
8392
8455
  }
@@ -8537,7 +8600,28 @@ function auditPreflightHold(slug, command, result, hold, extra = {}) {
8537
8600
  } catch { /* audit must not break dispatch */ }
8538
8601
  }
8539
8602
 
8540
- async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, siblingJobs = null) {
8603
+ // In-flight launch tracker: every spawnJob / spawnResumeRecovery / spawnInvestigation
8604
+ // run is registered here until it settles, so whenIdle() is a deterministic
8605
+ // "nothing this module launched is still running" signal (no polling, no clock).
8606
+ const inFlightLaunches = new Set();
8607
+ function trackInFlight(promise) {
8608
+ inFlightLaunches.add(promise);
8609
+ const done = () => { inFlightLaunches.delete(promise); };
8610
+ promise.then(done, done);
8611
+ return promise;
8612
+ }
8613
+
8614
+ /** Resolves once every tracked launch has settled, including launches that a
8615
+ * settling launch's own finally-tick started. Never rejects. */
8616
+ async function whenIdle() {
8617
+ while (inFlightLaunches.size > 0) {
8618
+ await Promise.allSettled([...inFlightLaunches]);
8619
+ }
8620
+ }
8621
+
8622
+ function spawnJob(...args) { return trackInFlight(spawnJobUntracked(...args)); }
8623
+
8624
+ async function spawnJobUntracked(job, runId, runDir, defaultCwd, resumeTarget = null, siblingJobs = null) {
8541
8625
  // PRD 1408: the queue rows in scope at dispatch (tickQueue's own
8542
8626
  // state.jobs, threaded straight down — never re-read here or inside
8543
8627
  // executeJob) decide whether this job's own finish protocol still needs to
@@ -9221,7 +9305,13 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9221
9305
  let siblingOverlap = false;
9222
9306
  if (!worktree.ok) {
9223
9307
  rangeCommits = await gitTreeGuard.gitRangeCommits(guardCwd, guardHeadBefore, headAtExit);
9224
- transcriptCommitShas = parseLog(path.join(runDir, `${job.slug}.log`)).transcriptCommitShas || [];
9308
+ // One parseLog call: harness-reported shas plus shas git printed for the run's own
9309
+ // `git commit` Bash call. Both are claims; resolveRunCommitAttribution only credits one inside rangeCommits.
9310
+ const parsedRunLog = parseLog(path.join(runDir, `${job.slug}.log`));
9311
+ transcriptCommitShas = [...new Set([
9312
+ ...(parsedRunLog.transcriptCommitShas || []),
9313
+ ...(parsedRunLog.transcriptCommitOutputShas || []),
9314
+ ])];
9225
9315
  const overlapState = await readQueue().catch(() => ({ jobs: [] }));
9226
9316
  const myStart = Date.parse(dispatchStartedAt) || 0;
9227
9317
  const myEnd = Date.now();
@@ -10320,7 +10410,9 @@ async function reclaimTerminalJobOrphansThrottled(state) {
10320
10410
  * own dispatch mutate is what stamps resumeRecoveryAttempted, atomically
10321
10411
  * with the 'running' transition).
10322
10412
  */
10323
- async function spawnResumeRecovery(job, resumeTarget) {
10413
+ function spawnResumeRecovery(job, resumeTarget) { return trackInFlight(spawnResumeRecoveryUntracked(job, resumeTarget)); }
10414
+
10415
+ async function spawnResumeRecoveryUntracked(job, resumeTarget) {
10324
10416
  // No queue rows in scope here (unlike tickQueue's own dispatch loop) — read
10325
10417
  // once, before delegating to spawnJob, so hasDownstreamValidator still
10326
10418
  // never runs inside executeJob itself. Its config also feeds the hold below.
@@ -12678,6 +12770,42 @@ async function attributeLandedCommits(job, pathCommits, cwd) {
12678
12770
  return null;
12679
12771
  }
12680
12772
 
12773
+ /**
12774
+ * Resolve a commit this job's own transcript names that actually landed on HEAD
12775
+ * during its run. Rule: the transcript SHA resolves to a commit, is an ancestor
12776
+ * of HEAD, and its committer date is within [startedAt, finishedAt + 60s].
12777
+ * Fails closed per candidate and never throws.
12778
+ *
12779
+ * @param {{cwd?: string, logPath?: string, startedAt?: string, finishedAt?: string}} [opts]
12780
+ * @returns {Promise<string|null>}
12781
+ */
12782
+ async function ownTranscriptCommitOnHead({ cwd, logPath, startedAt, finishedAt } = {}) {
12783
+ try {
12784
+ if (!cwd || !logPath) return null;
12785
+ const start = Date.parse(startedAt);
12786
+ const end = Date.parse(finishedAt);
12787
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
12788
+ const parsed = parseLog(logPath);
12789
+ const candidates = [...new Set([
12790
+ ...(parsed.transcriptCommitShas || []),
12791
+ ...(parsed.transcriptCommitOutputShas || []),
12792
+ ])];
12793
+ for (const cand of candidates) {
12794
+ try {
12795
+ if (typeof cand !== 'string' || !/^[0-9a-f]{4,64}$/i.test(cand)) continue;
12796
+ const full = String(await execGitAt(cwd, ['rev-parse', '--verify', `${cand}^{commit}`])).trim();
12797
+ if (!/^[0-9a-f]{40,64}$/i.test(full)) continue;
12798
+ await execGitAt(cwd, ['merge-base', '--is-ancestor', full, 'HEAD']);
12799
+ const cIso = String(await execGitAt(cwd, ['show', '-s', '--format=%cI', full])).trim();
12800
+ const ct = Date.parse(cIso);
12801
+ if (!Number.isFinite(ct) || ct < start || ct > end + 60_000) continue;
12802
+ return full;
12803
+ } catch { /* this candidate fails closed */ }
12804
+ }
12805
+ } catch { /* never throws */ }
12806
+ return null;
12807
+ }
12808
+
12681
12809
  /**
12682
12810
  * Widened evidence check (PRD 1102, narrowed to per-job attribution by a
12683
12811
  * later PRD): does at least one commit ATTRIBUTABLE TO THIS JOB land AFTER
@@ -13154,6 +13282,7 @@ async function reverifyNeedsReview() {
13154
13282
  // rescan) rather than through the isRescanCandidate machinery.
13155
13283
  const candidates = snap.jobs.filter((j) => reviewLadder.isRescanCandidate(j) || reviewLadder.isGuardParkedWithoutAutoFix(j) || reviewLadder.isStaleSharedTreeRevertedPark(j));
13156
13284
  const healed = [];
13285
+ const transcriptHealed = new Map();
13157
13286
  const leftForReview = [];
13158
13287
  const looksDoneUpdates = [];
13159
13288
  // Shared across every computeLooksDone call in this one pass — dedupes
@@ -13223,6 +13352,9 @@ async function reverifyNeedsReview() {
13223
13352
  const hist = await queueHistory.historyTerminalBySlug().catch(() => null);
13224
13353
  priorLandedCommit = hist?.get(job.slug)?.landedCommit ?? null;
13225
13354
  }
13355
+ const transcriptOwn = !job.landedCommit && reviewLadder.NO_ATTRIBUTABLE_COMMIT_VERDICTS.has(job.verifierVerdict)
13356
+ ? await ownTranscriptCommitOnHead({ cwd: job.cwd, logPath: path.join(runDir, `${job.slug}.log`), startedAt: job.startedAt, finishedAt: job.finishedAt })
13357
+ : null;
13226
13358
  let v = null;
13227
13359
  try {
13228
13360
  v = await verifyRun({
@@ -13241,16 +13373,17 @@ async function reverifyNeedsReview() {
13241
13373
  // ground-truth-outranks-heuristics evidence spawnJob passes live,
13242
13374
  // just read back post-hoc since there is no in-flight guardHeadBefore/
13243
13375
  // headAtExit pair to recompute for an already-terminal row.
13244
- jobLandedCommitThisRun: job.landedCommit ?? null,
13376
+ jobLandedCommitThisRun: job.landedCommit ?? transcriptOwn,
13245
13377
  exitCode: job.exitCode ?? null,
13246
13378
  });
13247
13379
  } catch { leftForReview.push({ slug: job.slug, reason: 'verifyRun threw' }); continue; }
13248
- const refusal = reviewLadder.healRefusalReason(job, v, committedDuringRun);
13380
+ const refusal = reviewLadder.healRefusalReason(transcriptOwn ? { ...job, landedCommit: transcriptOwn } : job, v, committedDuringRun);
13249
13381
  let stillOpen = true;
13250
13382
  if (refusal) {
13251
13383
  leftForReview.push({ slug: job.slug, reason: refusal });
13252
13384
  } else if (v && COMPLETED_EQUIVALENT_VERDICTS.has(v.verdict)) {
13253
13385
  healed.push(job.slug);
13386
+ if (transcriptOwn) transcriptHealed.set(job.slug, transcriptOwn);
13254
13387
  stillOpen = false;
13255
13388
  } else {
13256
13389
  leftForReview.push({ slug: job.slug, reason: v ? `${v.verdict}: ${v.reason}` : 'null verdict' });
@@ -13356,6 +13489,10 @@ async function reverifyNeedsReview() {
13356
13489
  j.error = null;
13357
13490
  delete j.verifierVerdict;
13358
13491
  delete j.looksDone;
13492
+ if (transcriptHealed.has(j.slug) && !j.landedCommit) {
13493
+ j.landedCommit = transcriptHealed.get(j.slug);
13494
+ j.landedCommitSource = 'transcript-output';
13495
+ }
13359
13496
  healedPrds.push({ slug: j.slug, cwd: j.cwd });
13360
13497
  }
13361
13498
  }
@@ -15170,6 +15307,18 @@ const remote = {
15170
15307
  prdCreate.mcpReachDeps,
15171
15308
  ));
15172
15309
  } catch { /* advisory only — never fails the update */ }
15310
+ try {
15311
+ const effFiles = Array.isArray(files) ? files : extractDeclaredPaths(newBody);
15312
+ const crit = Array.isArray(fm.criteria) && fm.criteria.length
15313
+ ? fm.criteria.map((c) => (typeof c === 'string' ? c : c?.statement))
15314
+ : [extractPrdSection(newBody, 'Acceptance criteria')];
15315
+ patchWarnings = patchWarnings.concat(sandboxWarnings({
15316
+ files: effFiles,
15317
+ goal: extractPrdSection(newBody, 'Goal'),
15318
+ implementationNotes: extractPrdSection(newBody, 'Implementation notes'),
15319
+ acceptanceCriteria: crit.filter((c) => typeof c === 'string'),
15320
+ }));
15321
+ } catch { /* advisory only — never fails the update */ }
15173
15322
  return patchWarnings.length
15174
15323
  ? { ok: true, slug, bytesWritten: stat.size, warnings: patchWarnings }
15175
15324
  : { ok: true, slug, bytesWritten: stat.size };
@@ -15569,6 +15718,7 @@ queueOps.bindQueueAccess({
15569
15718
  });
15570
15719
 
15571
15720
  module.exports = {
15721
+ readQueue,
15572
15722
  PARK_ERRORS,
15573
15723
  applyPlanReviewHolds,
15574
15724
  starveRootFor,
@@ -15659,6 +15809,7 @@ module.exports = {
15659
15809
  applyNeedsReviewAutoResolve,
15660
15810
  applyStuckFailedAutoSkip,
15661
15811
  computeLooksDone,
15812
+ ownTranscriptCommitOnHead,
15662
15813
  attributeLandedCommits,
15663
15814
  isPromotableOriginal,
15664
15815
  applyRcaClassification,
@@ -15748,6 +15899,7 @@ module.exports = {
15748
15899
  driveUpgradeDrain,
15749
15900
  clearStaleDrainAtBoot,
15750
15901
  stop,
15902
+ whenIdle,
15751
15903
  runDueJobs,
15752
15904
  pollLoop,
15753
15905
  maybeLaunchWhenAvailable,
@@ -1,4 +1,4 @@
1
- <!-- PRD_AUTHORING.md v36 -->
1
+ <!-- PRD_AUTHORING.md v37 -->
2
2
  # PRD Authoring Guide — Scheduler Safety Rules
3
3
 
4
4
  Rule: every PRD you queue follows the rules below.
@@ -239,7 +239,7 @@ Why: those verdicts mean the run ended without a clean verdict line, not that th
239
239
 
240
240
  Rule: a park caused by a DIFFERENT actor already finishing the same objective (a sibling PRD, a human) does not self-heal this way. Why: the job has no landed commit of its own. Confirm in the tree that the work is really done, then call `scheduler_archive_prd` with the slug. Archiving marks the job completed and frees the PRDs that depend on it. Never hand-edit `queue.json`: the scheduler and the watchdog both write it. Archiving clears a stale label; it does not fix a real bug.
241
241
 
242
- Rule: a no-commit PASS (`pass_no_commit`) completes only with a prior landed commit of the same slug, or when every path in the Files list landed on the base branch since the PRD was written. Otherwise it parks.
242
+ Rule: a no-commit PASS (`pass_no_commit`) completes only when the run's own commit is found (in its HEAD range, CLI-recorded, or named in its transcript and on HEAD), a prior commit of the same slug landed, or a commit on a Files path is attributable to this job (its branch or slug in the message); path overlap alone never counts. Otherwise it parks.
243
243
  Why: a tracked path existing is not proof this PRD's work shipped.
244
244
 
245
245
  ---
@@ -1478,6 +1478,24 @@ async function serviceRevoke(serviceId) {
1478
1478
  return { ok: true, relayRevoked };
1479
1479
  }
1480
1480
 
1481
+ /** Owner grant: set (or with [] revoke) where work a service opens auto-starts. Audited. */
1482
+ async function serviceSetStartWork(serviceId, targets) {
1483
+ const store = getServiceStore();
1484
+ if (!store.list().some((s) => s.serviceId === serviceId)) return { ok: false, error: 'no_such_service' };
1485
+ let service;
1486
+ try {
1487
+ service = await store.setStartWork(serviceId, targets);
1488
+ } catch (e) {
1489
+ return { ok: false, error: e?.message || 'invalid_targets' };
1490
+ }
1491
+ const granted = service.startWork ? service.startWork.targets : [];
1492
+ const detail = granted.length === 0
1493
+ ? `ok:revoked:service=${auditToken(serviceId)}`
1494
+ : `ok:granted:service=${auditToken(serviceId)}:targets=${granted.map((t) => String(t).replace(/[^\x20-\x7e]/g, '_').replace(/[,\s]/g, '_')).join(',').slice(0, 1000)}`;
1495
+ await auditLog(new Date().toISOString(), 'service:set-start-work', undefined, undefined, detail, null);
1496
+ return { ok: true, service: redactService(service) };
1497
+ }
1498
+
1481
1499
  /**
1482
1500
  * Owner denied a pending pairing: drop it from the store and fail + tear down
1483
1501
  * any service client waiting on it, so a later hello for it is refused.
@@ -2155,6 +2173,10 @@ function registerRemoteHandlers() {
2155
2173
  return serviceRevoke(serviceId);
2156
2174
  }));
2157
2175
 
2176
+ ipcMain.handle('webRemote:service-set-start-work', validated(schemas.webRemoteServiceSetStartWork, async ({ serviceId, targets }) => {
2177
+ return serviceSetStartWork(serviceId, targets);
2178
+ }));
2179
+
2158
2180
  ipcMain.handle('webRemote:relay-client-revoke', validated(schemas.webRemoteRelayClientRevoke, async ({ clientId }) => {
2159
2181
  return relayClientRevoke(clientId);
2160
2182
  }));
@@ -2992,6 +2992,8 @@ export interface WebRemoteService {
2992
2992
  lastSeenAt: number;
2993
2993
  /** How the pairing was approved: owner window (default) or the loopback admin API. */
2994
2994
  pairedVia?: 'window' | 'local';
2995
+ /** Owner grant: work this service opens in these projects ('*' = all) starts without a second approval. null = off. */
2996
+ startWork?: { targets: string[] } | null;
2995
2997
  }
2996
2998
 
2997
2999
  export interface WebRemotePendingService {
@@ -3043,6 +3045,10 @@ export type WebRemoteServicePairCancelResult =
3043
3045
  | { ok: true; cancelled: boolean; dropped: number }
3044
3046
  | { ok: false; error: string };
3045
3047
 
3048
+ export type WebRemoteServiceSetStartWorkResult =
3049
+ | { ok: true; service: WebRemoteService }
3050
+ | { ok: false; error: string };
3051
+
3046
3052
  export type WebRemoteServiceRevokeResult =
3047
3053
  | { ok: true; relayRevoked: boolean }
3048
3054
  | { ok: false; error: string };
@@ -3772,6 +3778,8 @@ export interface SessionManagerAPI {
3772
3778
  servicePairCancel: (pairingId: string) => Promise<WebRemoteServicePairCancelResult>;
3773
3779
  /** Revoke a paired service locally and at the relay (relay failure still revokes locally). */
3774
3780
  serviceRevoke: (serviceId: string) => Promise<WebRemoteServiceRevokeResult>;
3781
+ /** Set (or with [] revoke) the owner's startWork grant: projects ('*' = all) where work this service opens auto-starts. */
3782
+ serviceSetStartWork: (serviceId: string, targets: string[]) => Promise<WebRemoteServiceSetStartWorkResult>;
3775
3783
  /** Revoke an orphaned relay client. */
3776
3784
  relayClientRevoke: (clientId: string) => Promise<WebRemoteMutationResult>;
3777
3785
  };
@@ -2314,6 +2314,17 @@
2314
2314
  "serviceId"
2315
2315
  ]
2316
2316
  },
2317
+ {
2318
+ "ns": "webRemote",
2319
+ "method": "serviceSetStartWork",
2320
+ "channel": "webRemote:service-set-start-work",
2321
+ "kind": "invoke",
2322
+ "remote": "deny",
2323
+ "pack": [
2324
+ "serviceId",
2325
+ "targets"
2326
+ ]
2327
+ },
2317
2328
  {
2318
2329
  "ns": "webRemote",
2319
2330
  "method": "relayClientRevoke",
@@ -591,6 +591,8 @@ contextBridge.exposeInMainWorld('api', {
591
591
  servicePairCancel: (pairingId) => ipcRenderer.invoke('webRemote:service-pair-cancel', { pairingId }),
592
592
  /** Revoke a paired service locally and at the relay. */
593
593
  serviceRevoke: (serviceId) => ipcRenderer.invoke('webRemote:service-revoke', { serviceId }),
594
+ /** Owner grant: auto-start work this service opens in `targets` (cwds or '*'); [] revokes. */
595
+ serviceSetStartWork: (serviceId, targets) => ipcRenderer.invoke('webRemote:service-set-start-work', { serviceId, targets }),
594
596
  /** Revoke a relay client no local service owns (an orphan). */
595
597
  relayClientRevoke: (clientId) => ipcRenderer.invoke('webRemote:relay-client-revoke', { clientId }),
596
598
  /** Push event when revokeAll completes (main broadcasts webRemote:revoked-all). */