@wildo-ai/dev-companion 1.1.15 → 1.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/esm/.tsbuildinfo +1 -1
  2. package/dist/esm/claude-cli/models/coding-agent-dispatch.models.d.ts +165 -5
  3. package/dist/esm/claude-cli/models/coding-agent-dispatch.models.d.ts.map +1 -1
  4. package/dist/esm/claude-cli/models/coding-agent-dispatch.models.js +239 -8
  5. package/dist/esm/claude-cli/models/coding-agent-dispatch.models.js.map +1 -1
  6. package/dist/esm/claude-cli/models/concurrent-coding-runs.models.d.ts +2 -1
  7. package/dist/esm/claude-cli/models/concurrent-coding-runs.models.d.ts.map +1 -1
  8. package/dist/esm/claude-cli/models/concurrent-coding-runs.models.js +2 -1
  9. package/dist/esm/claude-cli/models/concurrent-coding-runs.models.js.map +1 -1
  10. package/dist/esm/claude-cli/models/isolated-recheck-interference.models.d.ts +68 -0
  11. package/dist/esm/claude-cli/models/isolated-recheck-interference.models.d.ts.map +1 -0
  12. package/dist/esm/claude-cli/models/isolated-recheck-interference.models.js +198 -0
  13. package/dist/esm/claude-cli/models/isolated-recheck-interference.models.js.map +1 -0
  14. package/dist/esm/claude-cli/models/workspace-path-claims.models.d.ts +138 -0
  15. package/dist/esm/claude-cli/models/workspace-path-claims.models.d.ts.map +1 -0
  16. package/dist/esm/claude-cli/models/workspace-path-claims.models.js +204 -0
  17. package/dist/esm/claude-cli/models/workspace-path-claims.models.js.map +1 -0
  18. package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.d.ts +20 -0
  19. package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.d.ts.map +1 -1
  20. package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.js +27 -12
  21. package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.js.map +1 -1
  22. package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.d.ts +155 -3
  23. package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.d.ts.map +1 -1
  24. package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.js +791 -151
  25. package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.js.map +1 -1
  26. package/dist/esm/companion-api/controllers/companion.controller.d.ts.map +1 -1
  27. package/dist/esm/companion-api/controllers/companion.controller.js +7 -1
  28. package/dist/esm/companion-api/controllers/companion.controller.js.map +1 -1
  29. package/dist/esm/core/introspection/resources/creation-home-projection.companion.js +1 -1
  30. package/dist/esm/core/introspection/resources/creation-home-projection.companion.js.map +1 -1
  31. package/dist/esm/core/introspection/subprocess/app-shell-placement-content.behavior.d.ts +13 -0
  32. package/dist/esm/core/introspection/subprocess/app-shell-placement-content.behavior.d.ts.map +1 -1
  33. package/dist/esm/core/introspection/subprocess/app-shell-placement-content.behavior.js +98 -16
  34. package/dist/esm/core/introspection/subprocess/app-shell-placement-content.behavior.js.map +1 -1
  35. package/dist/esm/expert-personas/services/expert-persona.companion.service.d.ts +21 -1
  36. package/dist/esm/expert-personas/services/expert-persona.companion.service.d.ts.map +1 -1
  37. package/dist/esm/expert-personas/services/expert-persona.companion.service.js +35 -3
  38. package/dist/esm/expert-personas/services/expert-persona.companion.service.js.map +1 -1
  39. package/dist/esm/i18n/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.en.d.ts +62 -0
  40. package/dist/esm/i18n/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.en.d.ts.map +1 -0
  41. package/dist/esm/i18n/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.en.js +62 -0
  42. package/dist/esm/i18n/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.en.js.map +1 -0
  43. package/dist/esm/i18n/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.fr.d.ts +62 -0
  44. package/dist/esm/i18n/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.fr.d.ts.map +1 -0
  45. package/dist/esm/i18n/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.fr.js +62 -0
  46. package/dist/esm/i18n/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.fr.js.map +1 -0
  47. package/dist/esm/i18n/system_enums/workbench-build.en.d.ts +1 -1
  48. package/dist/esm/i18n/system_enums/workbench-build.en.js +1 -1
  49. package/dist/esm/i18n/system_enums/workbench-build.en.js.map +1 -1
  50. package/dist/esm/meta-workflows/models/carried-verification-failure.models.d.ts +23 -0
  51. package/dist/esm/meta-workflows/models/carried-verification-failure.models.d.ts.map +1 -1
  52. package/dist/esm/meta-workflows/models/carried-verification-failure.models.js +14 -0
  53. package/dist/esm/meta-workflows/models/carried-verification-failure.models.js.map +1 -1
  54. package/dist/esm/meta-workflows/models/creation-journey-timeline.models.d.ts +12 -1
  55. package/dist/esm/meta-workflows/models/creation-journey-timeline.models.d.ts.map +1 -1
  56. package/dist/esm/meta-workflows/models/creation-journey-timeline.models.js +99 -1
  57. package/dist/esm/meta-workflows/models/creation-journey-timeline.models.js.map +1 -1
  58. package/dist/esm/meta-workflows/services/application-assembly-checks.companion.utils.d.ts +5 -0
  59. package/dist/esm/meta-workflows/services/application-assembly-checks.companion.utils.d.ts.map +1 -1
  60. package/dist/esm/meta-workflows/services/application-assembly-checks.companion.utils.js +22 -1
  61. package/dist/esm/meta-workflows/services/application-assembly-checks.companion.utils.js.map +1 -1
  62. package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.d.ts +67 -20
  63. package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.d.ts.map +1 -1
  64. package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.js +344 -76
  65. package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.js.map +1 -1
  66. package/dist/esm/meta-workflows/services/application-build-follow-up-derivation.companion.d.ts.map +1 -1
  67. package/dist/esm/meta-workflows/services/application-build-follow-up-derivation.companion.js +9 -0
  68. package/dist/esm/meta-workflows/services/application-build-follow-up-derivation.companion.js.map +1 -1
  69. package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.d.ts +47 -1
  70. package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.d.ts.map +1 -1
  71. package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.js +98 -9
  72. package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.js.map +1 -1
  73. package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.d.ts +38 -2
  74. package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.d.ts.map +1 -1
  75. package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.js +176 -22
  76. package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.js.map +1 -1
  77. package/dist/esm/meta-workflows/services/application-build-website-context.companion.service.d.ts +45 -0
  78. package/dist/esm/meta-workflows/services/application-build-website-context.companion.service.d.ts.map +1 -1
  79. package/dist/esm/meta-workflows/services/application-build-website-context.companion.service.js +74 -0
  80. package/dist/esm/meta-workflows/services/application-build-website-context.companion.service.js.map +1 -1
  81. package/dist/esm/meta-workflows/services/creation-run-report.companion.service.d.ts.map +1 -1
  82. package/dist/esm/meta-workflows/services/creation-run-report.companion.service.js +9 -1
  83. package/dist/esm/meta-workflows/services/creation-run-report.companion.service.js.map +1 -1
  84. package/dist/esm/meta-workflows/services/playbook-run.companion.service.d.ts +64 -5
  85. package/dist/esm/meta-workflows/services/playbook-run.companion.service.d.ts.map +1 -1
  86. package/dist/esm/meta-workflows/services/playbook-run.companion.service.js +139 -14
  87. package/dist/esm/meta-workflows/services/playbook-run.companion.service.js.map +1 -1
  88. package/dist/esm/meta-workflows/services/website-demo-facts.models.d.ts +19 -1
  89. package/dist/esm/meta-workflows/services/website-demo-facts.models.d.ts.map +1 -1
  90. package/dist/esm/meta-workflows/services/website-demo-facts.models.js +7 -5
  91. package/dist/esm/meta-workflows/services/website-demo-facts.models.js.map +1 -1
  92. package/dist/esm/technical-doc/services/technical-documentation-pilot.companion.service.d.ts +2 -0
  93. package/dist/esm/technical-doc/services/technical-documentation-pilot.companion.service.d.ts.map +1 -1
  94. package/dist/esm/technical-doc/services/technical-documentation-pilot.companion.service.js +3 -1
  95. package/dist/esm/technical-doc/services/technical-documentation-pilot.companion.service.js.map +1 -1
  96. package/package.json +17 -17
@@ -126,7 +126,7 @@ import { listInFlightCodingRuns } from './in-flight-coding-runs.companion.js';
126
126
  import { APPLICATION_CODING_AGENT_BINDINGS, APPLICATION_CODING_TURN_CLASSIFIER_AGENT_REF, CodingTurnEndClassificationOutputSchema, APPLICATION_CODING_AGENT_REFS, APPLICATION_CODING_SYSTEM_REF, APPLICATION_CODING_WORKTREE_SUBJECT, isApplicationCodingAgentRef, resolveSelectedApplicationCodingAgentBinding, } from '../../meta-workflows/models/application-coding-agent.actors-system.definitions.js';
127
127
  import { humanDecisionSettler } from '../../meta-workflows/models/human-decision-settler.models.js';
128
128
  import { BRIEF_PROVENANCE_UNAVAILABLE_SOURCE_REF } from '../../meta-workflows/models/build-brief-content-trust.models.js';
129
- import { RESOURCES_REGISTRY_COULD_NOT_ASK_MARKER, failedOnlyForUnansweredVerification, readStaleCompiledModelPackage, STALE_COMPILED_MODEL_POLL_INTERVAL_MS, STALE_COMPILED_MODEL_WAIT_MS, DESIGN_SYSTEM_BRAND_ADVISORY_MARKER, DESIGN_SYSTEM_BRAND_COULD_NOT_ASK_MARKER, ApplicationCodingTaskDisposition, codingRunChangedNoFileOfItsOwn, deriveApplicationCodingTaskDisposition, CodingRunStart, deriveCodingRunFailureAttribution, verificationFailureIsCarried, deriveCodingRunStart, isAttributedToAnotherWriter, APPLICATION_CODING_CONTRACT_REFUSAL_MARKER, INTERRUPTED_AT_STARTUP_OUTPUT_FIELD, DISPATCH_DEFAULT_MAX_CAPTURED_BYTES, DISPATCH_DEFAULT_TIMEOUT_MS, DISPATCH_HARD_MAX_CAPTURED_BYTES, DISPATCH_HARD_MAX_TIMEOUT_MS, VerificationKind, renderApplicationCodingTaskAgentPrompt, resolveApplicationCodingTaskVerificationPlans, isClosingReport, parseClosingReportUnmetRequirements, parseClosingReportMetRequirements, SETTLED_HEAD_OUTPUT_FIELD, } from '../models/coding-agent-dispatch.models.js';
129
+ import { ChangeSetAttributionClass, RESOURCES_REGISTRY_COULD_NOT_ASK_MARKER, failedOnlyForUnansweredVerification, readStaleCompiledModelPackage, STALE_COMPILED_MODEL_POLL_INTERVAL_MS, STALE_COMPILED_MODEL_WAIT_MS, DESIGN_SYSTEM_BRAND_ADVISORY_MARKER, DESIGN_SYSTEM_BRAND_COULD_NOT_ASK_MARKER, ApplicationCodingTaskDisposition, codingRunChangedNoFileOfItsOwn, deriveApplicationCodingTaskDisposition, CodingRunStart, deriveCodingRunFailureAttribution, APPLICATION_CODING_TASK_FINDING_ATTRIBUTION, VerificationFindingAttribution, attributeVerificationFailure, applicationRelativeFileOfLocation, deriveCodingRunWrittenElements, readCodingTaskTargetModuleRefs, codingTaskOwnPackageCheckRefs, deriveCodingRunStart, isAttributedToAnotherWriter, APPLICATION_CODING_CONTRACT_REFUSAL_MARKER, INTERRUPTED_AT_STARTUP_OUTPUT_FIELD, DISPATCH_DEFAULT_MAX_CAPTURED_BYTES, DISPATCH_DEFAULT_TIMEOUT_MS, DISPATCH_HARD_MAX_CAPTURED_BYTES, DISPATCH_HARD_MAX_TIMEOUT_MS, VerificationKind, renderApplicationCodingTaskAgentPrompt, resolveApplicationCodingTaskVerificationPlans, isClosingReport, parseClosingReportUnmetRequirements, parseClosingReportMetRequirements, SETTLED_HEAD_OUTPUT_FIELD, } from '../models/coding-agent-dispatch.models.js';
130
130
  import { CodingSessionFrameRetention } from '../models/coding-session-frame-retention.js';
131
131
  import { ApplicationPackageCompileCurrency, isInfrastructureShapedAgentFailure, isProviderAccountAgentFailure, readApplicationPackageCompileCurrency, waitForApplicationPackageCompileCurrent, waitForApplicationPackagesPublished, } from '../../core/runtime/dev-compile-quiet.companion.js';
132
132
  import { readCodingAgentUsageLimit, readRecordedCodingAgentUsageLimit } from '../models/coding-agent-usage-limit.models.js';
@@ -147,6 +147,8 @@ import { APPLICATION_CODING_RUN_CHECKPOINT_KIND, ApplicationCodingRunCheckpointS
147
147
  import { findApplicationDocumentationChapterFileFaults } from '../../technical-doc/services/technical-documentation-chapter-files.companion.js';
148
148
  import { ACTOR_TASK_OUTPUT_FIELDS_HELD_ON_THE_TASK_ROW_ONLY } from '../../executions/models/execution-task-snapshot.models.js';
149
149
  import { readUnrecordedProviderDirectories } from './unrecorded-provider-directories.companion.js';
150
+ import { readApplicationWorkspacePackageGraph, readScopeChangedBetween, resolveVerificationReadScope, writeScopeMayReachReadScope, } from '../models/isolated-recheck-interference.models.js';
151
+ import { describeWorkspacePathClaims, generationStepWorkspaceClaimRoots, WorkspacePathClaimKind, WorkspacePathClaims, } from '../models/workspace-path-claims.models.js';
150
152
  /** The longest one read of the completed coding runs is shared, whatever else happens (#3204). */
151
153
  const COMPLETED_CODING_TASKS_HOLD_MS = 5_000;
152
154
  /** How many completed coding runs the shared read holds: the most recently updated (see {@link CodingAgentDispatchCompanionService}). */
@@ -185,6 +187,54 @@ const OVERRIDE_NOT_REPAIRED_AGENT_SAY_CHARS = 600;
185
187
  const VERIFICATION_MAX_CAPTURED_BYTES = 10 * 1024 * 1024;
186
188
  /** Tail size persisted on the task row; full streams go to traceability artifacts. */
187
189
  const OUTPUT_TAIL_CHARS = 16_000;
190
+ /**
191
+ * How long {@link CodingAgentDispatchCompanionService.recheckIsolatedBesideLiveRuns} leaves the workspace lock free between
192
+ * two runs' re-checks (#3998 review F3). Longer than the slowest poll of a waiter on that lock (`underBriefWorktreeLock`
193
+ * retries at most every 5 s), so a concurrent admission's pre-baseline commit or a settling run's commit waiting behind a
194
+ * batch is taken in the gap instead of starving and being refused after its ~9 minutes of retries, which would stop the
195
+ * wave filling.
196
+ */
197
+ const ISOLATED_RECHECK_LOCK_YIELD_MS = 6_000;
198
+ /**
199
+ * How long a concurrent coding run's admission, or a wave's end, waits for a path-scoped claim it meets to be released
200
+ * (#4020) before it gives up: a generation step writing what the run declares it writes, or a re-check reading it. The
201
+ * same order as the whole-tree lock's own wait (`underBriefWorktreeLock`: 120 retries of at most 5 s), which is what those
202
+ * waits replaced, so a run is never refused sooner than before; only a run whose scope meets the claim waits at all.
203
+ */
204
+ const WORKSPACE_PATH_CLAIM_WAIT_MS = 600_000;
205
+ /** The owner a wave's-end re-check claims its read scope under (#4020): it re-checks several runs, so no run is its owner. */
206
+ const WAVE_END_RECHECK_CLAIM_OWNER = 'wave-end-recheck';
207
+ /**
208
+ * The failed checks of a run's row that are owed an isolated re-check (#3220, #3204, #3998), or `undefined` when none is:
209
+ * the run did not fail its checks beside siblings ({@link failedVerificationBesideSiblings}), a re-check is already recorded
210
+ * (one per run), or every check it failed was carried: red from before it, or red only for findings another writer caused
211
+ * (#3881, `carriedBecause`).
212
+ */
213
+ function readOwedIsolatedRecheckCheckRefs(row) {
214
+ const output = isRecordValue(row.output) ? row.output : undefined;
215
+ // Interference suspected, or checks that could not be asked beside siblings (a sibling's red compile): #3204.
216
+ if (output === undefined || !failedVerificationBesideSiblings(output))
217
+ return undefined;
218
+ if (readIsolatedVerificationRecheck(row.memory) !== undefined)
219
+ return undefined;
220
+ const carried = new Set(Array.isArray(output.carriedVerificationFailures) ? output.carriedVerificationFailures.map(String) : []);
221
+ const checkRefs = [...new Set((Array.isArray(output.verification) ? output.verification : [])
222
+ .filter((entry) => isRecordValue(entry) && typeof entry.checkRef === 'string' && isRecordValue(entry.outcome))
223
+ .filter((entry) => entry.outcome.success === false && !carried.has(entry.checkRef))
224
+ .map((entry) => entry.checkRef))];
225
+ return checkRefs.length === 0 ? undefined : checkRefs;
226
+ }
227
+ /**
228
+ * The findings a run's FAILED checks were not charged with (#3881 review F3), per check: those red at its baseline and
229
+ * those another writer caused, as the run's row records them (`verificationFindingsNotCharged`). Empty for a row written
230
+ * before the field, so its re-check judges whole checks as before.
231
+ */
232
+ function readVerificationFindingsNotCharged(output) {
233
+ const recorded = isRecordValue(output) && isRecordValue(output.verificationFindingsNotCharged) ? output.verificationFindingsNotCharged : {};
234
+ return new Map(Object.entries(recorded).flatMap(([checkRef, findings]) => (Array.isArray(findings)
235
+ ? [[checkRef, new Set(findings.filter((finding) => typeof finding === 'string'))]]
236
+ : [])));
237
+ }
188
238
  /**
189
239
  * What became of a cancelled run's park (#1581, tenth review). Told apart because a person is told
190
240
  * which: a best-effort withdraw can fail, and the store can fail to answer at all.
@@ -647,6 +697,16 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
647
697
  * lazily for the same `Object.create` reason as the beat itself.
648
698
  */
649
699
  codingWorkDepth;
700
+ /**
701
+ * The PATH-SCOPED holds on the tree (#4020, {@link WorkspacePathClaims}): a generation step's declared write roots for
702
+ * its window and a re-check's read scope while its checks run (both inside the lock they hold), and a concurrent run
703
+ * between its admission and its registration. Built lazily for the same `Object.create` reason as the heartbeat.
704
+ */
705
+ workspacePathClaimRegistry;
706
+ get workspacePathClaims() {
707
+ this.workspacePathClaimRegistry ??= new WorkspacePathClaims();
708
+ return this.workspacePathClaimRegistry;
709
+ }
650
710
  adjustCodingWorkDepth(taskId, delta) {
651
711
  this.codingWorkDepth ??= new Map();
652
712
  const next = (this.codingWorkDepth.get(taskId) ?? 0) + delta;
@@ -973,51 +1033,81 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
973
1033
  const runBody = async () => {
974
1034
  let admitted;
975
1035
  /*
976
- * Not while this process is going away (#1026). The supervisor's restart HOLD reads the
977
- * workspace lock, so it protects a run that already holds it — but a dispatch still waiting
978
- * (the compile-quiet wait before admission) holds none, the supervisor restarts, and the SIGTERM
979
- * grace lets this process admit it anyway: measured 2026-09-25, a run was admitted at 11:18:12,
980
- * five seconds after the supervisor's stop began, and was SIGKILLed with the companion. Checked
981
- * here, under the lock and before anything is opened, so the refusal leaves no row behind and is
982
- * a HOST refusal (it counts against no attempt budget, #1581).
1036
+ * The PATH-SCOPED claims (#4020). A CONCURRENT run opens its admission claim at once, and holds it until it is a
1037
+ * registered live run, so a re-check that opens meanwhile sees it and does not run over its scope; it waits for
1038
+ * the claims that meet its scope below, before its baseline ({@link awaitWorkspaceLockUnlessHeldByAClaim}). A
1039
+ * SINGLE-FLIGHT run was promised the whole tree, so any open claim refuses it; it holds the whole-tree lock here,
1040
+ * under which every step and re-check claim is opened, so the answer cannot change while it starts.
983
1041
  */
984
- if (this.shutdownManager?.isShutdownInProgress() === true) {
985
- admission.reject(this.buildDispatchConflictError(`Coding task ${task.taskRef} was not started: the companion is shutting down. Dispatch it again once it is back.`));
986
- return;
987
- }
988
- // Before the baseline, never inside the run: a playbook file left uncommitted here would be
989
- // dirty at this run's baseline, and this run's own accept would then refuse it (#1534). A
990
- // concurrent run holds no lock, so it takes one for this commit only.
991
- await (mode === CodingRunConcurrency.CONCURRENT
992
- ? this.underBriefWorktreeLock(() => this.acceptPendingPlaybookRunsBeforeBaseline())
993
- : this.acceptPendingPlaybookRunsBeforeBaseline());
1042
+ let releaseAdmissionClaim;
994
1043
  try {
995
- const baseline = await this.gitChangeSetService.captureWorktreeSnapshot();
996
- // The run IS an actor-system execution from here on (#1359): the engine opens the
997
- // execution and its task, and will settle both however the run ends.
998
- const opened = selected
999
- ? await this.startSelectedApplicationCodingExecution(selected, task, baseline, sessionContext, origin)
1000
- : await this.openApplicationCodingExecution(task, baseline, sessionContext, origin, mode);
1001
- this.registerActiveRun({
1002
- taskId: opened.taskId,
1003
- startedAt: new Date().toISOString(),
1004
- abortController: new AbortController(),
1005
- mode,
1006
- });
1007
- this.openCodingRunWindow(opened.taskId, task.taskRef);
1008
- // Started: the run has left the next-task selection's ready set, and no file says so yet.
1009
- this.announceRunStateChanged();
1010
- admitted = { opened, baseline };
1011
- // Registered BEFORE the admission is resolved, so a caller that
1012
- // awaits the settlement right after admission can never miss it.
1013
- const settlement = createDeferred();
1014
- this.applicationCodingTaskSettlements.set(opened.taskId, { promise: settlement.promise, resolve: () => settlement.resolve(undefined) });
1015
- admission.resolve(admitted);
1044
+ if (mode === CodingRunConcurrency.CONCURRENT)
1045
+ releaseAdmissionClaim = this.workspacePathClaims.acquire(this.admissionClaimRequest(task));
1046
+ else
1047
+ this.refuseWhileWorkspacePathClaimsOpen(task.taskRef);
1016
1048
  }
1017
1049
  catch (error) {
1018
- admission.reject(this.translateWorktreeBusy(error));
1050
+ admission.reject(error);
1019
1051
  return;
1020
1052
  }
1053
+ try {
1054
+ /*
1055
+ * Not while this process is going away (#1026). The supervisor's restart HOLD reads the
1056
+ * workspace lock, so it protects a run that already holds it — but a dispatch still waiting
1057
+ * (the compile-quiet wait before admission) holds none, the supervisor restarts, and the SIGTERM
1058
+ * grace lets this process admit it anyway: measured 2026-09-25, a run was admitted at 11:18:12,
1059
+ * five seconds after the supervisor's stop began, and was SIGKILLed with the companion. Checked
1060
+ * here (under the lock for a single-flight run), after any wait for the workspace and before
1061
+ * anything is opened, so the refusal leaves no row behind and is a HOST refusal (it counts against
1062
+ * no attempt budget, #1581).
1063
+ */
1064
+ if (this.shutdownManager?.isShutdownInProgress() === true) {
1065
+ admission.reject(this.buildDispatchConflictError(`Coding task ${task.taskRef} was not started: the companion is shutting down. Dispatch it again once it is back.`));
1066
+ return;
1067
+ }
1068
+ // Before the baseline, never inside the run: a playbook file left uncommitted here would be
1069
+ // dirty at this run's baseline, and this run's own accept would then refuse it (#1534). A
1070
+ // concurrent run holds no lock, so it takes one for this commit only. With nothing to commit
1071
+ // (#4020) it only waits for the lock's holder, and not at all when the holder is this process
1072
+ // in a section that claims its paths: a step or a re-check, which the claim wait above judged.
1073
+ if (mode !== CodingRunConcurrency.CONCURRENT)
1074
+ await this.acceptPendingPlaybookRunsBeforeBaseline();
1075
+ else if (await this.playbookRunsAwaitAutomaticAccept())
1076
+ await this.underBriefWorktreeLock(() => this.acceptPendingPlaybookRunsBeforeBaseline());
1077
+ else
1078
+ await this.awaitWorkspaceLockUnlessHeldByAClaim(task);
1079
+ try {
1080
+ const baseline = await this.gitChangeSetService.captureWorktreeSnapshot();
1081
+ // The run IS an actor-system execution from here on (#1359): the engine opens the
1082
+ // execution and its task, and will settle both however the run ends.
1083
+ const opened = selected
1084
+ ? await this.startSelectedApplicationCodingExecution(selected, task, baseline, sessionContext, origin)
1085
+ : await this.openApplicationCodingExecution(task, baseline, sessionContext, origin, mode);
1086
+ this.registerActiveRun({
1087
+ taskId: opened.taskId,
1088
+ startedAt: new Date().toISOString(),
1089
+ abortController: new AbortController(),
1090
+ mode,
1091
+ });
1092
+ this.openCodingRunWindow(opened.taskId, task.taskRef);
1093
+ // Started: the run has left the next-task selection's ready set, and no file says so yet.
1094
+ this.announceRunStateChanged();
1095
+ admitted = { opened, baseline };
1096
+ // Registered BEFORE the admission is resolved, so a caller that
1097
+ // awaits the settlement right after admission can never miss it.
1098
+ const settlement = createDeferred();
1099
+ this.applicationCodingTaskSettlements.set(opened.taskId, { promise: settlement.promise, resolve: () => settlement.resolve(undefined) });
1100
+ admission.resolve(admitted);
1101
+ }
1102
+ catch (error) {
1103
+ admission.reject(this.translateWorktreeBusy(error));
1104
+ return;
1105
+ }
1106
+ }
1107
+ finally {
1108
+ // Registered (or refused) by now: a live run is what the claims' holders see from here on (#4020).
1109
+ releaseAdmissionClaim?.();
1110
+ }
1021
1111
  try {
1022
1112
  const trace = await this.openCodingRunTrace(admitted.opened.taskId, task.taskRef);
1023
1113
  await this.superviseCodingRun(task.taskRef, admitted.opened.taskId, trace, (capture) => this.actorsSystem.completeActorExecution(admitted.opened, async (opened) => capture(await this.executeApplicationCodingTask(task, renderedPrompt, verificationPlans, opened, admitted.baseline, trace)), trace.runSession, this.codingRunOptions));
@@ -1791,6 +1881,40 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
1791
1881
  }
1792
1882
  /** The reconciliation the last sharing episode's end started, for a caller that must see its commit. */
1793
1883
  sharingEpisodeReconciliation = Promise.resolve();
1884
+ /**
1885
+ * Who says what a generation step CLAIMS while it runs (#4020): the generation-step service, which knows what each step
1886
+ * writes beyond its write scope (`GENERATION_STEP_CLAIM_BASIS`). Unset, no step claims anything, and every coding run
1887
+ * waits for a step's lock as before: the fail-closed answer, never a guess from the write scope alone.
1888
+ */
1889
+ generationStepClaimResolver;
1890
+ /** Register {@link generationStepClaimResolver}; the generation-step service does, when it is built. */
1891
+ registerGenerationStepClaimResolver(resolver) {
1892
+ this.generationStepClaimResolver = resolver;
1893
+ }
1894
+ /**
1895
+ * The roots this step claims for its window (#4020), or `undefined` for none. The step is named by its own task row
1896
+ * (`input.generationStepRef`, written when its execution opens). Anything that cannot be answered (no resolver, no row,
1897
+ * a step the resolver does not know or has not audited, a resolver that throws) claims nothing: the fail-closed answer.
1898
+ */
1899
+ async resolveGenerationStepClaim(input) {
1900
+ const resolver = this.generationStepClaimResolver;
1901
+ if (resolver === undefined)
1902
+ return undefined;
1903
+ try {
1904
+ const row = await this.executionsService.getActorTask(input.taskId);
1905
+ const generationStepRef = row?.input?.generationStepRef;
1906
+ if (typeof generationStepRef !== 'string')
1907
+ return undefined;
1908
+ const resolved = await resolver({ generationStepRef, writableRoots: input.ownedPathPrefixes ?? [] });
1909
+ return resolved === undefined ? undefined : generationStepWorkspaceClaimRoots(resolved);
1910
+ }
1911
+ catch (error) {
1912
+ this.logDebug('Could not resolve a generation step\'s path claim; it claims nothing, so every coding run waits for it', {
1913
+ taskRef: input.taskRef, error: describeCaughtError(error),
1914
+ });
1915
+ return undefined;
1916
+ }
1917
+ }
1794
1918
  /**
1795
1919
  * Answers why runs must not be re-checked alone right now (#3880 review F1): while the application's start is refused,
1796
1920
  * every isolated re-check, the wave's own and the one a sharing episode's end runs, is deferred. A re-check against an
@@ -1862,6 +1986,105 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
1862
1986
  throw this.buildDispatchConflictError(`${concurrent.length} coding run(s) of a parallel build wave are live (${concurrent.map((run) => run.taskRef ?? run.executionId).join(', ')}). `
1863
1987
  + 'A single run cannot start beside them; it runs after the wave, or as part of the next one.');
1864
1988
  }
1989
+ /**
1990
+ * Refuse a SINGLE-FLIGHT run (409) while any path-scoped claim is open (#4020): a step still writing its directories, or
1991
+ * a concurrent run being admitted. A single-flight run was promised the whole tree, which those cannot share. Asked
1992
+ * under the whole-tree lock the run holds, under which every step and re-check claim is opened.
1993
+ */
1994
+ refuseWhileWorkspacePathClaimsOpen(taskRef) {
1995
+ const open = this.workspacePathClaims.list();
1996
+ if (open.length === 0)
1997
+ return;
1998
+ throw this.buildDispatchConflictError(`Coding task ${taskRef} was not started: it runs alone in the tree, and ${describeWorkspacePathClaims(open)} holds part of it now. `
1999
+ + 'Dispatch it again once that is done.');
2000
+ }
2001
+ /**
2002
+ * Whether the accept before a concurrent run's baseline has anything to commit (#4020), so the run takes the whole-tree
2003
+ * lock only then. Under a posture that keeps acceptance with a person, nothing is committed and no lock is needed. A
2004
+ * register that cannot answer counts as YES: the run then takes the lock as it always did, never skips a commit owed.
2005
+ */
2006
+ async playbookRunsAwaitAutomaticAccept() {
2007
+ if (laneBoundaryTreatmentFor(APPLICATION_CREATION_AUTONOMY_POSTURE, PlaybookLaneBoundaryDecision.APPROVE_RESULT) !== LaneBoundaryTreatment.NOTIFY_AND_PROCEED)
2008
+ return false;
2009
+ try {
2010
+ return await this.acceptedChangeCommit.hasPlaybookRunsTheAutomaticAcceptTakes();
2011
+ }
2012
+ catch {
2013
+ return true;
2014
+ }
2015
+ }
2016
+ /**
2017
+ * The roots generation steps are writing right now (#4020), which no commit may carry yet. Every automatic commit takes
2018
+ * the lock a step holds, so it cannot happen meanwhile; this is for the door that takes none, the person's build
2019
+ * checkpoint (`POST /build/checkpoint`).
2020
+ */
2021
+ generationStepRootsBeingWritten() {
2022
+ return this.workspacePathClaims.openStepWriteRoots();
2023
+ }
2024
+ /**
2025
+ * Wait for the whole-tree lock's current holder before a concurrent run's baseline (#4020), UNLESS that holder is this
2026
+ * process in a section that claims its paths, none of which meets the run's declared scope: a generation step's window
2027
+ * or an isolated re-check, whose STEP_WRITE and RECHECK_READ claims are opened and released inside the lock they hold. A
2028
+ * claim that does meet the scope is waited for. Every other holder is waited for exactly as the pre-baseline commit's
2029
+ * lock used to wait for it: a step that declares nothing, a commit, a CLI writer in another process. The baseline is
2030
+ * still taken after the lock is released, as before; a moving HEAD there is the snapshot's own retry (#3204).
2031
+ *
2032
+ * The scope is the contract's `allowedPathPrefixes`, a PREDICTION (#1268 lets a run write anywhere). A run that writes
2033
+ * outside it beside a step meets what #2240 records: the step's directories are its own, and a file a coding run wrote
2034
+ * under one anyway is committed under the step's name.
2035
+ *
2036
+ * Asked by taking the lock for nothing, polled like {@link underBriefWorktreeLock} and bounded the same way; past the
2037
+ * bound the run is refused (409), as a commit's lock wait past its retries refused it.
2038
+ */
2039
+ async awaitWorkspaceLockUnlessHeldByAClaim(task) {
2040
+ const request = this.admissionClaimRequest(task);
2041
+ const deadline = Date.now() + (this.workspacePathClaimWaitMs ?? WORKSPACE_PATH_CLAIM_WAIT_MS);
2042
+ const heldByAClaim = () => this.workspacePathClaims.list().some((claim) => claim.kind !== WorkspacePathClaimKind.ADMISSION_WRITE);
2043
+ let pollMs = 500;
2044
+ for (;;) {
2045
+ /*
2046
+ * Asked again at every turn, never only once: a step or a re-check may have opened its claim since the run's own
2047
+ * admission claim was opened, and one that meets the run's scope is waited for here as it would have been there.
2048
+ */
2049
+ const conflicting = this.workspacePathClaims.conflicting(request);
2050
+ if (conflicting.length === 0) {
2051
+ if (heldByAClaim())
2052
+ return;
2053
+ try {
2054
+ await withDedicatedFileLock(this.getWorkspaceMutationLockPath(), async () => undefined, { retries: { retries: 0 } });
2055
+ return;
2056
+ }
2057
+ catch (error) {
2058
+ if (error?.code !== 'ELOCKED')
2059
+ throw error;
2060
+ }
2061
+ }
2062
+ if (Date.now() >= deadline) {
2063
+ throw this.buildDispatchConflictError(`Coding task ${task.taskRef} was not started: ${conflicting.length > 0 ? describeWorkspacePathClaims(conflicting) : 'another writer'} `
2064
+ + 'still held the workspace past the wait bound. Dispatch it again once it is free.');
2065
+ }
2066
+ // Woken early when a claim opens or closes (a step's window may just have begun or ended), polled otherwise.
2067
+ let timer;
2068
+ await Promise.race([
2069
+ this.workspacePathClaims.nextChange(),
2070
+ new Promise((resolve) => { timer = setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))); }),
2071
+ ]);
2072
+ if (timer !== undefined)
2073
+ clearTimeout(timer);
2074
+ pollMs = Math.min(pollMs * 2, 5_000);
2075
+ }
2076
+ }
2077
+ /** The admission claim of a concurrent run (#4020): the write prefixes its contract declares. */
2078
+ admissionClaimRequest(task) {
2079
+ return {
2080
+ kind: WorkspacePathClaimKind.ADMISSION_WRITE,
2081
+ ownerTaskId: task.taskRef,
2082
+ ownerTaskRef: task.taskRef,
2083
+ writePrefixes: task.mutationScope.allowedPathPrefixes,
2084
+ };
2085
+ }
2086
+ /** {@link WORKSPACE_PATH_CLAIM_WAIT_MS}, a field so a test need not wait it. */
2087
+ workspacePathClaimWaitMs = WORKSPACE_PATH_CLAIM_WAIT_MS;
1865
2088
  /** Record that a run entered the tree, for the runs it will overlap (#1528). */
1866
2089
  openCodingRunWindow(taskId, taskRef) {
1867
2090
  const now = Date.now();
@@ -2374,8 +2597,41 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
2374
2597
  const during = (await this.codingRunWriteRegister.list())
2375
2598
  .filter((record) => record.concurrent === true && record.at >= input.startedAt)
2376
2599
  .map((record) => record.taskId);
2377
- // Under the workspace lock (review of 4a1b1f1bf F10): no generation step or newly admitted run writes during the re-check.
2378
- const recheck = () => this.recheckInterferedVerificationFailures([...new Set([...input.taskIds, ...during])]);
2600
+ /*
2601
+ * Under the workspace lock (review of 4a1b1f1bf F10): no generation step and no commit runs during the re-check.
2602
+ * Since #4020 a concurrent run is admitted without that lock when it has nothing to commit and its holder is a
2603
+ * claim-carrying section. So the re-check first waits, holding nothing, for runs being admitted (and for a step,
2604
+ * whose claim lasts its window); then, under the lock and in one synchronous step, finds none (or defers, as for a
2605
+ * concurrent run still writing) and opens a claim over the WHOLE application, which every later admission waits for.
2606
+ */
2607
+ const writersBeside = () => this.workspacePathClaims.list()
2608
+ .filter((claim) => claim.kind === WorkspacePathClaimKind.STEP_WRITE || claim.kind === WorkspacePathClaimKind.ADMISSION_WRITE);
2609
+ if (input.lock?.takeLock !== false) {
2610
+ await this.workspacePathClaims.waitUntilClear(writersBeside, { timeoutMs: this.workspacePathClaimWaitMs ?? WORKSPACE_PATH_CLAIM_WAIT_MS });
2611
+ }
2612
+ const recheck = async () => {
2613
+ const writing = writersBeside();
2614
+ if (writing.length > 0 || this.concurrentRunLiveInProcess(input.taskIds)) {
2615
+ deferred = true;
2616
+ this.logDebug('Deferred the isolated re-checks: a writer outside these runs is still writing', {
2617
+ taskIds: input.taskIds, writers: describeWorkspacePathClaims(writing),
2618
+ });
2619
+ return;
2620
+ }
2621
+ const release = this.workspacePathClaims.acquire({
2622
+ kind: WorkspacePathClaimKind.RECHECK_READ,
2623
+ ownerTaskId: WAVE_END_RECHECK_CLAIM_OWNER,
2624
+ ownerTaskRef: 'the end of a wave',
2625
+ readScope: { wholeApplication: true },
2626
+ graph: undefined,
2627
+ });
2628
+ try {
2629
+ await this.recheckInterferedVerificationFailures([...new Set([...input.taskIds, ...during])]);
2630
+ }
2631
+ finally {
2632
+ release();
2633
+ }
2634
+ };
2379
2635
  if (input.lock?.takeLock === false)
2380
2636
  await recheck();
2381
2637
  else
@@ -2386,6 +2642,178 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
2386
2642
  const committedPaths = outcome === undefined || outcome.alreadyCommitted ? 0 : outcome.committedPaths.length;
2387
2643
  return { deferred, results: (outcome?.namedTaskIds ?? []).map((taskId) => ({ taskId, committedPaths })) };
2388
2644
  }
2645
+ /**
2646
+ * Re-check alone NOW each run of `taskIds` that failed its checks beside siblings, wherever no run still live is
2647
+ * expected to write what its re-run checks read (#3998). Until then a failed run waited for the end of its whole wave,
2648
+ * so its task waited for the slowest run whatever that run wrote: on reference run 43961156770 the build ran nothing
2649
+ * with 27 tasks ready for 13.4 minutes, behind one schema follow-up.
2650
+ *
2651
+ * "Alone" keeps the meaning the wave's end gives it, narrowed to what the checks read:
2652
+ * - **Nothing else writes the tree during the checks except live coding runs.** Each run is re-checked under the
2653
+ * workspace lock, as at the wave's end, which no generation step, no run's commit and no new admission's baseline
2654
+ * commit takes meanwhile. Since #4020 a run with nothing to commit is admitted without that lock: the re-check claims
2655
+ * its read scope, so no run whose scope may reach it is admitted over it, and it waits while a run being admitted, or
2656
+ * a step's claim, meets what it reads.
2657
+ * - **No live coding run is expected to write a package the checks read.** A run's expected writes are the scope the
2658
+ * caller names for it (its task's target scope, `expectedWriteScopes`) plus every path its agent has claimed so far.
2659
+ * A run the caller names no scope for is UNKNOWN and holds every re-check, as does a check whose read set is unknown
2660
+ * (`resolveVerificationReadScope`).
2661
+ * - **Nothing the checks read changed while they ran.** The expected scope is a prediction (#1268 lets a run write
2662
+ * anywhere), so the verdict is kept only when a worktree snapshot taken before the checks and one taken after agree
2663
+ * on every path the checks read, and no run expected to write there became live meanwhile. A verdict that fails this
2664
+ * is never recorded: the task stays held, and the next settlement or the wave's end asks again.
2665
+ *
2666
+ * What this cannot see, and keeps a verdict through:
2667
+ * - a write a run made OUTSIDE its expected scope through a shell command, BEFORE the checks began, while it is still
2668
+ * working: the re-check reads that half-done state, as a wave's end reads what a failed sibling left;
2669
+ * - a write to a GITIGNORED path, which no worktree snapshot lists: compiled output above all (`shared-lib/dist`,
2670
+ * `backend-api/dist`, which the registry and schema-plan checks read). A watcher recompiling from a source a live run
2671
+ * wrote is caught through that source, not through the output.
2672
+ * And it discards more than it must: HEAD is compared repository-wide, so any commit during the checks (in framework
2673
+ * development, another session's) discards the verdict, which is the conservative direction.
2674
+ *
2675
+ * Under the posture that lets the system accept, and never while the application's start is refused (#3880). Best
2676
+ * effort per run: one that cannot be re-checked now waits for the next settlement or the wave's end.
2677
+ */
2678
+ async recheckIsolatedBesideLiveRuns(input) {
2679
+ const rechecked = new Map();
2680
+ const resolvedTaskIds = [];
2681
+ if (laneBoundaryTreatmentFor(APPLICATION_CREATION_AUTONOMY_POSTURE, PlaybookLaneBoundaryDecision.APPROVE_RESULT) !== LaneBoundaryTreatment.NOTIFY_AND_PROCEED)
2682
+ return { rechecked, resolvedTaskIds };
2683
+ if (await this.readIsolatedRecheckHold() !== undefined)
2684
+ return { rechecked, resolvedTaskIds };
2685
+ const beside = this.isolatedRecheckBesideLiveRuns(input.expectedWriteScopes);
2686
+ for (const taskId of new Set(input.taskIds)) {
2687
+ try {
2688
+ /*
2689
+ * Whether a re-check is owed, and whether a live run may write what it reads, are asked OUTSIDE the lock (review F3):
2690
+ * a run that would only wait never queues behind a generation step, nor holds the lock from an admission.
2691
+ */
2692
+ const checkRefs = readOwedIsolatedRecheckCheckRefs(await this.executionsService.getActorTask(taskId));
2693
+ if (checkRefs === undefined) {
2694
+ resolvedTaskIds.push(taskId);
2695
+ continue;
2696
+ }
2697
+ if (await beside.wouldWait(taskId, resolveApplicationCodingTaskVerificationPlans(checkRefs)))
2698
+ continue;
2699
+ /*
2700
+ * The lock is left free for longer than a waiter's poll after the last early re-check released it, so an admission or
2701
+ * a commit waiting gets it. Measured from the service's own record, not per call: the wave chains a new batch at once
2702
+ * when something settled during the previous one (review R2), and a per-call gap would leave none between batches.
2703
+ */
2704
+ const yieldMs = this.isolatedRecheckLockYieldMs ?? ISOLATED_RECHECK_LOCK_YIELD_MS;
2705
+ const freeForMs = this.isolatedRecheckLockReleasedAtMs === undefined ? Number.POSITIVE_INFINITY : Date.now() - this.isolatedRecheckLockReleasedAtMs;
2706
+ if (freeForMs < yieldMs)
2707
+ await new Promise((resolve) => setTimeout(resolve, yieldMs - freeForMs));
2708
+ /*
2709
+ * Asked again under the lock: the owed test and the interference test are repeated there, as at the wave's end.
2710
+ * And its READ scope is claimed while the checks run (#4020): a concurrent run is admitted without the lock now
2711
+ * when it has nothing to commit, so the claim is what keeps one whose scope reaches these checks from starting
2712
+ * beside them. Checked against the writers' claims and opened in one synchronous step; a writer holding part of
2713
+ * what it reads leaves the run held, as a live run expected to write there does.
2714
+ */
2715
+ const readRequest = {
2716
+ kind: WorkspacePathClaimKind.RECHECK_READ,
2717
+ ownerTaskId: taskId,
2718
+ ownerTaskRef: taskId,
2719
+ readScope: resolveVerificationReadScope(resolveApplicationCodingTaskVerificationPlans(checkRefs), beside.graph),
2720
+ graph: beside.graph,
2721
+ };
2722
+ let one;
2723
+ try {
2724
+ one = await this.underBriefWorktreeLock(async () => {
2725
+ const writing = this.workspacePathClaims.conflicting(readRequest);
2726
+ if (writing.length > 0) {
2727
+ this.logDebug('A run\'s isolated re-check waits: a path-scoped writer holds what its checks read', { taskId, writers: describeWorkspacePathClaims(writing) });
2728
+ return new Map();
2729
+ }
2730
+ const release = this.workspacePathClaims.acquire(readRequest);
2731
+ try {
2732
+ return await this.recheckInterferedVerificationFailures([taskId], beside);
2733
+ }
2734
+ finally {
2735
+ release();
2736
+ }
2737
+ });
2738
+ }
2739
+ finally {
2740
+ this.isolatedRecheckLockReleasedAtMs = Date.now();
2741
+ }
2742
+ for (const [id, recheck] of one) {
2743
+ rechecked.set(id, recheck);
2744
+ resolvedTaskIds.push(id);
2745
+ }
2746
+ }
2747
+ catch (error) {
2748
+ this.logger.warn('Could not re-check a run beside the live runs; it is asked again at the next settlement or the wave\'s end', { taskId, error: describeCaughtError(error) });
2749
+ }
2750
+ }
2751
+ return { rechecked, resolvedTaskIds };
2752
+ }
2753
+ /** {@link ISOLATED_RECHECK_LOCK_YIELD_MS}, a field so a test need not wait it. */
2754
+ isolatedRecheckLockYieldMs = ISOLATED_RECHECK_LOCK_YIELD_MS;
2755
+ /** When an early isolated re-check last released the workspace lock, across calls (#3998 review R2). */
2756
+ isolatedRecheckLockReleasedAtMs;
2757
+ /** The two questions {@link recheckIsolatedBesideLiveRuns} asks of each run's re-check (#3998). */
2758
+ isolatedRecheckBesideLiveRuns(expectedWriteScopes) {
2759
+ const saasRoot = this.companionContext.saasRoot;
2760
+ const graph = readApplicationWorkspacePackageGraph(saasRoot);
2761
+ // The live writers the existing "alone" counts (`concurrentRunLiveInProcess`), each expected to write what the checks read or unknown.
2762
+ const interferingRuns = async (exceptTaskId, scope) => {
2763
+ const interfering = [];
2764
+ for (const run of this.activeRuns.values()) {
2765
+ if (run.mode !== CodingRunConcurrency.CONCURRENT || run.withdrawalGuard === true || run.taskId === exceptTaskId)
2766
+ continue;
2767
+ const expected = expectedWriteScopes.get(run.taskId);
2768
+ let writes;
2769
+ if (expected !== undefined) {
2770
+ try {
2771
+ const claimed = collectRunClaimedPaths({ candidateRoots: applicationRootSpellings(saasRoot), reportedFileLocations: await this.codingRunWriteRegister.readInFlightClaims(run.taskId) });
2772
+ writes = [...expected, ...claimed];
2773
+ }
2774
+ catch {
2775
+ // Its claims cannot be read: what it wrote is unknown.
2776
+ writes = undefined;
2777
+ }
2778
+ }
2779
+ if (writeScopeMayReachReadScope(writes, scope, graph))
2780
+ interfering.push(run.taskId);
2781
+ }
2782
+ return interfering;
2783
+ };
2784
+ // A path-scoped writer (#4020) — a generation step holding its directories, a run being admitted — may write what the checks read.
2785
+ const interferingClaims = (taskId, scope) => this.workspacePathClaims.conflicting({
2786
+ kind: WorkspacePathClaimKind.RECHECK_READ, ownerTaskId: taskId, ownerTaskRef: taskId, readScope: scope, graph,
2787
+ });
2788
+ return {
2789
+ graph,
2790
+ wouldWait: async (taskId, plans) => {
2791
+ const scope = resolveVerificationReadScope(plans, graph);
2792
+ return interferingClaims(taskId, scope).length > 0 || (await interferingRuns(taskId, scope)).length > 0;
2793
+ },
2794
+ open: async (taskId, plans) => {
2795
+ const scope = resolveVerificationReadScope(plans, graph);
2796
+ const interfering = await interferingRuns(taskId, scope);
2797
+ if (interfering.length > 0) {
2798
+ this.logDebug('A run\'s isolated re-check waits: a live run may write what its checks read', { taskId, interfering });
2799
+ return null;
2800
+ }
2801
+ const before = await this.gitChangeSetService.captureWorktreeSnapshot();
2802
+ return {
2803
+ keptAfterChecks: async () => {
2804
+ const nowInterfering = await interferingRuns(taskId, scope);
2805
+ const after = await this.gitChangeSetService.captureWorktreeSnapshot();
2806
+ if (nowInterfering.length === 0 && !readScopeChangedBetween(before, after, scope, graph))
2807
+ return true;
2808
+ this.logger.info('A run\'s isolated re-check beside live runs was discarded: what its checks read moved while they ran; it is asked again', {
2809
+ taskId, interfering: nowInterfering,
2810
+ });
2811
+ return false;
2812
+ },
2813
+ };
2814
+ },
2815
+ };
2816
+ }
2389
2817
  /**
2390
2818
  * Re-run, ALONE, the failed checks of each run of this reconciliation that failed verification while siblings
2391
2819
  * shared the tree ({@link failedVerificationBesideSiblings}: interference suspected, #3220, or checks that could not be asked
@@ -2393,37 +2821,52 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
2393
2821
  * nothing writes while the checks run. Each re-check is recorded on its run, where the build record shows what
2394
2822
  * was decided; a run whose checks pass now has a result, and its files are committed.
2395
2823
  *
2396
- * A check carried red from before the run is not re-run: it was never this run's failure. Best effort: a re-check
2824
+ * A carried check (red from before the run, or red only for findings another writer caused, #3881) is not re-run: it was
2825
+ * never this run's failure. Best effort: a re-check
2397
2826
  * that cannot run, or cannot be recorded, leaves the run failed, which refuses its files (the safe direction).
2398
2827
  *
2399
2828
  * ONE re-check per run: once one is recorded, the run's standing follows it, and a run that failed again stays failed
2400
2829
  * for its task's next run to fix. "Alone" means no coding run of this process is writing; the tree still holds what
2401
2830
  * failed or cancelled siblings left (their files are refused, not removed), so a re-check can fail on a sibling's
2402
2831
  * half-written file. That keeps the run failed, the conservative answer, and its task is re-run.
2832
+ *
2833
+ * `beside` is set only by {@link recheckIsolatedBesideLiveRuns} (#3998): it says whether a check set may run now, beside
2834
+ * live runs, and whether its verdict may be kept. A check set it refuses is left unrecorded, so its task stays held.
2403
2835
  */
2404
- async recheckInterferedVerificationFailures(taskIds) {
2836
+ async recheckInterferedVerificationFailures(taskIds, beside) {
2405
2837
  const rechecks = new Map();
2406
2838
  for (const taskId of new Set(taskIds)) {
2407
2839
  try {
2408
2840
  const row = await this.executionsService.getActorTask(taskId);
2409
- const output = isRecordValue(row.output) ? row.output : undefined;
2410
- // Interference suspected, or checks that could not be asked beside siblings (a sibling's red compile): #3204.
2411
- if (output === undefined || !failedVerificationBesideSiblings(output))
2841
+ const checkRefs = readOwedIsolatedRecheckCheckRefs(row);
2842
+ if (checkRefs === undefined)
2412
2843
  continue;
2413
- if (readIsolatedVerificationRecheck(row.memory) !== undefined)
2844
+ const plans = resolveApplicationCodingTaskVerificationPlans(checkRefs);
2845
+ // #3998: beside live runs, only when none is expected to write what these checks read; otherwise left held.
2846
+ const besideWindow = beside === undefined ? undefined : await beside.open(taskId, plans);
2847
+ if (besideWindow === null)
2414
2848
  continue;
2415
- const carried = new Set(Array.isArray(output.carriedVerificationFailures) ? output.carriedVerificationFailures.map(String) : []);
2416
- const checkRefs = [...new Set((Array.isArray(output.verification) ? output.verification : [])
2417
- .filter((entry) => isRecordValue(entry) && typeof entry.checkRef === 'string' && isRecordValue(entry.outcome))
2418
- .filter((entry) => entry.outcome.success === false && !carried.has(entry.checkRef))
2419
- .map((entry) => entry.checkRef))];
2420
- if (checkRefs.length === 0)
2849
+ const { verification, unrunCheckRefs, unavailableVerificationTools } = await this.executeVerificationPlans(plans);
2850
+ // Kept only when nothing the checks read changed in the worktree while they ran (#3998): otherwise never recorded.
2851
+ if (besideWindow !== undefined && !(await besideWindow.keptAfterChecks()))
2421
2852
  continue;
2422
- const { verification, unrunCheckRefs, unavailableVerificationTools } = await this.executeVerificationPlans(resolveApplicationCodingTaskVerificationPlans(checkRefs));
2423
2853
  const unrun = new Set(unrunCheckRefs);
2424
- const results = verification.map(({ checkRef, outcome }) => ({
2425
- checkRef, success: outcome.success && !unrun.has(checkRef), message: outcome.message, ...(unrun.has(checkRef) ? { unanswered: true } : {}),
2426
- }));
2854
+ /*
2855
+ * A check charged for one of the run's findings passes the re-check when only findings the run was NOT charged with
2856
+ * remain (#3881 review F3): those red at its baseline and those another writer caused. Judged whole, it could never
2857
+ * pass while the application's finding stands, and the run's attempt would count for it.
2858
+ */
2859
+ const notCharged = readVerificationFindingsNotCharged(row.output);
2860
+ const results = verification.map(({ checkRef, outcome }) => {
2861
+ const onlyNotCharged = !outcome.success && (outcome.failureFindings?.length ?? 0) > 0
2862
+ && outcome.failureFindings.every((finding) => notCharged.get(checkRef)?.has(finding) === true);
2863
+ return {
2864
+ checkRef,
2865
+ success: (outcome.success || onlyNotCharged) && !unrun.has(checkRef),
2866
+ message: outcome.message,
2867
+ ...(unrun.has(checkRef) ? { unanswered: true } : {}),
2868
+ };
2869
+ });
2427
2870
  const recheck = {
2428
2871
  checkRefs,
2429
2872
  passed: results.length === checkRefs.length && results.every((result) => result.success),
@@ -2437,9 +2880,10 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
2437
2880
  });
2438
2881
  this.announceRunStateChanged();
2439
2882
  /*
2440
- * A re-check runs ALONE by construction, so what it could not ask is the host's, and what it asked proves the host
2441
- * answers again (run 43961156770): both feed the holds exactly as a run's settlement does. After the record, so the
2442
- * re-check's standing never depends on them.
2883
+ * A re-check runs ALONE by construction (at the wave's end, or beside live runs none of which was expected to write
2884
+ * what it reads and with nothing it reads moved meanwhile, #3998), so what it could not ask is the host's, and what it
2885
+ * asked proves the host answers again (run 43961156770): both feed the holds exactly as a run's settlement does.
2886
+ * After the record, so the re-check's standing never depends on them.
2443
2887
  */
2444
2888
  // The ledger counts BUILD tasks: a run with no task ref is never counted, or one task could pass for two.
2445
2889
  const recheckTaskRef = typeof row.input?.taskRef === 'string' ? row.input.taskRef : undefined;
@@ -2806,80 +3250,101 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
2806
3250
  * Accept works on a generation-step row too, under GUIDED, with the same refusals. The capture and
2807
3251
  * the accept are best effort: a step whose writes could not be registered still returns its
2808
3252
  * result, and stays visibly unlanded.
3253
+ *
3254
+ * **A step whose writes have been traced CLAIMS them (#4020).** It keeps the lock for its whole window; the claim only
3255
+ * lets a concurrent coding run whose declared scope does not meet them be admitted meanwhile, without waiting for that
3256
+ * lock. A step whose writes are not traced claims nothing, and every admission waits for it as before.
2809
3257
  */
2810
3258
  async runGenerationStepInWorktreeWindow(input) {
2811
3259
  await this.refuseWhileWorktreeIsHeld(null, input.sessionContext);
3260
+ const claimRoots = await this.resolveGenerationStepClaim(input);
2812
3261
  return withDedicatedFileLock(this.getWorkspaceMutationLockPath(), async () => {
2813
- await this.acceptPendingPlaybookRunsBeforeBaseline();
2814
- const baseline = await this.gitChangeSetService.captureWorktreeSnapshot();
2815
- await this.recordRunBaselineOnTask(input.taskId, baseline, input.sessionContext);
2816
- const concurrentAtStart = await this.concurrentCodingRunsLive(input.sessionContext);
2817
- // Beside a concurrent run, the step is part of that sharing episode from its own baseline (#1805).
2818
- if (concurrentAtStart)
2819
- this.markSharingEpisodeStarted(baseline.capturedAt);
2820
3262
  /*
2821
- * A step that throws, or whose capture fails, records no change set, and its window would stay OPEN to HEAD for the
2822
- * build-task decisions reader (#3224 F2): every later decision would read as made inside it. So its window is
2823
- * bounded at the HEAD it left.
3263
+ * The step's PATH CLAIM (#4020), opened and released inside the lock it holds for its whole window. The lock
3264
+ * still keeps every commit, every re-check, a single-flight run and a second step out of the window, as before;
3265
+ * the claim is what lets a concurrent coding run's ADMISSION stop waiting for that lock when the run has nothing
3266
+ * to commit before its baseline and its declared scope does not meet these roots
3267
+ * ({@link awaitWorkspaceLockUnlessHeldByAClaim}). Such a run joins the window as a wave's run joins a step it runs
3268
+ * inline (#1805 review N2): read below as sharing, so the step claims only its own directories.
2824
3269
  */
2825
- const boundWindow = () => this.recordRunWindowBound(input.taskId, input.taskRef, baseline);
2826
- let result;
2827
- try {
2828
- result = await input.execute();
2829
- }
2830
- catch (error) {
2831
- await boundWindow();
2832
- throw error;
2833
- }
2834
- let shared = concurrentAtStart;
2835
- let claimedPaths = [];
3270
+ const releaseClaim = claimRoots === undefined
3271
+ ? undefined
3272
+ : this.workspacePathClaims.acquire({ kind: WorkspacePathClaimKind.STEP_WRITE, ownerTaskId: input.taskId, ownerTaskRef: input.taskRef, writePrefixes: claimRoots });
2836
3273
  try {
2837
- const changeSet = await this.gitChangeSetService.captureChangeSet(baseline);
2838
- /*
2839
- * A step holds the workspace lock, but a CONCURRENT coding run takes that lock only to commit, so
2840
- * a wave's runs keep writing while the step runs inline (#1805 review N2). Its capture then holds
2841
- * their writes too. So when concurrent runs were live at either end of its window, or one recorded
2842
- * writes during it, the step is recorded as a sharing run and claims only what lies under the
2843
- * directories it alone writes (#2240): its record then says which files are its own. The checkpoint
2844
- * that follows commits the tree, its siblings' writes included (#3204).
2845
- */
2846
- const concurrentAtEnd = await this.concurrentCodingRunsLive(input.sessionContext);
2847
- if (concurrentAtEnd)
3274
+ await this.acceptPendingPlaybookRunsBeforeBaseline();
3275
+ const baseline = await this.gitChangeSetService.captureWorktreeSnapshot();
3276
+ await this.recordRunBaselineOnTask(input.taskId, baseline, input.sessionContext);
3277
+ const concurrentAtStart = await this.concurrentCodingRunsLive(input.sessionContext);
3278
+ // Beside a concurrent run, the step is part of that sharing episode from its own baseline (#1805).
3279
+ if (concurrentAtStart)
2848
3280
  this.markSharingEpisodeStarted(baseline.capturedAt);
2849
- shared = shared || concurrentAtEnd
2850
- || (await this.codingRunWriteRegister.list()).some((record) => record.concurrent === true && record.at >= baseline.capturedAt);
2851
- // The paths in a tree only this step writes (#2240), whether or not it shared the window: they are its claims when
2852
- // shared, and, shared or not, a file there that was already dirty is still the step's own output (#3233).
2853
- const stepOwnedPaths = claimGenerationStepOwnedPaths(changeSet.files.map((file) => file.path), input.ownedPathPrefixes ?? []);
2854
3281
  /*
2855
- * The step's own TypeScript must compile before it is committed (#3878). Its pipeline validates its output by its
2856
- * own rules, which can be weaker than the compiler: on reference run 43691253927 an email template passed its
2857
- * validator, imported names the application's email components do not export, was committed by the checkpoint
2858
- * below, and left the backend uncompiling for the rest of the run. Only errors in the step's own files refuse it.
3282
+ * A step that throws, or whose capture fails, records no change set, and its window would stay OPEN to HEAD for the
3283
+ * build-task decisions reader (#3224 F2): every later decision would read as made inside it. So its window is
3284
+ * bounded at the HEAD it left.
2859
3285
  */
2860
- const checkedPaths = generationStepCheckedPaths(changeSet.files.map((file) => file.path), input.ownedPathPrefixes ?? []);
2861
- const refusal = await this.typecheckGenerationStepOutput(checkedPaths);
2862
- if (refusal.length > 0) {
2863
- const { restored, kept } = await this.restoreGenerationStepPaths(checkedPaths);
2864
- await boundWindow();
2865
- throw new GenerationStepOutputRefusedError(input.taskRef, refusal, restored, kept);
3286
+ const boundWindow = () => this.recordRunWindowBound(input.taskId, input.taskRef, baseline);
3287
+ let result;
3288
+ try {
3289
+ result = await input.execute();
2866
3290
  }
2867
- if (shared)
2868
- claimedPaths = stepOwnedPaths;
2869
- await this.codingRunWriteRegister.record({ taskId: input.taskId, taskRef: input.taskRef, changeSet, stepOwnedPaths, ...(shared ? { claimedPaths } : {}) });
2870
- }
2871
- catch (error) {
2872
- if (error instanceof GenerationStepOutputRefusedError)
3291
+ catch (error) {
3292
+ await boundWindow();
2873
3293
  throw error;
2874
- this.logger.warn('Could not register a generation step\'s writes; no checkpoint names it until it runs again', {
2875
- taskId: input.taskId, taskRef: input.taskRef, error: describeCaughtError(error),
2876
- });
2877
- await boundWindow();
3294
+ }
3295
+ let shared = concurrentAtStart;
3296
+ let claimedPaths = [];
3297
+ try {
3298
+ const changeSet = await this.gitChangeSetService.captureChangeSet(baseline);
3299
+ /*
3300
+ * A step holds the workspace lock, but a CONCURRENT coding run takes that lock only to commit, so
3301
+ * a wave's runs keep writing while the step runs inline (#1805 review N2). Its capture then holds
3302
+ * their writes too. So when concurrent runs were live at either end of its window, or one recorded
3303
+ * writes during it, the step is recorded as a sharing run and claims only what lies under the
3304
+ * directories it alone writes (#2240): its record then says which files are its own. The checkpoint
3305
+ * that follows commits the tree, its siblings' writes included (#3204).
3306
+ */
3307
+ const concurrentAtEnd = await this.concurrentCodingRunsLive(input.sessionContext);
3308
+ if (concurrentAtEnd)
3309
+ this.markSharingEpisodeStarted(baseline.capturedAt);
3310
+ shared = shared || concurrentAtEnd
3311
+ || (await this.codingRunWriteRegister.list()).some((record) => record.concurrent === true && record.at >= baseline.capturedAt);
3312
+ // The paths in a tree only this step writes (#2240), whether or not it shared the window: they are its claims when
3313
+ // shared, and, shared or not, a file there that was already dirty is still the step's own output (#3233).
3314
+ const stepOwnedPaths = claimGenerationStepOwnedPaths(changeSet.files.map((file) => file.path), input.ownedPathPrefixes ?? []);
3315
+ /*
3316
+ * The step's own TypeScript must compile before it is committed (#3878). Its pipeline validates its output by its
3317
+ * own rules, which can be weaker than the compiler: on reference run 43691253927 an email template passed its
3318
+ * validator, imported names the application's email components do not export, was committed by the checkpoint
3319
+ * below, and left the backend uncompiling for the rest of the run. Only errors in the step's own files refuse it.
3320
+ */
3321
+ const checkedPaths = generationStepCheckedPaths(changeSet.files.map((file) => file.path), input.ownedPathPrefixes ?? []);
3322
+ const refusal = await this.typecheckGenerationStepOutput(checkedPaths);
3323
+ if (refusal.length > 0) {
3324
+ const { restored, kept } = await this.restoreGenerationStepPaths(checkedPaths);
3325
+ await boundWindow();
3326
+ throw new GenerationStepOutputRefusedError(input.taskRef, refusal, restored, kept);
3327
+ }
3328
+ if (shared)
3329
+ claimedPaths = stepOwnedPaths;
3330
+ await this.codingRunWriteRegister.record({ taskId: input.taskId, taskRef: input.taskRef, changeSet, stepOwnedPaths, ...(shared ? { claimedPaths } : {}) });
3331
+ }
3332
+ catch (error) {
3333
+ if (error instanceof GenerationStepOutputRefusedError)
3334
+ throw error;
3335
+ this.logger.warn('Could not register a generation step\'s writes; no checkpoint names it until it runs again', {
3336
+ taskId: input.taskId, taskRef: input.taskRef, error: describeCaughtError(error),
3337
+ });
3338
+ await boundWindow();
3339
+ return result;
3340
+ }
3341
+ // The step's writes, and whatever the tree holds besides, are committed by a checkpoint now (#3204), inside the lock this window holds.
3342
+ await this.requestBuildCheckpoint({ force: true, settlingTaskIds: [input.taskId], takeLock: false });
2878
3343
  return result;
2879
3344
  }
2880
- // The step's writes, and whatever the tree holds besides, are committed by a checkpoint now (#3204), inside the lock this window holds.
2881
- await this.requestBuildCheckpoint({ force: true, settlingTaskIds: [input.taskId], takeLock: false });
2882
- return result;
3345
+ finally {
3346
+ releaseClaim?.();
3347
+ }
2883
3348
  }, { retries: { retries: 0 } }).catch((error) => { throw this.mapLockError(error); });
2884
3349
  }
2885
3350
  /**
@@ -3047,8 +3512,10 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
3047
3512
  const baselineUnavailableTool = baselineVerification.unavailableVerificationTools[0];
3048
3513
  if (baselineUnavailableTool !== undefined)
3049
3514
  this.holdForUnavailableVerificationTool(baselineUnavailableTool, task.taskRef, taskId);
3515
+ // A red in a package this task is the author of is the task's, never carried (#4018, `codingTaskOwnPackageCheckRefs`).
3516
+ const ownPackageCheckRefs = new Set(codingTaskOwnPackageCheckRefs(task));
3050
3517
  const preexistingVerificationFailures = new Map(baselineVerification.verification
3051
- .filter(({ checkRef, outcome }) => !outcome.success && !unrunAtBaseline.has(checkRef))
3518
+ .filter(({ checkRef, outcome }) => !outcome.success && !unrunAtBaseline.has(checkRef) && !ownPackageCheckRefs.has(checkRef))
3052
3519
  .map(({ checkRef, outcome }) => [checkRef, outcome.failureFindings]));
3053
3520
  let runError = null;
3054
3521
  // When the agent's refusal reached the host: a usage limit's reset is read against THIS instant (#2388 review F2).
@@ -3396,31 +3863,71 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
3396
3863
  * The recording half is not decoration: a check red for every task is a project-level defect
3397
3864
  * that nothing else would surface, and forgiving it silently would replace a loud wrong answer
3398
3865
  * with a quiet one.
3866
+ *
3867
+ * Nor does a finding about the APPLICATION that another writer caused (#3881): on reference run 43691253927,
3868
+ * `check:website-demo-facts` failed 13 runs and `check:specification-exports` 4 on demos and specifications other
3869
+ * tasks were writing beside them. A check that names what each finding is about (`findingElements`) is attributed
3870
+ * per finding (`attributeVerificationFailure`): a new finding about elements another writer of this run's window
3871
+ * touched, and this run did not, is recorded for the application (`applicationVerificationFindings`, and the check is
3872
+ * carried); any other new finding is the run's. A carried check never reaches the attempt budget, the isolated
3873
+ * re-check or the retry's failed checks as the run's, since every reader excludes `carriedVerificationFailures`.
3399
3874
  */
3875
+ const verificationAttributions = await this.attributeFailedVerification({
3876
+ task,
3877
+ taskId,
3878
+ changeSet,
3879
+ verification,
3880
+ baseline: preexistingVerificationFailures,
3881
+ reportedFileLocations: codingReportedFileLocations,
3882
+ permissionDecisions: codingPermissionDecisions,
3883
+ });
3400
3884
  const carriedVerification = verification
3401
- .filter(({ checkRef, outcome }) => !outcome.success && verificationFailureIsCarried(preexistingVerificationFailures, checkRef, outcome.failureFindings));
3885
+ .filter(({ checkRef, outcome }) => !outcome.success && verificationAttributions.get(checkRef)?.chargedToRun === false);
3402
3886
  const carriedVerificationFailures = carriedVerification.map(({ checkRef }) => checkRef);
3887
+ const applicationVerificationFindings = [...verificationAttributions.values()].flatMap((attribution) => attribution.applicationFindings);
3888
+ if (applicationVerificationFindings.length > 0) {
3889
+ this.logger.info('A coding run met findings about the application that another writer caused; recorded for the application, not charged to the run', {
3890
+ taskRef: task.taskRef,
3891
+ findings: applicationVerificationFindings.map(({ checkRef, finding, writtenByTaskRefs }) => ({ checkRef, finding: finding.slice(0, 300), writtenByTaskRefs })),
3892
+ });
3893
+ }
3403
3894
  /*
3404
3895
  * And WHY it is red, captured while the output is in hand (#1529): the files the check names and
3405
3896
  * what generated them. A red nobody diagnoses is re-diagnosed by hand — on the first end-to-end run
3406
3897
  * that took an hour, for a fact the broken file's own banner stated.
3407
3898
  */
3408
- const carriedVerificationDiagnoses = carriedVerification.map(({ checkRef, outcome }) => diagnoseCarriedVerificationFailure({
3409
- checkRef,
3410
- checkPath: outcome.path,
3411
- message: outcome.message,
3412
- stdoutTail: outcome.stdoutTail,
3413
- stderrTail: outcome.stderrTail,
3414
- readHead: (relativePath) => {
3415
- try {
3416
- return readFileSync(join(this.companionContext.saasRoot, relativePath), 'utf8').slice(0, 8_000);
3417
- }
3418
- catch {
3419
- return undefined;
3420
- }
3421
- },
3899
+ const carriedVerificationDiagnoses = carriedVerification.map(({ checkRef, outcome }) => {
3900
+ const attribution = verificationAttributions.get(checkRef);
3901
+ return {
3902
+ ...diagnoseCarriedVerificationFailure({
3903
+ checkRef,
3904
+ checkPath: outcome.path,
3905
+ message: outcome.message,
3906
+ stdoutTail: outcome.stdoutTail,
3907
+ stderrTail: outcome.stderrTail,
3908
+ readHead: (relativePath) => {
3909
+ try {
3910
+ return readFileSync(join(this.companionContext.saasRoot, relativePath), 'utf8').slice(0, 8_000);
3911
+ }
3912
+ catch {
3913
+ return undefined;
3914
+ }
3915
+ },
3916
+ }),
3917
+ // Why it was carried, and which findings are the application's (#3881): what the repair owed reads.
3918
+ ...(attribution?.carriedBecause !== undefined ? { carriedBecause: attribution.carriedBecause } : {}),
3919
+ ...(attribution !== undefined && attribution.applicationFindings.length > 0
3920
+ ? { applicationFindings: attribution.applicationFindings.map(({ finding, writtenByTaskRefs }) => ({ finding, writtenByTaskRefs })) }
3921
+ : {}),
3922
+ };
3923
+ });
3924
+ const failedVerifications = verification.filter(({ checkRef, outcome }) => !outcome.success && verificationAttributions.get(checkRef)?.chargedToRun !== false);
3925
+ const verificationFindingsNotCharged = Object.fromEntries(failedVerifications.flatMap(({ checkRef, outcome }) => {
3926
+ const atBaseline = preexistingVerificationFailures.get(checkRef) ?? [];
3927
+ const theApplications = (verificationAttributions.get(checkRef)?.applicationFindings ?? []).map(({ finding }) => finding);
3928
+ const notCharged = (outcome.failureFindings ?? []).filter((finding) => atBaseline.includes(finding) || theApplications.includes(finding));
3929
+ return notCharged.length > 0 ? [[checkRef, notCharged]] : [];
3422
3930
  }));
3423
- const failedVerifications = verification.filter(({ checkRef, outcome }) => !outcome.success && !verificationFailureIsCarried(preexistingVerificationFailures, checkRef, outcome.failureFindings));
3424
3931
  const failedVerification = failedVerifications[0] ?? null;
3425
3932
  /*
3426
3933
  * Every check this run failed on could not ASK (#3258): a failed module that may be a stale build, a compiled tree
@@ -3579,6 +4086,13 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
3579
4086
  ...(codingSessionEventCount > 0 ? { codingSessionEventCount } : {}),
3580
4087
  // Red before this run started, and still red. Not this task's failure, and not nobody's.
3581
4088
  ...(carriedVerificationFailures.length > 0 ? { carriedVerificationFailures, carriedVerificationDiagnoses } : {}),
4089
+ /*
4090
+ * Findings about the application another writer caused (#3881), whether their check is carried or charged for a
4091
+ * finding of the run's own: the retry is told they are not its to fix, and the build owes them a repair.
4092
+ */
4093
+ ...(applicationVerificationFindings.length > 0 ? { applicationVerificationFindings } : {}),
4094
+ // Per charged check, the findings it was NOT charged with: what its isolated re-check may leave red (#3881 review F3).
4095
+ ...(Object.keys(verificationFindingsNotCharged).length > 0 ? { verificationFindingsNotCharged } : {}),
3582
4096
  ...(codingSessionRetention.frames().length > 0
3583
4097
  ? { codingSessionFrames: codingSessionRetention.frames(), codingSessionRetention: codingSessionRetention.summary() }
3584
4098
  : {}),
@@ -4520,6 +5034,9 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
4520
5034
  * nowhere earlier: a second, earlier check could only ever repeat this one.
4521
5035
  */
4522
5036
  this.refuseWhileRunChainIsLive(taskId);
5037
+ // A single-flight resume holds the whole-tree lock and takes the tree alone again, as its dispatch did (#4020).
5038
+ if (mode !== CodingRunConcurrency.CONCURRENT)
5039
+ this.refuseWhileWorkspacePathClaimsOpen(checkpoint.contract.taskRef);
4523
5040
  // ONE settlement for the whole chain: the resumed turn, and any questions the answering agent
4524
5041
  // then answers under the same hold (#1559) — a caller awaiting it sees the chain's final state.
4525
5042
  const settlement = createDeferred();
@@ -5192,6 +5709,80 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
5192
5709
  }
5193
5710
  return outcome;
5194
5711
  }
5712
+ /**
5713
+ * Whose each FAILED check of a settled run is (#3881, `attributeVerificationFailure`): the run's, or the application's.
5714
+ *
5715
+ * What THIS run touched: every file of its change set inside the application, whatever git says of it, less the ones a
5716
+ * sibling coding run claimed and this run did not (a run sharing the tree captures its siblings' files too, #1528); and
5717
+ * the business module its build task targets. A file committed during the run stays the run's: a wave's build checkpoint
5718
+ * commits a live run's own files (#3881 review F1), so a commit is no evidence of another writer. A file nobody claimed
5719
+ * stays the run's, so an agent that wrote through a shell is never relieved of its own finding. A file in a module
5720
+ * package's shared source (outside `src/modules/<module>/`) touches every module (review F2). Kept deliberately for
5721
+ * an UNCLAIMED shared-source file too, which may be a sibling's shell write: it is indistinguishable from the run's own,
5722
+ * and the cost is a charge (a relief withheld), never a forgiveness. Claims carry no timestamps, so "changed in this
5723
+ * window" is approximated by this run's change set: an accepted residual.
5724
+ *
5725
+ * The OTHER writers of its window: every coding run whose window overlapped it, with the paths it claimed (its record's
5726
+ * claimed files once it settled, its on-disk in-flight claims while it runs) that ALSO changed in this run's window (they
5727
+ * are in this run's change set, review F2: a sibling's write before this run's baseline is not this window's); and a
5728
+ * concurrent host lane's files (a research lane's store), unless this run claimed them. Claims are the only per-run
5729
+ * evidence there is: a sibling that wrote only through a shell claims nothing, so its findings stay the run's that met them.
5730
+ *
5731
+ * Only a check the table marks {@link VerificationFindingAttribution.PER_FINDING_ELEMENTS}
5732
+ * (`APPLICATION_CODING_TASK_FINDING_ATTRIBUTION`) is judged per finding: any other check's `findingElements` are ignored,
5733
+ * so the table is the one authority and an unlisted check fails closed (review F6). Best effort: an unreadable record or
5734
+ * claims file adds no writer, which can only leave a finding the run's.
5735
+ */
5736
+ async attributeFailedVerification(input) {
5737
+ const elementsOf = (checkRef, outcome) => APPLICATION_CODING_TASK_FINDING_ATTRIBUTION[checkRef]?.attribution === VerificationFindingAttribution.PER_FINDING_ELEMENTS ? outcome.findingElements : undefined;
5738
+ const failed = input.verification.filter(({ outcome }) => !outcome.success);
5739
+ const needsWriters = failed.some(({ checkRef, outcome }) => Object.keys(elementsOf(checkRef, outcome) ?? {}).length > 0);
5740
+ const roots = applicationRootSpellings(this.companionContext.saasRoot);
5741
+ const otherWriters = [];
5742
+ let runPaths = [];
5743
+ if (needsWriters) {
5744
+ const files = (input.changeSet?.files ?? []).filter((entry) => entry.attribution !== ChangeSetAttributionClass.OUTSIDE_APPLICATION_ROOT);
5745
+ const changedInWindow = new Set(files.map((entry) => entry.path));
5746
+ const selfClaimed = new Set(collectRunClaimedPaths({
5747
+ candidateRoots: roots,
5748
+ reportedFileLocations: input.reportedFileLocations,
5749
+ permissionDecisions: input.permissionDecisions,
5750
+ }));
5751
+ const self = this.codingRunWindows.find((window) => window.taskId === input.taskId);
5752
+ const siblings = self === undefined ? [] : this.codingRunWindows.filter((window) => window.taskId !== input.taskId
5753
+ && (window.endedAtMs === undefined || window.endedAtMs > self.startedAtMs));
5754
+ for (const sibling of siblings) {
5755
+ try {
5756
+ const record = await this.codingRunWriteRegister.read(sibling.taskId);
5757
+ const claimed = [
5758
+ ...(record?.files ?? []).filter((file) => file.claimedByRun === true).map((file) => file.path),
5759
+ ...collectRunClaimedPaths({ candidateRoots: roots, reportedFileLocations: await this.codingRunWriteRegister.readInFlightClaims(sibling.taskId) }),
5760
+ ].filter((path) => changedInWindow.has(path) && !selfClaimed.has(path));
5761
+ if (claimed.length > 0)
5762
+ otherWriters.push({ taskRef: sibling.taskRef, written: deriveCodingRunWrittenElements({ paths: claimed }) });
5763
+ }
5764
+ catch (error) {
5765
+ this.logDebug('Could not read a sibling run\'s claims; its findings stay the run\'s that met them', { taskId: input.taskId, siblingTaskId: sibling.taskId, error: describeCaughtError(error) });
5766
+ }
5767
+ }
5768
+ const hostLaneFiles = files
5769
+ .filter((entry) => entry.attribution === ChangeSetAttributionClass.CONCURRENT_HOST_LANE && !selfClaimed.has(entry.path))
5770
+ .map((entry) => entry.path);
5771
+ if (hostLaneFiles.length > 0)
5772
+ otherWriters.push({ written: deriveCodingRunWrittenElements({ paths: hostLaneFiles }) });
5773
+ const othersWrote = new Set(otherWriters.flatMap((writer) => writer.written.paths));
5774
+ runPaths = files.map((entry) => entry.path).filter((path) => selfClaimed.has(path) || !othersWrote.has(path));
5775
+ }
5776
+ const run = deriveCodingRunWrittenElements({ paths: runPaths, moduleRefs: readCodingTaskTargetModuleRefs(input.task), sharedCodeTouchesEveryModule: true });
5777
+ return new Map(failed.map(({ checkRef, outcome }) => [checkRef, attributeVerificationFailure({
5778
+ baseline: input.baseline,
5779
+ checkRef,
5780
+ failureFindings: outcome.failureFindings,
5781
+ findingElements: elementsOf(checkRef, outcome),
5782
+ run,
5783
+ otherWriters,
5784
+ })]));
5785
+ }
5195
5786
  /**
5196
5787
  * Every business module's conventional files, read from the working tree, held to the folders the framework reads them
5197
5788
  * from (#3904, `inspectModuleLayout`). Each misplaced file is one finding (its identity in `failureFindings`, so a
@@ -5214,7 +5805,11 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
5214
5805
  */
5215
5806
  : `${inspection.findings.length} module file(s) outside their conventional folder. Move the ones your task wrote or `
5216
5807
  + `moved; one that was already there before your run is not charged to it: ${inspection.findings.map((finding) => finding.correction).join(' | ')}`,
5217
- ...(success ? {} : { failureFindings: inspection.findings.map((finding) => finding.identity) }),
5808
+ ...(success ? {} : {
5809
+ failureFindings: inspection.findings.map((finding) => finding.identity),
5810
+ // Each finding is about the misplaced file (#3881): one another run placed is not charged to this one.
5811
+ findingElements: Object.fromEntries(inspection.findings.map((finding) => [finding.identity, { paths: [finding.path], moduleRefs: [] }])),
5812
+ }),
5218
5813
  stdoutTail: '',
5219
5814
  stderrTail: '',
5220
5815
  };
@@ -5264,14 +5859,35 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
5264
5859
  : findings.loadError !== null
5265
5860
  ? [`the specifications package cannot be evaluated: ${findings.loadError}`, ...chapterFileFaults].join(' | ')
5266
5861
  : [...findings.moduleFaults.map(describeModule), ...refused, ...chapterFileFaults].join(' | '),
5267
- ...(success ? {} : {
5268
- failureFindings: [
5269
- ...(findings.loadError === null ? [] : [`entry:${findings.loadError}`]),
5270
- ...findings.moduleFaults.filter((fault) => fault.causedBy.length === 0).map((fault) => `module:${fault.modulePath}:${fault.message}`),
5271
- ...findings.faults.map((fault) => `refused:${fault.kind}:${fault.key}:${fault.message}`),
5272
- ...chapterFileFaults.map((fault) => `chapter-file:${fault}`),
5273
- ],
5274
- }),
5862
+ ...(success ? {} : (() => {
5863
+ /*
5864
+ * What each finding is about (#3881): a root-cause module fault its module file (and the file its authored frame
5865
+ * names), a refused specification the file its factory was called from. A package that does not load, a refusal
5866
+ * with no authored frame and a chapter-file fault name nothing, so a new one stays the run's.
5867
+ */
5868
+ const roots = applicationRootSpellings(this.companionContext.saasRoot);
5869
+ const elementsOf = (paths) => ({
5870
+ paths: [...new Set(paths.filter((path) => path !== undefined && path.length > 0 && !path.startsWith('..') && !path.startsWith('/')))],
5871
+ moduleRefs: [],
5872
+ });
5873
+ const moduleFindings = findings.moduleFaults.filter((fault) => fault.causedBy.length === 0).map((fault) => [
5874
+ `module:${fault.modulePath}:${fault.message}`,
5875
+ elementsOf([fault.modulePath, fault.authoredFrame === null ? undefined : applicationRelativeFileOfLocation(fault.authoredFrame, roots)]),
5876
+ ]);
5877
+ const refusedFindings = findings.faults.map((fault) => [
5878
+ `refused:${fault.kind}:${fault.key}:${fault.message}`,
5879
+ elementsOf([fault.authoredFrame === null ? undefined : applicationRelativeFileOfLocation(fault.authoredFrame, roots)]),
5880
+ ]);
5881
+ return {
5882
+ failureFindings: [
5883
+ ...(findings.loadError === null ? [] : [`entry:${findings.loadError}`]),
5884
+ ...moduleFindings.map(([identity]) => identity),
5885
+ ...refusedFindings.map(([identity]) => identity),
5886
+ ...chapterFileFaults.map((fault) => `chapter-file:${fault}`),
5887
+ ],
5888
+ findingElements: Object.fromEntries([...moduleFindings, ...refusedFindings].filter(([, elements]) => elements.paths.length > 0)),
5889
+ };
5890
+ })()),
5275
5891
  stdoutTail: '',
5276
5892
  stderrTail: '',
5277
5893
  };
@@ -5626,7 +6242,14 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
5626
6242
  if (!collection.collected) {
5627
6243
  if (collection.fault === WebsiteDemoScenarioCollectionFault.HOST)
5628
6244
  throw new Error(`The website's demos could not be collected: ${collection.message}`);
5629
- return outcome(false, `the website's sections could not be imported, so its demos cannot be checked: ${collection.message.slice(0, 600)}`);
6245
+ /*
6246
+ * One identity, about nothing (#3881 re-review F1): a later red is then compared with it per finding, never carried
6247
+ * whole because the baseline named none, and a new import failure stays the run's.
6248
+ */
6249
+ return {
6250
+ ...outcome(false, `the website's sections could not be imported, so its demos cannot be checked: ${collection.message.slice(0, 600)}`),
6251
+ failureFindings: [`import:${(collection.message.split('\n')[0] ?? '').trim().slice(0, 300)}`],
6252
+ };
5630
6253
  }
5631
6254
  const reached = `reached from ${collection.entries.join(' and ')}`;
5632
6255
  if (collection.records.every((record) => record.scenario.resource === undefined)) {
@@ -5639,9 +6262,26 @@ let CodingAgentDispatchCompanionService = class CodingAgentDispatchCompanionServ
5639
6262
  const describeSite = (definedAt) => (definedAt === null ? 'a demo scenario (its definition site is unknown)' : relative(saasRoot, definedAt));
5640
6263
  const result = checkWebsiteDemoScenarios(collection.records, index.resources, describeSite);
5641
6264
  const against = `against the domain model (${describeWorkspaceFreshness(freshness)})`;
5642
- return result.problems.length === 0
5643
- ? outcome(true, `${result.bound} bound demo scenario(s) of ${result.defined} ${reached} show only what their resources allow, ${against}`)
5644
- : outcome(false, `${result.problems.length} demo value(s) untrue of the application, ${against}: ${result.problems.join(' | ')}`);
6265
+ if (result.problems.length === 0)
6266
+ return outcome(true, `${result.bound} bound demo scenario(s) of ${result.defined} ${reached} show only what their resources allow, ${against}`);
6267
+ /*
6268
+ * One identity per untrue demo (#3881): the file it is defined in (not the line, which moves), the resource and the
6269
+ * problem. It is ABOUT that file and the module of the resource it draws, so a demo another task wrote, or one a
6270
+ * module task made untrue by changing its resource, is not charged to a run that touched neither. A resource the
6271
+ * application lacks, or a site nobody can name, names nothing and stays the run's.
6272
+ */
6273
+ const roots = applicationRootSpellings(saasRoot);
6274
+ const identified = result.findings.map((finding) => {
6275
+ const site = finding.definedAt === null ? undefined : applicationRelativeFileOfLocation(finding.definedAt, roots);
6276
+ const identity = `demo:${site ?? 'unknown-site'}:${finding.resourceType}:${finding.problem}`;
6277
+ const named = site !== undefined && finding.moduleId !== undefined;
6278
+ return { identity, elements: named ? { paths: [site], moduleRefs: finding.moduleId === null ? [] : [finding.moduleId] } : undefined };
6279
+ });
6280
+ return {
6281
+ ...outcome(false, `${result.problems.length} demo value(s) untrue of the application, ${against}: ${result.problems.join(' | ')}`),
6282
+ failureFindings: [...new Set(identified.map(({ identity }) => identity))],
6283
+ findingElements: Object.fromEntries(identified.flatMap(({ identity, elements }) => (elements === undefined ? [] : [[identity, elements]]))),
6284
+ };
5645
6285
  }
5646
6286
  /**
5647
6287
  * A typecheck of a workspace package the application does not have answers "nothing to check" (#1540).